diff --git a/.clang-format b/.clang-format index 035c2f8..09fd2b5 100644 --- a/.clang-format +++ b/.clang-format @@ -1,11 +1,32 @@ +BasedOnStyle: LLVM +IndentWidth: 4 ColumnLimit: 120 -PointerAlignment: Left -ReferenceAlignment: Left -AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: true -CommentPragmas: '^' -BreakBeforeBraces: Allman -NamespaceIndentation: All -FixNamespaceComments: false +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: Always + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: false + BeforeWhile: true + SplitEmptyFunction: false + SplitEmptyRecord: false +RemoveBracesLLVM: true +InsertBraces: false +SortIncludes: Never +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AllowShortBlocksOnASingleLine: Never +AllowShortLambdasOnASingleLine: Inline +AccessModifierOffset: -4 IndentCaseLabels: true -IndentPPDirectives: BeforeHash \ No newline at end of file +NamespaceIndentation: None +PointerAlignment: Left diff --git a/CMakeLists.txt b/CMakeLists.txt index 1446246..2f9c219 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -98,7 +98,7 @@ endif() if(NOT MSVC) foreach(TARGET anm2ed_core anm2ed_app anm2ed) - target_compile_options(${TARGET} PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(${TARGET} PRIVATE -Wall -Wextra -Wpedantic -Wno-missing-field-initializers) endforeach() endif() diff --git a/src/asset_store.cpp b/src/asset_store.cpp index d7a23d9..594fbdb 100644 --- a/src/asset_store.cpp +++ b/src/asset_store.cpp @@ -2,50 +2,54 @@ #include - constexpr std::uint64_t FNV_OFFSET = 14695981039346656037ull; - constexpr std::uint64_t FNV_PRIME = 1099511628211ull; +constexpr std::uint64_t FNV_OFFSET = 14695981039346656037ull; +constexpr std::uint64_t FNV_PRIME = 1099511628211ull; - static std::uint64_t bytes_hash(std::span bytes, std::uint64_t hash = FNV_OFFSET) - { +static std::uint64_t bytes_hash(std::span bytes, std::uint64_t hash = FNV_OFFSET) +{ for (auto byte : bytes) - hash = (hash ^ byte) * FNV_PRIME; + hash = (hash ^ byte) * FNV_PRIME; return hash; - } +} - template static std::span value_bytes_get(const Value& value) - { +template static std::span value_bytes_get(const Value& value) +{ return {reinterpret_cast(&value), sizeof(value)}; - } +} - // Content hash; 0 stays free to mean "no asset". - static std::uint64_t hash_finish(std::uint64_t hash) { return hash ? hash : 1; } +// Content hash. 0 stays free to mean "no asset". +static std::uint64_t hash_finish(std::uint64_t hash) +{ + return hash ? hash : 1; +} - std::uint64_t AssetStore::image_add(Image image) - { +std::uint64_t AssetStore::image_add(Image image) +{ auto hash = bytes_hash(value_bytes_get(image.size)); hash = bytes_hash(value_bytes_get(image.isLinear), hash); hash = bytes_hash(image.pixels, hash); - if (image.svg) hash = bytes_hash({(const std::uint8_t*)image.svg->data(), image.svg->size()}, hash); + if (image.svg) + hash = bytes_hash({(const std::uint8_t*)image.svg->data(), image.svg->size()}, hash); hash = hash_finish(hash); images.try_emplace(hash, std::move(image)); return hash; - } +} - std::uint64_t AssetStore::audio_add(AudioData data) - { +std::uint64_t AssetStore::audio_add(AudioData data) +{ auto hash = hash_finish(bytes_hash(data.bytes)); audio.try_emplace(hash, std::move(data)); return hash; - } +} - const Image* AssetStore::image_get(std::uint64_t hash) const - { +const Image* AssetStore::image_get(std::uint64_t hash) const +{ auto it = images.find(hash); return it == images.end() ? nullptr : &it->second; - } +} - const AudioData* AssetStore::audio_get(std::uint64_t hash) const - { +const AudioData* AssetStore::audio_get(std::uint64_t hash) const +{ auto it = audio.find(hash); return it == audio.end() ? nullptr : &it->second; - } +} diff --git a/src/asset_store.h b/src/asset_store.h index 5f06b7c..3ec6a9b 100644 --- a/src/asset_store.h +++ b/src/asset_store.h @@ -6,16 +6,16 @@ #include "audio_data.h" #include "image.h" - // Immutable images and sounds keyed by content hash. Undo history records keys, never pixels or bytes, and - // entries live until the document closes so any step can be restored. - class AssetStore - { +// Immutable images and sounds keyed by content hash. Undo history records keys, never pixels or bytes, and +// entries live until the document closes so any step can be restored. +class AssetStore +{ std::unordered_map images; std::unordered_map audio; - public: +public: std::uint64_t image_add(Image); std::uint64_t audio_add(AudioData); const Image* image_get(std::uint64_t) const; const AudioData* audio_get(std::uint64_t) const; - }; +}; diff --git a/src/audio.cpp b/src/audio.cpp index f0cca6c..44e0b83 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -6,104 +6,115 @@ #include #include - struct AudioEntry - { +struct AudioEntry +{ MIX_Audio* audio = nullptr; std::vector tracks; // one per overlapping play, reused once finished std::atomic squares[2]{}; std::atomic sampleCount = {}; - }; +}; - // Sums the squares of the left/right samples the track plays, for its levels. - static void SDLCALL levels_update(void* userdata, MIX_Track*, const SDL_AudioSpec* spec, float* pcm, int samples) - { +// Sums the squares of the left/right samples the track plays, for its levels. +static void SDLCALL levels_update(void* userdata, MIX_Track*, const SDL_AudioSpec* spec, float* pcm, int samples) +{ auto entry = (AudioEntry*)userdata; auto channels = std::max(spec->channels, 1); float squares[2]{}; for (int i = 0; i < samples; ++i) - squares[std::min(i % channels, 1)] += pcm[i] * pcm[i]; - if (channels == 1) squares[1] = squares[0]; + squares[std::min(i % channels, 1)] += pcm[i] * pcm[i]; + if (channels == 1) + squares[1] = squares[0]; for (int channel = 0; channel < 2; ++channel) - entry->squares[channel] += squares[channel]; + entry->squares[channel] += squares[channel]; entry->sampleCount += samples / channels; - } +} - static std::unordered_map entries; +static std::unordered_map entries; - static MIX_Mixer* audio_mixer_get() - { +static MIX_Mixer* audio_mixer_get() +{ static auto mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr); return mixer; - } +} - static AudioEntry* entry_get(const AudioData& data) - { - if (!data.is_valid()) return nullptr; +static AudioEntry* entry_get(const AudioData& data) +{ + if (!data.is_valid()) + return nullptr; auto [it, isNew] = entries.try_emplace(data.uid); if (isNew) - if (auto io = SDL_IOFromConstMem(data.bytes.data(), data.bytes.size())) - it->second.audio = MIX_LoadAudio_IO(audio_mixer_get(), io, true, true); + if (auto io = SDL_IOFromConstMem(data.bytes.data(), data.bytes.size())) + it->second.audio = MIX_LoadAudio_IO(audio_mixer_get(), io, true, true); return it->second.audio ? &it->second : nullptr; - } +} - static bool is_on_mixer(MIX_Track* track, MIX_Mixer* mixer) { return !mixer || MIX_GetTrackMixer(track) == mixer; } +static bool is_on_mixer(MIX_Track* track, MIX_Mixer* mixer) +{ + return !mixer || MIX_GetTrackMixer(track) == mixer; +} - // A sound can play over itself: while a track is still playing it, another track takes the new play. - void audio_play(const AudioData& data, bool isLoop, MIX_Mixer* mixer) - { +// A sound can play over itself: while a track is still playing it, another track takes the new play. +void audio_play(const AudioData& data, bool isLoop, MIX_Mixer* mixer) +{ auto entry = entry_get(data); auto targetMixer = mixer ? mixer : audio_mixer_get(); - if (!entry || !targetMixer) return; + if (!entry || !targetMixer) + return; - auto free = std::ranges::find_if(entry->tracks, [&](MIX_Track* track) - { return is_on_mixer(track, targetMixer) && !MIX_TrackPlaying(track); }); + auto free = std::ranges::find_if( + entry->tracks, [&](MIX_Track* track) { return is_on_mixer(track, targetMixer) && !MIX_TrackPlaying(track); }); auto track = free != entry->tracks.end() ? *free : MIX_CreateTrack(targetMixer); - if (!track) return; + if (!track) + return; if (free == entry->tracks.end()) { - entry->tracks.push_back(track); - MIX_SetTrackCookedCallback(track, levels_update, entry); - MIX_SetTrackAudio(track, entry->audio); + entry->tracks.push_back(track); + MIX_SetTrackCookedCallback(track, levels_update, entry); + MIX_SetTrackAudio(track, entry->audio); } SDL_PropertiesID options = isLoop ? SDL_CreateProperties() : 0; - if (options) SDL_SetNumberProperty(options, MIX_PROP_PLAY_LOOPS_NUMBER, -1); + if (options) + SDL_SetNumberProperty(options, MIX_PROP_PLAY_LOOPS_NUMBER, -1); MIX_PlayTrack(track, options); - if (options) SDL_DestroyProperties(options); - } + if (options) + SDL_DestroyProperties(options); +} - void audio_stop(const AudioData& data, MIX_Mixer* mixer) - { +void audio_stop(const AudioData& data, MIX_Mixer* mixer) +{ if (auto it = entries.find(data.uid); it != entries.end()) - for (auto track : it->second.tracks) - if (is_on_mixer(track, mixer)) MIX_StopTrack(track, 0); - } + for (auto track : it->second.tracks) + if (is_on_mixer(track, mixer)) + MIX_StopTrack(track, 0); +} - void audio_track_detach(const AudioData& data, MIX_Mixer* mixer) - { +void audio_track_detach(const AudioData& data, MIX_Mixer* mixer) +{ auto it = entries.find(data.uid); - if (it == entries.end()) return; - std::erase_if(it->second.tracks, - [&](MIX_Track* track) - { - if (!is_on_mixer(track, mixer)) return false; - MIX_DestroyTrack(track); - return true; - }); - } + if (it == entries.end()) + return; + std::erase_if(it->second.tracks, [&](MIX_Track* track) { + if (!is_on_mixer(track, mixer)) + return false; + MIX_DestroyTrack(track); + return true; + }); +} - bool is_audio_playing(const AudioData& data) - { +bool is_audio_playing(const AudioData& data) +{ auto it = entries.find(data.uid); return it != entries.end() && std::ranges::any_of(it->second.tracks, MIX_TrackPlaying); - } +} - // The left/right loudness (RMS, 0-1) of what the track played since the last call. - glm::vec2 audio_levels_get(const AudioData& data) - { +// The left/right loudness (RMS, 0-1) of what the track played since the last call. +glm::vec2 audio_levels_get(const AudioData& data) +{ auto it = entries.find(data.uid); - if (it == entries.end()) return {}; + if (it == entries.end()) + return {}; auto& entry = it->second; auto count = (float)std::max(entry.sampleCount.exchange(0), 1); return {std::sqrt(entry.squares[0].exchange(0.0f) / count), std::sqrt(entry.squares[1].exchange(0.0f) / count)}; - } +} diff --git a/src/audio.h b/src/audio.h index 8bcfe0f..df7d557 100644 --- a/src/audio.h +++ b/src/audio.h @@ -5,9 +5,9 @@ #include "audio_data.h" -// Playback of AudioData; decoded audio and tracks are cached per AudioData uid. - void audio_play(const AudioData&, bool = false, MIX_Mixer* = nullptr); - void audio_stop(const AudioData&, MIX_Mixer* = nullptr); - void audio_track_detach(const AudioData&, MIX_Mixer* = nullptr); - bool is_audio_playing(const AudioData&); - glm::vec2 audio_levels_get(const AudioData&); +// Playback of AudioData. Decoded audio and tracks are cached per AudioData uid. +void audio_play(const AudioData&, bool = false, MIX_Mixer* = nullptr); +void audio_stop(const AudioData&, MIX_Mixer* = nullptr); +void audio_track_detach(const AudioData&, MIX_Mixer* = nullptr); +bool is_audio_playing(const AudioData&); +glm::vec2 audio_levels_get(const AudioData&); diff --git a/src/audio_data.cpp b/src/audio_data.cpp index 726695d..e85e3b2 100644 --- a/src/audio_data.cpp +++ b/src/audio_data.cpp @@ -5,18 +5,22 @@ #include "uid.h" - AudioData::AudioData(const unsigned char* memory, size_t size) - { - if (!memory || size == 0) return; +AudioData::AudioData(const unsigned char* memory, size_t size) +{ + if (!memory || size == 0) + return; bytes.assign(memory, memory + size); uid = uid_next(); - } +} - AudioData::AudioData(const std::filesystem::path& path) - { +AudioData::AudioData(const std::filesystem::path& path) +{ std::ifstream file(path, std::ios::binary); std::vector data = {std::istreambuf_iterator(file), {}}; *this = AudioData(data.data(), data.size()); - } +} - bool AudioData::is_valid() const { return !bytes.empty(); } +bool AudioData::is_valid() const +{ + return !bytes.empty(); +} diff --git a/src/audio_data.h b/src/audio_data.h index b0916a5..c521939 100644 --- a/src/audio_data.h +++ b/src/audio_data.h @@ -5,9 +5,9 @@ #include #include - // Encoded audio file bytes. uid identifies the bytes so playback state can be cached by it. - struct AudioData - { +// Encoded audio file bytes. uid identifies the bytes so playback state can be cached by it. +struct AudioData +{ std::vector bytes; std::uint64_t uid = 0; @@ -16,4 +16,4 @@ AudioData(const std::filesystem::path&); bool is_valid() const; - }; +}; diff --git a/src/audio_stream.cpp b/src/audio_stream.cpp index 8058c1f..8ac8c57 100644 --- a/src/audio_stream.cpp +++ b/src/audio_stream.cpp @@ -3,21 +3,23 @@ #include #if defined(__clang__) || defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-parameter" #endif - void AudioStream::callback(void* userData, MIX_Mixer* mixer, const SDL_AudioSpec* spec, float* pcm, int samples) - { +void AudioStream::callback(void* userData, MIX_Mixer* mixer, const SDL_AudioSpec* spec, float* pcm, int samples) +{ auto self = (AudioStream*)userData; if (!self->isFirstCallbackCaptured) { - self->firstCallbackCounter = SDL_GetPerformanceCounter(); - self->isFirstCallbackCaptured = true; + self->firstCallbackCounter = SDL_GetPerformanceCounter(); + self->isFirstCallbackCaptured = true; } self->callbackSamples = samples; self->stream.insert(self->stream.end(), pcm, pcm + samples); - } - - AudioStream::AudioStream(MIX_Mixer* mixer) { MIX_GetMixerFormat(mixer, &spec); } +} +AudioStream::AudioStream(MIX_Mixer* mixer) +{ + MIX_GetMixerFormat(mixer, &spec); +} diff --git a/src/audio_stream.h b/src/audio_stream.h index d7a830d..03c11a3 100644 --- a/src/audio_stream.h +++ b/src/audio_stream.h @@ -3,11 +3,11 @@ #include #include - class AudioStream - { +class AudioStream +{ static void callback(void*, MIX_Mixer*, const SDL_AudioSpec*, float*, int); - public: +public: std::vector stream; SDL_AudioSpec spec = {}; int callbackSamples = 0; @@ -16,4 +16,4 @@ bool isFirstCallbackCaptured = false; AudioStream(MIX_Mixer*); - }; +}; diff --git a/src/canvas.cpp b/src/canvas.cpp index bed40bc..85ef911 100644 --- a/src/canvas.cpp +++ b/src/canvas.cpp @@ -10,21 +10,21 @@ using namespace glm; - static void canvas_blend_premultiplied_set() - { +static void canvas_blend_premultiplied_set() +{ glEnable(GL_BLEND); glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - } +} - static void canvas_blend_straight_set() - { +static void canvas_blend_straight_set() +{ glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); - } +} - static void vertex_array_make(GLuint& vao, GLuint& vbo, const void* data, GLsizeiptr size, GLenum usage, - std::initializer_list attributeSizes) - { +static void vertex_array_make(GLuint& vao, GLuint& vbo, const void* data, GLsizeiptr size, GLenum usage, + std::initializer_list attributeSizes) +{ glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glBindVertexArray(vao); @@ -33,22 +33,22 @@ using namespace glm; auto stride = 0; for (auto attributeSize : attributeSizes) - stride += attributeSize; + stride += attributeSize; auto offset = 0; auto index = 0; for (auto attributeSize : attributeSizes) { - glEnableVertexAttribArray(index); - glVertexAttribPointer(index++, attributeSize, GL_FLOAT, GL_FALSE, stride * sizeof(float), - (void*)(offset * sizeof(float))); - offset += attributeSize; + glEnableVertexAttribArray(index); + glVertexAttribPointer(index++, attributeSize, GL_FLOAT, GL_FALSE, stride * sizeof(float), + (void*)(offset * sizeof(float))); + offset += attributeSize; } - } +} - Canvas::Canvas() = default; +Canvas::Canvas() = default; - Canvas::Canvas(vec2 size) - { +Canvas::Canvas(vec2 size) +{ Framebuffer::size_set(size); vertex_array_make(axisVAO, axisVBO, AXIS_VERTICES, sizeof(AXIS_VERTICES), GL_STATIC_DRAW, {2}); vertex_array_make(gridVAO, gridVBO, GRID_VERTICES, sizeof(GRID_VERTICES), GL_STATIC_DRAW, {2, 2}); @@ -58,19 +58,20 @@ using namespace glm; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, textureEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(TEXTURE_INDICES), TEXTURE_INDICES, GL_DYNAMIC_DRAW); glBindVertexArray(0); - } +} - Canvas::~Canvas() - { - if (!Framebuffer::is_valid()) return; +Canvas::~Canvas() +{ + if (!Framebuffer::is_valid()) + return; for (auto vao : {axisVAO, gridVAO, rectVAO, textureVAO}) - glDeleteVertexArrays(1, &vao); + glDeleteVertexArrays(1, &vao); for (auto buffer : {axisVBO, gridVBO, rectVBO, textureVBO, textureEBO}) - glDeleteBuffers(1, &buffer); - } + glDeleteBuffers(1, &buffer); +} - mat4 Canvas::transform_get(float zoom, vec2 pan) const - { +mat4 Canvas::transform_get(float zoom, vec2 pan) const +{ auto zoomFactor = percent_to_unit(zoom); auto projection = glm::ortho(0.0f, (float)size.x, 0.0f, (float)size.y, -1.0f, 1.0f); auto view = mat4{1.0f}; @@ -79,10 +80,10 @@ using namespace glm; view = glm::scale(view, vec3(zoomFactor, zoomFactor, 1.0f)); return projection * view; - } +} - void Canvas::axes_render(ShaderProgram& shader, float zoom, vec2 pan, vec4 color) const - { +void Canvas::axes_render(ShaderProgram& shader, float zoom, vec2 pan, vec4 color) const +{ canvas_blend_premultiplied_set(); auto originNDC = transform_get(zoom, pan) * vec4(0.0f, 0.0f, 0.0f, 1.0f); @@ -104,10 +105,10 @@ using namespace glm; glBindVertexArray(0); glUseProgram(0); canvas_blend_straight_set(); - } +} - void Canvas::grid_render(ShaderProgram& shader, float zoom, vec2 pan, ivec2 size, ivec2 offset, vec4 color) const - { +void Canvas::grid_render(ShaderProgram& shader, float zoom, vec2 pan, ivec2 size, ivec2 offset, vec4 color) const +{ canvas_blend_premultiplied_set(); auto transform = glm::inverse(transform_get(zoom, pan)); @@ -125,92 +126,94 @@ using namespace glm; glUseProgram(0); canvas_blend_straight_set(); - } +} - static void texture_uniform_set(const ShaderUniform& uniform, vec4 value) - { +static void texture_uniform_set(const ShaderUniform& uniform, vec4 value) +{ if (uniform.valueType == UNIFORM_VALUE_INT || uniform.valueType == UNIFORM_VALUE_SAMPLER2D) - return glUniform1i(uniform.location, uniform.intValue); + return glUniform1i(uniform.location, uniform.intValue); switch (UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount) { - case 2: - return glUniform2fv(uniform.location, 1, value_ptr(value)); - case 3: - return glUniform3fv(uniform.location, 1, value_ptr(value)); - case 4: - return glUniform4fv(uniform.location, 1, value_ptr(value)); - default: - if (uniform.valueType == UNIFORM_VALUE_FLOAT) glUniform1f(uniform.location, value.x); + case 2: + return glUniform2fv(uniform.location, 1, value_ptr(value)); + case 3: + return glUniform3fv(uniform.location, 1, value_ptr(value)); + case 4: + return glUniform4fv(uniform.location, 1, value_ptr(value)); + default: + if (uniform.valueType == UNIFORM_VALUE_FLOAT) + glUniform1f(uniform.location, value.x); } - } +} - static vec4 texture_uniform_components_get(const ShaderUniform& uniform, float playbackTime) - { +static vec4 texture_uniform_components_get(const ShaderUniform& uniform, float playbackTime) +{ vec4 result{}; for (int i = 0; i < (int)uniform.components.size(); ++i) - result[i] = uniform.components[i].binding == UNIFORM_BINDING_PLAYBACK_TIME ? playbackTime - : uniform.components[i].value; + result[i] = + uniform.components[i].binding == UNIFORM_BINDING_PLAYBACK_TIME ? playbackTime : uniform.components[i].value; return result; - } +} - static void texture_uniforms_set(ShaderProgram& shader, mat4 transform, vec4 tint, vec4 colorOffset, vec2 textureSize, - float playbackTime) - { +static void texture_uniforms_set(ShaderProgram& shader, mat4 transform, vec4 tint, vec4 colorOffset, vec2 textureSize, + float playbackTime) +{ if (shader.uniforms.empty()) { - glUniform1i(glGetUniformLocation(shader.id, UNIFORM_TEXTURE), 0); - glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_COLOR_OFFSET), 1, value_ptr(colorOffset)); - glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_TINT), 1, value_ptr(tint)); - glUniformMatrix4fv(glGetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); - return; + glUniform1i(glGetUniformLocation(shader.id, UNIFORM_TEXTURE), 0); + glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_COLOR_OFFSET), 1, value_ptr(colorOffset)); + glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_TINT), 1, value_ptr(tint)); + glUniformMatrix4fv(glGetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); + return; } for (auto& uniform : shader.uniforms) { - if (uniform.location == -1) continue; + if (uniform.location == -1) + continue; - switch (uniform.binding) - { - case UNIFORM_BINDING_MAIN_TEXTURE: - glUniform1i(uniform.location, 0); - break; - case UNIFORM_BINDING_TRANSFORM: - if (uniform.valueType == UNIFORM_VALUE_MAT4) - glUniformMatrix4fv(uniform.location, 1, GL_FALSE, value_ptr(transform)); - break; - case UNIFORM_BINDING_FRAME_TINT: - texture_uniform_set(uniform, tint); - break; - case UNIFORM_BINDING_COLOR_OFFSET: - texture_uniform_set(uniform, colorOffset); - break; - case UNIFORM_BINDING_TEXTURE_SIZE: - texture_uniform_set(uniform, vec4(textureSize, 0.0f, 0.0f)); - break; - case UNIFORM_BINDING_PLAYBACK_TIME: - texture_uniform_set(uniform, vec4(playbackTime)); - break; - case UNIFORM_BINDING_COMPONENTS: - texture_uniform_set(uniform, texture_uniform_components_get(uniform, playbackTime)); - break; - case UNIFORM_BINDING_MANUAL: - texture_uniform_set(uniform, uniform.value); - break; - default: - break; - } + switch (uniform.binding) + { + case UNIFORM_BINDING_MAIN_TEXTURE: + glUniform1i(uniform.location, 0); + break; + case UNIFORM_BINDING_TRANSFORM: + if (uniform.valueType == UNIFORM_VALUE_MAT4) + glUniformMatrix4fv(uniform.location, 1, GL_FALSE, value_ptr(transform)); + break; + case UNIFORM_BINDING_FRAME_TINT: + texture_uniform_set(uniform, tint); + break; + case UNIFORM_BINDING_COLOR_OFFSET: + texture_uniform_set(uniform, colorOffset); + break; + case UNIFORM_BINDING_TEXTURE_SIZE: + texture_uniform_set(uniform, vec4(textureSize, 0.0f, 0.0f)); + break; + case UNIFORM_BINDING_PLAYBACK_TIME: + texture_uniform_set(uniform, vec4(playbackTime)); + break; + case UNIFORM_BINDING_COMPONENTS: + texture_uniform_set(uniform, texture_uniform_components_get(uniform, playbackTime)); + break; + case UNIFORM_BINDING_MANUAL: + texture_uniform_set(uniform, uniform.value); + break; + default: + break; + } } - } +} - void Canvas::texture_render(ShaderProgram& shader, GLuint texture, mat4 transform, vec4 tint, vec4 colorOffset, - float* vertices, vec2 textureSize, float playbackTime, TextureBlur blur) const - { +void Canvas::texture_render(ShaderProgram& shader, GLuint texture, mat4 transform, vec4 tint, vec4 colorOffset, + float* vertices, vec2 textureSize, float playbackTime, TextureBlur blur) const +{ canvas_blend_premultiplied_set(); glUseProgram(shader.id); texture_uniforms_set(shader, transform, tint, colorOffset, textureSize, playbackTime); - // The editor's own texture shader blurs; a custom shader without these uniforms ignores them. + // The editor's own texture shader blurs. A custom shader without these uniforms ignores them. glUniform1f(glGetUniformLocation(shader.id, UNIFORM_BLUR), blur.radius); glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_REGION), 1, value_ptr(blur.region)); glUniform2fv(glGetUniformLocation(shader.id, UNIFORM_TEXEL), 1, @@ -233,159 +236,164 @@ using namespace glm; glUseProgram(0); canvas_blend_straight_set(); - } +} - static void rect_begin(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color) - { +static void rect_begin(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color) +{ canvas_blend_premultiplied_set(); glUseProgram(shader.id); glUniformMatrix4fv(glGetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); if (auto location = glGetUniformLocation(shader.id, UNIFORM_MODEL); location != -1) - glUniformMatrix4fv(location, 1, GL_FALSE, value_ptr(model)); + glUniformMatrix4fv(location, 1, GL_FALSE, value_ptr(model)); glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_COLOR), 1, value_ptr(color)); - } +} - static void rect_end(GLuint vao, GLenum mode, int count = 4) - { +static void rect_end(GLuint vao, GLenum mode, int count = 4) +{ glBindVertexArray(vao); glDrawArrays(mode, 0, count); glBindVertexArray(0); glUseProgram(0); canvas_blend_straight_set(); - } +} - void Canvas::dashed_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength, - float dashGap, float dashOffset, GLenum mode, int count) const - { +void Canvas::dashed_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color, + float dashLength, float dashGap, float dashOffset, GLenum mode, int count) const +{ rect_begin(shader, transform, model, color); auto origin = model * vec4(0.0f, 0.0f, 0.0f, 1.0f); for (auto [name, axis] : {std::pair{UNIFORM_AXIS_X, vec4(1.0f, 0.0f, 0.0f, 1.0f)}, std::pair{UNIFORM_AXIS_Y, vec4(0.0f, 1.0f, 0.0f, 1.0f)}}) - if (auto location = glGetUniformLocation(shader.id, name); location != -1) - glUniform2fv(location, 1, value_ptr(vec2(model * axis - origin))); - for (auto [name, value] : - {std::pair{UNIFORM_DASH_LENGTH, dashLength}, std::pair{UNIFORM_DASH_GAP, dashGap}, - std::pair{UNIFORM_DASH_OFFSET, dashOffset}}) - if (auto location = glGetUniformLocation(shader.id, name); location != -1) glUniform1f(location, value); + if (auto location = glGetUniformLocation(shader.id, name); location != -1) + glUniform2fv(location, 1, value_ptr(vec2(model * axis - origin))); + for (auto [name, value] : {std::pair{UNIFORM_DASH_LENGTH, dashLength}, std::pair{UNIFORM_DASH_GAP, dashGap}, + std::pair{UNIFORM_DASH_OFFSET, dashOffset}}) + if (auto location = glGetUniformLocation(shader.id, name); location != -1) + glUniform1f(location, value); rect_end(rectVAO, mode, count); - } +} - // A layer draw's crop of its spritesheet. A blurred one (Flash's BlurFilter: a box `blur` canvas pixels wide) grows by - // the box's reach, in texels at the draw's scale, and averages its crop over it. - void Canvas::layer_render(ShaderProgram& shader, GLuint texture, vec2 textureSize, const mat4& transform, - const Draw& draw, vec4 tint, vec4 colorOffset) const - { +// A layer draw's crop of its spritesheet. A blurred one (Flash's BlurFilter: a box `blur` canvas pixels wide) grows by +// the box's reach, in texels at the draw's scale, and averages its crop over it. +void Canvas::layer_render(ShaderProgram& shader, GLuint texture, vec2 textureSize, const mat4& transform, + const Draw& draw, vec4 tint, vec4 colorOffset) const +{ auto blurred = draw; auto& frame = blurred.frame; TextureBlur blur = {.region = vec4(frame.crop, frame.crop + frame.size) / vec4(textureSize, textureSize)}; if (frame.blur > 0.0f && frame.size.x > 0.0f && frame.size.y > 0.0f) { - auto canvasArea = std::abs(glm::determinant(glm::mat2(draw.parent * draw_quad_model_get(draw)))); - auto canvasPerTexel = std::sqrt(canvasArea / (frame.size.x * frame.size.y)); - blur.radius = canvasPerTexel > 0.0f ? std::round(frame.blur * 0.5f / canvasPerTexel) : 0.0f; - frame.crop -= blur.radius; - frame.size += blur.radius * 2.0f; - frame.pivot += blur.radius; + auto canvasArea = std::abs(glm::determinant(glm::mat2(draw.parent * draw_quad_model_get(draw)))); + auto canvasPerTexel = std::sqrt(canvasArea / (frame.size.x * frame.size.y)); + blur.radius = canvasPerTexel > 0.0f ? std::round(frame.blur * 0.5f / canvasPerTexel) : 0.0f; + frame.crop -= blur.radius; + frame.size += blur.radius * 2.0f; + frame.pivot += blur.radius; } auto vertices = uv_vertices_get(frame.crop / textureSize, (frame.crop + frame.size) / textureSize); texture_render(shader, texture, transform * blurred.parent * draw_quad_model_get(blurred), tint, colorOffset, vertices.data(), textureSize, draw.time, blur); - } +} - // An animation's layers alone (no markers or helpers); spritesheet images are looked up by draw, custom shaders by id. - void Canvas::layers_render(ShaderProgram& shader, const Model& model, const Animation& animation, - const DrawOptions& options, const mat4& transform, - const std::function& image_get, - const std::function& shader_get) const - { +// An animation's layers alone (no markers or helpers). Spritesheet images are looked up by draw, custom shaders by id. +void Canvas::layers_render(ShaderProgram& shader, const Model& model, const Animation& animation, + const DrawOptions& options, const mat4& transform, + const std::function& image_get, + const std::function& shader_get) const +{ for (auto& draw : animation_draws_get(model, animation, options)) { - if (draw.type != DrawType::LAYER) continue; - auto& frame = draw.frame; - auto image = image_get(draw); - if (!image || !image->is_valid() || frame.size == vec2()) continue; - auto customShader = shader_get ? shader_get(frame.shaderId) : nullptr; - layer_render(customShader ? *customShader : shader, texture_id_get(*image), image->unit_size_get(), transform, - draw, frame.tint, frame.colorOffset); + if (draw.type != DrawType::LAYER) + continue; + auto& frame = draw.frame; + auto image = image_get(draw); + if (!image || !image->is_valid() || frame.size == vec2()) + continue; + auto customShader = shader_get ? shader_get(frame.shaderId) : nullptr; + layer_render(customShader ? *customShader : shader, texture_id_get(*image), image->unit_size_get(), transform, + draw, frame.tint, frame.colorOffset); } - } +} - void Canvas::rect_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength, - float dashGap, float dashOffset) const - { +void Canvas::rect_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength, + float dashGap, float dashOffset) const +{ dashed_render(shader, transform, model, color, dashLength, dashGap, dashOffset, GL_LINE_LOOP, RECT_VERTEX_COUNT); - } +} - // A line from start to end: the bottom edge of a rectangle laid along it. - void Canvas::line_render(ShaderProgram& shader, const mat4& transform, vec2 start, vec2 end, vec4 color, float dashLength, - float dashGap, float dashOffset) const - { +// A line from start to end: the bottom edge of a rectangle laid along it. +void Canvas::line_render(ShaderProgram& shader, const mat4& transform, vec2 start, vec2 end, vec4 color, + float dashLength, float dashGap, float dashOffset) const +{ auto direction = end - start; auto normal = glm::length(direction) > 0.0f ? glm::normalize(vec2(-direction.y, direction.x)) : vec2(0.0f, 1.0f); auto model = mat4(vec4(direction, 0.0f, 0.0f), vec4(normal, 0.0f, 0.0f), vec4(0.0f, 0.0f, 1.0f, 0.0f), vec4(start, 0.0f, 1.0f)); dashed_render(shader, transform, model, color, dashLength, dashGap, dashOffset, GL_LINES, LINE_VERTEX_COUNT); - } +} - void Canvas::rect_fill_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color) const - { +void Canvas::rect_fill_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color) const +{ rect_begin(shader, transform, model, color); rect_end(rectVAO, GL_TRIANGLE_FAN); - } +} - float Canvas::zoom_level_get(float zoom, int levelDelta) const - { - if (levelDelta == 0) return zoom; - if (zoom < ZOOM_LEVELS.front()) return ZOOM_LEVELS.front(); - if (zoom > ZOOM_LEVELS.back()) return ZOOM_LEVELS.back(); +float Canvas::zoom_level_get(float zoom, int levelDelta) const +{ + if (levelDelta == 0) + return zoom; + if (zoom < ZOOM_LEVELS.front()) + return ZOOM_LEVELS.front(); + if (zoom > ZOOM_LEVELS.back()) + return ZOOM_LEVELS.back(); auto levelCount = (int)ZOOM_LEVELS.size(); int levelIndex = 0; if (levelDelta > 0) { - auto it = std::upper_bound(ZOOM_LEVELS.begin(), ZOOM_LEVELS.end(), zoom); - levelIndex = (int)std::distance(ZOOM_LEVELS.begin(), it) + levelDelta - 1; + auto it = std::upper_bound(ZOOM_LEVELS.begin(), ZOOM_LEVELS.end(), zoom); + levelIndex = (int)std::distance(ZOOM_LEVELS.begin(), it) + levelDelta - 1; } else { - auto it = std::lower_bound(ZOOM_LEVELS.begin(), ZOOM_LEVELS.end(), zoom); - levelIndex = (int)std::distance(ZOOM_LEVELS.begin(), it) + levelDelta; + auto it = std::lower_bound(ZOOM_LEVELS.begin(), ZOOM_LEVELS.end(), zoom); + levelIndex = (int)std::distance(ZOOM_LEVELS.begin(), it) + levelDelta; } return ZOOM_LEVELS[std::clamp(levelIndex, 0, levelCount - 1)]; - } +} - void Canvas::zoom_level_adjust(float& zoom, vec2& pan, vec2 focus, int levelDelta) const - { +void Canvas::zoom_level_adjust(float& zoom, vec2& pan, vec2 focus, int levelDelta) const +{ auto zoomFactor = percent_to_unit(zoom); float newZoom = zoom_level_get(zoom, levelDelta); if (newZoom != zoom) { - float newZoomFactor = percent_to_unit(newZoom); - pan += focus * (zoomFactor - newZoomFactor); - zoom = newZoom; + float newZoomFactor = percent_to_unit(newZoom); + pan += focus * (zoomFactor - newZoomFactor); + zoom = newZoom; } - } +} - vec2 Canvas::position_translate(float& zoom, vec2& pan, vec2 position) const - { +vec2 Canvas::position_translate(float& zoom, vec2& pan, vec2 position) const +{ auto zoomFactor = percent_to_unit(zoom); return (position - pan - (size * 0.5f)) / zoomFactor; - } +} - void Canvas::set_to_rect(float& zoom, vec2& pan, vec4 rect) const - { +void Canvas::set_to_rect(float& zoom, vec2& pan, vec4 rect) const +{ if (rect != vec4(-1.0f) && (rect.z > 0 && rect.w > 0)) { - f32 scaleX = size.x / rect.z; - f32 scaleY = size.y / rect.w; - f32 fitScale = std::min(scaleX, scaleY); + f32 scaleX = size.x / rect.z; + f32 scaleY = size.y / rect.w; + f32 fitScale = std::min(scaleX, scaleY); - zoom = unit_to_percent(fitScale); + zoom = unit_to_percent(fitScale); - vec2 rectCenter = {rect.x + rect.z * 0.5f, rect.y + rect.w * 0.5f}; - pan = -rectCenter * fitScale; + vec2 rectCenter = {rect.x + rect.z * 0.5f, rect.y + rect.w * 0.5f}; + pan = -rectCenter * fitScale; } - } +} diff --git a/src/canvas.h b/src/canvas.h index 0f6fa04..4567ea2 100644 --- a/src/canvas.h +++ b/src/canvas.h @@ -13,16 +13,16 @@ #include "types.h" - // A box blur `radius` texels wide each way over the texture's `region` (UV min, max); outside it is clear. - struct TextureBlur - { +// A box blur `radius` texels wide each way over the texture's `region` (UV min, max). Outside it is clear. +struct TextureBlur +{ float radius = 0; glm::vec4 region{}; - }; +}; - class Canvas : public Framebuffer - { - public: +class Canvas : public Framebuffer +{ +public: static constexpr float TEXTURE_VERTICES[] = {0, 0, 0.0f, 0.0f, 1, 0, 1.0f, 0.0f, 1, 1, 1.0f, 1.0f, 0, 1, 0.0f, 1.0f}; static constexpr auto PIVOT_SIZE = glm::vec2(8, 8); @@ -72,11 +72,10 @@ glm::vec4 = glm::vec4(1.0f)) const; void texture_render(ShaderProgram&, GLuint, glm::mat4 = {1.0f}, glm::vec4 = glm::vec4(1.0f), glm::vec4 = {}, float* = (float*)TEXTURE_VERTICES, glm::vec2 = {}, float = 0.0f, TextureBlur = {}) const; - void layer_render(ShaderProgram&, GLuint, glm::vec2, const glm::mat4&, const Draw&, glm::vec4, - glm::vec4) const; + void layer_render(ShaderProgram&, GLuint, glm::vec2, const glm::mat4&, const Draw&, glm::vec4, glm::vec4) const; void rect_fill_render(ShaderProgram&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f)) const; - void layers_render(ShaderProgram&, const Model&, const Animation&, const DrawOptions&, - const glm::mat4&, const std::function&, + void layers_render(ShaderProgram&, const Model&, const Animation&, const DrawOptions&, const glm::mat4&, + const std::function&, const std::function& = {}) const; void dashed_render(ShaderProgram&, const glm::mat4&, const glm::mat4&, glm::vec4, float, float, float, GLenum, int) const; @@ -88,4 +87,4 @@ void zoom_level_adjust(float&, glm::vec2&, glm::vec2, int) const; glm::vec2 position_translate(float&, glm::vec2&, glm::vec2) const; void set_to_rect(float& zoom, glm::vec2& pan, glm::vec4 rect) const; - }; +}; diff --git a/src/cli.cpp b/src/cli.cpp index a51a892..2b96f2a 100644 --- a/src/cli.cpp +++ b/src/cli.cpp @@ -19,7 +19,7 @@ #include "settings.h" #include "working_directory.h" - constexpr const char* USAGE = R"(usage: anm2ed [options] +constexpr const char* USAGE = R"(usage: anm2ed [options] commands: info animations, items, spritesheets and Isaac compatibility, as text @@ -42,100 +42,110 @@ options: --no-root-transform draw without the root's transform )"; - constexpr float SCALE_DEFAULT = 1.0f; - constexpr int HEX_BASE = 16; - constexpr int HEX_RGB_LENGTH = 6; - constexpr float CHANNEL_MAX = 255.0f; +constexpr float SCALE_DEFAULT = 1.0f; +constexpr int HEX_BASE = 16; +constexpr int HEX_RGB_LENGTH = 6; +constexpr float CHANNEL_MAX = 255.0f; - struct Arguments - { +struct Arguments +{ std::string command; std::filesystem::path file; std::map options; std::optional get(const std::string& name) const { - auto it = options.find(name); - return it == options.end() ? std::nullopt : std::optional(it->second); + auto it = options.find(name); + return it == options.end() ? std::nullopt : std::optional(it->second); } template T number_get(const std::string& name, T value) const { - if (auto text = get(name)) std::from_chars(text->data(), text->data() + text->size(), value); - return value; + if (auto text = get(name)) + std::from_chars(text->data(), text->data() + text->size(), value); + return value; } - bool is(const std::string& name) const { return options.contains(name); } - }; + bool is(const std::string& name) const + { + return options.contains(name); + } +}; - // PNG sequences go into a folder; everything else is a file. - static bool type_is_folder(const Arguments& arguments) - { +// PNG sequences go into a folder. Everything else is a file. +static bool type_is_folder(const Arguments& arguments) +{ return arguments.command == "render" && arguments.get("type").value_or("") == "pngs"; - } +} - static std::optional arguments_get(int argc, const char** argv) - { - if (argc < 3) return {}; +static std::optional arguments_get(int argc, const char** argv) +{ + if (argc < 3) + return {}; // Absolute, so a bare file name still has a folder for the paths in it. Arguments arguments = {.command = argv[1], .file = std::filesystem::absolute(path_from_utf8(argv[2]))}; for (int i = 3; i < argc; ++i) { - std::string name = argv[i]; - if (!name.starts_with("--")) return {}; - name.erase(0, 2); - auto isFlag = i + 1 >= argc || std::string_view(argv[i + 1]).starts_with("--"); - arguments.options[name] = isFlag ? std::string{} : std::string(argv[++i]); + std::string name = argv[i]; + if (!name.starts_with("--")) + return {}; + name.erase(0, 2); + auto isFlag = i + 1 >= argc || std::string_view(argv[i + 1]).starts_with("--"); + arguments.options[name] = isFlag ? std::string{} : std::string(argv[++i]); } return arguments; - } +} - // RRGGBB (opaque) or "transparent". - static glm::vec4 background_get(const Arguments& arguments) - { +// RRGGBB (opaque) or "transparent". +static glm::vec4 background_get(const Arguments& arguments) +{ auto text = arguments.get("background").value_or("transparent"); - if (text.starts_with('#')) text.erase(0, 1); + if (text.starts_with('#')) + text.erase(0, 1); unsigned value = 0; if (text.size() != HEX_RGB_LENGTH || std::from_chars(text.data(), text.data() + text.size(), value, HEX_BASE).ec != std::errc{}) - return {}; + return {}; return {(float)((value >> 16) & 0xFF) / CHANNEL_MAX, (float)((value >> 8) & 0xFF) / CHANNEL_MAX, (float)(value & 0xFF) / CHANNEL_MAX, 1.0f}; - } +} - // --ffmpeg, or else the FFmpeg the editor's Render Animation uses (or "ffmpeg" on the PATH). - static std::filesystem::path ffmpeg_path_get(const Arguments& arguments) - { - if (auto ffmpeg = arguments.get("ffmpeg")) return path_from_utf8(*ffmpeg); +// --ffmpeg, or else the FFmpeg the editor's Render Animation uses (or "ffmpeg" on the PATH). +static std::filesystem::path ffmpeg_path_get(const Arguments& arguments) +{ + if (auto ffmpeg = arguments.get("ffmpeg")) + return path_from_utf8(*ffmpeg); auto settingsPath = preferences_directory_get() / "settings.ini"; auto settingsFfmpeg = is_path_exist(settingsPath) ? Settings(settingsPath).renderFFmpegPath : std::filesystem::path{}; return settingsFfmpeg.empty() ? std::filesystem::path("ffmpeg") : settingsFfmpeg; - } +} - // By index or name; the default animation otherwise. - static std::pair animation_get(const Model& model, const Arguments& arguments) - { +// By index or name. The default animation otherwise. +static std::pair animation_get(const Model& model, const Arguments& arguments) +{ auto animations = model.animations_get(); auto name = arguments.get("animation").value_or(model.animations.defaultAnimation); int index = -1; if (std::from_chars(name.data(), name.data() + name.size(), index).ec == std::errc{} && index >= 0 && index < (int)animations.size()) - return animations[index]; + return animations[index]; for (auto [i, animation] : animations) - if (animation->name == name) return {i, animation}; - if (!arguments.is("animation") && !animations.empty()) return animations.front(); + if (animation->name == name) + return {i, animation}; + if (!arguments.is("animation") && !animations.empty()) + return animations.front(); return {-1, nullptr}; - } +} - static int info_print(const Arguments& arguments) - { +static int info_print(const Arguments& arguments) +{ Model model = {}; std::string error; if (!model_load(model, arguments.file, &error)) { - std::println(stderr, "could not load {}: {}", path_to_utf8(arguments.file), error); - return 1; + std::println(stderr, "could not load {}: {}", path_to_utf8(arguments.file), error); + return 1; } auto& content = model.content; std::println("file: {}", path_to_utf8(arguments.file)); @@ -144,37 +154,37 @@ options: std::println("animations (default: {}):", model.animations.defaultAnimation); for (auto [index, animation] : model.animations_get()) { - int layers{}, nulls{}; - tracks_each(animation->layers, [&](const Track&, auto*) { ++layers; }); - tracks_each(animation->nulls, [&](const Track&, auto*) { ++nulls; }); - std::println(" [{}] {}: {} frames{}, {} layer tracks, {} null tracks, {} triggers", index, animation->name, - animation->frameNum, animation->isLoop ? ", loops" : "", layers, nulls, - animation->triggers.frames.size()); + int layers{}, nulls{}; + tracks_each(animation->layers, [&](const Track&, auto*) { ++layers; }); + tracks_each(animation->nulls, [&](const Track&, auto*) { ++nulls; }); + std::println(" [{}] {}: {} frames{}, {} layer tracks, {} null tracks, {} triggers", index, animation->name, + animation->frameNum, animation->isLoop ? ", loops" : "", layers, nulls, + animation->triggers.frames.size()); } WorkingDirectory workingDirectory(arguments.file.parent_path()); std::println("spritesheets:"); for (auto& spritesheet : content.spritesheets) { - auto image = Image(path_case_insensitive_find(spritesheet.path)); - auto status = image.is_valid() ? std::format("{}x{}", image.size.x, image.size.y) : std::string("missing"); - std::println(" #{} {} ({}), {} regions", spritesheet.id, path_to_utf8(spritesheet.path), status, - spritesheet.regions.size()); + auto image = Image(path_case_insensitive_find(spritesheet.path)); + auto status = image.is_valid() ? std::format("{}x{}", image.size.x, image.size.y) : std::string("missing"); + std::println(" #{} {} ({}), {} regions", spritesheet.id, path_to_utf8(spritesheet.path), status, + spritesheet.regions.size()); } for (auto& library : content.libraries) - std::println("library #{} {}", library.id, path_to_utf8(library.path)); + std::println("library #{} {}", library.id, path_to_utf8(library.path)); for (auto& layer : content.layers) - if (layer.is_animation()) - std::println("layer #{} {} (animation {}, library #{})", layer.id, layer.name, layer.animation, - layer.libraryId); - else - std::println("layer #{} {} (spritesheet #{})", layer.id, layer.name, layer.spritesheetId); + if (layer.is_animation()) + std::println("layer #{} {} (animation {}, library #{})", layer.id, layer.name, layer.animation, + layer.libraryId); + else + std::println("layer #{} {} (spritesheet #{})", layer.id, layer.name, layer.spritesheetId); for (auto& null : content.nulls) - std::println("null #{} {}", null.id, null.name); + std::println("null #{} {}", null.id, null.name); for (auto& event : content.events) - std::println("event #{} {}", event.id, event.name); + std::println("event #{} {}", event.id, event.name); for (auto& sound : content.sounds) - std::println("sound #{} {}", sound.id, path_to_utf8(sound.path)); + std::println("sound #{} {}", sound.id, path_to_utf8(sound.path)); auto issues = isaac_issues_get(model); std::println("isaac issues: {} eased frames, {} group transforms, {} skewed frames, {} shader frames, {} depth " @@ -184,36 +194,36 @@ options: issues.alphaOffsetFrames, issues.blurFrames, issues.extraEvents, issues.triggerSounds, issues.animationLayers, issues.vectorSpritesheets); return 0; - } +} - static int draw_run(const Arguments& arguments) - { +static int draw_run(const Arguments& arguments) +{ auto out = arguments.get("out"); if (!out) { - std::println(stderr, "--out is required"); - return 2; + std::println(stderr, "--out is required"); + return 2; } HeadlessGL gl = {}; if (!gl.is_valid()) { - std::println(stderr, "could not create an OpenGL 3.3 context"); - return 1; + std::println(stderr, "could not create an OpenGL 3.3 context"); + return 1; } std::string error; Document document(arguments.file, false, &error); if (!document.is_valid()) { - std::println(stderr, "could not load {}: {}", path_to_utf8(arguments.file), error); - return 1; + std::println(stderr, "could not load {}: {}", path_to_utf8(arguments.file), error); + return 1; } auto [index, animation] = animation_get(document.model, arguments); if (!animation) { - std::println(stderr, "no such animation: {}", arguments.get("animation").value_or("")); - return 1; + std::println(stderr, "no such animation: {}", arguments.get("animation").value_or("")); + return 1; } auto& textureInfo = SHADERS[SHADER_TEXTURE]; @@ -223,10 +233,9 @@ options: auto bounds = animation_bounds_get(document, *animation, isRootTransform); auto scale = arguments.number_get("scale", SCALE_DEFAULT); auto background = background_get(arguments); - auto frame_render = [&](float time) - { - return animation_frame_render(canvas, shader, document, *animation, time, bounds, scale, background, - isRootTransform); + auto frame_render = [&](float time) { + return animation_frame_render(canvas, shader, document, *animation, time, bounds, scale, background, + isRootTransform); }; auto outPath = path_from_utf8(*out); std::error_code ec; @@ -234,103 +243,108 @@ options: if (arguments.command == "frame") { - auto pixels = frame_render(arguments.number_get("time", 0.0f)); - pixels_unpremultiply(pixels); - if (!Image::write_pixels_png(outPath, glm::ivec2(canvas.size), pixels.data())) - { - std::println(stderr, "could not write {}", *out); - return 1; - } - std::println("{}: \"{}\" at time {}, {}x{}", *out, animation->name, arguments.number_get("time", 0.0f), - (int)canvas.size.x, (int)canvas.size.y); - return 0; + auto pixels = frame_render(arguments.number_get("time", 0.0f)); + pixels_unpremultiply(pixels); + if (!Image::write_pixels_png(outPath, glm::ivec2(canvas.size), pixels.data())) + { + std::println(stderr, "could not write {}", *out); + return 1; + } + std::println("{}: \"{}\" at time {}, {}x{}", *out, animation->name, arguments.number_get("time", 0.0f), + (int)canvas.size.x, (int)canvas.size.y); + return 0; } auto typeName = arguments.get("type").value_or("sheet"); auto type = typeName == "sheet" ? RENDER_SPRITESHEET : RENDER_PNGS; for (int i = 0; i < RENDER_COUNT; ++i) - if (RENDER_EXTENSIONS[i] == "." + typeName) type = (RenderType)i; + if (RENDER_EXTENSIONS[i] == "." + typeName) + type = (RenderType)i; if (typeName != "sheet" && typeName != "pngs" && type == RENDER_PNGS) { - std::println(stderr, "unknown --type: {}", typeName); - return 2; + std::println(stderr, "unknown --type: {}", typeName); + return 2; } auto fps = std::max(document.model.info.fps, 1); RecorderOptions options{.type = type, - .path = outPath, - .format = path_from_utf8(arguments.get("format").value_or("{}.png")), - .ffmpegPath = ffmpeg_path_get(arguments), - .start = arguments.number_get("start", 0), - .end = arguments.number_get("end", animation->frameNum - 1), - .animationFps = fps, - .fps = arguments.number_get("fps", fps), - .rows = arguments.number_get("rows", 0), - .columns = arguments.number_get("columns", 0)}; + .path = outPath, + .format = path_from_utf8(arguments.get("format").value_or("{}.png")), + .ffmpegPath = ffmpeg_path_get(arguments), + .start = arguments.number_get("start", 0), + .end = arguments.number_get("end", animation->frameNum - 1), + .animationFps = fps, + .fps = arguments.number_get("fps", fps), + .rows = arguments.number_get("rows", 0), + .columns = arguments.number_get("columns", 0)}; auto count = frame_count_get(options.start, options.end, options.animationFps, options.fps); - if (!animation_record(options, canvas, shader, document, *animation, bounds, scale, background, - isRootTransform)) + if (!animation_record(options, canvas, shader, document, *animation, bounds, scale, background, isRootTransform)) { - std::println(stderr, "could not write {} (FFmpeg: {})", *out, path_to_utf8(options.ffmpegPath)); - return 1; + std::println(stderr, "could not write {} (FFmpeg: {})", *out, path_to_utf8(options.ffmpegPath)); + return 1; } std::print("{}: \"{}\", {} frames ({} to {} at {} fps), each {}x{}", *out, animation->name, count, options.start, options.end, options.fps, (int)canvas.size.x, (int)canvas.size.y); if (type == RENDER_SPRITESHEET) { - auto layout = spritesheet_layout_get(options.rows, options.columns, count); - std::print(", {} rows x {} columns, left to right", layout.rows, layout.columns); + auto layout = spritesheet_layout_get(options.rows, options.columns, count); + std::print(", {} rows x {} columns, left to right", layout.rows, layout.columns); } std::println(""); return 0; - } +} - // Saved as the editor saves it: XML (the game's copy, with the editor's embedded) or the editor's JSON. - static int convert_run(const Arguments& arguments) - { +// Saved as the editor saves it: XML (the game's copy, with the editor's embedded) or the editor's JSON. +static int convert_run(const Arguments& arguments) +{ auto format = arguments.get("format").value_or("xml"); if (format != "xml" && format != "json") { - std::println(stderr, "--format must be json or xml"); - return 2; + std::println(stderr, "--format must be json or xml"); + return 2; } // The game's copy bakes what it can't draw with OpenGL (and the document's shaders compile only with it). std::optional gl; - if (format == "xml") gl.emplace(); + if (format == "xml") + gl.emplace(); std::string error; Document document(arguments.file, false, &error); auto fileUtf8 = path_to_utf8(arguments.file); if (!document.is_valid()) { - std::println(stderr, "could not load {}: {}", fileUtf8, error); - return 1; + std::println(stderr, "could not load {}: {}", fileUtf8, error); + return 1; } - if (!error.empty()) std::println(stderr, "{}:\n{}", fileUtf8, error); + if (!error.empty()) + std::println(stderr, "{}:\n{}", fileUtf8, error); auto out = std::filesystem::absolute(arguments.get("out").transform(path_from_utf8).value_or(arguments.file)); Options options = {}; options.isJson = format == "json"; - if (document.save(out, &error, options)) return 0; + if (document.save(out, &error, options)) + return 0; std::println(stderr, "could not write {}: {}", path_to_utf8(out), error); return 1; - } +} - constexpr std::string_view COMMANDS[] = {"info", "frame", "render", "convert"}; +constexpr std::string_view COMMANDS[] = {"info", "frame", "render", "convert"}; - bool is_cli(int argc, const char** argv) - { +bool is_cli(int argc, const char** argv) +{ return argc >= 2 && std::ranges::contains(COMMANDS, std::string_view(argv[1])) && !is_path_exist(argv[1]); - } +} - int cli_run(int argc, const char** argv) - { +int cli_run(int argc, const char** argv) +{ auto arguments = arguments_get(argc, argv); if (!arguments) { - std::print(stderr, "{}", USAGE); - return 2; + std::print(stderr, "{}", USAGE); + return 2; } - if (arguments->command == "info") return info_print(*arguments); - if (arguments->command == "convert") return convert_run(*arguments); + if (arguments->command == "info") + return info_print(*arguments); + if (arguments->command == "convert") + return convert_run(*arguments); return draw_run(*arguments); - } +} diff --git a/src/cli.h b/src/cli.h index df47a6f..99d3704 100644 --- a/src/cli.h +++ b/src/cli.h @@ -3,5 +3,5 @@ // The command-line mode: "anm2ed [options]" looks at a file without the editor, as // text or drawn (by the editor's OpenGL renderer, in a hidden window) to a PNG frame, a contact sheet, PNGs, a GIF or // a video. - bool is_cli(int, const char**); - int cli_run(int, const char**); +bool is_cli(int, const char**); +int cli_run(int, const char**); diff --git a/src/clipboard.cpp b/src/clipboard.cpp index 394024f..7211fa5 100644 --- a/src/clipboard.cpp +++ b/src/clipboard.cpp @@ -3,17 +3,26 @@ #include #include - Clipboard::Clipboard() { set(""); } +Clipboard::Clipboard() +{ + set(""); +} - std::string Clipboard::get() - { +std::string Clipboard::get() +{ auto text = SDL_GetClipboardText(); auto string = std::string(text); SDL_free(text); return string; - } +} - bool Clipboard::is_empty() { return !SDL_HasClipboardText(); } +bool Clipboard::is_empty() +{ + return !SDL_HasClipboardText(); +} - void Clipboard::set(const std::string& string) { SDL_SetClipboardText(string.c_str()); } +void Clipboard::set(const std::string& string) +{ + SDL_SetClipboardText(string.c_str()); +} diff --git a/src/clipboard.h b/src/clipboard.h index 6a946fc..2190134 100644 --- a/src/clipboard.h +++ b/src/clipboard.h @@ -2,11 +2,11 @@ #include - class Clipboard - { - public: +class Clipboard +{ +public: Clipboard(); bool is_empty(); std::string get(); void set(const std::string&); - }; +}; diff --git a/src/dialog.cpp b/src/dialog.cpp index 8d8612c..afbdc3d 100644 --- a/src/dialog.cpp +++ b/src/dialog.cpp @@ -1,12 +1,12 @@ #include "dialog.h" #ifdef _WIN32 - #include +#include #elif __unix__ #else - #include "log.h" - #include "localization.h" - #include "ui/toast.h" +#include "log.h" +#include "localization.h" +#include "ui/toast.h" #endif #include @@ -16,45 +16,47 @@ #include "path.h" - static void callback(void* userData, const char* const* filelist, int filter) - { +static void callback(void* userData, const char* const* filelist, int filter) +{ auto self = (Dialog*)(userData); if (filelist && filelist[0] && strlen(filelist[0]) > 0) { - self->paths.clear(); - for (int i = 0; filelist[i] && strlen(filelist[i]) > 0; ++i) - self->paths.push_back(path_from_utf8(filelist[i])); - self->path = self->paths.empty() ? std::filesystem::path{} : self->paths.front(); - self->selectedFilter = filter; + self->paths.clear(); + for (int i = 0; filelist[i] && strlen(filelist[i]) > 0; ++i) + self->paths.push_back(path_from_utf8(filelist[i])); + self->path = self->paths.empty() ? std::filesystem::path{} : self->paths.front(); + self->selectedFilter = filter; } else { - self->selectedFilter = -1; - self->path.clear(); - self->paths.clear(); + self->selectedFilter = -1; + self->path.clear(); + self->paths.clear(); } - } +} - Dialog::Dialog(SDL_Window* window) - { +Dialog::Dialog(SDL_Window* window) +{ *this = Dialog(); this->window = window; - } +} - void Dialog::file_open(Type type, bool isMany) - { - if (type == Dialog::NONE) return; +void Dialog::file_open(Type type, bool isMany) +{ + if (type == Dialog::NONE) + return; path.clear(); paths.clear(); SDL_ShowOpenFileDialog(callback, this, window, FILTERS[TYPE_FILTERS[type]], std::size(FILTERS[TYPE_FILTERS[type]]), nullptr, isMany); this->type = type; - } +} - void Dialog::file_save(Type type, const std::filesystem::path& defaultPath) - { - if (type == Dialog::NONE) return; +void Dialog::file_save(Type type, const std::filesystem::path& defaultPath) +{ + if (type == Dialog::NONE) + return; path.clear(); paths.clear(); auto defaultPathString = path_to_utf8(defaultPath); @@ -62,57 +64,59 @@ SDL_ShowSaveFileDialog(callback, this, window, FILTERS[TYPE_FILTERS[type]], std::size(FILTERS[TYPE_FILTERS[type]]), defaultPathCStr); this->type = type; - } +} - void Dialog::folder_open(Type type) - { - if (type == Dialog::NONE) return; +void Dialog::folder_open(Type type) +{ + if (type == Dialog::NONE) + return; path.clear(); paths.clear(); SDL_ShowOpenFolderDialog(callback, this, window, nullptr, false); this->type = type; - } +} #ifdef __unix__ - // A string as one single-quoted shell word. - static std::string shell_quote(std::string_view text) - { +// A string as one single-quoted shell word. +static std::string shell_quote(std::string_view text) +{ std::string quoted = "'"; for (auto character : text) - quoted += character == '\'' ? std::string("'\\''") : std::string(1, character); + quoted += character == '\'' ? std::string("'\\''") : std::string(1, character); return quoted + "'"; - } +} - // A file:// URI; everything but unreserved characters and slashes is percent-encoded (commas too, which dbus-send - // would otherwise take as array separators). - static std::string file_uri_get(const std::filesystem::path& path) - { +// A file:// URI. Everything but unreserved characters and slashes is percent-encoded (commas too, which dbus-send +// would otherwise take as array separators). +static std::string file_uri_get(const std::filesystem::path& path) +{ std::string uri = "file://"; for (unsigned char character : path_to_utf8(path)) - if (std::isalnum(character) || std::string_view("-._~/").contains((char)character)) - uri += (char)character; - else - uri += std::format("%{:02X}", character); + if (std::isalnum(character) || std::string_view("-._~/").contains((char)character)) + uri += (char)character; + else + uri += std::format("%{:02X}", character); return uri; - } +} #endif - // Shows a folder in the system's file manager; a file is shown selected in its folder. - void Dialog::file_explorer_open(const std::filesystem::path& path) - { - if (path.empty()) return; +// Shows a folder in the system's file manager. A file is shown selected in its folder. +void Dialog::file_explorer_open(const std::filesystem::path& path) +{ + if (path.empty()) + return; std::error_code ec; auto absolutePath = std::filesystem::absolute(path, ec); auto isFile = std::filesystem::is_regular_file(absolutePath, ec); #ifdef _WIN32 if (isFile) - ShellExecuteW(nullptr, L"open", L"explorer.exe", (L"/select,\"" + absolutePath.native() + L"\"").c_str(), nullptr, - SW_SHOWNORMAL); + ShellExecuteW(nullptr, L"open", L"explorer.exe", (L"/select,\"" + absolutePath.native() + L"\"").c_str(), + nullptr, SW_SHOWNORMAL); else - ShellExecuteW(nullptr, L"open", absolutePath.native().c_str(), nullptr, nullptr, SW_SHOWNORMAL); + ShellExecuteW(nullptr, L"open", absolutePath.native().c_str(), nullptr, nullptr, SW_SHOWNORMAL); #elif __unix__ // File managers that implement org.freedesktop.FileManager1 (Nautilus, Dolphin, Nemo, Caja, Thunar...) select the - // file; anything else opens its folder. + // file. Anything else opens its folder. auto folder = shell_quote(path_to_utf8(isFile ? absolutePath.parent_path() : absolutePath)); auto command = isFile ? std::format("(dbus-send --session --print-reply --dest=org.freedesktop.FileManager1 " "--type=method_call /org/freedesktop/FileManager1 " @@ -124,9 +128,14 @@ #else toast_log(Level::WARNING, TOAST_NOT_SUPPORTED); #endif - } +} - void Dialog::reset() { *this = Dialog(this->window); } - - bool Dialog::is_selected(Type type) const { return this->type == type && !paths.empty(); } +void Dialog::reset() +{ + *this = Dialog(this->window); +} +bool Dialog::is_selected(Type type) const +{ + return this->type == type && !paths.empty(); +} diff --git a/src/dialog.h b/src/dialog.h index a210fb7..9e25a62 100644 --- a/src/dialog.h +++ b/src/dialog.h @@ -5,32 +5,32 @@ #include - class Dialog - { - public: +class Dialog +{ +public: #if defined(_WIN32) - #define EXECUTABLE_FILTER {"Executable", "exe"} +#define EXECUTABLE_FILTER {"Executable", "exe"} #else - #define EXECUTABLE_FILTER {"Executable", "*"} +#define EXECUTABLE_FILTER {"Executable", "*"} #endif #define FILTER_LIST \ - X(NO_FILTER, {}) \ - X(ANM2, {"Anm2 file", "anm2;xml"}) \ - X(PNG, {"PNG image", "png;PNG"}) \ - X(SPRITESHEET, {"PNG or SVG image", "png;PNG;svg;SVG"}) \ - X(SHADER, {"Shader file", "fs;vs;FS;VS"}) \ - X(SOUND, {"WAV file;OGG file", "wav;ogg"}) \ - X(GIF, {"GIF image", "gif"}) \ - X(WEBM, {"WebM video", "webm"}) \ - X(OGV, {"OGV video", "ogv"}) \ - X(MP4, {"MP4 video", "MP4"}) \ - X(EXECUTABLE, EXECUTABLE_FILTER) + X(NO_FILTER, {}) \ + X(ANM2, {"Anm2 file", "anm2;xml"}) \ + X(PNG, {"PNG image", "png;PNG"}) \ + X(SPRITESHEET, {"PNG or SVG image", "png;PNG;svg;SVG"}) \ + X(SHADER, {"Shader file", "fs;vs;FS;VS"}) \ + X(SOUND, {"WAV file;OGG file", "wav;ogg"}) \ + X(GIF, {"GIF image", "gif"}) \ + X(WEBM, {"WebM video", "webm"}) \ + X(OGV, {"OGV video", "ogv"}) \ + X(MP4, {"MP4 video", "MP4"}) \ + X(EXECUTABLE, EXECUTABLE_FILTER) enum Filter { #define X(symbol, ...) symbol, - FILTER_LIST + FILTER_LIST #undef X }; @@ -43,31 +43,31 @@ #undef FILTER_LIST #define DIALOG_LIST \ - X(NONE, NO_FILTER) \ - X(ANM2_CREATE, ANM2) \ - X(ANM2_OPEN, ANM2) \ - X(ANM2_SAVE, ANM2) \ - X(SOUND_OPEN, SOUND) \ - X(LIBRARY_OPEN, ANM2) \ - X(SOUND_REPLACE, SOUND) \ - X(SPRITESHEET_OPEN, SPRITESHEET) \ - X(SPRITESHEET_REPLACE, SPRITESHEET) \ - X(SPRITESHEET_PATH_SET, PNG) \ - X(SHADER_FRAGMENT_PATH_SET, SHADER) \ - X(SHADER_VERTEX_PATH_SET, SHADER) \ - X(FFMPEG_PATH_SET, EXECUTABLE) \ - X(PNG_DIRECTORY_SET, NO_FILTER) \ - X(PNG_PATH_SET, PNG) \ - X(REGION_EXPORT_PATH_SET, PNG) \ - X(GIF_PATH_SET, GIF) \ - X(WEBM_PATH_SET, WEBM) \ - X(OGV_PATH_SET, OGV) \ - X(MP4_PATH_SET, MP4) + X(NONE, NO_FILTER) \ + X(ANM2_CREATE, ANM2) \ + X(ANM2_OPEN, ANM2) \ + X(ANM2_SAVE, ANM2) \ + X(SOUND_OPEN, SOUND) \ + X(LIBRARY_OPEN, ANM2) \ + X(SOUND_REPLACE, SOUND) \ + X(SPRITESHEET_OPEN, SPRITESHEET) \ + X(SPRITESHEET_REPLACE, SPRITESHEET) \ + X(SPRITESHEET_PATH_SET, PNG) \ + X(SHADER_FRAGMENT_PATH_SET, SHADER) \ + X(SHADER_VERTEX_PATH_SET, SHADER) \ + X(FFMPEG_PATH_SET, EXECUTABLE) \ + X(PNG_DIRECTORY_SET, NO_FILTER) \ + X(PNG_PATH_SET, PNG) \ + X(REGION_EXPORT_PATH_SET, PNG) \ + X(GIF_PATH_SET, GIF) \ + X(WEBM_PATH_SET, WEBM) \ + X(OGV_PATH_SET, OGV) \ + X(MP4_PATH_SET, MP4) enum Type { #define X(symbol, filter) symbol, - DIALOG_LIST + DIALOG_LIST #undef X }; @@ -93,4 +93,4 @@ bool is_selected(Type type) const; void reset(); void file_explorer_open(const std::filesystem::path&); - }; +}; diff --git a/src/document.cpp b/src/document.cpp index 4b832ff..40d1c0c 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -30,166 +30,175 @@ using namespace glm; - constexpr std::string_view BAKED_EXTENSION = ".baked.png"; - constexpr std::string_view AUTOSAVE_EXTENSION = ".autosave"; - constexpr int VECTOR_LEVEL_MAX = 3; - constexpr int VECTOR_SIZE_MAX = 8192; - constexpr std::uint64_t HASH_COMBINE_CONSTANT = 0x9e3779b97f4a7c15ULL; +constexpr std::string_view BAKED_EXTENSION = ".baked.png"; +constexpr std::string_view AUTOSAVE_EXTENSION = ".autosave"; +constexpr int VECTOR_LEVEL_MAX = 3; +constexpr int VECTOR_SIZE_MAX = 8192; +constexpr std::uint64_t HASH_COMBINE_CONSTANT = 0x9e3779b97f4a7c15ULL; - // A path written in a document in `directory`, as an absolute path. - static std::filesystem::path absolute_path_get(const std::filesystem::path& directory, const std::filesystem::path& path) - { +// A path written in a document in `directory`, as an absolute path. +static std::filesystem::path absolute_path_get(const std::filesystem::path& directory, + const std::filesystem::path& path) +{ WorkingDirectory workingDirectory(directory); std::error_code ec; auto absolutePath = std::filesystem::weakly_canonical(directory / path_case_insensitive_find(path), ec); return ec ? directory / path : absolutePath; - } +} - static void library_load(const std::filesystem::path& path, LibraryData& library) - { +static void library_load(const std::filesystem::path& path, LibraryData& library) +{ library = {}; std::string errorString; model_load(library.model, path, &errorString); // Why it couldn't load, or what a JSON library couldn't read. - if (!errorString.empty()) toast_log(Level::WARNING, TOAST_LIBRARY_ISSUES, path_to_utf8(path), errorString); + if (!errorString.empty()) + toast_log(Level::WARNING, TOAST_LIBRARY_ISSUES, path_to_utf8(path), errorString); std::error_code ec; library.writeTime = std::filesystem::last_write_time(path, ec); WorkingDirectory workingDirectory(path.parent_path()); for (auto& spritesheet : library.model.content.spritesheets) - library.images.emplace(spritesheet.id, Image(path_case_insensitive_find(spritesheet.path))); + library.images.emplace(spritesheet.id, Image(path_case_insensitive_find(spritesheet.path))); for (auto& sound : library.model.content.sounds) - library.sounds.emplace(sound.id, AudioData(path_case_insensitive_find(sound.path))); - } + library.sounds.emplace(sound.id, AudioData(path_case_insensitive_find(sound.path))); +} - static uint64_t document_tab_id_next() - { +static uint64_t document_tab_id_next() +{ static uint64_t next = 1; return next++; - } +} - static std::filesystem::path shader_absolute_path_get(Document& document, const std::filesystem::path& path) - { +static std::filesystem::path shader_absolute_path_get(Document& document, const std::filesystem::path& path) +{ auto loadPath = path_backslash_handle(path); - if (loadPath.empty() || loadPath.is_absolute()) return loadPath; + if (loadPath.empty() || loadPath.is_absolute()) + return loadPath; return document.directory_get() / loadPath; - } +} - static void shader_status_append(const ShaderCompileResult& result, std::string* status) - { - if (!status) return; +static void shader_status_append(const ShaderCompileResult& result, std::string* status) +{ + if (!status) + return; *status += localize.get(result.isCompiled ? LABEL_SHADER_COMPILE_SUCCEEDED : LABEL_SHADER_COMPILE_FAILED); *status += "\n"; if (result.isCompiled) { - *status += localize.get(result.isLinked ? LABEL_SHADER_LINK_SUCCEEDED : LABEL_SHADER_LINK_FAILED); - *status += "\n"; + *status += localize.get(result.isLinked ? LABEL_SHADER_LINK_SUCCEEDED : LABEL_SHADER_LINK_FAILED); + *status += "\n"; } - if (!result.output.empty()) *status += result.output; - } + if (!result.output.empty()) + *status += result.output; +} - static std::string shader_source_lines_get(std::string_view label, std::string_view source) - { +static std::string shader_source_lines_get(std::string_view label, std::string_view source) +{ std::string output = std::format("\n{}:\n", label); int lineNumber = 1; std::size_t position = 0; while (position <= source.size()) { - auto end = source.find('\n', position); - auto isEnd = end == std::string_view::npos; - output += std::format("{:4}: {}\n", lineNumber++, - source.substr(position, isEnd ? std::string_view::npos : end - position)); - if (isEnd) break; - position = end + 1; + auto end = source.find('\n', position); + auto isEnd = end == std::string_view::npos; + output += std::format("{:4}: {}\n", lineNumber++, + source.substr(position, isEnd ? std::string_view::npos : end - position)); + if (isEnd) + break; + position = end + 1; } return output; - } +} - static void shader_status_format_append(std::string* status, StringType format, StringType argument) - { - if (!status) return; +static void shader_status_format_append(std::string* status, StringType format, StringType argument) +{ + if (!status) + return; auto argumentString = std::string(localize.get(argument)); *status += std::vformat(localize.get(format), std::make_format_args(argumentString)) + "\n"; - } +} - static bool shader_source_load(Document& document, const std::filesystem::path& shaderPath, std::string& source, - StringType label, std::string* status, const char* fallback = nullptr) - { +static bool shader_source_load(Document& document, const std::filesystem::path& shaderPath, std::string& source, + StringType label, std::string* status, const char* fallback = nullptr) +{ if (shaderPath.empty() && !fallback) { - shader_status_format_append(status, LABEL_SHADER_PATH_EMPTY, label); - return false; + shader_status_format_append(status, LABEL_SHADER_PATH_EMPTY, label); + return false; } if (shaderPath.empty()) { - source = fallback; - return true; + source = fallback; + return true; } auto absolute = path_case_insensitive_find(shader_absolute_path_get(document, shaderPath)); - if (file_text_load(absolute, &source)) return true; + if (file_text_load(absolute, &source)) + return true; if (status) { - auto pathString = path_to_utf8(shaderPath); - *status += std::vformat(localize.get(LABEL_SHADER_READ_FAILED), std::make_format_args(pathString)) + "\n"; + auto pathString = path_to_utf8(shaderPath); + *status += std::vformat(localize.get(LABEL_SHADER_READ_FAILED), std::make_format_args(pathString)) + "\n"; } return false; - } +} - // Loads assets for elements that are new or whose path changed, and forgets those of removed elements. - template - void resources_sync(Document& document, const Items& items, std::map& keys, - std::unordered_map& paths, Load&& load) - { +// Loads assets for elements that are new or whose path changed, and forgets those of removed elements. +template +void resources_sync(Document& document, const Items& items, std::map& keys, + std::unordered_map& paths, Load&& load) +{ std::set validIds; WorkingDirectory workingDirectory(document.directory_get()); for (auto& element : items) { - validIds.insert(element.id); - auto path = paths.find(element.id); - if (!keys.contains(element.id) || path == paths.end() || path->second != element.path) - { - load(element.id, path_case_insensitive_find(element.path)); - paths[element.id] = element.path; - } + validIds.insert(element.id); + auto path = paths.find(element.id); + if (!keys.contains(element.id) || path == paths.end() || path->second != element.path) + { + load(element.id, path_case_insensitive_find(element.path)); + paths[element.id] = element.path; + } } std::erase_if(keys, [&](const auto& pair) { return !validIds.contains(pair.first); }); std::erase_if(paths, [&](const auto& pair) { return !validIds.contains(pair.first); }); - } +} - // A spritesheet is dirty when its path or image asset differs from what was last saved. - static uint64_t spritesheet_hash_get(const Spritesheet& spritesheet, std::uint64_t imageKey) - { +// A spritesheet is dirty when its path or image asset differs from what was last saved. +static uint64_t spritesheet_hash_get(const Spritesheet& spritesheet, std::uint64_t imageKey) +{ auto seed = std::hash{}(path_to_utf8(spritesheet.path)); return seed ^ (imageKey + HASH_COMBINE_CONSTANT + (seed << 6) + (seed >> 2)); - } +} - static Reference item_reference_get(Reference reference) - { +static Reference item_reference_get(Reference reference) +{ reference.frameIndex = -1; return reference; - } +} - static void frame_time_sync(Document& document) - { +static void frame_time_sync(Document& document) +{ auto reference = document.reference_get(); auto item = document.model.track_get(reference); auto frameIndex = reference.frameIndex; document.frameTime = item && frameIndex >= 0 ? frame_time_from_index_get(*item, frameIndex) : 0.0f; - } +} - Document::Document(const std::filesystem::path& path, bool isNew, std::string* errorString) - { +Document::Document(const std::filesystem::path& path, bool isNew, std::string* errorString) +{ tabId = document_tab_id_next(); model = model_make(); - if (!isNew) model_load(model, path, errorString); + if (!isNew) + model_load(model, path, errorString); if (isNew ? !save(path, errorString) : !model.isValid) { - isValid = false; - this->path.clear(); - return; + isValid = false; + this->path.clear(); + return; } this->path = path; @@ -197,156 +206,161 @@ using namespace glm; model.uids_repair(); clean(); change(); - } +} - Document::Document(Document&& other) noexcept : DocumentData(std::move(other)), editTarget(other.editTarget) {} +Document::Document(Document&& other) noexcept : DocumentData(std::move(other)), editTarget(other.editTarget) +{} - Document& Document::operator=(Document&& other) noexcept - { - if (this != &other) this->~Document(); +Document& Document::operator=(Document&& other) noexcept +{ + if (this != &other) + this->~Document(); new (this) Document(std::move(other)); return *this; - } +} - bool Document::save(const std::filesystem::path& path, std::string* errorString, Options options) - { +bool Document::save(const std::filesystem::path& path, std::string* errorString, Options options) +{ auto absolutePath = !path.empty() ? path : this->path; auto absolutePathUtf8 = path_to_utf8(absolutePath); if (file_write(absolutePath, errorString, options)) { - this->path = absolutePath; - toast_log(Level::INFO, TOAST_SAVE_DOCUMENT, absolutePathUtf8); - clean(); - return true; + this->path = absolutePath; + toast_log(Level::INFO, TOAST_SAVE_DOCUMENT, absolutePathUtf8); + clean(); + return true; } - if (errorString) toast_log(Level::ERROR, TOAST_SAVE_DOCUMENT_FAILED, absolutePathUtf8, *errorString); + if (errorString) + toast_log(Level::ERROR, TOAST_SAVE_DOCUMENT_FAILED, absolutePathUtf8, *errorString); return false; - } +} - // A library's spritesheet path, made relative to this document (for flattening its animation layers). - SpritesheetPathGet Document::spritesheet_path_resolver_get() const - { - return [this](const Model& source, const std::filesystem::path& spritesheetPath) - { - for (auto& [libraryPath, library] : libraries) - if (&library.model == &source) - return path_backslash_replace( - path_make_relative(absolute_path_get(libraryPath.parent_path(), spritesheetPath), - std::filesystem::absolute(directory_get()))); - return spritesheetPath; +// A library's spritesheet path, made relative to this document (for flattening its animation layers). +SpritesheetPathGet Document::spritesheet_path_resolver_get() const +{ + return [this](const Model& source, const std::filesystem::path& spritesheetPath) { + for (auto& [libraryPath, library] : libraries) + if (&library.model == &source) + return path_backslash_replace( + path_make_relative(absolute_path_get(libraryPath.parent_path(), spritesheetPath), + std::filesystem::absolute(directory_get()))); + return spritesheetPath; }; - } +} - // Writes the document; the game's copy has its animation layers flattened into plain layers, and what else the game - // can't show worked around. - bool Document::file_write(const std::filesystem::path& path, std::string* errorString, Options options) - { +// Writes the document. The game's copy has its animation layers flattened into plain layers, and what else the game +// can't show worked around. +bool Document::file_write(const std::filesystem::path& path, std::string* errorString, Options options) +{ std::optional game; if (!options.isJson) { - game = animation_layers_flatten(model, library_resolver_get(), spritesheet_path_resolver_get()); - if (!model.info.isIsaacIgnored) - { - auto bakedPath = path; - if (options.isPixelBaked) - frames_bake(*this, *game, bakedPath.replace_extension(BAKED_EXTENSION)); - game = isaac_bridge(std::move(*game)); - } + game = animation_layers_flatten(model, library_resolver_get(), spritesheet_path_resolver_get()); + if (!model.info.isIsaacIgnored) + { + auto bakedPath = path; + if (options.isPixelBaked) + frames_bake(*this, *game, bakedPath.replace_extension(BAKED_EXTENSION)); + game = isaac_bridge(std::move(*game)); + } } options.gameModel = game ? &*game : nullptr; return model_save(model, path, errorString, options); - } +} - std::filesystem::path Document::autosave_path_get() - { - return directory_get() / - path_from_utf8("." + path_to_utf8(filename_get()) + std::string(AUTOSAVE_EXTENSION)); - } +std::filesystem::path Document::autosave_path_get() +{ + return directory_get() / path_from_utf8("." + path_to_utf8(filename_get()) + std::string(AUTOSAVE_EXTENSION)); +} - std::filesystem::path Document::path_from_autosave_get(const std::filesystem::path& path) - { +std::filesystem::path Document::path_from_autosave_get(const std::filesystem::path& path) +{ auto fileName = path_to_utf8(path.filename()); - if (fileName.starts_with('.')) fileName.erase(fileName.begin()); + if (fileName.starts_with('.')) + fileName.erase(fileName.begin()); if (fileName.ends_with(AUTOSAVE_EXTENSION)) - fileName.erase(fileName.size() - AUTOSAVE_EXTENSION.size()); + fileName.erase(fileName.size() - AUTOSAVE_EXTENSION.size()); return path.parent_path() / std::filesystem::path(std::u8string(fileName.begin(), fileName.end())); - } +} - bool Document::autosave(std::string* errorString, Options options) - { +bool Document::autosave(std::string* errorString, Options options) +{ auto autosavePath = autosave_path_get(); auto autosavePathUtf8 = path_to_utf8(autosavePath); // An autosave is read back from the editor's copy, so the game's needs no baked spritesheet. options.isPixelBaked = false; if (file_write(autosavePath, errorString, options)) { - for (auto id : spritesheets_autosave_dirty_get()) - { - auto spritesheet = item_get(model.content.spritesheets, id); - auto texture = texture_get(id); - if (texture && texture->write(spritesheet_autosave_path_get(*spritesheet))) - spritesheetAutosaveHashes[id] = spritesheetHashes.at(id); - } - autosaveHash = hash; - lastAutosaveTime = 0.0f; - toast_log(Level::INFO, TOAST_AUTOSAVING); - logger.info(std::format("Autosaved document to: {}", autosavePathUtf8)); - return true; + for (auto id : spritesheets_autosave_dirty_get()) + { + auto spritesheet = item_get(model.content.spritesheets, id); + auto texture = texture_get(id); + if (texture && texture->write(spritesheet_autosave_path_get(*spritesheet))) + spritesheetAutosaveHashes[id] = spritesheetHashes.at(id); + } + autosaveHash = hash; + lastAutosaveTime = 0.0f; + toast_log(Level::INFO, TOAST_AUTOSAVING); + logger.info(std::format("Autosaved document to: {}", autosavePathUtf8)); + return true; } - if (errorString) toast_log(Level::ERROR, TOAST_AUTOSAVE_FAILED, autosavePathUtf8, *errorString); + if (errorString) + toast_log(Level::ERROR, TOAST_AUTOSAVE_FAILED, autosavePathUtf8, *errorString); return false; - } +} - void Document::texture_change(int id) - { - if (texture_get(id) && item_get(model.content.spritesheets, id)) change(); - } +void Document::texture_change(int id) +{ + if (texture_get(id) && item_get(model.content.spritesheets, id)) + change(); +} - bool Document::texture_reload(int id) - { +bool Document::texture_reload(int id) +{ auto spritesheet = item_get(model.content.spritesheets, id); - if (!spritesheet) return false; + if (!spritesheet) + return false; WorkingDirectory workingDirectory(directory_get()); texture_set(id, Image(path_case_insensitive_find(spritesheet->path))); texturePaths[id] = spritesheet->path; return true; - } +} - bool Document::sound_reload(int id) - { +bool Document::sound_reload(int id) +{ auto sound = item_get(model.content.sounds, id); - if (!sound) return false; + if (!sound) + return false; WorkingDirectory workingDirectory(directory_get()); sound_set(id, AudioData(path_case_insensitive_find(sound->path))); soundPaths[id] = sound->path; return true; - } +} - bool Document::shader_reload(int shaderId, std::string* status) - { - auto shader_erase = [&]() - { - shaders.erase(shaderId); - shaderVertexPaths.erase(shaderId); - shaderFragmentPaths.erase(shaderId); - return false; +bool Document::shader_reload(int shaderId, std::string* status) +{ + auto shader_erase = [&]() { + shaders.erase(shaderId); + shaderVertexPaths.erase(shaderId); + shaderFragmentPaths.erase(shaderId); + return false; }; // Without an OpenGL context (as the command line converts), there is nothing to compile it with. auto shaderElement = SDL_GL_GetCurrentContext() ? item_get(model.content.shaders, shaderId) : nullptr; if (!shaderElement) { - shader_status_format_append(status, LABEL_SHADER_PATH_EMPTY, LABEL_FRAGMENT); - return shader_erase(); + shader_status_format_append(status, LABEL_SHADER_PATH_EMPTY, LABEL_FRAGMENT); + return shader_erase(); } std::string vertexSource; std::string fragmentSource; auto isVertexLoaded = shader_source_load(*this, shaderElement->vertex, vertexSource, LABEL_VERTEX, status, - TEXTURE_COMPATIBILITY_VERTEX); - auto isFragmentLoaded = - shader_source_load(*this, shaderElement->fragment, fragmentSource, LABEL_FRAGMENT, status); - if (!isVertexLoaded || !isFragmentLoaded) return shader_erase(); + TEXTURE_COMPATIBILITY_VERTEX); + auto isFragmentLoaded = shader_source_load(*this, shaderElement->fragment, fragmentSource, LABEL_FRAGMENT, status); + if (!isVertexLoaded || !isFragmentLoaded) + return shader_erase(); auto vertex = gles_vertex_convert(vertexSource); auto fragment = gles_fragment_convert(fragmentSource); @@ -354,54 +368,56 @@ using namespace glm; shader_status_append(result, status); if (status && (!result.isCompiled || !result.isLinked)) { - *status += shader_source_lines_get("Converted vertex shader", vertex); - *status += shader_source_lines_get("Converted fragment shader", fragment); + *status += shader_source_lines_get("Converted vertex shader", vertex); + *status += shader_source_lines_get("Converted fragment shader", fragment); } - if (!result.isLinked || !result.id) return shader_erase(); + if (!result.isLinked || !result.id) + return shader_erase(); ShaderProgram runtime = {}; runtime.id = result.id; runtime.uniforms = std::move(result.uniforms); - if (uniform_configs_trim(*shaderElement, runtime.uniforms)) hash_set(); + if (uniform_configs_trim(*shaderElement, runtime.uniforms)) + hash_set(); uniform_configs_apply(*shaderElement, runtime.uniforms); shaders[shaderId] = std::move(runtime); shaderVertexPaths[shaderId] = shaderElement->vertex; shaderFragmentPaths[shaderId] = shaderElement->fragment; return true; - } +} - void Document::assets_sync() - { +void Document::assets_sync() +{ libraries_sync(); resources_sync(*this, model.content.spritesheets, textures, texturePaths, - [&](int id, const std::filesystem::path& path) - { texture_set(id, Image(path)); }); + [&](int id, const std::filesystem::path& path) { texture_set(id, Image(path)); }); resources_sync(*this, model.content.sounds, sounds, soundPaths, - [&](int id, const std::filesystem::path& path) - { sound_set(id, AudioData(path)); }); + [&](int id, const std::filesystem::path& path) { sound_set(id, AudioData(path)); }); std::set validShaderIds; WorkingDirectory workingDirectory(directory_get()); for (auto& shaderElement : model.content.shaders) { - auto id = shaderElement.id; - validShaderIds.insert(id); - auto isReload = !shaders.contains(id) || !shaderVertexPaths.contains(id) || !shaderFragmentPaths.contains(id) || - shaderVertexPaths.at(id) != shaderElement.vertex || - shaderFragmentPaths.at(id) != shaderElement.fragment; - if (shaderElement.fragment.empty()) - { - shaders.erase(id); - shaderVertexPaths.erase(id); - shaderFragmentPaths.erase(id); - } - else if (isReload) - shader_reload(id); - else if (auto shader = shader_get(id)) - uniform_configs_apply(shaderElement, shader->uniforms); + auto id = shaderElement.id; + validShaderIds.insert(id); + auto isReload = !shaders.contains(id) || !shaderVertexPaths.contains(id) || !shaderFragmentPaths.contains(id) || + shaderVertexPaths.at(id) != shaderElement.vertex || + shaderFragmentPaths.at(id) != shaderElement.fragment; + if (shaderElement.fragment.empty()) + { + shaders.erase(id); + shaderVertexPaths.erase(id); + shaderFragmentPaths.erase(id); + } + else if (isReload) + shader_reload(id); + else if (auto shader = shader_get(id)) + uniform_configs_apply(shaderElement, shader->uniforms); } - auto is_invalid = [&](const auto& pair) { return !validShaderIds.contains(pair.first); }; + auto is_invalid = [&](const auto& pair) { + return !validShaderIds.contains(pair.first); + }; std::erase_if(shaders, is_invalid); std::erase_if(shaderVertexPaths, is_invalid); std::erase_if(shaderFragmentPaths, is_invalid); @@ -409,798 +425,884 @@ using namespace glm; // Vector images drawn from spritesheet images no longer in use are dropped. std::set imageUids; for (auto& spritesheet : model.content.spritesheets) - if (auto image = texture_get(spritesheet.id)) imageUids.insert(image->uid); + if (auto image = texture_get(spritesheet.id)) + imageUids.insert(image->uid); for (auto& [path, library] : libraries) - for (auto& [id, image] : library.images) - imageUids.insert(image.uid); + for (auto& [id, image] : library.images) + imageUids.insert(image.uid); std::erase_if(vectorImages, [&](const auto& pair) { return !imageUids.contains(pair.first.first); }); - } +} - std::filesystem::path Document::library_path_get(int id) const - { +std::filesystem::path Document::library_path_get(int id) const +{ auto library = item_get(model.content.libraries, id); return library ? absolute_path_get(std::filesystem::absolute(directory_get()), library->path) : std::filesystem::path{}; - } +} - // A library of this document (or of a copy of it) or of one of its libraries. - const LibraryData* Document::library_get(const Model& from, int id) const - { +// A library of this document (or of a copy of it) or of one of its libraries. +const LibraryData* Document::library_get(const Model& from, int id) const +{ auto isLibrary = std::ranges::any_of(libraries, [&](const auto& pair) { return &pair.second.model == &from; }); auto link = libraryLinks.find({isLibrary ? &from : nullptr, id}); return link == libraryLinks.end() ? nullptr : link->second; - } +} - LibraryGet Document::library_resolver_get() const - { - return [this](const Model& from, int id) - { - auto library = library_get(from, id); - return library ? &library->model : nullptr; +LibraryGet Document::library_resolver_get() const +{ + return [this](const Model& from, int id) { + auto library = library_get(from, id); + return library ? &library->model : nullptr; }; - } +} - // An animation layer whose animation isn't there; a library that didn't load leaves the question open (false). - bool Document::is_layer_animation_missing(const Layer& layer) const - { - if (!layer.is_animation()) return false; +// An animation layer whose animation isn't there. A library that didn't load leaves the question open (false). +bool Document::is_layer_animation_missing(const Layer& layer) const +{ + if (!layer.is_animation()) + return false; auto library = layer.libraryId == -1 ? nullptr : library_get(model, layer.libraryId); auto source = layer.libraryId == -1 ? &model : library && library->model.isValid ? &library->model : nullptr; return source && !source->animation_named_get(layer.animation); - } +} - // The animation names of library `libraryId`, or of this document at -1. - std::vector Document::animation_names_get(int libraryId) const - { +// The animation names of library `libraryId`, or of this document at -1. +std::vector Document::animation_names_get(int libraryId) const +{ auto library = libraryId == -1 ? nullptr : library_get(model, libraryId); auto source = libraryId == -1 ? &model : library ? &library->model : nullptr; std::vector names; if (source) - for (auto [index, animation] : source->animations_get()) - names.push_back(animation->name); + for (auto [index, animation] : source->animations_get()) + names.push_back(animation->name); return names; - } +} - // A layer draw's spritesheet image, at `scale` (see vector_image_get). - const Image* Document::draw_image_get(const Draw& draw, float scale) const - { +// A layer draw's spritesheet image, at `scale` (see vector_image_get). +const Image* Document::draw_image_get(const Draw& draw, float scale) const +{ const Image* image = nullptr; - if (!draw.source || draw.source == &model) image = texture_get(draw.spritesheetId); + if (!draw.source || draw.source == &model) + image = texture_get(draw.spritesheetId); for (auto& [path, library] : libraries) - if (&library.model == draw.source) - if (auto found = library.images.find(draw.spritesheetId); found != library.images.end()) image = &found->second; + if (&library.model == draw.source) + if (auto found = library.images.find(draw.spritesheetId); found != library.images.end()) + image = &found->second; return vector_image_get(image, scale); - } +} - // A vector image drawn again (cached) for when `scale` screen pixels show each of its pixels; others as they are. - const Image* Document::vector_image_get(const Image* image, float scale) const - { - if (!image || !image->is_vector() || scale <= 1.0f) return image; +// A vector image drawn again (cached) for when `scale` screen pixels show each of its pixels. Others as they are. +const Image* Document::vector_image_get(const Image* image, float scale) const +{ + if (!image || !image->is_vector() || scale <= 1.0f) + return image; auto level = std::min((int)std::ceil(std::log2(scale)), VECTOR_LEVEL_MAX); while (level > 0 && std::max(image->size.x, image->size.y) << level > VECTOR_SIZE_MAX) - --level; - if (level == 0) return image; + --level; + if (level == 0) + return image; auto [it, isNew] = vectorImages.try_emplace({image->uid, level}); - if (isNew) it->second = image->vector_render(image->scale * (float)(1 << level)); + if (isNew) + it->second = image->vector_render(image->scale * (float)(1 << level)); return &it->second; - } +} - // Loads every library this document reaches (libraries' own libraries too) and forgets the ones it no longer does. - void Document::libraries_sync() - { +// Loads every library this document reaches (libraries' own libraries too) and forgets the ones it no longer does. +void Document::libraries_sync() +{ libraryLinks.clear(); std::set reached; std::vector> pending{ {&model, std::filesystem::absolute(directory_get())}}; while (!pending.empty()) { - auto [from, directory] = pending.back(); - pending.pop_back(); - for (auto& library : from->content.libraries) - { - auto path = absolute_path_get(directory, library.path); - auto [it, isNew] = libraries.try_emplace(path); - if (isNew) + auto [from, directory] = pending.back(); + pending.pop_back(); + for (auto& library : from->content.libraries) { - library_load(path, it->second); - ++librariesRevision; + auto path = absolute_path_get(directory, library.path); + auto [it, isNew] = libraries.try_emplace(path); + if (isNew) + { + library_load(path, it->second); + ++librariesRevision; + } + libraryLinks[{from == &model ? nullptr : from, library.id}] = &it->second; + if (reached.insert(path).second) + pending.emplace_back(&it->second.model, path.parent_path()); } - libraryLinks[{from == &model ? nullptr : from, library.id}] = &it->second; - if (reached.insert(path).second) pending.emplace_back(&it->second.model, path.parent_path()); - } } std::erase_if(libraries, [&](const auto& pair) { return !reached.contains(pair.first); }); - } +} - // Reloads the libraries whose file changed on disk; true when any did. - bool Document::libraries_reload() - { +// Reloads the libraries whose file changed on disk. True when any did. +bool Document::libraries_reload() +{ bool isReloaded = false; for (auto& [path, library] : libraries) { - std::error_code ec; - auto time = std::filesystem::last_write_time(path, ec); - if (ec || time == library.writeTime) continue; - library_load(path, library); - ++librariesRevision; - isReloaded = true; + std::error_code ec; + auto time = std::filesystem::last_write_time(path, ec); + if (ec || time == library.writeTime) + continue; + library_load(path, library); + ++librariesRevision; + isReloaded = true; } - if (isReloaded) assets_sync(); + if (isReloaded) + assets_sync(); return isReloaded; - } +} - void Document::library_reload(int id) - { +void Document::library_reload(int id) +{ libraries.erase(library_path_get(id)); libraries_sync(); - } +} - const Image* Document::texture_get(int id) const - { - if (auto draft = textureDrafts.find(id); draft != textureDrafts.end()) return &draft->second; +const Image* Document::texture_get(int id) const +{ + if (auto draft = textureDrafts.find(id); draft != textureDrafts.end()) + return &draft->second; auto key = textures.find(id); return key == textures.end() ? nullptr : assets.image_get(key->second); - } +} - // A private copy of the spritesheet's image to draw on; it becomes a new asset on the next change(). - Image* Document::texture_edit(int id) - { +// A private copy of the spritesheet's image to draw on. It becomes a new asset on the next change(). +Image* Document::texture_edit(int id) +{ auto texture = texture_get(id); - if (!texture || texture->is_vector()) return nullptr; + if (!texture || texture->is_vector()) + return nullptr; return &textureDrafts.try_emplace(id, *texture).first->second; - } +} - void Document::texture_set(int id, Image image) - { +void Document::texture_set(int id, Image image) +{ textureDrafts.erase(id); textures[id] = assets.image_add(std::move(image)); - } +} - const AudioData* Document::sound_get(int id) const - { +const AudioData* Document::sound_get(int id) const +{ auto key = sounds.find(id); return key == sounds.end() ? nullptr : assets.audio_get(key->second); - } +} - // Every sound that may be playing: this document's and its libraries'. - std::vector Document::sounds_get() const - { +// Every sound that may be playing: this document's and its libraries'. +std::vector Document::sounds_get() const +{ std::vector result; for (auto& [id, key] : sounds) - if (auto sound = sound_get(id)) result.push_back(sound); + if (auto sound = sound_get(id)) + result.push_back(sound); for (auto& [path, library] : libraries) - for (auto& [id, sound] : library.sounds) - result.push_back(&sound); + for (auto& [id, sound] : library.sounds) + result.push_back(&sound); return result; - } +} - // The sounds triggers play on an animation's frame, its children's included: one of each trigger's sounds, at random - // (or picked by `index` for repeatable renders). - std::vector Document::trigger_sounds_get(const Animation& animation, int time, - int index) const - { +// The sounds triggers play on an animation's frame, its children's included: one of each trigger's sounds, at random +// (or picked by `index` for repeatable renders). +std::vector Document::trigger_sounds_get(const Animation& animation, int time, int index) const +{ std::vector result; - for (auto& [source, trigger, layerId] : - animation_triggers_get(model, animation, time, library_resolver_get())) + for (auto& [source, trigger, layerId] : animation_triggers_get(model, animation, time, library_resolver_get())) { - if (trigger.soundIds.empty()) continue; - auto count = trigger.soundIds.size(); - auto soundIndex = std::min( - index >= 0 ? (std::size_t)index % count : (std::size_t)random_in_range(0.0f, (float)count), count - 1); - auto soundId = trigger.soundIds[soundIndex]; - const AudioData* sound = nullptr; - if (source == &model) sound = sound_get(soundId); - for (auto& [path, library] : libraries) - if (&library.model == source) - if (auto found = library.sounds.find(soundId); found != library.sounds.end()) sound = &found->second; - if (sound) result.push_back(sound); + if (trigger.soundIds.empty()) + continue; + auto count = trigger.soundIds.size(); + auto soundIndex = std::min( + index >= 0 ? (std::size_t)index % count : (std::size_t)random_in_range(0.0f, (float)count), count - 1); + auto soundId = trigger.soundIds[soundIndex]; + const AudioData* sound = nullptr; + if (source == &model) + sound = sound_get(soundId); + for (auto& [path, library] : libraries) + if (&library.model == source) + if (auto found = library.sounds.find(soundId); found != library.sounds.end()) + sound = &found->second; + if (sound) + result.push_back(sound); } return result; - } +} - void Document::sound_set(int id, AudioData data) { sounds[id] = assets.audio_add(std::move(data)); } +void Document::sound_set(int id, AudioData data) +{ + sounds[id] = assets.audio_add(std::move(data)); +} - ShaderProgram* Document::shader_get(int shaderId) - { +ShaderProgram* Document::shader_get(int shaderId) +{ auto it = shaders.find(shaderId); return it == shaders.end() || !it->second.is_valid() ? nullptr : &it->second; - } +} - bool Document::regions_trim(int spritesheetId, const std::set& ids) - { +bool Document::regions_trim(int spritesheetId, const std::set& ids) +{ auto texture = texture_get(spritesheetId); return texture && ::regions_trim(model, spritesheetId, ids, *texture); - } +} - bool Document::spritesheet_pack(int id, int padding) - { +bool Document::spritesheet_pack(int id, int padding) +{ auto texture = texture_get(id); auto packed = texture ? ::spritesheet_pack(model, id, *texture, padding) : std::nullopt; - if (!packed) return false; + if (!packed) + return false; texture_set(id, std::move(*packed)); assets_sync(); return true; - } +} - bool Document::spritesheets_merge(const std::set& ids, bool isAppendRight, bool isMakeRegions, - bool isMakePrimaryRegion, Origin origin) - { +bool Document::spritesheets_merge(const std::set& ids, bool isAppendRight, bool isMakeRegions, + bool isMakePrimaryRegion, Origin origin) +{ auto merged = ::spritesheets_merge( model, ids, [this](int id) { return texture_get(id); }, isAppendRight, isMakeRegions, isMakePrimaryRegion, origin); - if (!merged) return false; + if (!merged) + return false; texture_set(*ids.begin(), std::move(*merged)); - // The merged sheet may now be an SVG (or a PNG) under a new name; it is written when saved. + // The merged sheet may now be an SVG (or a PNG) under a new name. It is written when saved. texturePaths[*ids.begin()] = item_get(model.content.spritesheets, *ids.begin())->path; for (auto id : ids) - if (id != *ids.begin()) textures.erase(id); + if (id != *ids.begin()) + textures.erase(id); assets_sync(); return true; - } +} - void Document::hash_set() { hash = model_hash(model); } +void Document::hash_set() +{ + hash = model_hash(model); +} - void Document::clean() - { +void Document::clean() +{ assets_sync(); saveHash = model_hash(model); hash = saveHash; lastAutosaveTime = 0.0f; isForceDirty = false; - } +} - void Document::spritesheet_hashes_sync() - { +void Document::spritesheet_hashes_sync() +{ std::set validIds; for (auto& spritesheet : model.content.spritesheets) { - validIds.insert(spritesheet.id); - auto currentHash = spritesheet_hash_get( - spritesheet, textures.contains(spritesheet.id) ? textures.at(spritesheet.id) : 0); - spritesheetHashes[spritesheet.id] = currentHash; - spritesheetSaveHashes.try_emplace(spritesheet.id, currentHash); + validIds.insert(spritesheet.id); + auto currentHash = + spritesheet_hash_get(spritesheet, textures.contains(spritesheet.id) ? textures.at(spritesheet.id) : 0); + spritesheetHashes[spritesheet.id] = currentHash; + spritesheetSaveHashes.try_emplace(spritesheet.id, currentHash); } - auto is_invalid = [&](const auto& pair) { return !validIds.contains(pair.first); }; + auto is_invalid = [&](const auto& pair) { + return !validIds.contains(pair.first); + }; std::erase_if(spritesheetHashes, is_invalid); std::erase_if(spritesheetSaveHashes, is_invalid); - } +} - // Commits the pending edit and rebuilds everything derived from the model. - void Document::change() - { +// Commits the pending edit and rebuilds everything derived from the model. +void Document::change() +{ for (auto& [id, draft] : std::exchange(textureDrafts, {})) - textures[id] = assets.image_add(std::move(draft)); + textures[id] = assets.image_add(std::move(draft)); hash_set(); assets_sync(); spritesheet_hashes_sync(); snapshots.commit(); index = UidIndex(model); - } +} - void Document::edit_begin(StringType label) { snapshots.push(localize.get(label)); } +void Document::edit_begin(StringType label) +{ + snapshots.push(localize.get(label)); +} - Uids Document::edit_run(StringType label, const std::function& operation) - { +Uids Document::edit_run(StringType label, const std::function& operation) +{ edit_begin(label); auto uids = operation(model); change(); return uids; - } +} - std::vector Document::references_get(const Uids& uids) const - { +std::vector Document::references_get(const Uids& uids) const +{ UidIndex index(model); std::vector references; for (auto uid : uids) - if (auto reference = index.reference_get(uid)) references.push_back(*reference); + if (auto reference = index.reference_get(uid)) + references.push_back(*reference); return references; - } +} - bool Document::is_dirty() const { return hash != saveHash; } - bool Document::is_autosave_dirty() { return hash != autosaveHash || !spritesheets_autosave_dirty_get().empty(); } +bool Document::is_dirty() const +{ + return hash != saveHash; +} - // Edited spritesheets are autosaved as a hidden copy beside their file: ..png.autosave. - std::filesystem::path Document::spritesheet_autosave_path_get(const Spritesheet& spritesheet) - { +bool Document::is_autosave_dirty() +{ + return hash != autosaveHash || !spritesheets_autosave_dirty_get().empty(); +} + +// Edited spritesheets are autosaved as a hidden copy beside their file: ..png.autosave. +std::filesystem::path Document::spritesheet_autosave_path_get(const Spritesheet& spritesheet) +{ auto path = directory_get() / spritesheet.path; - return path.parent_path() / - path_from_utf8("." + path_to_utf8(path.filename()) + std::string(AUTOSAVE_EXTENSION)); - } + return path.parent_path() / path_from_utf8("." + path_to_utf8(path.filename()) + std::string(AUTOSAVE_EXTENSION)); +} - // Spritesheets with unsaved pixel edits that their autosave copy doesn't have yet. - std::set Document::spritesheets_autosave_dirty_get() - { +// Spritesheets with unsaved pixel edits that their autosave copy doesn't have yet. +std::set Document::spritesheets_autosave_dirty_get() +{ std::set ids; for (auto& spritesheet : model.content.spritesheets) { - auto id = spritesheet.id; - auto autosaveHash = spritesheetAutosaveHashes.find(id); - if (spritesheet_is_dirty(id) && - (autosaveHash == spritesheetAutosaveHashes.end() || autosaveHash->second != spritesheetHashes.at(id))) - ids.insert(id); + auto id = spritesheet.id; + auto autosaveHash = spritesheetAutosaveHashes.find(id); + if (spritesheet_is_dirty(id) && + (autosaveHash == spritesheetAutosaveHashes.end() || autosaveHash->second != spritesheetHashes.at(id))) + ids.insert(id); } return ids; - } +} - // After a crash, autosaved spritesheets come back as unsaved edits; their files are left as they are. - void Document::spritesheets_autosave_restore() - { +// After a crash, autosaved spritesheets come back as unsaved edits. Their files are left as they are. +void Document::spritesheets_autosave_restore() +{ for (auto& spritesheet : model.content.spritesheets) { - auto path = spritesheet_autosave_path_get(spritesheet); - if (!is_path_exist(path)) continue; - if (auto image = Image(path); image.is_valid()) texture_set(spritesheet.id, std::move(image)); + auto path = spritesheet_autosave_path_get(spritesheet); + if (!is_path_exist(path)) + continue; + if (auto image = Image(path); image.is_valid()) + texture_set(spritesheet.id, std::move(image)); } - } +} - void Document::spritesheets_autosave_clear() - { +void Document::spritesheets_autosave_clear() +{ std::error_code ec; for (auto& spritesheet : model.content.spritesheets) - std::filesystem::remove(spritesheet_autosave_path_get(spritesheet), ec); + std::filesystem::remove(spritesheet_autosave_path_get(spritesheet), ec); spritesheetAutosaveHashes.clear(); - } +} - void Document::spritesheet_hash_update(int id) - { +void Document::spritesheet_hash_update(int id) +{ auto spritesheet = item_get(model.content.spritesheets, id); - if (!spritesheet) return; + if (!spritesheet) + return; assets_sync(); spritesheetHashes[id] = spritesheet_hash_get(*spritesheet, textures.contains(id) ? textures.at(id) : 0); - } +} - // The spritesheet matches its file (just saved or reloaded); its file's time is remembered to notice later changes. - void Document::spritesheet_hash_set_saved(int id) - { +// The spritesheet matches its file (just saved or reloaded). Its file's time is remembered to notice later changes. +void Document::spritesheet_hash_set_saved(int id) +{ spritesheet_hash_update(id); - if (spritesheetHashes.contains(id)) spritesheetSaveHashes[id] = spritesheetHashes[id]; + if (spritesheetHashes.contains(id)) + spritesheetSaveHashes[id] = spritesheetHashes[id]; textureWriteTimes.erase(id); spritesheets_changed_get(); if (auto spritesheet = item_get(model.content.spritesheets, id)) { - std::error_code ec; - std::filesystem::remove(spritesheet_autosave_path_get(*spritesheet), ec); + std::error_code ec; + std::filesystem::remove(spritesheet_autosave_path_get(*spritesheet), ec); } spritesheetAutosaveHashes.erase(id); - } +} - // Spritesheets whose file changed on disk since it was last loaded or saved; ones with unsaved edits are left alone. - std::set Document::spritesheets_changed_get() - { +// Spritesheets whose file changed on disk since it was last loaded or saved. Ones with unsaved edits are left alone. +std::set Document::spritesheets_changed_get() +{ std::set ids; WorkingDirectory workingDirectory(directory_get()); for (auto& spritesheet : model.content.spritesheets) { - std::error_code ec; - auto time = std::filesystem::last_write_time(path_case_insensitive_find(spritesheet.path), ec); - if (ec) continue; - auto [it, isNew] = textureWriteTimes.try_emplace(spritesheet.id, time); - if (!isNew && it->second != time && !spritesheet_is_dirty(spritesheet.id)) ids.insert(spritesheet.id); + std::error_code ec; + auto time = std::filesystem::last_write_time(path_case_insensitive_find(spritesheet.path), ec); + if (ec) + continue; + auto [it, isNew] = textureWriteTimes.try_emplace(spritesheet.id, time); + if (!isNew && it->second != time && !spritesheet_is_dirty(spritesheet.id)) + ids.insert(spritesheet.id); } return ids; - } +} - // Reloads spritesheets from their files as one undoable edit. - void Document::spritesheets_reload(const std::set& ids) - { - edit_apply(EDIT_RELOAD_SPRITESHEETS, - [&](Model&) - { - for (auto id : ids) - texture_reload(id); - }); +// Reloads spritesheets from their files as one undoable edit. +void Document::spritesheets_reload(const std::set& ids) +{ + edit_apply(EDIT_RELOAD_SPRITESHEETS, [&](Model&) { + for (auto id : ids) + texture_reload(id); + }); for (auto id : ids) - if (auto spritesheet = item_get(model.content.spritesheets, id)) - { - spritesheet_hash_set_saved(id); - toast_log(Level::INFO, TOAST_RELOAD_SPRITESHEET, id, path_to_utf8(spritesheet->path)); - } - } + if (auto spritesheet = item_get(model.content.spritesheets, id)) + { + spritesheet_hash_set_saved(id); + toast_log(Level::INFO, TOAST_RELOAD_SPRITESHEET, id, path_to_utf8(spritesheet->path)); + } +} - // Rasterizes SVG spritesheets: each is written as a PNG beside it (as drawn now), and points at the PNG. - void Document::spritesheets_vector_convert(const std::set& ids) - { +// Rasterizes SVG spritesheets: each is written as a PNG beside it (as drawn now), and points at the PNG. +void Document::spritesheets_vector_convert(const std::set& ids) +{ std::set converted; - edit_apply(EDIT_CONVERT_SVG_SPRITESHEETS, - [&](Model& model) - { - for (auto id : ids) - { - auto spritesheet = item_get(model.content.spritesheets, id); - auto texture = texture_get(id); - if (!spritesheet || !texture || !texture->is_vector()) continue; - auto pngPath = - std::filesystem::path(spritesheet->path).replace_extension(PNG_EXTENSION); - auto pathString = path_to_utf8(pngPath); - if (!texture->write_png(std::filesystem::absolute(directory_get()) / pngPath)) - { - toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); - continue; - } - spritesheet->path = pngPath; - texture_reload(id); - converted.insert(id); - toast_log(Level::INFO, TOAST_CONVERT_SVG_SPRITESHEET, id, pathString); - } - }); + edit_apply(EDIT_CONVERT_SVG_SPRITESHEETS, [&](Model& model) { + for (auto id : ids) + { + auto spritesheet = item_get(model.content.spritesheets, id); + auto texture = texture_get(id); + if (!spritesheet || !texture || !texture->is_vector()) + continue; + auto pngPath = std::filesystem::path(spritesheet->path).replace_extension(PNG_EXTENSION); + auto pathString = path_to_utf8(pngPath); + if (!texture->write_png(std::filesystem::absolute(directory_get()) / pngPath)) + { + toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); + continue; + } + spritesheet->path = pngPath; + texture_reload(id); + converted.insert(id); + toast_log(Level::INFO, TOAST_CONVERT_SVG_SPRITESHEET, id, pathString); + } + }); for (auto id : converted) - spritesheet_hash_set_saved(id); - } + spritesheet_hash_set_saved(id); +} - bool Document::spritesheet_is_dirty(int id) - { - if (!item_get(model.content.spritesheets, id)) return false; - if (!spritesheetHashes.contains(id)) spritesheet_hash_update(id); +bool Document::spritesheet_is_dirty(int id) +{ + if (!item_get(model.content.spritesheets, id)) + return false; + if (!spritesheetHashes.contains(id)) + spritesheet_hash_update(id); auto saveIt = spritesheetSaveHashes.find(id); return saveIt != spritesheetSaveHashes.end() && spritesheetHashes.at(id) != saveIt->second; - } +} - bool Document::spritesheet_any_dirty() - { - return std::ranges::any_of(model.content.spritesheets, [&](const Spritesheet& spritesheet) - { return spritesheet_is_dirty(spritesheet.id); }); - } +bool Document::spritesheet_any_dirty() +{ + return std::ranges::any_of(model.content.spritesheets, + [&](const Spritesheet& spritesheet) { return spritesheet_is_dirty(spritesheet.id); }); +} - std::filesystem::path Document::directory_get() const { return path.parent_path(); } - std::filesystem::path Document::filename_get() const { return path.filename(); } - bool Document::is_valid() const { return isValid && !path.empty(); } +std::filesystem::path Document::directory_get() const +{ + return path.parent_path(); +} - void Document::command_run(Manager& manager, Command& command) - { - if (command.run) command.run(manager, *this); - } +std::filesystem::path Document::filename_get() const +{ + return path.filename(); +} - Reference Document::reference_get() const { return selection_focus_get(selection, index); } +bool Document::is_valid() const +{ + return isValid && !path.empty(); +} - void Document::reference_set(Reference reference) { selection_focus_set(selection, model, reference); } +void Document::command_run(Manager& manager, Command& command) +{ + if (command.run) + command.run(manager, *this); +} - std::set Document::selected_get(SelectionKind kind) const - { +Reference Document::reference_get() const +{ + return selection_focus_get(selection, index); +} + +void Document::reference_set(Reference reference) +{ + selection_focus_set(selection, model, reference); +} + +std::set Document::selected_get(SelectionKind kind) const +{ return selection_references_get(selection, index, kind); - } +} - void Document::selected_set(SelectionKind kind, const std::set& references) - { +void Document::selected_set(SelectionKind kind, const std::set& references) +{ selection_references_set(selection, model, kind, references); - } +} - std::set Document::selected_ids_get(SelectionKind kind) const - { +std::set Document::selected_ids_get(SelectionKind kind) const +{ return selection_ids_get(selection, model, kind); - } +} - void Document::selected_ids_set(SelectionKind kind, const std::set& ids) - { +void Document::selected_ids_set(SelectionKind kind, const std::set& ids) +{ selection_ids_set(selection, model, kind, ids); - } +} - int Document::focused_id_get(SelectionKind kind) const { return selection_focus_id_get(selection, model, kind); } +int Document::focused_id_get(SelectionKind kind) const +{ + return selection_focus_id_get(selection, model, kind); +} - void Document::focused_id_set(SelectionKind kind, int id) { selection_focus_id_set(selection, model, kind, id); } +void Document::focused_id_set(SelectionKind kind, int id) +{ + selection_focus_id_set(selection, model, kind, id); +} - void Document::selected_clear(SelectionKind kind) - { +void Document::selected_clear(SelectionKind kind) +{ selection.uids.erase(kind); selection.focuses.erase(kind); - } +} - // Combo entries for a content kind (regions are those of layer `layerId`'s spritesheet); all but spritesheets start with None. - Choices Document::choices_get(SelectionKind kind, int layerId) const - { +// Combo entries for a content kind (regions are those of layer `layerId`'s spritesheet). All but spritesheets start +// with None. +Choices Document::choices_get(SelectionKind kind, int layerId) const +{ Choices choices = {}; if (kind != SelectionKind::SPRITESHEETS) { - choices.ids.push_back(-1); - choices.labels.emplace_back(localize.get(BASIC_NONE)); + choices.ids.push_back(-1); + choices.labels.emplace_back(localize.get(BASIC_NONE)); } - auto add = [&](const auto& items, auto&& label_get) - { - for (auto& item : items) - { - choices.ids.push_back(item.id); - choices.labels.push_back(label_get(item)); - } + auto add = [&](const auto& items, auto&& label_get) { + for (auto& item : items) + { + choices.ids.push_back(item.id); + choices.labels.push_back(label_get(item)); + } }; - auto name_get = [](const auto& item) { return item.name; }; - auto path_label_get = [](StringType format) - { - return [format](const auto& item) - { - auto pathString = path_to_utf8(item.path); - return std::vformat(localize.get(format), std::make_format_args(item.id, pathString)); - }; + auto name_get = [](const auto& item) { + return item.name; + }; + auto path_label_get = [](StringType format) { + return [format](const auto& item) { + auto pathString = path_to_utf8(item.path); + return std::vformat(localize.get(format), std::make_format_args(item.id, pathString)); + }; }; auto& content = model.content; - if (kind == SelectionKind::SPRITESHEETS) add(content.spritesheets, path_label_get(FORMAT_SPRITESHEET)); - if (kind == SelectionKind::SOUNDS) add(content.sounds, path_label_get(FORMAT_SOUND)); - if (kind == SelectionKind::LIBRARIES) add(content.libraries, path_label_get(FORMAT_SOUND)); - if (kind == SelectionKind::EVENTS) add(content.events, name_get); - if (kind == SelectionKind::SHADERS) add(content.shaders, name_get); + if (kind == SelectionKind::SPRITESHEETS) + add(content.spritesheets, path_label_get(FORMAT_SPRITESHEET)); + if (kind == SelectionKind::SOUNDS) + add(content.sounds, path_label_get(FORMAT_SOUND)); + if (kind == SelectionKind::LIBRARIES) + add(content.libraries, path_label_get(FORMAT_SOUND)); + if (kind == SelectionKind::EVENTS) + add(content.events, name_get); + if (kind == SelectionKind::SHADERS) + add(content.shaders, name_get); if (kind == SelectionKind::REGIONS) - if (auto spritesheet = model.layer_spritesheet_get(layerId)) add(spritesheet->regions, name_get); + if (auto spritesheet = model.layer_spritesheet_get(layerId)) + add(spritesheet->regions, name_get); return choices; - } +} - // Selects the frames an edit returned and moves the playhead to the first. - void Document::frames_select(const Uids& uids) - { +// Selects the frames an edit returned and moves the playhead to the first. +void Document::frames_select(const Uids& uids) +{ auto references = references_get(uids); - if (references.empty()) return; + if (references.empty()) + return; auto focus = references.front(); editTarget = EditTarget::FRAME; frame_references_set({references.begin(), references.end()}); reference_set(focus); if (auto item = model.track_get(focus); item && focus.itemType != TRIGGER) - frameTime = frame_time_from_index_get(*item, focus.frameIndex); - } + frameTime = frame_time_from_index_get(*item, focus.frameIndex); +} - void Document::frame_select(Reference frameReference) - { +void Document::frame_select(Reference frameReference) +{ selection.uids[SelectionKind::GROUPS].clear(); editTarget = EditTarget::FRAME; frame_references_set({frameReference}); reference_set(frameReference); - } +} - void Document::frame_toggle(Reference frameReference) - { +void Document::frame_toggle(Reference frameReference) +{ selection.uids[SelectionKind::GROUPS].clear(); editTarget = EditTarget::FRAME; auto frames = frame_references_get(FrameReferenceFallback::NONE); if (!frames.contains(frameReference)) - frames.insert(frameReference); + frames.insert(frameReference); else if (frames.size() > 1) - frames.erase(frameReference); + frames.erase(frameReference); frame_references_set(frames); reference_set(frameReference); - } +} - // Selects frames first..last of one track (added to the selection when additive). - bool Document::frames_range_select(Reference firstReference, Reference lastReference, bool isAdditive) - { +// Selects frames first..last of one track (added to the selection when additive). +bool Document::frames_range_select(Reference firstReference, Reference lastReference, bool isAdditive) +{ selection.uids[SelectionKind::GROUPS].clear(); editTarget = EditTarget::FRAME; - if (item_reference_get(firstReference) != item_reference_get(lastReference) || - firstReference.frameIndex < 0 || lastReference.frameIndex < 0) - return false; + if (item_reference_get(firstReference) != item_reference_get(lastReference) || firstReference.frameIndex < 0 || + lastReference.frameIndex < 0) + return false; auto item = model.track_get(lastReference); if (!item || std::max(firstReference.frameIndex, lastReference.frameIndex) >= track_frames_count_get(*item)) - return false; + return false; auto [firstIndex, lastIndex] = std::minmax(firstReference.frameIndex, lastReference.frameIndex); auto selectedFrames = isAdditive ? frame_references_get(FrameReferenceFallback::NONE) : std::set{}; for (int i = firstIndex; i <= lastIndex; ++i) { - auto frameReference = lastReference; - frameReference.frameIndex = i; - selectedFrames.insert(frameReference); + auto frameReference = lastReference; + frameReference.frameIndex = i; + selectedFrames.insert(frameReference); } frame_references_set(selectedFrames); reference_set(lastReference); return true; - } +} - void Document::frame_focus_select() - { +void Document::frame_focus_select() +{ auto targetReference = reference_get(); - if (targetReference.frameIndex < 0) return frame_references_clear(); + if (targetReference.frameIndex < 0) + return frame_references_clear(); editTarget = EditTarget::FRAME; frame_references_set({targetReference}); - } +} - void Document::focus_clear() - { +void Document::focus_clear() +{ reference_set({reference_get().animationIndex}); frame_references_clear(); selection.uids[SelectionKind::TRACKS].clear(); - } +} - // Selects a track (its layer's spritesheet becomes the focused one). - void Document::track_select(Reference itemReference) - { +// Selects a track (its layer's spritesheet becomes the focused one). +void Document::track_select(Reference itemReference) +{ itemReference.frameIndex = -1; if (itemReference.itemType == LAYER) - if (auto layer = item_get(model.content.layers, itemReference.itemID)) - focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); + if (auto layer = item_get(model.content.layers, itemReference.itemID)) + focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); reference_set(itemReference); frame_references_clear(); selected_set(SelectionKind::TRACKS, {itemReference}); - } +} - std::set Document::animations_selected_get() const - { +std::set Document::animations_selected_get() const +{ std::set indices; for (auto reference : selected_get(SelectionKind::ANIMATIONS)) - indices.insert(reference.animationIndex); + indices.insert(reference.animationIndex); return indices; - } +} - void Document::animations_selected_set(const std::set& indices) - { +void Document::animations_selected_set(const std::set& indices) +{ std::set references; for (auto index : indices) - references.insert({index}); + references.insert({index}); selected_set(SelectionKind::ANIMATIONS, references); - } +} - std::set Document::item_frame_references_get(Reference itemReference) const - { +std::set Document::item_frame_references_get(Reference itemReference) const +{ std::set result; itemReference.frameIndex = -1; auto item = itemReference.itemType == NONE ? nullptr : model.track_get(itemReference); for (int frameIndex = 0; item && frameIndex < (int)item->frames.size(); ++frameIndex) { - itemReference.frameIndex = frameIndex; - result.insert(itemReference); + itemReference.frameIndex = frameIndex; + result.insert(itemReference); } return result; - } +} - std::set Document::selected_item_frame_references_get() const - { +std::set Document::selected_item_frame_references_get() const +{ auto selectedItems = selected_get(SelectionKind::TRACKS); if (auto reference = reference_get(); selectedItems.empty() && reference.itemType != NONE) - selectedItems.insert(item_reference_get(reference)); + selectedItems.insert(item_reference_get(reference)); std::set result; for (auto itemReference : selectedItems) - result.merge(item_frame_references_get(itemReference)); + result.merge(item_frame_references_get(itemReference)); return result; - } +} - std::set Document::frame_references_get(FrameReferenceFallback fallback) const - { +std::set Document::frame_references_get(FrameReferenceFallback fallback) const +{ auto result = selected_get(SelectionKind::FRAMES); auto reference = reference_get(); if (result.empty() && fallback == FrameReferenceFallback::CURRENT && reference.frameIndex >= 0) - result.insert(reference); + result.insert(reference); return result; - } +} - // Selects frames together with their tracks; the focus moves to the first frame unless it is already selected. - void Document::frame_references_set(std::set frameReferences) - { +// Selects frames together with their tracks. The focus moves to the first frame unless it is already selected. +void Document::frame_references_set(std::set frameReferences) +{ std::erase_if(frameReferences, [&](const Reference& frame) { return !model.frame_get(frame); }); std::set tracks; for (auto frame : frameReferences) - tracks.insert(item_reference_get(frame)); + tracks.insert(item_reference_get(frame)); selected_set(SelectionKind::FRAMES, frameReferences); selected_set(SelectionKind::TRACKS, tracks); - if (!frameReferences.empty() && !frameReferences.contains(reference_get())) reference_set(*frameReferences.begin()); + if (!frameReferences.empty() && !frameReferences.contains(reference_get())) + reference_set(*frameReferences.begin()); // The spritesheet editor follows the first selected layer frame's spritesheet. for (auto frame : frameReferences) - if (auto spritesheet = frame.itemType == LAYER ? model.layer_spritesheet_get(frame.itemID) : nullptr) - return focused_id_set(SelectionKind::SPRITESHEETS, spritesheet->id); - } + if (auto spritesheet = frame.itemType == LAYER ? model.layer_spritesheet_get(frame.itemID) : nullptr) + return focused_id_set(SelectionKind::SPRITESHEETS, spritesheet->id); +} - void Document::frame_references_clear() { selection.uids[SelectionKind::FRAMES].clear(); } +void Document::frame_references_clear() +{ + selection.uids[SelectionKind::FRAMES].clear(); +} - std::vector Document::layer_references_get() - { +std::vector Document::layer_references_get() +{ auto reference = reference_get(); std::set selectedReferences = selected_get(SelectionKind::TRACKS); if (selectedReferences.empty() && reference.itemType != NONE) - selectedReferences.insert(item_reference_get(reference)); + selectedReferences.insert(item_reference_get(reference)); std::vector result; for (auto itemReference : selectedReferences) { - if (itemReference.itemType != LAYER) return {}; - result.push_back(itemReference); + if (itemReference.itemType != LAYER) + return {}; + result.push_back(itemReference); } return result; - } +} - void Document::spritesheets_add(const std::vector& paths) - { +void Document::spritesheets_add(const std::vector& paths) +{ auto& items = model.content.spritesheets; auto directory = directory_get(); std::vector> loaded; for (auto& path : paths) { - auto storagePath = path_backslash_handle(path); - std::optional workingDirectory; - if (!storagePath.is_absolute()) workingDirectory.emplace(directory); - auto texture = Image(path_case_insensitive_find(storagePath)); - if (!texture.is_valid()) - { - toast_log(Level::ERROR, TOAST_SPRITESHEET_INIT_FAILED, path_to_utf8(path)); - continue; - } - loaded.emplace_back(path_backslash_replace(path_make_relative(storagePath, directory)), std::move(texture)); + auto storagePath = path_backslash_handle(path); + std::optional workingDirectory; + if (!storagePath.is_absolute()) + workingDirectory.emplace(directory); + auto texture = Image(path_case_insensitive_find(storagePath)); + if (!texture.is_valid()) + { + toast_log(Level::ERROR, TOAST_SPRITESHEET_INIT_FAILED, path_to_utf8(path)); + continue; + } + loaded.emplace_back(path_backslash_replace(path_make_relative(storagePath, directory)), std::move(texture)); } - if (loaded.empty()) return; + if (loaded.empty()) + return; edit_begin(EDIT_ADD_SPRITESHEET); std::set added; for (auto& [relativePath, texture] : loaded) { - auto& element = - items.emplace_back(Spritesheet{.id = item_next_id_get(items), .path = relativePath}); - texture_set(element.id, std::move(texture)); - texturePaths[element.id] = element.path; - added.insert(element.id); - spritesheet_hash_set_saved(element.id); - toast_log(Level::INFO, TOAST_SPRITESHEET_INITIALIZED, element.id, path_to_utf8(element.path)); + auto& element = items.emplace_back(Spritesheet{.id = item_next_id_get(items), .path = relativePath}); + texture_set(element.id, std::move(texture)); + texturePaths[element.id] = element.path; + added.insert(element.id); + spritesheet_hash_set_saved(element.id); + toast_log(Level::INFO, TOAST_SPRITESHEET_INITIALIZED, element.id, path_to_utf8(element.path)); } selected_ids_set(SelectionKind::SPRITESHEETS, added); focused_id_set(SelectionKind::SPRITESHEETS, *added.rbegin()); change(); - } +} - void Document::sounds_add(const std::vector& paths) - { +void Document::sounds_add(const std::vector& paths) +{ auto& items = model.content.sounds; - if (std::ranges::all_of(paths, [](const auto& path) { return path.empty(); })) return; + if (std::ranges::all_of(paths, [](const auto& path) { return path.empty(); })) + return; edit_begin(EDIT_ADD_SOUND); std::set added; for (auto& path : paths) { - if (path.empty()) continue; - auto& element = items.emplace_back(Sound{ - .id = item_next_id_get(items), - .path = path_backslash_replace(path_make_relative(path_backslash_handle(path), directory_get()))}); - WorkingDirectory workingDirectory(directory_get()); - sound_set(element.id, AudioData(path_case_insensitive_find(element.path))); - soundPaths[element.id] = element.path; - added.insert(element.id); - toast_log(Level::INFO, TOAST_SOUND_INITIALIZED, element.id, path_to_utf8(element.path)); + if (path.empty()) + continue; + auto& element = items.emplace_back( + Sound{.id = item_next_id_get(items), + .path = path_backslash_replace(path_make_relative(path_backslash_handle(path), directory_get()))}); + WorkingDirectory workingDirectory(directory_get()); + sound_set(element.id, AudioData(path_case_insensitive_find(element.path))); + soundPaths[element.id] = element.path; + added.insert(element.id); + toast_log(Level::INFO, TOAST_SOUND_INITIALIZED, element.id, path_to_utf8(element.path)); } selected_ids_set(SelectionKind::SOUNDS, added); focused_id_set(SelectionKind::SOUNDS, *added.rbegin()); change(); - } +} - void Document::libraries_add(const std::vector& paths) - { +void Document::libraries_add(const std::vector& paths) +{ std::set added; - edit_apply( - EDIT_ADD_LIBRARY, - [&](Model& model) - { - auto& libraries = model.content.libraries; - for (auto& path : paths) + edit_apply(EDIT_ADD_LIBRARY, [&](Model& model) { + auto& libraries = model.content.libraries; + for (auto& path : paths) if (!path.empty()) { - auto& library = libraries.emplace_back(Library{ - .id = item_next_id_get(libraries), - .path = path_backslash_replace(path_make_relative(path_backslash_handle(path), directory_get()))}); - added.insert(library.id); + auto& library = libraries.emplace_back(Library{ + .id = item_next_id_get(libraries), + .path = path_backslash_replace(path_make_relative(path_backslash_handle(path), directory_get()))}); + added.insert(library.id); } - }); - if (added.empty()) return; + }); + if (added.empty()) + return; for (auto id : added) - toast_log(Level::INFO, TOAST_LIBRARY_INITIALIZED, id, - path_to_utf8(item_get(model.content.libraries, id)->path)); + toast_log(Level::INFO, TOAST_LIBRARY_INITIALIZED, id, + path_to_utf8(item_get(model.content.libraries, id)->path)); selected_ids_set(SelectionKind::LIBRARIES, added); focused_id_set(SelectionKind::LIBRARIES, *added.rbegin()); - } +} - void Document::undo() - { - if (!snapshots.undo()) return; +void Document::undo() +{ + if (!snapshots.undo()) + return; frame_time_sync(*this); toast_log(Level::INFO, TOAST_UNDO, message); change(); - } +} - void Document::redo() - { - if (!snapshots.redo()) return; +void Document::redo() +{ + if (!snapshots.redo()) + return; frame_time_sync(*this); toast_log(Level::INFO, TOAST_REDO, message); change(); - } +} - bool Document::is_able_to_undo() { return !snapshots.undoStack.is_empty(); } - bool Document::is_able_to_redo() { return !snapshots.redoStack.is_empty(); } +bool Document::is_able_to_undo() +{ + return !snapshots.undoStack.is_empty(); +} + +bool Document::is_able_to_redo() +{ + return !snapshots.redoStack.is_empty(); +} diff --git a/src/document.h b/src/document.h index 8ad9019..b6ed706 100644 --- a/src/document.h +++ b/src/document.h @@ -20,29 +20,29 @@ #include "shader.h" - class Manager; - struct Command; +class Manager; +struct Command; - // Ids and labels for a combo box of content items. - struct Choices - { +// Ids and labels for a combo box of content items. +struct Choices +{ std::vector ids; std::vector labels; - }; +}; - // A linked .anm2, loaded read-only: its document, its spritesheets' images and its sounds. - struct LibraryData - { +// A linked .anm2, loaded read-only: its document, its spritesheets' images and its sounds. +struct LibraryData +{ Model model = {}; std::map images; std::map sounds; std::filesystem::file_time_type writeTime; - }; +}; - // A step into an animation layer's child: the parent's tab, animation, time and layer track it was taken from, - // and the animation it led to (in this tab, or a library's). - struct ChildStep - { +// A step into an animation layer's child: the parent's tab, animation, time and layer track it was taken from, +// and the animation it led to (in this tab, or a library's). +struct ChildStep +{ std::uint64_t tabId = 0; int animationIndex = -1; float frameTime = 0; @@ -50,10 +50,10 @@ std::string animationName; std::string layerName; int childAnimationIndex = -1; - }; +}; - struct DocumentData - { +struct DocumentData +{ std::filesystem::path path; uint64_t tabId = 0; Snapshots snapshots = {}; @@ -77,8 +77,8 @@ bool isOpen = true; bool isForceDirty = false; bool isVectorKept = false; - std::vector - childSteps{}; // the steps that led to the animation being edited (the breadcrumb) // asked this session to keep SVG spritesheets in a Rebirth document + std::vector childSteps{}; // the steps that led to the animation being edited (the breadcrumb) // asked + // this session to keep SVG spritesheets in a Rebirth document std::unordered_map spritesheetHashes; std::unordered_map spritesheetSaveHashes; std::unordered_map spritesheetAutosaveHashes; @@ -96,23 +96,23 @@ mutable std::map, Image> vectorImages; bool isAnimationPreviewSet = false; bool isSpritesheetEditorSet = false; - }; +}; - class Document : public DocumentData - { - public: +class Document : public DocumentData +{ +public: enum class FrameReferenceFallback { - NONE, - CURRENT, + NONE, + CURRENT, }; enum class EditTarget { - NONE, - FRAME, - REGION, - SPRITESHEET + NONE, + FRAME, + REGION, + SPRITESHEET }; Snapshot& current = snapshots.current; @@ -162,20 +162,18 @@ void edit_begin(StringType); Uids edit_run(StringType, const std::function&); - // Snapshots for undo, runs the operation on the model, then commits; void operations select nothing. + // Snapshots for undo, runs the operation on the model, then commits. Void operations select nothing. template Uids edit_apply(StringType label, Operation&& operation) { - return edit_run(label, - [&](Model& model) -> Uids - { - if constexpr (std::is_void_v>) - { - operation(model); - return {}; - } - else - return operation(model); - }); + return edit_run(label, [&](Model& model) -> Uids { + if constexpr (std::is_void_v>) + { + operation(model); + return {}; + } + else + return operation(model); + }); } std::vector references_get(const Uids&) const; bool is_dirty() const; @@ -235,4 +233,4 @@ void redo(); bool is_able_to_undo(); bool is_able_to_redo(); - }; +}; diff --git a/src/edit/animations.cpp b/src/edit/animations.cpp index 5681e5f..d0c367c 100644 --- a/src/edit/animations.cpp +++ b/src/edit/animations.cpp @@ -2,233 +2,246 @@ #include "model/xml.h" - constexpr std::string_view ANIMATION_MERGED_SUFFIX = " (Merged)"; +constexpr std::string_view ANIMATION_MERGED_SUFFIX = " (Merged)"; - using AnimationPointer = std::shared_ptr; +using AnimationPointer = std::shared_ptr; - std::set animation_group_ids_get(const Model& model) - { +std::set animation_group_ids_get(const Model& model) +{ std::set ids; for (auto& entry : model.animations.entries) - if (auto group = std::get_if(&entry)) ids.insert(group->id); + if (auto group = std::get_if(&entry)) + ids.insert(group->id); return ids; - } +} - std::set animation_group_indices_get(const Model& model, int groupId) - { +std::set animation_group_indices_get(const Model& model, int groupId) +{ std::set indices; for (int i = 0; i < model.animations_count_get(); ++i) - if (model.animation_group_id_get(i) == groupId) indices.insert(i); + if (model.animation_group_id_get(i) == groupId) + indices.insert(i); return indices; - } +} - // Animations and whole groups taken out of the list, remembering the order they had. - struct AnimationsTaken - { +// Animations and whole groups taken out of the list, remembering the order they had. +struct AnimationsTaken +{ std::vector animations; std::vector groups; - }; +}; - static AnimationsTaken animations_take(Model& model, const std::set& indices, const std::set& groupIds) - { +static AnimationsTaken animations_take(Model& model, const std::set& indices, const std::set& groupIds) +{ AnimationsTaken taken = {}; int index = 0; - std::erase_if(model.animations.entries, - [&](AnimationEntry& entry) - { - if (auto animation = std::get_if(&entry)) - { - if (!indices.contains(index++)) return false; - taken.animations.push_back(std::move(*animation)); - return true; - } - auto& group = std::get(entry); - if (groupIds.contains(group.id)) - { - index += (int)group.animations.size(); - taken.groups.push_back(std::move(group)); - return true; - } - std::erase_if(group.animations, - [&](AnimationPointer& animation) - { - if (!indices.contains(index++)) return false; - taken.animations.push_back(std::move(animation)); - return true; - }); - return false; - }); + std::erase_if(model.animations.entries, [&](AnimationEntry& entry) { + if (auto animation = std::get_if(&entry)) + { + if (!indices.contains(index++)) + return false; + taken.animations.push_back(std::move(*animation)); + return true; + } + auto& group = std::get(entry); + if (groupIds.contains(group.id)) + { + index += (int)group.animations.size(); + taken.groups.push_back(std::move(group)); + return true; + } + std::erase_if(group.animations, [&](AnimationPointer& animation) { + if (!indices.contains(index++)) + return false; + taken.animations.push_back(std::move(animation)); + return true; + }); + return false; + }); return taken; - } +} - // Where an animation with this uid sits: its top-level entry, and its group (or nullptr) and position there. - struct AnimationPlace - { +// Where an animation with this uid sits: its top-level entry, and its group (or nullptr) and position there. +struct AnimationPlace +{ int entry = -1; AnimationGroup* group = nullptr; int position = -1; - }; +}; - static AnimationPlace animation_place_get(Model& model, std::uint64_t uid) - { +static AnimationPlace animation_place_get(Model& model, std::uint64_t uid) +{ auto& entries = model.animations.entries; for (int i = 0; i < (int)entries.size(); ++i) { - if (auto animation = std::get_if(&entries[i])) - { - if ((*animation)->uid == uid) return {i, nullptr, -1}; - continue; - } - auto& group = std::get(entries[i]); - for (int j = 0; j < (int)group.animations.size(); ++j) - if (group.animations[j]->uid == uid) return {i, &group, j}; + if (auto animation = std::get_if(&entries[i])) + { + if ((*animation)->uid == uid) + return {i, nullptr, -1}; + continue; + } + auto& group = std::get(entries[i]); + for (int j = 0; j < (int)group.animations.size(); ++j) + if (group.animations[j]->uid == uid) + return {i, &group, j}; } return {}; - } +} - static int animation_group_entry_get(const Model& model, int groupId) - { +static int animation_group_entry_get(const Model& model, int groupId) +{ auto& entries = model.animations.entries; for (int i = 0; i < (int)entries.size(); ++i) - if (auto group = std::get_if(&entries[i]); group && group->id == groupId) return i; + if (auto group = std::get_if(&entries[i]); group && group->id == groupId) + return i; return -1; - } +} - static AnimationGroup* animation_group_find(Model& model, int groupId) - { +static AnimationGroup* animation_group_find(Model& model, int groupId) +{ auto entry = animation_group_entry_get(model, groupId); return entry == -1 ? nullptr : &std::get(model.animations.entries[entry]); - } +} - // Inserts animations before the animation at a flat index (or at the end), inside `groupId` when given. - static void animations_insert(Model& model, int index, int groupId, std::vector animations) - { +// Inserts animations before the animation at a flat index (or at the end), inside `groupId` when given. +static void animations_insert(Model& model, int index, int groupId, std::vector animations) +{ auto before = model.animation_get(index); auto place = before ? animation_place_get(model, before->uid) : AnimationPlace{}; if (auto group = animation_group_find(model, groupId)) { - auto position = place.group == group ? place.position : (int)group->animations.size(); - group->animations.insert(group->animations.begin() + position, animations.begin(), animations.end()); - return; + auto position = place.group == group ? place.position : (int)group->animations.size(); + group->animations.insert(group->animations.begin() + position, animations.begin(), animations.end()); + return; } auto& entries = model.animations.entries; auto position = place.entry == -1 ? (int)entries.size() : place.entry; entries.insert(entries.begin() + position, animations.begin(), animations.end()); - } +} - void animation_groups_remove(Model& model, const std::set& groupIds) - { +void animation_groups_remove(Model& model, const std::set& groupIds) +{ auto& entries = model.animations.entries; for (int i = 0; i < (int)entries.size(); ++i) { - auto group = std::get_if(&entries[i]); - if (!group || !groupIds.contains(group->id)) continue; - auto animations = std::move(group->animations); - entries.erase(entries.begin() + i); - entries.insert(entries.begin() + i, animations.begin(), animations.end()); - i += (int)animations.size() - 1; + auto group = std::get_if(&entries[i]); + if (!group || !groupIds.contains(group->id)) + continue; + auto animations = std::move(group->animations); + entries.erase(entries.begin() + i); + entries.insert(entries.begin() + i, animations.begin(), animations.end()); + i += (int)animations.size() - 1; } - } +} - // An empty copy of a track list: same tracks and groups, no frames. - static std::vector track_entries_shell_get(const std::vector& entries) - { +// An empty copy of a track list: same tracks and groups, no frames. +static std::vector track_entries_shell_get(const std::vector& entries) +{ std::vector shell; - auto track_shell_get = [](const Track& track) - { return Track{.type = track.type, .id = track.id, .isVisible = track.isVisible}; }; + auto track_shell_get = [](const Track& track) { + return Track{.type = track.type, .id = track.id, .isVisible = track.isVisible}; + }; for (auto& entry : entries) - if (auto track = std::get_if(&entry)) - shell.emplace_back(track_shell_get(*track)); - else - { - auto& group = std::get(entry); - TrackGroup copy{ - .id = group.id, .name = group.name, .isExpanded = group.isExpanded, .isVisible = group.isVisible}; - for (auto& groupTrack : group.tracks) - copy.tracks.push_back(track_shell_get(groupTrack)); - shell.emplace_back(std::move(copy)); - } + if (auto track = std::get_if(&entry)) + shell.emplace_back(track_shell_get(*track)); + else + { + auto& group = std::get(entry); + TrackGroup copy{ + .id = group.id, .name = group.name, .isExpanded = group.isExpanded, .isVisible = group.isVisible}; + for (auto& groupTrack : group.tracks) + copy.tracks.push_back(track_shell_get(groupTrack)); + shell.emplace_back(std::move(copy)); + } return shell; - } +} - // Adds an animation with the same (empty) tracks as the template animation. - Uids animation_add(Model& model, int index, int groupId, int templateIndex, const std::string& name) - { +// Adds an animation with the same (empty) tracks as the template animation. +Uids animation_add(Model& model, int index, int groupId, int templateIndex, const std::string& name) +{ Animation animation = {.name = name}; if (auto source = model.animation_get(templateIndex)) { - animation.layers = track_entries_shell_get(source->layers); - animation.nulls = track_entries_shell_get(source->nulls); + animation.layers = track_entries_shell_get(source->layers); + animation.nulls = track_entries_shell_get(source->nulls); } - if (model.animations_count_get() == 0) model.animations.defaultAnimation = animation.name; + if (model.animations_count_get() == 0) + model.animations.defaultAnimation = animation.name; auto uid = animation.uid; animations_insert(model, index, groupId, {std::make_shared(std::move(animation))}); return {uid}; - } +} - Uids animations_remove(Model& model, const std::set& indices, const std::set& groupIds) - { +Uids animations_remove(Model& model, const std::set& indices, const std::set& groupIds) +{ animations_take(model, indices, {}); animation_groups_remove(model, groupIds); return {}; - } +} - // Moves animations and whole groups beside a target animation or group; animations dropped on their own join the - // target's group (or the group dropped into). - Uids animations_move(Model& model, const std::set& indices, const std::set& groupIds, - AnimationTarget target) - { +// Moves animations and whole groups beside a target animation or group. Animations dropped on their own join the +// target's group (or the group dropped into). +Uids animations_move(Model& model, const std::set& indices, const std::set& groupIds, AnimationTarget target) +{ auto targetAnimation = model.animation_get(target.animationIndex); auto targetUid = targetAnimation ? targetAnimation->uid : 0; - if (targetAnimation && groupIds.contains(model.animation_group_id_get(target.animationIndex))) return {}; - if (targetAnimation && indices.contains(target.animationIndex)) return {}; - if (!targetAnimation && groupIds.contains(target.groupId)) return {}; + if (targetAnimation && groupIds.contains(model.animation_group_id_get(target.animationIndex))) + return {}; + if (targetAnimation && indices.contains(target.animationIndex)) + return {}; + if (!targetAnimation && groupIds.contains(target.groupId)) + return {}; auto taken = animations_take(model, indices, groupIds); - if (taken.animations.empty() && taken.groups.empty()) return {}; + if (taken.animations.empty() && taken.groups.empty()) + return {}; Uids uids = {}; for (auto& animation : taken.animations) - uids.push_back(animation->uid); + uids.push_back(animation->uid); auto& entries = model.animations.entries; auto topIndex = (int)entries.size(); if (targetUid) { - auto place = animation_place_get(model, targetUid); - if (place.group) - place.group->animations.insert(place.group->animations.begin() + place.position + target.isAfter, - taken.animations.begin(), taken.animations.end()); - else if (place.entry != -1) - entries.insert(entries.begin() + place.entry + target.isAfter, taken.animations.begin(), - taken.animations.end()); - place = animation_place_get(model, targetUid); - if (place.entry != -1) topIndex = place.entry + (target.isAfter || place.group); + auto place = animation_place_get(model, targetUid); + if (place.group) + place.group->animations.insert(place.group->animations.begin() + place.position + target.isAfter, + taken.animations.begin(), taken.animations.end()); + else if (place.entry != -1) + entries.insert(entries.begin() + place.entry + target.isAfter, taken.animations.begin(), + taken.animations.end()); + place = animation_place_get(model, targetUid); + if (place.entry != -1) + topIndex = place.entry + (target.isAfter || place.group); } else if (auto entry = animation_group_entry_get(model, target.groupId); entry != -1) { - auto& group = std::get(entries[entry]); - if (target.isInto) - group.animations.insert(group.animations.end(), taken.animations.begin(), taken.animations.end()); - else - entries.insert(entries.begin() + entry + target.isAfter, taken.animations.begin(), taken.animations.end()); - if (!target.isInto && !target.isAfter) entry += (int)taken.animations.size(); - topIndex = entry + (target.isAfter || target.isInto); + auto& group = std::get(entries[entry]); + if (target.isInto) + group.animations.insert(group.animations.end(), taken.animations.begin(), taken.animations.end()); + else + entries.insert(entries.begin() + entry + target.isAfter, taken.animations.begin(), taken.animations.end()); + if (!target.isInto && !target.isAfter) + entry += (int)taken.animations.size(); + topIndex = entry + (target.isAfter || target.isInto); } else - entries.insert(entries.end(), taken.animations.begin(), taken.animations.end()); + entries.insert(entries.end(), taken.animations.begin(), taken.animations.end()); entries.insert(entries.begin() + std::clamp(topIndex, 0, (int)entries.size()), std::make_move_iterator(taken.groups.begin()), std::make_move_iterator(taken.groups.end())); return uids; - } +} - // Wraps ungrouped animations in a new group placed where the first of them was. - Uids animations_group(Model& model, const std::set& indices, const std::string& name) - { - if (indices.empty()) return {}; +// Wraps ungrouped animations in a new group placed where the first of them was. +Uids animations_group(Model& model, const std::set& indices, const std::string& name) +{ + if (indices.empty()) + return {}; auto first = model.animation_get(*indices.begin()); - if (!first) return {}; + if (!first) + return {}; auto firstUid = first->uid; auto entry = animation_place_get(model, firstUid).entry; auto groupIds = animation_group_ids_get(model); @@ -238,15 +251,16 @@ auto& entries = model.animations.entries; entries.insert(entries.begin() + std::clamp(entry, 0, (int)entries.size()), std::move(group)); return {}; - } +} - // Pastes clipboard animations (and groups, which get new ids) before the animation at `start`; lone animations join - // `targetGroupId` when no group came with them. - Uids animations_paste(Model& model, const std::string& text, int start, int targetGroupId, std::set& groupIds, - std::string* errorString) - { +// Pastes clipboard animations (and groups, which get new ids) before the animation at `start`. Lone animations join +// `targetGroupId` when no group came with them. +Uids animations_paste(Model& model, const std::string& text, int start, int targetGroupId, std::set& groupIds, + std::string* errorString) +{ auto entries = animations_from_string(text, errorString); - if (entries.empty()) return {}; + if (entries.empty()) + return {}; auto existingGroupIds = animation_group_ids_get(model); auto nextGroupId = existingGroupIds.empty() ? 0 : *existingGroupIds.rbegin() + 1; @@ -254,26 +268,26 @@ std::vector loose; std::vector placed; for (auto& entry : entries) - if (auto animation = std::get_if(&entry)) - { - uids.push_back((*animation)->uid); - loose.push_back(*animation); - placed.push_back(entry); - } - else - { - auto& group = std::get(entry); - group.id = nextGroupId++; - groupIds.insert(group.id); - for (auto& animation : group.animations) - uids.push_back(animation->uid); - placed.push_back(std::move(entry)); - } + if (auto animation = std::get_if(&entry)) + { + uids.push_back((*animation)->uid); + loose.push_back(*animation); + placed.push_back(entry); + } + else + { + auto& group = std::get(entry); + group.id = nextGroupId++; + groupIds.insert(group.id); + for (auto& animation : group.animations) + uids.push_back(animation->uid); + placed.push_back(std::move(entry)); + } if (groupIds.empty() && targetGroupId != -1 && animation_group_find(model, targetGroupId)) { - animations_insert(model, start, targetGroupId, std::move(loose)); - return uids; + animations_insert(model, start, targetGroupId, std::move(loose)); + return uids; } auto before = model.animation_get(start); @@ -281,146 +295,145 @@ model.animations.entries.insert(model.animations.entries.begin() + position, std::make_move_iterator(placed.begin()), std::make_move_iterator(placed.end())); return uids; - } +} - static void track_merge(Track& destination, const Track& source, Merge type) - { +static void track_merge(Track& destination, const Track& source, Merge type) +{ std::vector frames; for (auto& frame : source.frames) - frames.push_back(frame_clone(frame)); + frames.push_back(frame_clone(frame)); switch (type) { - case MERGE_APPEND: - destination.frames.insert(destination.frames.end(), frames.begin(), frames.end()); - break; - case MERGE_PREPEND: - destination.frames.insert(destination.frames.begin(), frames.begin(), frames.end()); - break; - case MERGE_REPLACE: - if (destination.frames.size() < frames.size()) destination.frames.resize(frames.size()); - std::ranges::copy(frames, destination.frames.begin()); - break; - default: - break; + case MERGE_APPEND: + destination.frames.insert(destination.frames.end(), frames.begin(), frames.end()); + break; + case MERGE_PREPEND: + destination.frames.insert(destination.frames.begin(), frames.begin(), frames.end()); + break; + case MERGE_REPLACE: + if (destination.frames.size() < frames.size()) + destination.frames.resize(frames.size()); + std::ranges::copy(frames, destination.frames.begin()); + break; + default: + break; } - } +} - // Merges a source animation's layer or null tracks: groups match by name (else are added), tracks match by id - // within their group (else are added). - static void track_entries_merge(std::vector& destination, const std::vector& source, - Merge type) - { +// Merges a source animation's layer or null tracks: groups match by name (else are added), tracks match by id +// within their group (else are added). +static void track_entries_merge(std::vector& destination, const std::vector& source, Merge type) +{ std::map groupRemap; std::set matchedGroupIds; int nextGroupId = 0; groups_each(destination, [&](const TrackGroup& group) { nextGroupId = std::max(nextGroupId, group.id + 1); }); - groups_each(source, - [&](const TrackGroup& sourceGroup) - { - TrackGroup* matched = nullptr; - groups_each(destination, - [&](TrackGroup& group) - { - if (!matched && group.name == sourceGroup.name && !matchedGroupIds.contains(group.id)) - matched = &group; - }); - if (matched) - track_merge(matched->root, sourceGroup.root, type); - else - { - TrackGroup group{.id = nextGroupId++, - .name = sourceGroup.name, - .isExpanded = sourceGroup.isExpanded, - .isVisible = sourceGroup.isVisible, - .root = track_clone(sourceGroup.root), - .extras = sourceGroup.extras}; - destination.emplace_back(std::move(group)); - matched = &std::get(destination.back()); - } - groupRemap[sourceGroup.id] = matched->id; - matchedGroupIds.insert(matched->id); - }); + groups_each(source, [&](const TrackGroup& sourceGroup) { + TrackGroup* matched = nullptr; + groups_each(destination, [&](TrackGroup& group) { + if (!matched && group.name == sourceGroup.name && !matchedGroupIds.contains(group.id)) + matched = &group; + }); + if (matched) + track_merge(matched->root, sourceGroup.root, type); + else + { + TrackGroup group{.id = nextGroupId++, + .name = sourceGroup.name, + .isExpanded = sourceGroup.isExpanded, + .isVisible = sourceGroup.isVisible, + .root = track_clone(sourceGroup.root), + .extras = sourceGroup.extras}; + destination.emplace_back(std::move(group)); + matched = &std::get(destination.back()); + } + groupRemap[sourceGroup.id] = matched->id; + matchedGroupIds.insert(matched->id); + }); - tracks_each(source, - [&](const Track& sourceTrack, const TrackGroup* sourceGroup) - { - TrackGroup* group = nullptr; - if (sourceGroup) - groups_each(destination, - [&](TrackGroup& candidate) - { - if (candidate.id == groupRemap[sourceGroup->id]) group = &candidate; - }); - Track* existing = nullptr; - if (group) - { - for (auto& track : group->tracks) - if (track.id == sourceTrack.id) existing = &track; - } - else - for (auto& entry : destination) - if (auto track = std::get_if(&entry); track && track->id == sourceTrack.id) - existing = track; + tracks_each(source, [&](const Track& sourceTrack, const TrackGroup* sourceGroup) { + TrackGroup* group = nullptr; + if (sourceGroup) + groups_each(destination, [&](TrackGroup& candidate) { + if (candidate.id == groupRemap[sourceGroup->id]) + group = &candidate; + }); + Track* existing = nullptr; + if (group) + { + for (auto& track : group->tracks) + if (track.id == sourceTrack.id) + existing = &track; + } + else + for (auto& entry : destination) + if (auto track = std::get_if(&entry); track && track->id == sourceTrack.id) + existing = track; - if (existing) - track_merge(*existing, sourceTrack, type); - else if (group) - group->tracks.push_back(track_clone(sourceTrack)); - else - destination.emplace_back(track_clone(sourceTrack)); - }); - } + if (existing) + track_merge(*existing, sourceTrack, type); + else if (group) + group->tracks.push_back(track_clone(sourceTrack)); + else + destination.emplace_back(track_clone(sourceTrack)); + }); +} - // Merges source animations into the target (frames appended, prepended, replacing or ignored), optionally deleting - // the sources; `ungroupIds` dissolves groups afterwards. Returns the merged animation's uid. - Uids animations_merge(Model& model, int target, std::set sources, Merge type, bool isDeleteAfter, - const std::set& ungroupIds) - { - if (!model.animation_get(target)) return {}; +// Merges source animations into the target (frames appended, prepended, replacing or ignored), optionally deleting +// the sources. `ungroupIds` dissolves groups afterwards. Returns the merged animation's uid. +Uids animations_merge(Model& model, int target, std::set sources, Merge type, bool isDeleteAfter, + const std::set& ungroupIds) +{ + if (!model.animation_get(target)) + return {}; auto isMerge = sources.size() > 1 || !sources.contains(target); if (isMerge) { - auto& merged = *model.animation_edit(target); - if (!merged.name.ends_with(ANIMATION_MERGED_SUFFIX)) merged.name += std::string(ANIMATION_MERGED_SUFFIX); - // Triggers are placed by time, so whichever animation ends up second has its triggers moved past the first. - auto length = merged.frameNum; - for (auto index : sources) - { - if (index == target) continue; - auto source = model.animation_get(index); - if (!source) continue; - auto sourceCopy = *source; - auto& destination = *model.animation_edit(target); - if (type == MERGE_APPEND) - for (auto& trigger : sourceCopy.triggers.frames) - trigger.atFrame += length; - if (type == MERGE_PREPEND) - for (auto& trigger : destination.triggers.frames) - trigger.atFrame += sourceCopy.frameNum; - if (type == MERGE_APPEND || type == MERGE_PREPEND) length += sourceCopy.frameNum; - track_merge(destination.root, sourceCopy.root, type); - track_entries_merge(destination.layers, sourceCopy.layers, type); - track_entries_merge(destination.nulls, sourceCopy.nulls, type); - track_merge(destination.triggers, sourceCopy.triggers, type); - } - - auto targetUid = model.animation_get(target)->uid; - if (isDeleteAfter) - { - sources.erase(target); - animations_take(model, sources, {}); - } - for (int i = 0; i < model.animations_count_get(); ++i) - if (model.animation_get(i)->uid == targetUid) + auto& merged = *model.animation_edit(target); + if (!merged.name.ends_with(ANIMATION_MERGED_SUFFIX)) + merged.name += std::string(ANIMATION_MERGED_SUFFIX); + // Triggers are placed by time, so whichever animation ends up second has its triggers moved past the first. + auto length = merged.frameNum; + for (auto index : sources) { - auto& finalAnimation = *model.animation_edit(i); - finalAnimation.frameNum = animation_length_get(finalAnimation); - target = i; + if (index == target) + continue; + auto source = model.animation_get(index); + if (!source) + continue; + auto sourceCopy = *source; + auto& destination = *model.animation_edit(target); + if (type == MERGE_APPEND) + for (auto& trigger : sourceCopy.triggers.frames) + trigger.atFrame += length; + if (type == MERGE_PREPEND) + for (auto& trigger : destination.triggers.frames) + trigger.atFrame += sourceCopy.frameNum; + if (type == MERGE_APPEND || type == MERGE_PREPEND) + length += sourceCopy.frameNum; + track_merge(destination.root, sourceCopy.root, type); + track_entries_merge(destination.layers, sourceCopy.layers, type); + track_entries_merge(destination.nulls, sourceCopy.nulls, type); + track_merge(destination.triggers, sourceCopy.triggers, type); } + + auto targetUid = model.animation_get(target)->uid; + if (isDeleteAfter) + { + sources.erase(target); + animations_take(model, sources, {}); + } + for (int i = 0; i < model.animations_count_get(); ++i) + if (model.animation_get(i)->uid == targetUid) + { + auto& finalAnimation = *model.animation_edit(i); + finalAnimation.frameNum = animation_length_get(finalAnimation); + target = i; + } } auto uid = model.animation_get(target)->uid; animation_groups_remove(model, ungroupIds); return {uid}; - } +} diff --git a/src/edit/content.cpp b/src/edit/content.cpp index a4b2085..d210226 100644 --- a/src/edit/content.cpp +++ b/src/edit/content.cpp @@ -6,538 +6,534 @@ #include "model/frames.h" #include "model/xml.h" - std::string region_name_get(const std::string& format, int number) - { +std::string region_name_get(const std::string& format, int number) +{ try { - return std::vformat(format, std::make_format_args(number)); + return std::vformat(format, std::make_format_args(number)); } catch (const std::format_error&) { - return format; + return format; } - } +} - static bool is_region_matched(const Region& region, const Frame& frame) - { +static bool is_region_matched(const Region& region, const Frame& frame) +{ return glm::ivec2(region.crop) == glm::ivec2(frame.crop) && glm::ivec2(region.size) == glm::ivec2(frame.size) && glm::ivec2(region.pivot) == glm::ivec2(frame.pivot); - } +} - // Every frame of every layer track whose layer has a spritesheet, with that spritesheet's id. - template static void layer_frames_each(Model& model, int animationIndex, Callback&& callback) - { +// Every frame of every layer track whose layer has a spritesheet, with that spritesheet's id. +template static void layer_frames_each(Model& model, int animationIndex, Callback&& callback) +{ auto animation = model.animation_get(animationIndex); - if (!animation) return; + if (!animation) + return; std::vector> tracks; - tracks_each(animation->layers, - [&](const Track& track, const TrackGroup* group) - { - if (model.layer_spritesheet_get(track.id)) tracks.emplace_back(track.id, group ? group->id : -1); - }); + tracks_each(animation->layers, [&](const Track& track, const TrackGroup* group) { + if (model.layer_spritesheet_get(track.id)) + tracks.emplace_back(track.id, group ? group->id : -1); + }); for (auto [id, groupId] : tracks) { - auto spritesheetId = model.layer_spritesheet_get(id)->id; - auto track = model.track_edit({animationIndex, LAYER, id, -1, groupId == -1 ? NONE : LAYER, groupId}); - for (auto& frame : track->frames) - callback(frame, spritesheetId); + auto spritesheetId = model.layer_spritesheet_get(id)->id; + auto track = model.track_edit({animationIndex, LAYER, id, -1, groupId == -1 ? NONE : LAYER, groupId}); + for (auto& frame : track->frames) + callback(frame, spritesheetId); } - } +} - // Makes a region for each distinct crop/size/pivot among the frames (and points frames at them when mapping is SET). - Uids regions_generate(Model& model, const std::set& animationIndices, const std::set& frames, - const std::string& format, RegionFrameMapping mapping) - { +// Makes a region for each distinct crop/size/pivot among the frames (and points frames at them when mapping is SET). +Uids regions_generate(Model& model, const std::set& animationIndices, const std::set& frames, + const std::string& format, RegionFrameMapping mapping) +{ std::unordered_map regionNumbers; - auto frame_apply = [&](Frame& frame, int spritesheetId) - { - auto& regions = item_get(model.content.spritesheets, spritesheetId)->regions; - auto region = - std::ranges::find_if(regions, [&](const Region& region) { return is_region_matched(region, frame); }); - if (region == regions.end()) - { - regions.push_back({.id = item_next_id_get(regions), - .name = region_name_get(format, ++regionNumbers[spritesheetId]), - .crop = frame.crop, - .size = frame.size, - .pivot = frame.pivot}); - region = regions.end() - 1; - } - if (mapping == RegionFrameMapping::SET) frame.regionId = region->id; + auto frame_apply = [&](Frame& frame, int spritesheetId) { + auto& regions = item_get(model.content.spritesheets, spritesheetId)->regions; + auto region = + std::ranges::find_if(regions, [&](const Region& region) { return is_region_matched(region, frame); }); + if (region == regions.end()) + { + regions.push_back({.id = item_next_id_get(regions), + .name = region_name_get(format, ++regionNumbers[spritesheetId]), + .crop = frame.crop, + .size = frame.size, + .pivot = frame.pivot}); + region = regions.end() - 1; + } + if (mapping == RegionFrameMapping::SET) + frame.regionId = region->id; }; for (auto index : animationIndices) - layer_frames_each(model, index, frame_apply); + layer_frames_each(model, index, frame_apply); for (auto reference : frames) { - auto spritesheet = reference.itemType == LAYER ? model.layer_spritesheet_get(reference.itemID) : nullptr; - auto source = model.frame_get(reference); - if (spritesheet && source && source->regionId == -1) frame_apply(*model.frame_edit(reference), spritesheet->id); + auto spritesheet = reference.itemType == LAYER ? model.layer_spritesheet_get(reference.itemID) : nullptr; + auto source = model.frame_get(reference); + if (spritesheet && source && source->regionId == -1) + frame_apply(*model.frame_edit(reference), spritesheet->id); } return {}; - } +} - // Points frames without a region at a region of their spritesheet with the same crop/size/pivot. - Uids regions_scan(Model& model) - { +// Points frames without a region at a region of their spritesheet with the same crop/size/pivot. +Uids regions_scan(Model& model) +{ for (int i = 0; i < model.animations_count_get(); ++i) - layer_frames_each(model, i, - [&](Frame& frame, int spritesheetId) - { - if (frame.regionId != -1) return; - for (auto& region : item_get(model.content.spritesheets, spritesheetId)->regions) - if (is_region_matched(region, frame)) - { - frame.regionId = region.id; - break; - } - }); + layer_frames_each(model, i, [&](Frame& frame, int spritesheetId) { + if (frame.regionId != -1) + return; + for (auto& region : item_get(model.content.spritesheets, spritesheetId)->regions) + if (is_region_matched(region, frame)) + { + frame.regionId = region.id; + break; + } + }); return {}; - } +} - // Copies each layer frame's region crop/size/pivot onto it; frames pointing at a missing region lose it. - Uids region_frames_sync(Model& model) - { +// Copies each layer frame's region crop/size/pivot onto it. Frames pointing at a missing region lose it. +Uids region_frames_sync(Model& model) +{ for (int i = 0; i < model.animations_count_get(); ++i) - layer_frames_each(model, i, - [&](Frame& frame, int spritesheetId) - { - if (frame.regionId == -1) return; - auto region = - item_get(item_get(model.content.spritesheets, spritesheetId)->regions, frame.regionId); - if (!region) - { - frame.regionId = -1; - return; - } - frame.crop = region->crop; - frame.size = region->size; - frame.pivot = region->pivot; - }); + layer_frames_each(model, i, [&](Frame& frame, int spritesheetId) { + if (frame.regionId == -1) + return; + auto region = item_get(item_get(model.content.spritesheets, spritesheetId)->regions, frame.regionId); + if (!region) + { + frame.regionId = -1; + return; + } + frame.crop = region->crop; + frame.size = region->size; + frame.pivot = region->pivot; + }); return {}; - } +} - // Clears frame references to the spritesheet's unused regions, then removes them. - // Removes content items (regions of spritesheet `spritesheetId`) with what refers to them: a layer's or null's tracks - // in every animation, an event or sound from its triggers (dropping those left with neither), a shader from its - // frames (which go back to the default), a region from its frames (which keep its crop, size and pivot), a - // spritesheet's plain layers, and a library's layers, flattened into plain ones. - Uids content_remove(Model& model, ElementType type, const std::set& ids, int spritesheetId, - const LibraryGet& library_get, const SpritesheetPathGet& path_get) - { +// Clears frame references to the spritesheet's unused regions, then removes them. +// Removes content items (regions of spritesheet `spritesheetId`) with what refers to them: a layer's or null's tracks +// in every animation, an event or sound from its triggers (dropping those left with neither), a shader from its +// frames (which go back to the default), a region from its frames (which keep its crop, size and pivot), a +// spritesheet's plain layers, and a library's layers, flattened into plain ones. +Uids content_remove(Model& model, ElementType type, const std::set& ids, int spritesheetId, + const LibraryGet& library_get, const SpritesheetPathGet& path_get) +{ auto& content = model.content; - auto items_erase = [&](auto& items) - { std::erase_if(items, [&](const auto& item) { return ids.contains(item.id); }); }; - auto layer_ids_get = [&](auto&& is_removed) - { - std::set layerIds; - for (auto& layer : content.layers) - if (is_removed(layer)) layerIds.insert(layer.id); - return layerIds; + auto items_erase = [&](auto& items) { + std::erase_if(items, [&](const auto& item) { return ids.contains(item.id); }); + }; + auto layer_ids_get = [&](auto&& is_removed) { + std::set layerIds; + for (auto& layer : content.layers) + if (is_removed(layer)) + layerIds.insert(layer.id); + return layerIds; }; // Only the animations that refer to them are edited. - auto animations_edit = [&](auto&& edit) - { - for (int i = 0; i < model.animations_count_get(); ++i) - if (model.uses_count(type, ids, spritesheetId, model.animation_get(i)) > 0) edit(*model.animation_edit(i), i); + auto animations_edit = [&](auto&& edit) { + for (int i = 0; i < model.animations_count_get(); ++i) + if (model.uses_count(type, ids, spritesheetId, model.animation_get(i)) > 0) + edit(*model.animation_edit(i), i); }; switch (type) { - case ElementType::LIBRARY: - model = - animation_layers_flatten(std::move(model), library_get, path_get, - layer_ids_get([&](const Layer& layer) { return ids.contains(layer.libraryId); })); - items_erase(content.libraries); - break; - case ElementType::SPRITESHEET: - content_remove(model, ElementType::LAYER_ELEMENT, - layer_ids_get([&](const Layer& layer) - { return !layer.is_animation() && ids.contains(layer.spritesheetId); }), - -1, library_get, path_get); - items_erase(content.spritesheets); - break; - case ElementType::LAYER_ELEMENT: - case ElementType::NULL_ELEMENT: - { - auto itemType = type == ElementType::LAYER_ELEMENT ? LAYER : NULL_; - animations_edit([&](Animation&, int index) { items_remove(model, index, {{itemType, ids}}, {}); }); - if (type == ElementType::LAYER_ELEMENT) - items_erase(content.layers); - else - items_erase(content.nulls); - break; - } - case ElementType::EVENT_ELEMENT: - case ElementType::SOUND_ELEMENT: - animations_edit( - [&](Animation& animation, int) - { - std::erase_if(animation.triggers.frames, - [&](Frame& trigger) - { - auto& triggerIds = - type == ElementType::EVENT_ELEMENT ? trigger.eventIds : trigger.soundIds; - if (!std::erase_if(triggerIds, [&](int id) { return ids.contains(id); })) return false; - return trigger.eventIds.empty() && trigger.soundIds.empty(); - }); + case ElementType::LIBRARY: + model = animation_layers_flatten( + std::move(model), library_get, path_get, + layer_ids_get([&](const Layer& layer) { return ids.contains(layer.libraryId); })); + items_erase(content.libraries); + break; + case ElementType::SPRITESHEET: + content_remove(model, ElementType::LAYER_ELEMENT, layer_ids_get([&](const Layer& layer) { + return !layer.is_animation() && ids.contains(layer.spritesheetId); + }), + -1, library_get, path_get); + items_erase(content.spritesheets); + break; + case ElementType::LAYER_ELEMENT: + case ElementType::NULL_ELEMENT: + { + auto itemType = type == ElementType::LAYER_ELEMENT ? LAYER : NULL_; + animations_edit([&](Animation&, int index) { items_remove(model, index, {{itemType, ids}}, {}); }); + if (type == ElementType::LAYER_ELEMENT) + items_erase(content.layers); + else + items_erase(content.nulls); + break; + } + case ElementType::EVENT_ELEMENT: + case ElementType::SOUND_ELEMENT: + animations_edit([&](Animation& animation, int) { + std::erase_if(animation.triggers.frames, [&](Frame& trigger) { + auto& triggerIds = type == ElementType::EVENT_ELEMENT ? trigger.eventIds : trigger.soundIds; + if (!std::erase_if(triggerIds, [&](int id) { return ids.contains(id); })) + return false; + return trigger.eventIds.empty() && trigger.soundIds.empty(); + }); }); - if (type == ElementType::EVENT_ELEMENT) - items_erase(content.events); - else - items_erase(content.sounds); - break; - case ElementType::SHADER: - animations_edit( - [&](Animation& animation, int) - { - animation_tracks_each(animation, - [&](Track& track) - { - for (auto& frame : track.frames) - if (ids.contains(frame.shaderId)) frame.shaderId = -1; - }); + if (type == ElementType::EVENT_ELEMENT) + items_erase(content.events); + else + items_erase(content.sounds); + break; + case ElementType::SHADER: + animations_edit([&](Animation& animation, int) { + animation_tracks_each(animation, [&](Track& track) { + for (auto& frame : track.frames) + if (ids.contains(frame.shaderId)) + frame.shaderId = -1; + }); }); - items_erase(content.shaders); - break; - case ElementType::REGION: - animations_edit( - [&](Animation& animation, int) - { - tracks_each(animation.layers, - [&](Track& track, auto*) - { - auto layer = item_get(content.layers, track.id); - if (!layer || layer->spritesheetId != spritesheetId) return; - for (auto& frame : track.frames) - if (ids.contains(frame.regionId)) frame.regionId = -1; - }); + items_erase(content.shaders); + break; + case ElementType::REGION: + animations_edit([&](Animation& animation, int) { + tracks_each(animation.layers, [&](Track& track, auto*) { + auto layer = item_get(content.layers, track.id); + if (!layer || layer->spritesheetId != spritesheetId) + return; + for (auto& frame : track.frames) + if (ids.contains(frame.regionId)) + frame.regionId = -1; + }); }); - if (auto spritesheet = item_get(content.spritesheets, spritesheetId)) items_erase(spritesheet->regions); - break; - default: - break; + if (auto spritesheet = item_get(content.spritesheets, spritesheetId)) + items_erase(spritesheet->regions); + break; + default: + break; } return {}; - } +} - // Pastes regions into a spritesheet at a position; they get fresh ids after the existing ones. - Uids regions_paste(Model& model, int spritesheetId, const std::string& text, int insertIndex, - std::string* errorString) - { +// Pastes regions into a spritesheet at a position. They get fresh ids after the existing ones. +Uids regions_paste(Model& model, int spritesheetId, const std::string& text, int insertIndex, std::string* errorString) +{ auto spritesheet = item_get(model.content.spritesheets, spritesheetId); - if (!spritesheet) return {}; + if (!spritesheet) + return {}; auto regions = items_from_string(text, errorString); for (auto& region : regions) - region.id = item_next_id_get(spritesheet->regions) + (int)(®ion - regions.data()); + region.id = item_next_id_get(spritesheet->regions) + (int)(®ion - regions.data()); insertIndex = std::clamp(insertIndex, 0, (int)spritesheet->regions.size()); spritesheet->regions.insert(spritesheet->regions.begin() + insertIndex, regions.begin(), regions.end()); return {}; - } +} - // Appends grid frames to each layer track (optionally making a region per frame) and fits the animation length. - Uids animation_grid_generate(Model& model, const std::vector& tracks, const GridOptions& options) - { +// Appends grid frames to each layer track (optionally making a region per frame) and fits the animation length. +Uids animation_grid_generate(Model& model, const std::vector& tracks, const GridOptions& options) +{ Uids uids = {}; for (auto reference : tracks) { - if (!model.track_get(reference)) continue; - auto spritesheetId = - model.layer_spritesheet_get(reference.itemID) ? model.layer_spritesheet_get(reference.itemID)->id : -1; - auto& track = *model.track_edit(reference); - auto start = (int)track.frames.size(); - frames_generate_from_grid(track, options.start, options.size, options.pivot, options.columns, options.count, - options.delay); - auto spritesheet = item_get(model.content.spritesheets, spritesheetId); - for (int i = start; i < (int)track.frames.size(); ++i) - { - auto& frame = track.frames[i]; - uids.push_back(frame.uid); - if (!options.isMakeRegions || !spritesheet) continue; - auto& region = - spritesheet->regions.emplace_back(Region{.id = item_next_id_get(spritesheet->regions), - .name = region_name_get(options.regionNameFormat, i - start), - .crop = frame.crop, - .size = frame.size, - .pivot = frame.pivot}); - frame.regionId = region.id; - } - auto& animation = *model.animation_edit(reference.animationIndex); - animation.frameNum = animation_length_get(animation); + if (!model.track_get(reference)) + continue; + auto spritesheetId = + model.layer_spritesheet_get(reference.itemID) ? model.layer_spritesheet_get(reference.itemID)->id : -1; + auto& track = *model.track_edit(reference); + auto start = (int)track.frames.size(); + frames_generate_from_grid(track, options.start, options.size, options.pivot, options.columns, options.count, + options.delay); + auto spritesheet = item_get(model.content.spritesheets, spritesheetId); + for (int i = start; i < (int)track.frames.size(); ++i) + { + auto& frame = track.frames[i]; + uids.push_back(frame.uid); + if (!options.isMakeRegions || !spritesheet) + continue; + auto& region = + spritesheet->regions.emplace_back(Region{.id = item_next_id_get(spritesheet->regions), + .name = region_name_get(options.regionNameFormat, i - start), + .crop = frame.crop, + .size = frame.size, + .pivot = frame.pivot}); + frame.regionId = region.id; + } + auto& animation = *model.animation_edit(reference.animationIndex); + animation.frameNum = animation_length_get(animation); } return uids; - } +} - // Applies a frame change to explicit frames, to whole tracks (frameIndex -1), and to every matching track of the - // given animations. - Uids frames_change_apply(Model& model, const ChangeTargets& targets, FrameChange change, ChangeType type) - { +// Applies a frame change to explicit frames, to whole tracks (frameIndex -1), and to every matching track of the +// given animations. +Uids frames_change_apply(Model& model, const ChangeTargets& targets, FrameChange change, ChangeType type) +{ std::map> frames; std::set wholeTracks; for (auto reference : targets.references) { - auto index = std::exchange(reference.frameIndex, -1); - index < 0 ? (void)wholeTracks.insert(reference) : (void)frames[reference].insert(index); + auto index = std::exchange(reference.frameIndex, -1); + index < 0 ? (void)wholeTracks.insert(reference) : (void)frames[reference].insert(index); } - auto is_animation_layer = [&](const Track& track) - { - auto layer = track.type == ItemType::LAYER ? item_get(model.content.layers, track.id) : nullptr; - return layer && layer->is_animation(); + auto is_animation_layer = [&](const Track& track) { + auto layer = track.type == ItemType::LAYER ? item_get(model.content.layers, track.id) : nullptr; + return layer && layer->is_animation(); }; - auto whole_apply = [&](Track& track) - { - std::set indices; - for (int i = 0; i < (int)track.frames.size(); ++i) - indices.insert(i); - frames_change(track, change, track.type, type, indices, is_animation_layer(track)); + auto whole_apply = [&](Track& track) { + std::set indices; + for (int i = 0; i < (int)track.frames.size(); ++i) + indices.insert(i); + frames_change(track, change, track.type, type, indices, is_animation_layer(track)); }; for (auto& [reference, indices] : frames) - if (auto track = model.track_edit(reference)) - frames_change(*track, change, track->type, type, indices, is_animation_layer(*track)); + if (auto track = model.track_edit(reference)) + frames_change(*track, change, track->type, type, indices, is_animation_layer(*track)); for (auto reference : wholeTracks) - if (auto track = model.track_edit(reference)) whole_apply(*track); + if (auto track = model.track_edit(reference)) + whole_apply(*track); for (auto index : targets.animations) { - auto animation = model.animation_edit(index); - if (!animation) continue; - if (targets.isRoot) whole_apply(animation->root); - if (targets.isLayers) tracks_each(animation->layers, [&](Track& track, auto*) { whole_apply(track); }); - if (targets.isNulls) tracks_each(animation->nulls, [&](Track& track, auto*) { whole_apply(track); }); + auto animation = model.animation_edit(index); + if (!animation) + continue; + if (targets.isRoot) + whole_apply(animation->root); + if (targets.isLayers) + tracks_each(animation->layers, [&](Track& track, auto*) { whole_apply(track); }); + if (targets.isNulls) + tracks_each(animation->nulls, [&](Track& track, auto*) { whole_apply(track); }); } return {}; - } +} - // Merges another anm2 file: content matched by name (or path for sounds) is replaced unless appending as new, - // animations are added, replaced, or merged track by track depending on the preset. - bool file_merge(Model& model, const std::filesystem::path& path, const std::filesystem::path& directory, - FileMergePreset preset) - { +// Merges another anm2 file: content matched by name (or path for sounds) is replaced unless appending as new, +// animations are added, replaced, or merged track by track depending on the preset. +bool file_merge(Model& model, const std::filesystem::path& path, const std::filesystem::path& directory, + FileMergePreset preset) +{ Model source = {}; - if (!model_load(source, path) || !source.isValid) return false; + if (!model_load(source, path) || !source.isValid) + return false; auto isAppendAsNew = preset == FILE_MERGE_PRESET_APPEND_AS_NEW; std::map> remaps; auto& content = model.content; - 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 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 id_remap = [&](ElementType type, int id) { + auto it = remaps[type].find(id); + return it == remaps[type].end() ? -1 : it->second; }; - auto name_find = [](auto& items, const std::string& name) - { - auto it = std::ranges::find_if(items, [&](const auto& item) { return item.name == name; }); - return it == items.end() ? nullptr : &*it; + auto name_find = [](auto& items, const std::string& name) { + auto it = std::ranges::find_if(items, [&](const auto& item) { return item.name == name; }); + return it == items.end() ? nullptr : &*it; }; - auto name_unique_get = [&](auto& items, const std::string& name) - { - auto candidate = name; - for (int i = 2; name_find(items, candidate); ++i) - candidate = std::format("{} {}", name, i); - return candidate; + auto name_unique_get = [&](auto& items, const std::string& name) { + auto candidate = name; + for (int i = 2; name_find(items, candidate); ++i) + candidate = std::format("{} {}", name, i); + return candidate; }; - auto named_merge = [&](auto& items, auto item) - { - auto existing = isAppendAsNew ? nullptr : name_find(items, item.name); - if (existing) - { - item.id = existing->id; - item.uid = existing->uid; - *existing = item; + auto named_merge = [&](auto& items, auto item) { + auto existing = isAppendAsNew ? nullptr : name_find(items, item.name); + if (existing) + { + item.id = existing->id; + item.uid = existing->uid; + *existing = item; + return item.id; + } + item.id = item_next_id_get(items); + if (isAppendAsNew) + item.name = name_unique_get(items, item.name); + items.push_back(item); return item.id; - } - item.id = item_next_id_get(items); - if (isAppendAsNew) item.name = name_unique_get(items, item.name); - items.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 = item_get(source.content.spritesheets, sourceId); - if (sourceId < 0 || !spritesheet) return -1; - auto imported = *spritesheet; - imported.id = item_next_id_get(content.spritesheets); - imported.path = path_remap(imported.path); - content.spritesheets.push_back(imported); - return remap[sourceId] = imported.id; + auto spritesheet_import = [&](int sourceId) { + auto& remap = remaps[ElementType::SPRITESHEET]; + if (remap.contains(sourceId)) + return remap[sourceId]; + auto spritesheet = item_get(source.content.spritesheets, sourceId); + if (sourceId < 0 || !spritesheet) + return -1; + auto imported = *spritesheet; + imported.id = item_next_id_get(content.spritesheets); + imported.path = path_remap(imported.path); + content.spritesheets.push_back(imported); + return remap[sourceId] = imported.id; }; // Sounds and libraries are matched by path. - auto paths_merge = [&](auto& items, const auto& sourceItems, ElementType type) - { - for (auto item : sourceItems) - { - auto sourceId = item.id; - item.path = path_remap(item.path); - auto existing = isAppendAsNew - ? items.end() - : std::ranges::find_if(items, [&](const auto& other) { return other.path == item.path; }); - item.id = existing != items.end() ? existing->id : item_next_id_get(items); - if (existing != items.end()) - *existing = item; - else - items.push_back(item); - remaps[type][sourceId] = item.id; - } + auto paths_merge = [&](auto& items, const auto& sourceItems, ElementType type) { + for (auto item : sourceItems) + { + auto sourceId = item.id; + item.path = path_remap(item.path); + auto existing = + isAppendAsNew ? items.end() + : std::ranges::find_if(items, [&](const auto& other) { return other.path == item.path; }); + item.id = existing != items.end() ? existing->id : item_next_id_get(items); + if (existing != items.end()) + *existing = item; + else + items.push_back(item); + remaps[type][sourceId] = item.id; + } }; paths_merge(content.sounds, source.content.sounds, ElementType::SOUND_ELEMENT); paths_merge(content.libraries, source.content.libraries, ElementType::LIBRARY); for (auto layer : source.content.layers) { - auto existing = isAppendAsNew ? nullptr : name_find(content.layers, layer.name); - auto sourceId = layer.id; - layer.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(layer.spritesheetId); - layer.libraryId = id_remap(ElementType::LIBRARY, layer.libraryId); - remaps[ElementType::LAYER_ELEMENT][sourceId] = named_merge(content.layers, layer); + auto existing = isAppendAsNew ? nullptr : name_find(content.layers, layer.name); + auto sourceId = layer.id; + layer.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(layer.spritesheetId); + layer.libraryId = id_remap(ElementType::LIBRARY, layer.libraryId); + remaps[ElementType::LAYER_ELEMENT][sourceId] = named_merge(content.layers, layer); } for (auto null : source.content.nulls) - remaps[ElementType::NULL_ELEMENT][null.id] = named_merge(content.nulls, null); + remaps[ElementType::NULL_ELEMENT][null.id] = named_merge(content.nulls, null); for (auto event : source.content.events) - remaps[ElementType::EVENT_ELEMENT][event.id] = named_merge(content.events, event); + remaps[ElementType::EVENT_ELEMENT][event.id] = named_merge(content.events, event); - auto track_remap = [&](Track& track) - { - for (auto& frame : track.frames) - { - for (auto& soundId : frame.soundIds) - soundId = id_remap(ElementType::SOUND_ELEMENT, soundId); - for (auto& eventId : frame.eventIds) - eventId = id_remap(ElementType::EVENT_ELEMENT, eventId); - } - }; - - auto entries_remap = [&](std::vector& entries, ElementType type) - { - std::vector result; - auto track_keep = [&](Track& track) - { - track.id = id_remap(type, track.id); - if (track.id < 0) return false; - track_remap(track); - return true; - }; - for (auto& entry : entries) - if (auto track = std::get_if(&entry)) + auto track_remap = [&](Track& track) { + for (auto& frame : track.frames) { - if (track_keep(*track)) result.push_back(std::move(entry)); + for (auto& soundId : frame.soundIds) + soundId = id_remap(ElementType::SOUND_ELEMENT, soundId); + for (auto& eventId : frame.eventIds) + eventId = id_remap(ElementType::EVENT_ELEMENT, eventId); } - else - { - auto& group = std::get(entry); - std::erase_if(group.tracks, [&](Track& groupTrack) { return !track_keep(groupTrack); }); - result.push_back(std::move(entry)); - } - entries = std::move(result); }; - auto animation_build = [&](const Animation& incoming) - { - auto animation = animation_clone(incoming); - animation.extras = animation.layersExtras = animation.nullsExtras = {}; - track_remap(animation.root); - track_remap(animation.triggers); - entries_remap(animation.layers, ElementType::LAYER_ELEMENT); - entries_remap(animation.nulls, ElementType::NULL_ELEMENT); - return animation; + auto entries_remap = [&](std::vector& entries, ElementType type) { + std::vector result; + auto track_keep = [&](Track& track) { + track.id = id_remap(type, track.id); + if (track.id < 0) + return false; + track_remap(track); + return true; + }; + for (auto& entry : entries) + if (auto track = std::get_if(&entry)) + { + if (track_keep(*track)) + result.push_back(std::move(entry)); + } + else + { + auto& group = std::get(entry); + std::erase_if(group.tracks, [&](Track& groupTrack) { return !track_keep(groupTrack); }); + result.push_back(std::move(entry)); + } + entries = std::move(result); }; - auto animation_find = [&](const std::string& name) -> int - { - for (int i = 0; i < model.animations_count_get(); ++i) - if (model.animation_get(i)->name == name) return i; - return -1; + auto animation_build = [&](const Animation& incoming) { + auto animation = animation_clone(incoming); + animation.extras = animation.layersExtras = animation.nullsExtras = {}; + track_remap(animation.root); + track_remap(animation.triggers); + entries_remap(animation.layers, ElementType::LAYER_ELEMENT); + entries_remap(animation.nulls, ElementType::NULL_ELEMENT); + return animation; + }; + + auto animation_find = [&](const std::string& name) -> int { + for (int i = 0; i < model.animations_count_get(); ++i) + if (model.animation_get(i)->name == name) + return i; + return -1; }; std::string defaultAnimationName; for (auto [index, incoming] : source.animations_get()) { - auto processed = animation_build(*incoming); - auto destination = animation_find(processed.name); - if (isAppendAsNew) - { - auto candidate = processed.name; - for (int i = 2; animation_find(candidate) != -1; ++i) - candidate = std::format("{} {}", processed.name, i); - processed.name = candidate; - } - if (incoming->name == source.animations.defaultAnimation) defaultAnimationName = processed.name; - - if (destination == -1 || isAppendAsNew) - { - model.animations.entries.emplace_back(std::make_shared(std::move(processed))); - continue; - } - - auto& target = *model.animation_edit(destination); - if (preset == FILE_MERGE_PRESET_REPLACE_MATCHING) - { - processed.uid = target.uid; - target = std::move(processed); - continue; - } - - target.isLoop = processed.isLoop; - if (!processed.root.frames.empty()) target.root = processed.root; - if (!processed.triggers.frames.empty()) target.triggers = processed.triggers; - - for (auto [targetEntries, sourceEntries] : - {std::pair{&target.layers, &processed.layers}, std::pair{&target.nulls, &processed.nulls}}) - { - auto nextGroupId = 0; - groups_each(*targetEntries, - [&](const TrackGroup& group) { nextGroupId = std::max(nextGroupId, group.id + 1); }); - for (auto& entry : *sourceEntries) + auto processed = animation_build(*incoming); + auto destination = animation_find(processed.name); + if (isAppendAsNew) { - if (auto group = std::get_if(&entry)) - { - auto copy = *group; - copy.id = nextGroupId++; - std::erase_if(copy.tracks, - [&](const Track& track) - { - auto existing = animation_track_get(target, (int)track.type, track.id); - if (existing && !track.frames.empty()) *existing = track; - return existing != nullptr; - }); - targetEntries->push_back(std::move(copy)); - continue; - } - auto& track = std::get(entry); - if (auto existing = animation_track_get(target, (int)track.type, track.id)) - { - if (!track.frames.empty()) *existing = track; - } - else - targetEntries->push_back(track); + auto candidate = processed.name; + for (int i = 2; animation_find(candidate) != -1; ++i) + candidate = std::format("{} {}", processed.name, i); + processed.name = candidate; } - } + if (incoming->name == source.animations.defaultAnimation) + defaultAnimationName = processed.name; - target.frameNum = std::max({target.frameNum, processed.frameNum, animation_length_get(target)}); + if (destination == -1 || isAppendAsNew) + { + model.animations.entries.emplace_back(std::make_shared(std::move(processed))); + continue; + } + + auto& target = *model.animation_edit(destination); + if (preset == FILE_MERGE_PRESET_REPLACE_MATCHING) + { + processed.uid = target.uid; + target = std::move(processed); + continue; + } + + target.isLoop = processed.isLoop; + if (!processed.root.frames.empty()) + target.root = processed.root; + if (!processed.triggers.frames.empty()) + target.triggers = processed.triggers; + + for (auto [targetEntries, sourceEntries] : + {std::pair{&target.layers, &processed.layers}, std::pair{&target.nulls, &processed.nulls}}) + { + auto nextGroupId = 0; + groups_each(*targetEntries, + [&](const TrackGroup& group) { nextGroupId = std::max(nextGroupId, group.id + 1); }); + for (auto& entry : *sourceEntries) + { + if (auto group = std::get_if(&entry)) + { + auto copy = *group; + copy.id = nextGroupId++; + std::erase_if(copy.tracks, [&](const Track& track) { + auto existing = animation_track_get(target, (int)track.type, track.id); + if (existing && !track.frames.empty()) + *existing = track; + return existing != nullptr; + }); + targetEntries->push_back(std::move(copy)); + continue; + } + auto& track = std::get(entry); + if (auto existing = animation_track_get(target, (int)track.type, track.id)) + { + if (!track.frames.empty()) + *existing = track; + } + else + targetEntries->push_back(track); + } + } + + target.frameNum = std::max({target.frameNum, processed.frameNum, animation_length_get(target)}); } if (model.animations.defaultAnimation.empty() && !source.animations.defaultAnimation.empty()) - model.animations.defaultAnimation = - defaultAnimationName.empty() ? source.animations.defaultAnimation : defaultAnimationName; + model.animations.defaultAnimation = + defaultAnimationName.empty() ? source.animations.defaultAnimation : defaultAnimationName; return true; - } +} diff --git a/src/edit/edit.h b/src/edit/edit.h index 805b97d..f4b8821 100644 --- a/src/edit/edit.h +++ b/src/edit/edit.h @@ -13,28 +13,28 @@ #include "model/model.h" // Document edits as plain functions of the model. Each returns the uids of the elements it created or changed that -// the caller may want to select (the first one is the focus); selection itself stays with the UI. - using Uids = std::vector; - using ImageGet = std::function; +// the caller may want to select (the first one is the focus). Selection itself stays with the UI. +using Uids = std::vector; +using ImageGet = std::function; - struct RowTarget - { +struct RowTarget +{ bool isGroup = false; int type = NONE; int id = -1; int groupId = -1; - }; +}; - struct RootBakeOptions - { +struct RootBakeOptions +{ bool isRoundScale = false; bool isRoundRotation = false; bool isMatchRootInterpolation = false; bool isUseRootPivot = false; - }; +}; - struct GridOptions - { +struct GridOptions +{ glm::ivec2 start{}; glm::ivec2 size{}; glm::vec2 pivot{}; @@ -43,28 +43,28 @@ int delay = 0; bool isMakeRegions = false; std::string regionNameFormat; - }; +}; - struct ChangeTargets - { +struct ChangeTargets +{ std::set references; std::set animations; bool isRoot = false; bool isLayers = false; bool isNulls = false; - }; +}; - struct AnimationTarget - { +struct AnimationTarget +{ int animationIndex = -1; int groupId = -1; bool isAfter = false; bool isInto = false; - }; +}; - // Frame properties that can be copied on their own. - enum class FrameProperty - { +// Frame properties that can be copied on their own. +enum class FrameProperty +{ POSITION, SCALE, ROTATION, @@ -85,61 +85,57 @@ EVENT, SOUNDS, COUNT - }; +}; - bool is_frame_property_valid(FrameProperty, ItemType); - void frame_property_copy(Frame&, const Frame&, FrameProperty); - Uids frames_property_set(Model&, const std::set&, FrameProperty, const Frame&); +bool is_frame_property_valid(FrameProperty, ItemType); +void frame_property_copy(Frame&, const Frame&, FrameProperty); +Uids frames_property_set(Model&, const std::set&, FrameProperty, const Frame&); - std::map> frames_by_track_get(const std::set&); +std::map> frames_by_track_get(const std::set&); - Uids frame_insert(Model&, Reference, int); - Uids frames_delete(Model&, const std::set&); - Uids frames_duplicate(Model&, const std::set&, Reference); - Uids frames_reverse(Model&, const std::set&); - Uids frames_bake(Model&, const std::set&, int, bool, bool); - Uids frame_split(Model&, Reference, int); - Uids frames_split(Model&, const std::set&, int); - Uids frames_move(Model&, const std::set&, Reference, int); - Uids frame_durations_set(Model&, const std::map&); - Uids trigger_at_frame_set(Model&, Reference, int); - Uids frames_paste(Model&, Reference, const std::set&, const std::string&, int, std::string*); - Uids root_bake_into(Model&, const std::set&, const std::set&, RootBakeOptions); +Uids frame_insert(Model&, Reference, int); +Uids frames_delete(Model&, const std::set&); +Uids frames_duplicate(Model&, const std::set&, Reference); +Uids frames_reverse(Model&, const std::set&); +Uids frames_bake(Model&, const std::set&, int, bool, bool); +Uids frame_split(Model&, Reference, int); +Uids frames_split(Model&, const std::set&, int); +Uids frames_move(Model&, const std::set&, Reference, int); +Uids frame_durations_set(Model&, const std::map&); +Uids trigger_at_frame_set(Model&, Reference, int); +Uids frames_paste(Model&, Reference, const std::set&, const std::string&, int, std::string*); +Uids root_bake_into(Model&, const std::set&, const std::set&, RootBakeOptions); - Uids items_remove(Model&, int, const std::map>&, const std::map>&); - Uids items_group(Model&, int, int, const std::set&, const std::string&); - Uids items_move(Model&, int, int, const std::set&, const std::set&, RowTarget, bool, bool); - Uids animation_length_fit(Model&, int); - int item_add(Model&, ItemType, int, int, Layer, Null, int, Destination); +Uids items_remove(Model&, int, const std::map>&, const std::map>&); +Uids items_group(Model&, int, int, const std::set&, const std::string&); +Uids items_move(Model&, int, int, const std::set&, const std::set&, RowTarget, bool, bool); +Uids animation_length_fit(Model&, int); +int item_add(Model&, ItemType, int, int, Layer, Null, int, Destination); - std::set animation_group_ids_get(const Model&); - std::set animation_group_indices_get(const Model&, int); - void animation_groups_remove(Model&, const std::set&); - Uids animation_add(Model&, int, int, int, const std::string&); - Uids animations_remove(Model&, const std::set&, const std::set&); - Uids animations_move(Model&, const std::set&, const std::set&, AnimationTarget); - Uids animations_group(Model&, const std::set&, const std::string&); - Uids animations_paste(Model&, const std::string&, int, int, std::set&, std::string*); - Uids animations_merge(Model&, int, std::set, Merge, bool, const std::set&); +std::set animation_group_ids_get(const Model&); +std::set animation_group_indices_get(const Model&, int); +void animation_groups_remove(Model&, const std::set&); +Uids animation_add(Model&, int, int, int, const std::string&); +Uids animations_remove(Model&, const std::set&, const std::set&); +Uids animations_move(Model&, const std::set&, const std::set&, AnimationTarget); +Uids animations_group(Model&, const std::set&, const std::string&); +Uids animations_paste(Model&, const std::string&, int, int, std::set&, std::string*); +Uids animations_merge(Model&, int, std::set, Merge, bool, const std::set&); - std::string region_name_get(const std::string&, int); - Uids regions_generate(Model&, const std::set&, const std::set&, const std::string&, - RegionFrameMapping); - Uids regions_scan(Model&); - Uids region_frames_sync(Model&); - Uids regions_paste(Model&, int, const std::string&, int, std::string*); - Uids animation_grid_generate(Model&, const std::vector&, const GridOptions&); - Uids frames_change_apply(Model&, const ChangeTargets&, FrameChange, ChangeType); - bool regions_trim(Model&, int, const std::set&, const Image&); - std::optional spritesheet_pack(Model&, int, const Image&, int); - std::optional spritesheets_merge(Model&, const std::set&, const ImageGet&, bool, bool, - bool, Origin); +std::string region_name_get(const std::string&, int); +Uids regions_generate(Model&, const std::set&, const std::set&, const std::string&, RegionFrameMapping); +Uids regions_scan(Model&); +Uids region_frames_sync(Model&); +Uids regions_paste(Model&, int, const std::string&, int, std::string*); +Uids animation_grid_generate(Model&, const std::vector&, const GridOptions&); +Uids frames_change_apply(Model&, const ChangeTargets&, FrameChange, ChangeType); +bool regions_trim(Model&, int, const std::set&, const Image&); +std::optional spritesheet_pack(Model&, int, const Image&, int); +std::optional spritesheets_merge(Model&, const std::set&, const ImageGet&, bool, bool, bool, Origin); - // Where a spritesheet path of a document (this one, or a library) points, from this document. - using SpritesheetPathGet = std::function; - Model animation_layers_flatten(Model, const LibraryGet&, const SpritesheetPathGet&, - const std::set& = {}); - Uids content_remove(Model&, ElementType, const std::set&, int, const LibraryGet&, - const SpritesheetPathGet&); - Model isaac_bridge(Model); - bool file_merge(Model&, const std::filesystem::path&, const std::filesystem::path&, FileMergePreset); +// Where a spritesheet path of a document (this one, or a library) points, from this document. +using SpritesheetPathGet = std::function; +Model animation_layers_flatten(Model, const LibraryGet&, const SpritesheetPathGet&, const std::set& = {}); +Uids content_remove(Model&, ElementType, const std::set&, int, const LibraryGet&, const SpritesheetPathGet&); +Model isaac_bridge(Model); +bool file_merge(Model&, const std::filesystem::path&, const std::filesystem::path&, FileMergePreset); diff --git a/src/edit/flatten.cpp b/src/edit/flatten.cpp index 6578c2f..a8a14e2 100644 --- a/src/edit/flatten.cpp +++ b/src/edit/flatten.cpp @@ -7,10 +7,10 @@ #include "math_util.h" #include "model/frames.h" - // A draw as a plain layer frame of one frame: its transform (parents included) taken apart into position, scale and - // rotation. Skew has no place in a plain frame, and is dropped. - static Frame draw_frame_bake(const Draw& draw) - { +// A draw as a plain layer frame of one frame: its transform (parents included) taken apart into position, scale and +// rotation. Skew has no place in a plain frame, and is dropped. +static Frame draw_frame_bake(const Draw& draw) +{ auto frame = draw.frame; auto size = glm::max(frame.size, glm::vec2(1.0f)); auto model = draw.parent * draw_quad_model_get(draw); @@ -28,133 +28,142 @@ frame.interpolation = Interpolation::NONE; frame.isVisible = true; return frame; - } +} - static bool is_frame_baked_equal(Frame a, const Frame& b) - { +static bool is_frame_baked_equal(Frame a, const Frame& b) +{ a.uid = b.uid; a.duration = b.duration; return a == b; - } +} - // The game's copy of a document: each animation layer's track (or only those of `layerIds`) becomes plain layer - // tracks (one per layer its child animation draws), baked a frame at a time. A library's spritesheets join the copy, - // at paths from `path_get`. - Model animation_layers_flatten(Model model, const LibraryGet& library_get, const SpritesheetPathGet& path_get, - const std::set& layerIds) - { +// The game's copy of a document: each animation layer's track (or only those of `layerIds`) becomes plain layer +// tracks (one per layer its child animation draws), baked a frame at a time. A library's spritesheets join the copy, +// at paths from `path_get`. +Model animation_layers_flatten(Model model, const LibraryGet& library_get, const SpritesheetPathGet& path_get, + const std::set& layerIds) +{ auto& content = model.content; - auto is_flattened = [&](const Layer& layer) - { return layer.is_animation() && (layerIds.empty() || layerIds.contains(layer.id)); }; - if (std::ranges::none_of(content.layers, is_flattened)) return model; + auto is_flattened = [&](const Layer& layer) { + return layer.is_animation() && (layerIds.empty() || layerIds.contains(layer.id)); + }; + if (std::ranges::none_of(content.layers, is_flattened)) + return model; std::map, int> spritesheetIds; - auto spritesheet_id_get = [&](const Model* source, int id) - { - if (source == &model) return id; - auto [it, isNew] = spritesheetIds.try_emplace({source, id}); - if (!isNew) return it->second; - auto spritesheet = item_get(source->content.spritesheets, id); - it->second = item_next_id_get(content.spritesheets); - content.spritesheets.push_back( - {.id = it->second, .path = spritesheet ? path_get(*source, spritesheet->path) : std::filesystem::path{}}); - return it->second; + auto spritesheet_id_get = [&](const Model* source, int id) { + if (source == &model) + return id; + auto [it, isNew] = spritesheetIds.try_emplace({source, id}); + if (!isNew) + return it->second; + auto spritesheet = item_get(source->content.spritesheets, id); + it->second = item_next_id_get(content.spritesheets); + content.spritesheets.push_back( + {.id = it->second, .path = spritesheet ? path_get(*source, spritesheet->path) : std::filesystem::path{}}); + return it->second; }; // (animation layer, source, source layer) -> the plain layer standing in for it. std::map, int> plainIds; - auto layer_id_get = [&](const Draw& draw) - { - auto [it, isNew] = plainIds.try_emplace({draw.id, draw.source, draw.sourceId}); - if (!isNew) return it->second; - auto parent = item_get(content.layers, draw.id); - auto sourceLayer = item_get(draw.source->content.layers, draw.sourceId); - it->second = item_next_id_get(content.layers); - content.layers.push_back({.id = it->second, - .name = parent->name + "/" + (sourceLayer ? sourceLayer->name : std::string{}), - .spritesheetId = spritesheet_id_get(draw.source, draw.spritesheetId)}); - return it->second; + auto layer_id_get = [&](const Draw& draw) { + auto [it, isNew] = plainIds.try_emplace({draw.id, draw.source, draw.sourceId}); + if (!isNew) + return it->second; + auto parent = item_get(content.layers, draw.id); + auto sourceLayer = item_get(draw.source->content.layers, draw.sourceId); + it->second = item_next_id_get(content.layers); + content.layers.push_back({.id = it->second, + .name = parent->name + "/" + (sourceLayer ? sourceLayer->name : std::string{}), + .spritesheetId = spritesheet_id_get(draw.source, draw.spritesheetId)}); + return it->second; }; for (int index = 0; index < model.animations_count_get(); ++index) { - // Drawn as stored, so an animation layer playing its own animation is still caught. - auto& source = *model.animation_get(index); - auto tracks_flatten = [&](const Track& track) - { - auto layer = item_get(content.layers, track.id); - if (!layer || !is_flattened(*layer)) return std::vector{track}; - std::map> frames; - std::vector order; - for (int time = 0; time < source.frameNum; ++time) - for (auto& draw : animation_draws_get(model, source, {.time = (float)time, .library_get = library_get})) - { - if (draw.type != DrawType::LAYER || draw.id != track.id || draw.frame.size == glm::vec2()) continue; - auto id = layer_id_get(draw); - auto [it, isNew] = frames.try_emplace(id, source.frameNum, Frame{.isVisible = false}); - if (isNew) order.push_back(id); - it->second[time] = draw_frame_bake(draw); - } - std::vector tracks; - for (auto id : order) - { - auto& baked = tracks.emplace_back(Track{.type = ItemType::LAYER, .id = id, .isVisible = track.isVisible}); - for (auto& frame : frames[id]) - if (!baked.frames.empty() && is_frame_baked_equal(frame, baked.frames.back())) - ++baked.frames.back().duration; - else - baked.frames.push_back(frame); - } - return tracks; - }; - - std::vector entries; - for (auto& entry : source.layers) - if (auto track = std::get_if(&entry)) - for (auto& flat : tracks_flatten(*track)) - entries.emplace_back(std::move(flat)); - else - { - auto group = std::get(entry); - group.tracks.clear(); - for (auto& groupTrack : std::get(entry).tracks) - for (auto& flat : tracks_flatten(groupTrack)) - group.tracks.push_back(std::move(flat)); - entries.emplace_back(std::move(group)); - } - // The flattened children's triggers join the animation's own, on the frames they fire (their events found by - // name). - auto triggers = source.triggers; - for (int time = 0; time < source.frameNum; ++time) - { - std::vector eventIds; - for (auto& fire : animation_triggers_get(model, source, time, library_get)) - { - auto layer = item_get(content.layers, fire.layerId); - if (!layer || !is_flattened(*layer)) continue; - for (auto eventId : fire.trigger.eventIds) - if (auto event = item_get(fire.source->content.events, eventId)) + // Drawn as stored, so an animation layer playing its own animation is still caught. + auto& source = *model.animation_get(index); + auto tracks_flatten = [&](const Track& track) { + auto layer = item_get(content.layers, track.id); + if (!layer || !is_flattened(*layer)) + return std::vector{track}; + std::map> frames; + std::vector order; + for (int time = 0; time < source.frameNum; ++time) + for (auto& draw : animation_draws_get(model, source, {.time = (float)time, .library_get = library_get})) + { + if (draw.type != DrawType::LAYER || draw.id != track.id || draw.frame.size == glm::vec2()) + continue; + auto id = layer_id_get(draw); + auto [it, isNew] = frames.try_emplace(id, source.frameNum, Frame{.isVisible = false}); + if (isNew) + order.push_back(id); + it->second[time] = draw_frame_bake(draw); + } + std::vector tracks; + for (auto id : order) { - auto existing = std::ranges::find(content.events, event->name, &Event::name); - eventIds.push_back( - existing != content.events.end() - ? existing->id - : content.events.emplace_back(Event{.id = item_next_id_get(content.events), .name = event->name}) - .id); + auto& baked = + tracks.emplace_back(Track{.type = ItemType::LAYER, .id = id, .isVisible = track.isVisible}); + for (auto& frame : frames[id]) + if (!baked.frames.empty() && is_frame_baked_equal(frame, baked.frames.back())) + ++baked.frames.back().duration; + else + baked.frames.push_back(frame); } - } - if (eventIds.empty()) continue; - auto trigger = std::ranges::find(triggers.frames, time, &Frame::atFrame); - if (trigger == triggers.frames.end()) - trigger = triggers.frames.insert(triggers.frames.end(), Frame{.atFrame = time}); - trigger->eventIds.insert(trigger->eventIds.end(), eventIds.begin(), eventIds.end()); - } - frames_sort_by_at_frame(triggers); + return tracks; + }; - auto flattened = model.animation_edit(index); - flattened->layers = std::move(entries); - flattened->triggers = std::move(triggers); + std::vector entries; + for (auto& entry : source.layers) + if (auto track = std::get_if(&entry)) + for (auto& flat : tracks_flatten(*track)) + entries.emplace_back(std::move(flat)); + else + { + auto group = std::get(entry); + group.tracks.clear(); + for (auto& groupTrack : std::get(entry).tracks) + for (auto& flat : tracks_flatten(groupTrack)) + group.tracks.push_back(std::move(flat)); + entries.emplace_back(std::move(group)); + } + // The flattened children's triggers join the animation's own, on the frames they fire (their events found by + // name). + auto triggers = source.triggers; + for (int time = 0; time < source.frameNum; ++time) + { + std::vector eventIds; + for (auto& fire : animation_triggers_get(model, source, time, library_get)) + { + auto layer = item_get(content.layers, fire.layerId); + if (!layer || !is_flattened(*layer)) + continue; + for (auto eventId : fire.trigger.eventIds) + if (auto event = item_get(fire.source->content.events, eventId)) + { + auto existing = std::ranges::find(content.events, event->name, &Event::name); + eventIds.push_back( + existing != content.events.end() + ? existing->id + : content.events + .emplace_back(Event{.id = item_next_id_get(content.events), .name = event->name}) + .id); + } + } + if (eventIds.empty()) + continue; + auto trigger = std::ranges::find(triggers.frames, time, &Frame::atFrame); + if (trigger == triggers.frames.end()) + trigger = triggers.frames.insert(triggers.frames.end(), Frame{.atFrame = time}); + trigger->eventIds.insert(trigger->eventIds.end(), eventIds.begin(), eventIds.end()); + } + frames_sort_by_at_frame(triggers); + + auto flattened = model.animation_edit(index); + flattened->layers = std::move(entries); + flattened->triggers = std::move(triggers); } std::erase_if(content.layers, is_flattened); return model; - } +} diff --git a/src/edit/frames.cpp b/src/edit/frames.cpp index 81546b0..f9588dc 100644 --- a/src/edit/frames.cpp +++ b/src/edit/frames.cpp @@ -7,38 +7,40 @@ #include "model/frames.h" #include "model/xml.h" - std::map> frames_by_track_get(const std::set& frames) - { +std::map> frames_by_track_get(const std::set& frames) +{ std::map> result; for (auto frame : frames) { - auto index = std::exchange(frame.frameIndex, -1); - result[frame].insert(index); + auto index = std::exchange(frame.frameIndex, -1); + result[frame].insert(index); } return result; - } +} - static Uids frames_uids_get(const Track& track, int start, int count) - { +static Uids frames_uids_get(const Track& track, int start, int count) +{ Uids uids = {}; for (int i = std::max(start, 0); i < std::min(start + count, (int)track.frames.size()); ++i) - uids.push_back(track.frames[i].uid); + uids.push_back(track.frames[i].uid); return uids; - } +} - Uids frame_insert(Model& model, Reference reference, int time) - { +Uids frame_insert(Model& model, Reference reference, int time) +{ auto track = model.track_edit(reference); - if (!track) return {}; + if (!track) + return {}; if (track->type == ItemType::TRIGGER) { - if (std::ranges::any_of(track->frames, [&](const Frame& trigger) { return trigger.atFrame == time; })) return {}; - Frame trigger = {}; - trigger.atFrame = time; - track->frames.push_back(trigger); - frames_sort_by_at_frame(*track); - return {trigger.uid}; + if (std::ranges::any_of(track->frames, [&](const Frame& trigger) { return trigger.atFrame == time; })) + return {}; + Frame trigger = {}; + trigger.atFrame = time; + track->frames.push_back(trigger); + frames_sort_by_at_frame(*track); + return {trigger.uid}; } auto count = (int)track->frames.size(); @@ -49,286 +51,306 @@ auto index = isSource ? reference.frameIndex + 1 : count; track->frames.insert(track->frames.begin() + index, frame); return {frame.uid}; - } +} - Uids frames_delete(Model& model, const std::set& frames) - { +Uids frames_delete(Model& model, const std::set& frames) +{ for (auto& [trackReference, indices] : frames_by_track_get(frames)) - if (auto track = model.track_edit(trackReference)) - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - if (*it >= 0 && *it < (int)track->frames.size()) track->frames.erase(track->frames.begin() + *it); + if (auto track = model.track_edit(trackReference)) + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + if (*it >= 0 && *it < (int)track->frames.size()) + track->frames.erase(track->frames.begin() + *it); return {}; - } +} - Uids frames_duplicate(Model& model, const std::set& frames, Reference focus) - { +Uids frames_duplicate(Model& model, const std::set& frames, Reference focus) +{ Uids uids = {}; std::uint64_t focusUid = 0; for (auto& [trackReference, indices] : frames_by_track_get(frames)) { - auto track = model.track_edit(trackReference); - if (!track) continue; + auto track = model.track_edit(trackReference); + if (!track) + continue; - std::vector copies; - int lastIndex = -1; - for (auto index : indices) - { - if (index < 0 || index >= (int)track->frames.size()) continue; - copies.push_back(frame_clone(track->frames[index])); - lastIndex = index; - auto focusTrack = focus; - focusTrack.frameIndex = -1; - if (focusTrack == trackReference && index == focus.frameIndex) focusUid = copies.back().uid; - } - if (copies.empty()) continue; + std::vector copies; + int lastIndex = -1; + for (auto index : indices) + { + if (index < 0 || index >= (int)track->frames.size()) + continue; + copies.push_back(frame_clone(track->frames[index])); + lastIndex = index; + auto focusTrack = focus; + focusTrack.frameIndex = -1; + if (focusTrack == trackReference && index == focus.frameIndex) + focusUid = copies.back().uid; + } + if (copies.empty()) + continue; - for (auto& copy : copies) - uids.push_back(copy.uid); - track->frames.insert(track->frames.begin() + lastIndex + 1, copies.begin(), copies.end()); + for (auto& copy : copies) + uids.push_back(copy.uid); + track->frames.insert(track->frames.begin() + lastIndex + 1, copies.begin(), copies.end()); } if (auto it = std::ranges::find(uids, focusUid); focusUid && it != uids.end()) - std::rotate(uids.begin(), it, it + 1); + std::rotate(uids.begin(), it, it + 1); return uids; - } +} - // Reverses the selected frames of each track as one block placed where the first of them was. - Uids frames_reverse(Model& model, const std::set& frames) - { +// Reverses the selected frames of each track as one block placed where the first of them was. +Uids frames_reverse(Model& model, const std::set& frames) +{ for (auto& [trackReference, indices] : frames_by_track_get(frames)) { - auto track = model.track_edit(trackReference); - if (!track || indices.size() < 2) continue; + auto track = model.track_edit(trackReference); + if (!track || indices.size() < 2) + continue; - std::vector reversed; - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - if (*it >= 0 && *it < (int)track->frames.size()) - { - reversed.push_back(std::move(track->frames[*it])); - track->frames.erase(track->frames.begin() + *it); - } - auto index = std::min(*indices.begin(), (int)track->frames.size()); - track->frames.insert(track->frames.begin() + index, reversed.begin(), reversed.end()); + std::vector reversed; + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + if (*it >= 0 && *it < (int)track->frames.size()) + { + reversed.push_back(std::move(track->frames[*it])); + track->frames.erase(track->frames.begin() + *it); + } + auto index = std::min(*indices.begin(), (int)track->frames.size()); + track->frames.insert(track->frames.begin() + index, reversed.begin(), reversed.end()); } return {}; - } +} - Uids frames_bake(Model& model, const std::set& frames, int interval, bool isRoundScale, - bool isRoundRotation) - { +Uids frames_bake(Model& model, const std::set& frames, int interval, bool isRoundScale, bool isRoundRotation) +{ Uids uids = {}; for (auto& [trackReference, indices] : frames_by_track_get(frames)) { - auto track = model.track_edit(trackReference); - if (!track) continue; + auto track = model.track_edit(trackReference); + if (!track) + continue; - int inserted = 0; - for (auto originalIndex : indices) - { - auto index = originalIndex + inserted; - if (index < 0 || index >= (int)track->frames.size()) continue; - auto duration = track->frames[index].duration; - auto count = duration <= FRAME_DURATION_MIN ? 1 : (int)std::ceil((float)duration / interval); - frame_bake(*track, index, interval, isRoundScale, isRoundRotation); - uids.append_range(frames_uids_get(*track, index, count)); - inserted += count - 1; - } + int inserted = 0; + for (auto originalIndex : indices) + { + auto index = originalIndex + inserted; + if (index < 0 || index >= (int)track->frames.size()) + continue; + auto duration = track->frames[index].duration; + auto count = duration <= FRAME_DURATION_MIN ? 1 : (int)std::ceil((float)duration / interval); + frame_bake(*track, index, interval, isRoundScale, isRoundRotation); + uids.append_range(frames_uids_get(*track, index, count)); + inserted += count - 1; + } } return uids; - } +} - Uids frame_split(Model& model, Reference reference, int time) - { +Uids frame_split(Model& model, Reference reference, int time) +{ auto source = model.frame_get(reference); - if (!source || reference.itemType == TRIGGER || source->duration <= 1) return {}; + if (!source || reference.itemType == TRIGGER || source->duration <= 1) + return {}; auto duration = source->duration; auto firstDuration = time - (int)std::round(frame_time_from_index_get(*model.track_get(reference), reference.frameIndex)) + 1; - if (firstDuration <= 0 || firstDuration >= duration) return {}; + if (firstDuration <= 0 || firstDuration >= duration) + return {}; auto& track = *model.track_edit(reference); auto& frame = track.frames[reference.frameIndex]; auto split = frame_clone(frame); split.duration = duration - firstDuration; if (reference.frameIndex + 1 < (int)track.frames.size() && frame.interpolation != Interpolation::NONE) - frame_mix(split, track.frames[reference.frameIndex + 1], - interpolation_factor(frame.interpolation, (float)firstDuration / (float)duration)); + frame_mix(split, track.frames[reference.frameIndex + 1], + interpolation_factor(frame.interpolation, (float)firstDuration / (float)duration)); frame.duration = firstDuration; auto uid = frame.uid; track.frames.insert(track.frames.begin() + reference.frameIndex + 1, split); return {uid}; - } +} - // Splits each of the frames that spans the time (last first, so earlier references stay valid). - Uids frames_split(Model& model, const std::set& references, int time) - { +// Splits each of the frames that spans the time (last first, so earlier references stay valid). +Uids frames_split(Model& model, const std::set& references, int time) +{ Uids uids = {}; for (auto it = references.rbegin(); it != references.rend(); ++it) - std::ranges::copy(frame_split(model, *it, time), std::back_inserter(uids)); + std::ranges::copy(frame_split(model, *it, time), std::back_inserter(uids)); return uids; - } +} - // Moves frames (from any tracks) into one track before the frame at the given index. - Uids frames_move(Model& model, const std::set& frames, Reference target, int insertIndex) - { +// Moves frames (from any tracks) into one track before the frame at the given index. +Uids frames_move(Model& model, const std::set& frames, Reference target, int insertIndex) +{ target.frameIndex = -1; auto targetTrack = model.track_get(target); - if (!targetTrack) return {}; + if (!targetTrack) + return {}; auto targetUid = targetTrack->uid; insertIndex = std::clamp(insertIndex, 0, (int)targetTrack->frames.size()); std::vector moved; for (auto& [trackReference, indices] : frames_by_track_get(frames)) { - auto track = model.track_edit(trackReference); - if (!track) continue; - std::vector trackMoved; - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - { - if (*it < 0 || *it >= (int)track->frames.size()) continue; - trackMoved.insert(trackMoved.begin(), std::move(track->frames[*it])); - track->frames.erase(track->frames.begin() + *it); - if (track->uid == targetUid && *it < insertIndex) --insertIndex; - } - moved.append_range(trackMoved); + auto track = model.track_edit(trackReference); + if (!track) + continue; + std::vector trackMoved; + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + { + if (*it < 0 || *it >= (int)track->frames.size()) + continue; + trackMoved.insert(trackMoved.begin(), std::move(track->frames[*it])); + track->frames.erase(track->frames.begin() + *it); + if (track->uid == targetUid && *it < insertIndex) + --insertIndex; + } + moved.append_range(trackMoved); } - if (moved.empty()) return {}; + if (moved.empty()) + return {}; auto& destination = *model.track_edit(target); insertIndex = std::clamp(insertIndex, 0, (int)destination.frames.size()); destination.frames.insert(destination.frames.begin() + insertIndex, moved.begin(), moved.end()); return frames_uids_get(destination, insertIndex, (int)moved.size()); - } +} - // Triggers have an event and sounds; layer frames add a pivot, crop, size, region and shader to the others' transform. - bool is_frame_property_valid(FrameProperty property, ItemType type) - { - if (type == ItemType::TRIGGER) return property == FrameProperty::EVENT || property == FrameProperty::SOUNDS; - if (property == FrameProperty::EVENT || property == FrameProperty::SOUNDS) return false; +// Triggers have an event and sounds. Layer frames add a pivot, crop, size, region and shader to the others' transform. +bool is_frame_property_valid(FrameProperty property, ItemType type) +{ + if (type == ItemType::TRIGGER) + return property == FrameProperty::EVENT || property == FrameProperty::SOUNDS; + if (property == FrameProperty::EVENT || property == FrameProperty::SOUNDS) + return false; auto isLayerOnly = property == FrameProperty::PIVOT || property == FrameProperty::CROP || property == FrameProperty::SIZE || property == FrameProperty::REGION || property == FrameProperty::SHADER || property == FrameProperty::DEPTH || property == FrameProperty::BLUR || property == FrameProperty::CHILD; return type == ItemType::LAYER || !isLayerOnly; - } +} - void frame_property_copy(Frame& target, const Frame& source, FrameProperty property) - { +void frame_property_copy(Frame& target, const Frame& source, FrameProperty property) +{ switch (property) { - case FrameProperty::POSITION: - target.position = source.position; - break; - case FrameProperty::SCALE: - target.scale = source.scale; - break; - case FrameProperty::ROTATION: - target.rotation = source.rotation; - break; - case FrameProperty::SKEW: - target.skew = source.skew; - break; - case FrameProperty::PIVOT: - target.pivot = source.pivot; - break; - case FrameProperty::CROP: - target.crop = source.crop; - break; - case FrameProperty::SIZE: - target.size = source.size; - break; - case FrameProperty::REGION: - target.regionId = source.regionId; - target.crop = source.crop; - target.size = source.size; - target.pivot = source.pivot; - break; - case FrameProperty::TINT: - target.tint = source.tint; - break; - case FrameProperty::COLOR_OFFSET: - target.colorOffset = source.colorOffset; - break; - case FrameProperty::VISIBLE: - target.isVisible = source.isVisible; - break; - case FrameProperty::INTERPOLATION: - target.interpolation = source.interpolation; - break; - case FrameProperty::DURATION: - target.duration = source.duration; - break; - case FrameProperty::SHADER: - target.shaderId = source.shaderId; - break; - case FrameProperty::DEPTH: - target.depth = source.depth; - break; - case FrameProperty::BLUR: - target.blur = source.blur; - break; - case FrameProperty::CHILD: - target.childAnimation = source.childAnimation; - target.childMode = source.childMode; - target.childStart = source.childStart; - target.isChildStartRandom = source.isChildStartRandom; - target.isChildRestart = source.isChildRestart; - break; - case FrameProperty::EVENT: - target.eventIds = source.eventIds; - break; - case FrameProperty::SOUNDS: - target.soundIds = source.soundIds; - break; - default: - break; + case FrameProperty::POSITION: + target.position = source.position; + break; + case FrameProperty::SCALE: + target.scale = source.scale; + break; + case FrameProperty::ROTATION: + target.rotation = source.rotation; + break; + case FrameProperty::SKEW: + target.skew = source.skew; + break; + case FrameProperty::PIVOT: + target.pivot = source.pivot; + break; + case FrameProperty::CROP: + target.crop = source.crop; + break; + case FrameProperty::SIZE: + target.size = source.size; + break; + case FrameProperty::REGION: + target.regionId = source.regionId; + target.crop = source.crop; + target.size = source.size; + target.pivot = source.pivot; + break; + case FrameProperty::TINT: + target.tint = source.tint; + break; + case FrameProperty::COLOR_OFFSET: + target.colorOffset = source.colorOffset; + break; + case FrameProperty::VISIBLE: + target.isVisible = source.isVisible; + break; + case FrameProperty::INTERPOLATION: + target.interpolation = source.interpolation; + break; + case FrameProperty::DURATION: + target.duration = source.duration; + break; + case FrameProperty::SHADER: + target.shaderId = source.shaderId; + break; + case FrameProperty::DEPTH: + target.depth = source.depth; + break; + case FrameProperty::BLUR: + target.blur = source.blur; + break; + case FrameProperty::CHILD: + target.childAnimation = source.childAnimation; + target.childMode = source.childMode; + target.childStart = source.childStart; + target.isChildStartRandom = source.isChildStartRandom; + target.isChildRestart = source.isChildRestart; + break; + case FrameProperty::EVENT: + target.eventIds = source.eventIds; + break; + case FrameProperty::SOUNDS: + target.soundIds = source.soundIds; + break; + default: + break; } - } +} - // Sets one property of the frames that have it from a source frame (a default frame clears it). - Uids frames_property_set(Model& model, const std::set& references, FrameProperty property, - const Frame& source) - { +// Sets one property of the frames that have it from a source frame (a default frame clears it). +Uids frames_property_set(Model& model, const std::set& references, FrameProperty property, + const Frame& source) +{ Uids uids = {}; for (auto reference : references) - if (is_frame_property_valid(property, (ItemType)reference.itemType)) - if (auto frame = model.frame_edit(reference)) - { - frame_property_copy(*frame, source, property); - uids.push_back(frame->uid); - } + if (is_frame_property_valid(property, (ItemType)reference.itemType)) + if (auto frame = model.frame_edit(reference)) + { + frame_property_copy(*frame, source, property); + uids.push_back(frame->uid); + } return uids; - } +} - Uids frame_durations_set(Model& model, const std::map& durations) - { +Uids frame_durations_set(Model& model, const std::map& durations) +{ for (auto [reference, duration] : durations) - if (auto frame = model.frame_edit(reference)) - frame->duration = std::clamp(duration, FRAME_DURATION_MIN, FRAME_DURATION_MAX); + if (auto frame = model.frame_edit(reference)) + frame->duration = std::clamp(duration, FRAME_DURATION_MIN, FRAME_DURATION_MAX); return {}; - } +} - // Places a trigger at a frame, stepping it back past any other trigger already there. - Uids trigger_at_frame_set(Model& model, Reference reference, int atFrame) - { +// Places a trigger at a frame, stepping it back past any other trigger already there. +Uids trigger_at_frame_set(Model& model, Reference reference, int atFrame) +{ auto trigger = model.frame_edit(reference); - if (!trigger) return {}; + if (!trigger) + return {}; trigger->atFrame = atFrame; for (auto& other : model.track_get(reference)->frames) - if (&other != trigger && other.atFrame == trigger->atFrame) trigger->atFrame--; + if (&other != trigger && other.atFrame == trigger->atFrame) + trigger->atFrame--; return {}; - } +} - // Pastes clipboard frames after the track's selected frames (or its current frame); triggers go at `time`, stepping - // past occupied frames. Frames lose regions that do not exist on the target layer. - Uids frames_paste(Model& model, Reference reference, const std::set& selection, const std::string& text, - int time, std::string* errorString) - { +// Pastes clipboard frames after the track's selected frames (or its current frame). Triggers go at `time`, stepping +// past occupied frames. Frames lose regions that do not exist on the target layer. +Uids frames_paste(Model& model, Reference reference, const std::set& selection, const std::string& text, + int time, std::string* errorString) +{ auto source = model.track_get(reference); - if (!source) return {}; + if (!source) + return {}; auto frames = frames_from_string(text, source->type, errorString); - if (frames.empty()) return {}; + if (frames.empty()) + return {}; auto trackReference = reference; trackReference.frameIndex = -1; @@ -336,108 +358,113 @@ auto count = (int)source->frames.size(); auto insertIndex = count; if (auto it = selected.find(trackReference); it != selected.end() && !it->second.empty()) - insertIndex = std::min(count, *it->second.rbegin() + 1); + insertIndex = std::min(count, *it->second.rbegin() + 1); else if (reference.frameIndex >= 0 && reference.frameIndex < count) - insertIndex = reference.frameIndex + 1; + insertIndex = reference.frameIndex + 1; auto spritesheet = reference.itemType == LAYER ? model.layer_spritesheet_get(reference.itemID) : nullptr; for (auto& frame : frames) - if (reference.itemType != LAYER && reference.itemType != TRIGGER) - { - frame.regionId = -1; - frame.crop = frame.size = frame.pivot = {}; - } - else if (frame.regionId != -1 && (!spritesheet || !item_get(spritesheet->regions, frame.regionId))) - frame.regionId = -1; + if (reference.itemType != LAYER && reference.itemType != TRIGGER) + { + frame.regionId = -1; + frame.crop = frame.size = frame.pivot = {}; + } + else if (frame.regionId != -1 && (!spritesheet || !item_get(spritesheet->regions, frame.regionId))) + frame.regionId = -1; auto& track = *model.track_edit(reference); Uids uids = {}; if (track.type != ItemType::TRIGGER) { - track.frames.insert(track.frames.begin() + insertIndex, frames.begin(), frames.end()); - return frames_uids_get(track, insertIndex, (int)frames.size()); + track.frames.insert(track.frames.begin() + insertIndex, frames.begin(), frames.end()); + return frames_uids_get(track, insertIndex, (int)frames.size()); } for (int i = 0; i < (int)frames.size(); ++i) { - auto& trigger = frames[i]; - trigger.atFrame = time + i; - while (frame_index_from_at_frame_get(track, trigger.atFrame) != -1) - ++trigger.atFrame; - uids.push_back(trigger.uid); - track.frames.push_back(trigger); + auto& trigger = frames[i]; + trigger.atFrame = time + i; + while (frame_index_from_at_frame_get(track, trigger.atFrame) != -1) + ++trigger.atFrame; + uids.push_back(trigger.uid); + track.frames.push_back(trigger); } frames_sort_by_at_frame(track); return uids; - } +} - // Applies the selected root frames' transforms to the target tracks' frames under them, then resets those root - // frames to a default frame spanning the same time. - Uids root_bake_into(Model& model, const std::set& rootFrames, const std::set& targets, - RootBakeOptions options) - { +// Applies the selected root frames' transforms to the target tracks' frames under them, then resets those root +// frames to a default frame spanning the same time. +Uids root_bake_into(Model& model, const std::set& rootFrames, const std::set& targets, + RootBakeOptions options) +{ auto byTrack = frames_by_track_get(rootFrames); - if (byTrack.size() != 1 || targets.empty()) return {}; + if (byTrack.size() != 1 || targets.empty()) + return {}; auto& [rootReference, rootIndices] = *byTrack.begin(); auto rootTrack = model.track_get(rootReference); - if (!rootTrack) return {}; + if (!rootTrack) + return {}; auto root = *rootTrack; std::vector> spans; for (auto index : rootIndices) - if (index >= 0 && index < (int)root.frames.size()) - { - auto start = (int)frame_time_from_index_get(root, index); - spans.emplace_back(start, start + root.frames[index].duration); - } - if (spans.empty()) return {}; - auto is_spanned = [&](int time) - { return std::ranges::any_of(spans, [&](auto span) { return time >= span.first && time < span.second; }); }; + if (index >= 0 && index < (int)root.frames.size()) + { + auto start = (int)frame_time_from_index_get(root, index); + spans.emplace_back(start, start + root.frames[index].duration); + } + if (spans.empty()) + return {}; + auto is_spanned = [&](int time) { + return std::ranges::any_of(spans, [&](auto span) { return time >= span.first && time < span.second; }); + }; for (auto target : targets) { - auto track = model.track_edit(target); - if (!track) continue; + auto track = model.track_edit(target); + if (!track) + continue; - if (options.isMatchRootInterpolation) - for (int index = (int)track->frames.size() - 1; index >= 0; --index) - if (is_spanned((int)frame_time_from_index_get(*track, index))) - frame_bake(*track, index, FRAME_DURATION_MIN, options.isRoundScale, options.isRoundRotation); + if (options.isMatchRootInterpolation) + for (int index = (int)track->frames.size() - 1; index >= 0; --index) + if (is_spanned((int)frame_time_from_index_get(*track, index))) + frame_bake(*track, index, FRAME_DURATION_MIN, options.isRoundScale, options.isRoundRotation); - for (int index = 0; index < (int)track->frames.size(); ++index) - { - auto start = (int)frame_time_from_index_get(*track, index); - if (is_spanned(start)) - frame_root_transform_apply(track->frames[index], frame_generate(root, (float)start), options.isRoundScale, - options.isRoundRotation, options.isUseRootPivot); - } + for (int index = 0; index < (int)track->frames.size(); ++index) + { + auto start = (int)frame_time_from_index_get(*track, index); + if (is_spanned(start)) + frame_root_transform_apply(track->frames[index], frame_generate(root, (float)start), + options.isRoundScale, options.isRoundRotation, options.isUseRootPivot); + } } Uids uids = {}; std::vector rewritten; int defaultDuration = 0; - auto default_push = [&]() - { - if (defaultDuration <= 0) return; - Frame frame = {}; - frame.duration = std::max(defaultDuration, FRAME_DURATION_MIN); - uids.push_back(frame.uid); - rewritten.push_back(frame); - defaultDuration = 0; + auto default_push = [&]() { + if (defaultDuration <= 0) + return; + Frame frame = {}; + frame.duration = std::max(defaultDuration, FRAME_DURATION_MIN); + uids.push_back(frame.uid); + rewritten.push_back(frame); + defaultDuration = 0; }; for (int index = 0; index < (int)root.frames.size(); ++index) { - if (rootIndices.contains(index)) - { - defaultDuration += root.frames[index].duration; - continue; - } - default_push(); - rewritten.push_back(root.frames[index]); + if (rootIndices.contains(index)) + { + defaultDuration += root.frames[index].duration; + continue; + } + default_push(); + rewritten.push_back(root.frames[index]); } default_push(); model.track_edit(rootReference)->frames = std::move(rewritten); return uids; - } +} diff --git a/src/edit/isaac.cpp b/src/edit/isaac.cpp index a52b554..4feaf4f 100644 --- a/src/edit/isaac.cpp +++ b/src/edit/isaac.cpp @@ -7,108 +7,113 @@ #include "math_util.h" #include "model/frames.h" - // An alpha offset joins the alpha tint: exact on opaque pixels, which the offset can only fade. - static void alpha_offsets_bridge(Model& model) - { - auto is_offset = [](const Frame& frame) { return float_to_uint8(frame.colorOffset.a) != 0; }; +// An alpha offset joins the alpha tint: exact on opaque pixels, which the offset can only fade. +static void alpha_offsets_bridge(Model& model) +{ + auto is_offset = [](const Frame& frame) { + return float_to_uint8(frame.colorOffset.a) != 0; + }; for (int i = 0; i < model.animations_count_get(); ++i) { - auto isUsed = false; - animation_tracks_each(*model.animation_get(i), - [&](const Track& track) { isUsed |= std::ranges::any_of(track.frames, is_offset); }); - if (!isUsed) continue; - animation_tracks_each(*model.animation_edit(i), - [&](Track& track) - { - if (track.type == ItemType::TRIGGER) return; - for (auto& frame : track.frames) - { - frame.tint.a = std::clamp(frame.tint.a + frame.colorOffset.a, 0.0f, 1.0f); - frame.colorOffset.a = 0.0f; - } - }); + auto isUsed = false; + animation_tracks_each(*model.animation_get(i), + [&](const Track& track) { isUsed |= std::ranges::any_of(track.frames, is_offset); }); + if (!isUsed) + continue; + animation_tracks_each(*model.animation_edit(i), [&](Track& track) { + if (track.type == ItemType::TRIGGER) + return; + for (auto& frame : track.frames) + { + frame.tint.a = std::clamp(frame.tint.a + frame.colorOffset.a, 0.0f, 1.0f); + frame.colorOffset.a = 0.0f; + } + }); } - } +} - // A layer frame's depth becomes a copy of its layer, named for the depth, standing where the editor draws it (the - // layer at the copy's place + depth, past the layer already there), and showing only the frames at that depth; the - // layer itself shows the rest. Groups can't stand apart in the game, so their roots go into their tracks first. - static void depths_bridge(Model& model) - { +// A layer frame's depth becomes a copy of its layer, named for the depth, standing where the editor draws it (the +// layer at the copy's place + depth, past the layer already there), and showing only the frames at that depth. The +// layer itself shows the rest. Groups can't stand apart in the game, so their roots go into their tracks first. +static void depths_bridge(Model& model) +{ auto& content = model.content; std::map, int> copyIds; - auto copy_id_get = [&](int layerId, int depth) - { - auto [it, isNew] = copyIds.try_emplace({layerId, depth}); - if (!isNew) return it->second; - auto layer = item_get(content.layers, layerId) ? *item_get(content.layers, layerId) : Layer{}; - layer.id = item_next_id_get(content.layers); - layer.name = std::format("{} (depth {:+})", layer.name, depth); - content.layers.push_back(layer); - return it->second = layer.id; + auto copy_id_get = [&](int layerId, int depth) { + auto [it, isNew] = copyIds.try_emplace({layerId, depth}); + if (!isNew) + return it->second; + auto layer = item_get(content.layers, layerId) ? *item_get(content.layers, layerId) : Layer{}; + layer.id = item_next_id_get(content.layers); + layer.name = std::format("{} (depth {:+})", layer.name, depth); + content.layers.push_back(layer); + return it->second = layer.id; + }; + auto is_depth = [](const Frame& frame) { + return frame.depth != 0; }; - auto is_depth = [](const Frame& frame) { return frame.depth != 0; }; for (int i = 0; i < model.animations_count_get(); ++i) { - auto isUsed = false; - tracks_each(model.animation_get(i)->layers, - [&](const Track& track, auto*) { isUsed |= std::ranges::any_of(track.frames, is_depth); }); - if (!isUsed) continue; - auto& animation = *model.animation_edit(i); + auto isUsed = false; + tracks_each(model.animation_get(i)->layers, + [&](const Track& track, auto*) { isUsed |= std::ranges::any_of(track.frames, is_depth); }); + if (!isUsed) + continue; + auto& animation = *model.animation_edit(i); - std::vector tracks; - for (auto& entry : animation.layers) - if (auto track = std::get_if(&entry)) - tracks.push_back(std::move(*track)); - else - { - auto& group = std::get(entry); - for (auto& groupTrack : group.tracks) - { - track_group_root_bake(groupTrack, group.root, animation.frameNum); - groupTrack.isVisible = groupTrack.isVisible && group.isVisible; - tracks.push_back(std::move(groupTrack)); - } - } + std::vector tracks; + for (auto& entry : animation.layers) + if (auto track = std::get_if(&entry)) + tracks.push_back(std::move(*track)); + else + { + auto& group = std::get(entry); + for (auto& groupTrack : group.tracks) + { + track_group_root_bake(groupTrack, group.root, animation.frameNum); + groupTrack.isVisible = groupTrack.isVisible && group.isVisible; + tracks.push_back(std::move(groupTrack)); + } + } - // Each track's place in drawing order: (its position + depth, depth), kept in position order when equal. - std::vector, Track>> placed; - auto shown_set = [](Track& track, int depth) - { - for (auto& frame : track.frames) + // Each track's place in drawing order: (its position + depth, depth), kept in position order when equal. + std::vector, Track>> placed; + auto shown_set = [](Track& track, int depth) { + for (auto& frame : track.frames) + { + frame.isVisible = frame.isVisible && frame.depth == depth; + frame.depth = 0; + } + }; + for (int position = 0; position < (int)tracks.size(); ++position) { - frame.isVisible = frame.isVisible && frame.depth == depth; - frame.depth = 0; + auto& track = tracks[position]; + std::set depths; + for (auto& frame : track.frames) + if (frame.depth != 0) + depths.insert(frame.depth); + for (auto depth : depths) + { + auto copy = track; + copy.id = copy_id_get(track.id, depth); + shown_set(copy, depth); + placed.push_back({{position + depth, depth}, std::move(copy)}); + } + shown_set(track, 0); + placed.push_back({{position, 0}, std::move(track)}); } - }; - for (int position = 0; position < (int)tracks.size(); ++position) - { - auto& track = tracks[position]; - std::set depths; - for (auto& frame : track.frames) - if (frame.depth != 0) depths.insert(frame.depth); - for (auto depth : depths) - { - auto copy = track; - copy.id = copy_id_get(track.id, depth); - shown_set(copy, depth); - placed.push_back({{position + depth, depth}, std::move(copy)}); - } - shown_set(track, 0); - placed.push_back({{position, 0}, std::move(track)}); - } - std::ranges::stable_sort(placed, {}, &std::pair, Track>::first); - animation.layers.clear(); - for (auto& [order, track] : placed) - animation.layers.emplace_back(std::move(track)); + std::ranges::stable_sort(placed, {}, &std::pair, Track>::first); + animation.layers.clear(); + for (auto& [order, track] : placed) + animation.layers.emplace_back(std::move(track)); } - } +} - // The game's copy with what the game can't show worked around (Convert and Save). - Model isaac_bridge(Model model) - { +// The game's copy with what the game can't show worked around (Convert and Save). +Model isaac_bridge(Model model) +{ alpha_offsets_bridge(model); depths_bridge(model); return model; - } +} diff --git a/src/edit/spritesheets.cpp b/src/edit/spritesheets.cpp index 629668e..b021597 100644 --- a/src/edit/spritesheets.cpp +++ b/src/edit/spritesheets.cpp @@ -10,110 +10,117 @@ #include "path.h" // Spritesheet pixel edits: the model changes in place, and a new image is returned for the document to store. - bool regions_trim(Model& model, int spritesheetId, const std::set& ids, const Image& source) - { +bool regions_trim(Model& model, int spritesheetId, const std::set& ids, const Image& source) +{ auto spritesheet = item_get(model.content.spritesheets, spritesheetId); - if (!spritesheet || !source.is_valid() || source.pixels.empty()) return false; + if (!spritesheet || !source.is_valid() || source.pixels.empty()) + return false; bool isChanged = false; for (auto id : ids) { - auto region = item_get(spritesheet->regions, id); - if (!region) continue; - - auto minPoint = glm::max(glm::ivec2(glm::min(region->crop, region->crop + region->size)), glm::ivec2(0)); - auto maxPoint = glm::min(glm::ivec2(glm::max(region->crop, region->crop + region->size)), source.size); - auto contentMin = glm::ivec2(std::numeric_limits::max()); - auto contentMax = glm::ivec2(std::numeric_limits::min()); - - for (int y = minPoint.y; y < maxPoint.y; ++y) - for (int x = minPoint.x; x < maxPoint.x; ++x) - { - auto index = ((std::size_t)y * source.size.x + x) * IMAGE_CHANNELS; - if (index + IMAGE_CHANNELS > source.pixels.size()) continue; - if (std::all_of(source.pixels.begin() + index, source.pixels.begin() + index + IMAGE_CHANNELS, - [](auto channel) { return channel == 0; })) + auto region = item_get(spritesheet->regions, id); + if (!region) continue; - contentMin = glm::min(contentMin, glm::ivec2(x, y)); - contentMax = glm::max(contentMax, glm::ivec2(x, y)); - } - if (contentMin.x == std::numeric_limits::max()) continue; + auto minPoint = glm::max(glm::ivec2(glm::min(region->crop, region->crop + region->size)), glm::ivec2(0)); + auto maxPoint = glm::min(glm::ivec2(glm::max(region->crop, region->crop + region->size)), source.size); + auto contentMin = glm::ivec2(std::numeric_limits::max()); + auto contentMax = glm::ivec2(std::numeric_limits::min()); - auto newCrop = glm::vec2(contentMin); - auto newSize = glm::vec2(contentMax - contentMin + 1); - if (region->crop == newCrop && region->size == newSize) continue; + for (int y = minPoint.y; y < maxPoint.y; ++y) + for (int x = minPoint.x; x < maxPoint.x; ++x) + { + auto index = ((std::size_t)y * source.size.x + x) * IMAGE_CHANNELS; + if (index + IMAGE_CHANNELS > source.pixels.size()) + continue; + if (std::all_of(source.pixels.begin() + index, source.pixels.begin() + index + IMAGE_CHANNELS, + [](auto channel) { return channel == 0; })) + continue; + contentMin = glm::min(contentMin, glm::ivec2(x, y)); + contentMax = glm::max(contentMax, glm::ivec2(x, y)); + } - auto previousCrop = region->crop; - region->crop = newCrop; - region->size = newSize; - if (region->origin == Origin::TOP_LEFT) - region->pivot = {}; - else if (region->origin == Origin::CENTER) - region->pivot = region->size * 0.5f; - else - region->pivot -= region->crop - previousCrop; - isChanged = true; + if (contentMin.x == std::numeric_limits::max()) + continue; + + auto newCrop = glm::vec2(contentMin); + auto newSize = glm::vec2(contentMax - contentMin + 1); + if (region->crop == newCrop && region->size == newSize) + continue; + + auto previousCrop = region->crop; + region->crop = newCrop; + region->size = newSize; + if (region->origin == Origin::TOP_LEFT) + region->pivot = {}; + else if (region->origin == Origin::CENTER) + region->pivot = region->size * 0.5f; + else + region->pivot -= region->crop - previousCrop; + isChanged = true; } return isChanged; - } +} - std::optional spritesheet_pack(Model& model, int id, const Image& sheet, int padding) - { +std::optional spritesheet_pack(Model& model, int id, const Image& sheet, int padding) +{ struct PackItem { - int regionId = -1; - glm::ivec2 source{}; - glm::ivec2 size{}; + int regionId = -1; + glm::ivec2 source{}; + glm::ivec2 size{}; }; auto spritesheet = item_get(model.content.spritesheets, id); - if (!spritesheet || !sheet.is_valid() || sheet.pixels.empty()) return {}; + if (!spritesheet || !sheet.is_valid() || sheet.pixels.empty()) + return {}; padding = std::max(0, padding); std::vector items; for (auto& region : spritesheet->regions) { - auto minPoint = glm::ivec2(glm::min(region.crop, region.crop + region.size)); - auto maxPoint = glm::ivec2(glm::max(region.crop, region.crop + region.size)); - items.push_back({region.id, minPoint, glm::max(maxPoint - minPoint, glm::ivec2(1))}); + auto minPoint = glm::ivec2(glm::min(region.crop, region.crop + region.size)); + auto maxPoint = glm::ivec2(glm::max(region.crop, region.crop + region.size)); + items.push_back({region.id, minPoint, glm::max(maxPoint - minPoint, glm::ivec2(1))}); } - std::sort(items.begin(), items.end(), - [](const PackItem& a, const PackItem& b) - { - auto areaA = a.size.x * a.size.y; - auto areaB = b.size.x * b.size.y; - return areaA != areaB ? areaA > areaB : a.regionId < b.regionId; - }); + std::sort(items.begin(), items.end(), [](const PackItem& a, const PackItem& b) { + auto areaA = a.size.x * a.size.y; + auto areaB = b.size.x * b.size.y; + return areaA != areaB ? areaA > areaB : a.regionId < b.regionId; + }); std::vector sizes{}; for (auto& item : items) - sizes.push_back(item.size + padding * 2); + sizes.push_back(item.size + padding * 2); glm::ivec2 packedSize{}; std::vector positions{}; - if (!rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0) return {}; + if (!rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0) + return {}; std::vector parts; for (int i = 0; i < (int)items.size(); ++i) - parts.push_back({&sheet, items[i].source, items[i].size, positions[i] + padding}); + parts.push_back({&sheet, items[i].source, items[i].size, positions[i] + padding}); for (auto& region : spritesheet->regions) - for (int i = 0; i < (int)items.size(); ++i) - if (items[i].regionId == region.id) region.crop = parts[i].destination; + for (int i = 0; i < (int)items.size(); ++i) + if (items[i].regionId == region.id) + region.crop = parts[i].destination; return Image::compose(parts, packedSize, sheet.is_vector()); - } +} - // Appends sheets to the first, right or below. The result is an SVG (holding any PNG sheets as images) when any of - // them is one; the first sheet's path takes the result's extension. - std::optional spritesheets_merge(Model& model, const std::set& ids, const ImageGet& image_get, - bool isAppendRight, bool isMakeRegions, bool isMakePrimaryRegion, - Origin origin) - { - if (ids.size() < 2) return {}; +// Appends sheets to the first, right or below. The result is an SVG (holding any PNG sheets as images) when any of +// them is one. The first sheet's path takes the result's extension. +std::optional spritesheets_merge(Model& model, const std::set& ids, const ImageGet& image_get, + bool isAppendRight, bool isMakeRegions, bool isMakePrimaryRegion, Origin origin) +{ + if (ids.size() < 2) + return {}; for (auto id : ids) - if (!item_get(model.content.spritesheets, id) || !image_get(id) || !image_get(id)->is_valid()) return {}; + if (!item_get(model.content.spritesheets, id) || !image_get(id) || !image_get(id)->is_valid()) + return {}; auto baseId = *ids.begin(); auto base = item_get(model.content.spritesheets, baseId); @@ -121,67 +128,70 @@ std::vector parts{{image_get(baseId), {}, mergedSize, {}}}; std::unordered_map> regionIdMap; - auto location_region_add = [&](int sourceId, glm::ivec2 crop, glm::ivec2 size) - { - auto source = item_get(model.content.spritesheets, sourceId); - Region region = {}; - region.id = item_next_id_get(base->regions); - auto stem = path_to_utf8(source->path.stem()); - region.name = stem.empty() ? std::format("#{}", sourceId) : stem; - region.crop = crop; - region.size = size; - region.pivot = origin == Origin::CENTER ? glm::vec2(size) * 0.5f : glm::vec2(); - region.origin = origin; - base->regions.push_back(region); + auto location_region_add = [&](int sourceId, glm::ivec2 crop, glm::ivec2 size) { + auto source = item_get(model.content.spritesheets, sourceId); + Region region = {}; + region.id = item_next_id_get(base->regions); + auto stem = path_to_utf8(source->path.stem()); + region.name = stem.empty() ? std::format("#{}", sourceId) : stem; + region.crop = crop; + region.size = size; + region.pivot = origin == Origin::CENTER ? glm::vec2(size) * 0.5f : glm::vec2(); + region.origin = origin; + base->regions.push_back(region); }; - if (isMakeRegions && isMakePrimaryRegion) location_region_add(baseId, {}, mergedSize); + if (isMakeRegions && isMakePrimaryRegion) + location_region_add(baseId, {}, mergedSize); for (auto id : ids) { - if (id == baseId) continue; - auto texture = image_get(id); - auto offset = isAppendRight ? glm::ivec2(mergedSize.x, 0) : glm::ivec2(0, mergedSize.y); - mergedSize = isAppendRight ? glm::ivec2(mergedSize.x + texture->size.x, std::max(mergedSize.y, texture->size.y)) - : glm::ivec2(std::max(mergedSize.x, texture->size.x), mergedSize.y + texture->size.y); - parts.push_back({texture, {}, texture->size, offset}); - if (!isMakeRegions) continue; + if (id == baseId) + continue; + auto texture = image_get(id); + auto offset = isAppendRight ? glm::ivec2(mergedSize.x, 0) : glm::ivec2(0, mergedSize.y); + mergedSize = isAppendRight + ? glm::ivec2(mergedSize.x + texture->size.x, std::max(mergedSize.y, texture->size.y)) + : glm::ivec2(std::max(mergedSize.x, texture->size.x), mergedSize.y + texture->size.y); + parts.push_back({texture, {}, texture->size, offset}); + if (!isMakeRegions) + continue; - location_region_add(id, offset, texture->size); - for (auto sourceRegion : item_get(model.content.spritesheets, id)->regions) - { - auto sourceRegionId = sourceRegion.id; - sourceRegion.id = item_next_id_get(base->regions); - sourceRegion.uid = uid_next(); - sourceRegion.crop += offset; - base->regions.push_back(sourceRegion); - regionIdMap[id][sourceRegionId] = sourceRegion.id; - } + location_region_add(id, offset, texture->size); + for (auto sourceRegion : item_get(model.content.spritesheets, id)->regions) + { + auto sourceRegionId = sourceRegion.id; + sourceRegion.id = item_next_id_get(base->regions); + sourceRegion.uid = uid_next(); + sourceRegion.crop += offset; + base->regions.push_back(sourceRegion); + regionIdMap[id][sourceRegionId] = sourceRegion.id; + } } std::unordered_map layerSpritesheetBefore; for (auto& layer : model.content.layers) - if (ids.contains(layer.spritesheetId)) - { - layerSpritesheetBefore[layer.id] = layer.spritesheetId; - layer.spritesheetId = baseId; - } + if (ids.contains(layer.spritesheetId)) + { + layerSpritesheetBefore[layer.id] = layer.spritesheetId; + layer.spritesheetId = baseId; + } for (int i = 0; i < model.animations_count_get(); ++i) - tracks_each(model.animation_edit(i)->layers, - [&](Track& track, auto*) - { - auto before = layerSpritesheetBefore.find(track.id); - if (before == layerSpritesheetBefore.end() || before->second == baseId) return; - auto& remap = regionIdMap[before->second]; - for (auto& frame : track.frames) - if (frame.regionId != -1) - frame.regionId = remap.contains(frame.regionId) ? remap.at(frame.regionId) : -1; - }); + tracks_each(model.animation_edit(i)->layers, [&](Track& track, auto*) { + auto before = layerSpritesheetBefore.find(track.id); + if (before == layerSpritesheetBefore.end() || before->second == baseId) + return; + auto& remap = regionIdMap[before->second]; + for (auto& frame : track.frames) + if (frame.regionId != -1) + frame.regionId = remap.contains(frame.regionId) ? remap.at(frame.regionId) : -1; + }); auto isVector = std::ranges::any_of(parts, [](const ImagePart& part) { return part.image->is_vector(); }); if (isVector != is_path_extension(base->path, SVG_EXTENSION)) - base->path.replace_extension(isVector ? SVG_EXTENSION : PNG_EXTENSION); - std::erase_if(model.content.spritesheets, [&](const Spritesheet& spritesheet) - { return spritesheet.id != baseId && ids.contains(spritesheet.id); }); + base->path.replace_extension(isVector ? SVG_EXTENSION : PNG_EXTENSION); + std::erase_if(model.content.spritesheets, [&](const Spritesheet& spritesheet) { + return spritesheet.id != baseId && ids.contains(spritesheet.id); + }); return Image::compose(parts, mergedSize, isVector); - } +} diff --git a/src/edit/tracks.cpp b/src/edit/tracks.cpp index c16b6ef..78628d5 100644 --- a/src/edit/tracks.cpp +++ b/src/edit/tracks.cpp @@ -1,42 +1,44 @@ #include "edit/edit.h" - static std::vector* track_entries_edit(Model& model, int animationIndex, int type) - { - if (type != LAYER && type != NULL_) return nullptr; +static std::vector* track_entries_edit(Model& model, int animationIndex, int type) +{ + if (type != LAYER && type != NULL_) + return nullptr; auto animation = model.animation_edit(animationIndex); return animation ? &animation_entries_get(*animation, type) : nullptr; - } +} - Uids items_remove(Model& model, int animationIndex, const std::map>& ids, - const std::map>& groupIds) - { +Uids items_remove(Model& model, int animationIndex, const std::map>& ids, + const std::map>& groupIds) +{ for (auto type : {LAYER, NULL_}) { - auto typeIds = ids.contains(type) ? ids.at(type) : std::set{}; - auto typeGroupIds = groupIds.contains(type) ? groupIds.at(type) : std::set{}; - if (typeIds.empty() && typeGroupIds.empty()) continue; - auto entries = track_entries_edit(model, animationIndex, type); - if (!entries) continue; + auto typeIds = ids.contains(type) ? ids.at(type) : std::set{}; + auto typeGroupIds = groupIds.contains(type) ? groupIds.at(type) : std::set{}; + if (typeIds.empty() && typeGroupIds.empty()) + continue; + auto entries = track_entries_edit(model, animationIndex, type); + if (!entries) + continue; - std::erase_if(*entries, - [&](TrackEntry& entry) - { - if (auto group = std::get_if(&entry)) - { - std::erase_if(group->tracks, [&](const Track& track) { return typeIds.contains(track.id); }); - return typeGroupIds.contains(group->id); - } - return typeIds.contains(std::get(entry).id); - }); + std::erase_if(*entries, [&](TrackEntry& entry) { + if (auto group = std::get_if(&entry)) + { + std::erase_if(group->tracks, [&](const Track& track) { return typeIds.contains(track.id); }); + return typeGroupIds.contains(group->id); + } + return typeIds.contains(std::get(entry).id); + }); } return {}; - } +} - // Wraps ungrouped tracks in a new group placed where the first of them was. - Uids items_group(Model& model, int animationIndex, int type, const std::set& ids, const std::string& name) - { +// Wraps ungrouped tracks in a new group placed where the first of them was. +Uids items_group(Model& model, int animationIndex, int type, const std::set& ids, const std::string& name) +{ auto entries = track_entries_edit(model, animationIndex, type); - if (!entries) return {}; + if (!entries) + return {}; int nextId = 0; groups_each(*entries, [&](const TrackGroup& group) { nextId = std::max(nextId, group.id + 1); }); @@ -45,153 +47,157 @@ auto insertIndex = -1; for (int i = 0; i < (int)entries->size(); ++i) { - auto track = std::get_if(&(*entries)[i]); - if (!track || !ids.contains(track->id)) continue; - if (insertIndex == -1) insertIndex = i; - group.tracks.push_back(std::move(*track)); - entries->erase(entries->begin() + i--); + auto track = std::get_if(&(*entries)[i]); + if (!track || !ids.contains(track->id)) + continue; + if (insertIndex == -1) + insertIndex = i; + group.tracks.push_back(std::move(*track)); + entries->erase(entries->begin() + i--); } - if (insertIndex == -1) return {}; + if (insertIndex == -1) + return {}; auto uid = group.uid; entries->insert(entries->begin() + insertIndex, std::move(group)); return {uid}; - } +} - // Moves tracks and whole groups next to (or into) a target row. Layers are listed bottom-up, so for them "after" on - // screen is "before" in the file. - Uids items_move(Model& model, int animationIndex, int type, const std::set& ids, const std::set& groupIds, - RowTarget target, bool isDropAfter, bool isDropIntoGroup) - { - if (target.groupId != -1 && groupIds.contains(target.groupId)) return {}; - if (target.isGroup && groupIds.contains(target.id)) return {}; +// Moves tracks and whole groups next to (or into) a target row. Layers are listed bottom-up, so for them "after" on +// screen is "before" in the file. +Uids items_move(Model& model, int animationIndex, int type, const std::set& ids, const std::set& groupIds, + RowTarget target, bool isDropAfter, bool isDropIntoGroup) +{ + if (target.groupId != -1 && groupIds.contains(target.groupId)) + return {}; + if (target.isGroup && groupIds.contains(target.id)) + return {}; auto entries = track_entries_edit(model, animationIndex, type); - if (!entries) return {}; + if (!entries) + return {}; std::vector movedTracks; std::vector movedGroups; - std::erase_if(*entries, - [&](TrackEntry& entry) - { - if (auto group = std::get_if(&entry)) - { - if (groupIds.contains(group->id)) - { - movedGroups.push_back(std::move(entry)); - return true; - } - std::erase_if(group->tracks, - [&](Track& track) - { - if (!ids.contains(track.id)) return false; - movedTracks.push_back(std::move(track)); - return true; - }); - return false; - } - auto& track = std::get(entry); - if (!ids.contains(track.id)) return false; - movedTracks.push_back(std::move(track)); - return true; - }); - if (movedTracks.empty() && movedGroups.empty()) return {}; + std::erase_if(*entries, [&](TrackEntry& entry) { + if (auto group = std::get_if(&entry)) + { + if (groupIds.contains(group->id)) + { + movedGroups.push_back(std::move(entry)); + return true; + } + std::erase_if(group->tracks, [&](Track& track) { + if (!ids.contains(track.id)) + return false; + movedTracks.push_back(std::move(track)); + return true; + }); + return false; + } + auto& track = std::get(entry); + if (!ids.contains(track.id)) + return false; + movedTracks.push_back(std::move(track)); + return true; + }); + if (movedTracks.empty() && movedGroups.empty()) + return {}; auto isAfter = type == LAYER ? !isDropAfter : isDropAfter; - auto group_find = [&](int groupId) - { - return std::ranges::find_if(*entries, - [&](const TrackEntry& entry) - { - auto group = std::get_if(&entry); - return group && group->id == groupId; - }); + auto group_find = [&](int groupId) { + return std::ranges::find_if(*entries, [&](const TrackEntry& entry) { + auto group = std::get_if(&entry); + return group && group->id == groupId; + }); }; // Where top-level items go: beside the target row, or beside the group that holds it. auto topIndex = (int)entries->size(); if (target.isGroup || target.groupId != -1) { - auto group = group_find(target.isGroup ? target.id : target.groupId); - if (group != entries->end()) topIndex = (int)(group - entries->begin()) + isAfter; + auto group = group_find(target.isGroup ? target.id : target.groupId); + if (group != entries->end()) + topIndex = (int)(group - entries->begin()) + isAfter; } else if (target.type == type) { - auto track = std::ranges::find_if(*entries, - [&](const TrackEntry& entry) - { - auto track = std::get_if(&entry); - return track && track->id == target.id; - }); - if (track != entries->end()) topIndex = (int)(track - entries->begin()) + isAfter; + auto track = std::ranges::find_if(*entries, [&](const TrackEntry& entry) { + auto track = std::get_if(&entry); + return track && track->id == target.id; + }); + if (track != entries->end()) + topIndex = (int)(track - entries->begin()) + isAfter; } auto intoGroupId = target.isGroup && isDropIntoGroup ? target.id : !target.isGroup ? target.groupId : -1; auto intoGroup = intoGroupId == -1 ? entries->end() : group_find(intoGroupId); if (intoGroup != entries->end()) { - // Into a group header lands just under it on screen; beside a grouped track lands beside it. - auto& tracks = std::get(*intoGroup).tracks; - auto beside = std::ranges::find_if(tracks, [&](const Track& track) { return track.id == target.id; }); - auto position = target.isGroup ? (type == LAYER ? tracks.end() : tracks.begin()) - : beside != tracks.end() ? beside + isAfter - : tracks.end(); - tracks.insert(position, std::make_move_iterator(movedTracks.begin()), std::make_move_iterator(movedTracks.end())); - movedTracks.clear(); + // Into a group header lands just under it on screen. Beside a grouped track lands beside it. + auto& tracks = std::get(*intoGroup).tracks; + auto beside = std::ranges::find_if(tracks, [&](const Track& track) { return track.id == target.id; }); + auto position = target.isGroup ? (type == LAYER ? tracks.end() : tracks.begin()) + : beside != tracks.end() ? beside + isAfter + : tracks.end(); + tracks.insert(position, std::make_move_iterator(movedTracks.begin()), + std::make_move_iterator(movedTracks.end())); + movedTracks.clear(); } std::vector topMoved; for (auto& track : movedTracks) - topMoved.emplace_back(std::move(track)); + topMoved.emplace_back(std::move(track)); topMoved.insert(topMoved.end(), std::make_move_iterator(movedGroups.begin()), std::make_move_iterator(movedGroups.end())); entries->insert(entries->begin() + std::clamp(topIndex, 0, (int)entries->size()), std::make_move_iterator(topMoved.begin()), std::make_move_iterator(topMoved.end())); return {}; - } +} - Uids animation_length_fit(Model& model, int animationIndex) - { - if (auto animation = model.animation_edit(animationIndex)) animation->frameNum = animation_length_get(*animation); +Uids animation_length_fit(Model& model, int animationIndex) +{ + if (auto animation = model.animation_edit(animationIndex)) + animation->frameNum = animation_length_get(*animation); return {}; - } +} - // Adds a layer or null (or updates the one with the item's id) and gives it a track in one or every animation. - // Adds track `id` (a new item, from `layer` or `null`, at -1) to an animation or all of them. - int item_add(Model& model, ItemType type, int animationIndex, int id, Layer layer, Null null, int insertBeforeId, - Destination destination) - { +// Adds a layer or null (or updates the one with the item's id) and gives it a track in one or every animation. +// Adds track `id` (a new item, from `layer` or `null`, at -1) to an animation or all of them. +int item_add(Model& model, ItemType type, int animationIndex, int id, Layer layer, Null null, int insertBeforeId, + Destination destination) +{ auto& content = model.content; - auto item_insert = [&](auto& items, auto item) - { - if (id == -1) id = item_next_id_get(items); - if (item_get(items, id)) return; - item.id = id; - items.push_back(item); + auto item_insert = [&](auto& items, auto item) { + if (id == -1) + id = item_next_id_get(items); + if (item_get(items, id)) + return; + item.id = id; + items.push_back(item); }; - if (!item_get(content.spritesheets, layer.spritesheetId)) layer.spritesheetId = 0; + if (!item_get(content.spritesheets, layer.spritesheetId)) + layer.spritesheetId = 0; if (type == ItemType::LAYER) - item_insert(content.layers, layer); + item_insert(content.layers, layer); else if (type == ItemType::NULL_) - item_insert(content.nulls, null); + item_insert(content.nulls, null); else - return -1; + return -1; - auto add = [&](int index) - { - if (model.track_get({index, (int)type, id})) return; - auto& entries = animation_entries_get(*model.animation_edit(index), (int)type); - auto before = std::ranges::find_if(entries, - [&](const TrackEntry& entry) - { - auto track = std::get_if(&entry); - return track && track->id == insertBeforeId; - }); - entries.insert(insertBeforeId == -1 ? entries.end() : before, Track{.type = type, .id = id}); + auto add = [&](int index) { + if (model.track_get({index, (int)type, id})) + return; + auto& entries = animation_entries_get(*model.animation_edit(index), (int)type); + auto before = std::ranges::find_if(entries, [&](const TrackEntry& entry) { + auto track = std::get_if(&entry); + return track && track->id == insertBeforeId; + }); + entries.insert(insertBeforeId == -1 ? entries.end() : before, Track{.type = type, .id = id}); }; if (destination == DESTINATION_ALL) - for (int i = 0; i < model.animations_count_get(); ++i) - add(i); + for (int i = 0; i < model.animations_count_get(); ++i) + add(i); else if (model.animation_get(animationIndex)) - add(animationIndex); + add(animationIndex); return id; - } +} diff --git a/src/file.cpp b/src/file.cpp index 68a5ca9..4b63288 100644 --- a/src/file.cpp +++ b/src/file.cpp @@ -2,65 +2,82 @@ #include - File::File(const std::filesystem::path& path, const char* mode) { open(path, mode); } +File::File(const std::filesystem::path& path, const char* mode) +{ + open(path, mode); +} - File::~File() { close(); } +File::~File() +{ + close(); +} - bool File::open(const std::filesystem::path& path, const char* mode) - { +bool File::open(const std::filesystem::path& path, const char* mode) +{ close(); #ifdef _WIN32 std::wstring wideMode = {}; if (mode) - for (auto character = mode; *character; ++character) - wideMode.push_back((wchar_t)*character); + for (auto character = mode; *character; ++character) + wideMode.push_back((wchar_t)*character); else - wideMode = L"rb"; + wideMode = L"rb"; handle = _wfopen(path.native().c_str(), wideMode.c_str()); #else handle = std::fopen(path.string().c_str(), mode); #endif return handle != nullptr; - } +} - int File::close() - { +int File::close() +{ if (handle) { - auto result = std::fclose(handle); - handle = nullptr; - return result; + auto result = std::fclose(handle); + handle = nullptr; + return result; } return -1; - } +} - FILE* File::get() const { return handle; } +FILE* File::get() const +{ + return handle; +} - File::operator bool() const { return handle != nullptr; } +File::operator bool() const +{ + return handle != nullptr; +} - bool file_text_load(const std::filesystem::path& path, std::string* output, const char* mode) +bool file_text_load(const std::filesystem::path& path, std::string* output, const char* mode) +{ + if (!output) + return false; + + File file(path, mode); + if (!file) + return false; + + output->clear(); + std::array buffer = {}; + while (true) { - if (!output) return false; - - File file(path, mode); - if (!file) return false; - - output->clear(); - std::array buffer = {}; - while (true) - { auto read = std::fread(buffer.data(), 1, buffer.size(), file.get()); - if (read > 0) output->append(buffer.data(), read); - if (read < buffer.size()) return std::feof(file.get()) != 0; - } + if (read > 0) + output->append(buffer.data(), read); + if (read < buffer.size()) + return std::feof(file.get()) != 0; } +} - bool file_text_save(const std::filesystem::path& path, std::string_view data, const char* mode) - { - File file(path, mode); - if (!file) return false; +bool file_text_save(const std::filesystem::path& path, std::string_view data, const char* mode) +{ + File file(path, mode); + if (!file) + return false; - return std::fwrite(data.data(), 1, data.size(), file.get()) == data.size(); - } + return std::fwrite(data.data(), 1, data.size(), file.get()) == data.size(); +} diff --git a/src/file.h b/src/file.h index cfbf408..e35069e 100644 --- a/src/file.h +++ b/src/file.h @@ -4,9 +4,9 @@ #include #include - class File - { - public: +class File +{ +public: File() = default; File(const std::filesystem::path&, const char* mode); ~File(); @@ -16,9 +16,9 @@ FILE* get() const; explicit operator bool() const; - private: +private: FILE* handle = nullptr; - }; +}; - bool file_text_load(const std::filesystem::path&, std::string*, const char* mode = "rb"); - bool file_text_save(const std::filesystem::path&, std::string_view, const char* mode = "wb"); +bool file_text_load(const std::filesystem::path&, std::string*, const char* mode = "rb"); +bool file_text_save(const std::filesystem::path&, std::string_view, const char* mode = "wb"); diff --git a/src/font.cpp b/src/font.cpp index 12d5f32..38b1eda 100644 --- a/src/font.cpp +++ b/src/font.cpp @@ -1,52 +1,56 @@ #include "font.h" - Font::Font() = default; +Font::Font() = default; - Font::Font(void* data, size_t length, int size) - { +Font::Font(void* data, size_t length, int size) +{ ImFontConfig config; config.FontDataOwnedByAtlas = false; pointer = ImGui::GetIO().Fonts->AddFontFromMemoryTTF(data, length, size, &config); - } +} - Font::Font(const char* path, int size, int number) - { +Font::Font(const char* path, int size, int number) +{ ImFontConfig config; config.FontDataOwnedByAtlas = false; config.FontNo = number; pointer = ImGui::GetIO().Fonts->AddFontFromFileTTF(path, size); - } +} - void Font::append(void* data, size_t length, int size) - { +void Font::append(void* data, size_t length, int size) +{ ImFontConfig config; config.MergeMode = true; config.FontDataOwnedByAtlas = false; ImGui::GetIO().Fonts->AddFontFromMemoryTTF(data, length, size, &config); - } +} - bool Font::append(const char* path, int size, int number) - { +bool Font::append(const char* path, int size, int number) +{ ImFontConfig config; config.MergeMode = true; config.FontDataOwnedByAtlas = false; config.FontNo = number; return ImGui::GetIO().Fonts->AddFontFromFileTTF(path, size, &config); - } +} - Font::~Font() - { - if (get()) ImGui::GetIO().Fonts->RemoveFont(pointer); - } +Font::~Font() +{ + if (get()) + ImGui::GetIO().Fonts->RemoveFont(pointer); +} - ImFont* Font::get() { return pointer; } +ImFont* Font::get() +{ + return pointer; +} - Font& Font::operator=(Font&& other) noexcept - { +Font& Font::operator=(Font&& other) noexcept +{ if (this != &other) { - pointer = other.pointer; - other.pointer = nullptr; + pointer = other.pointer; + other.pointer = nullptr; } return *this; - } +} diff --git a/src/font.h b/src/font.h index 2c6355f..f3750b1 100644 --- a/src/font.h +++ b/src/font.h @@ -3,25 +3,26 @@ #include #include "embed.h" - constexpr auto FONT_SIZE = 16; - constexpr auto FONT_SIZE_LARGE = 32; +constexpr auto FONT_SIZE = 16; +constexpr auto FONT_SIZE_LARGE = 32; - enum FontStyle - { +enum FontStyle +{ FONT_REGULAR, FONT_ITALICS, FONT_BOLD, FONT_BOLD_ITALICS, FONT_COUNT - }; +}; - constexpr const Embed* FONTS[FONT_COUNT] = {&FONT_REGULAR_TTF, &FONT_ITALICS_TTF, &FONT_BOLD_TTF, &FONT_BOLD_ITALICS_TTF}; +constexpr const Embed* FONTS[FONT_COUNT] = {&FONT_REGULAR_TTF, &FONT_ITALICS_TTF, &FONT_BOLD_TTF, + &FONT_BOLD_ITALICS_TTF}; - class Font - { +class Font +{ ImFont* pointer = nullptr; - public: +public: Font(); Font(void*, size_t, int); Font(const char* path, int size, int number = 0); @@ -30,4 +31,4 @@ ~Font(); ImFont* get(); Font& operator=(Font&&) noexcept; - }; +}; diff --git a/src/framebuffer.cpp b/src/framebuffer.cpp index 43dde62..161c735 100644 --- a/src/framebuffer.cpp +++ b/src/framebuffer.cpp @@ -4,25 +4,26 @@ using namespace glm; - Framebuffer::Framebuffer() - { +Framebuffer::Framebuffer() +{ glGenFramebuffers(1, &fbo); glGenRenderbuffers(1, &rbo); glGenTextures(1, &texture); set(); - } +} - Framebuffer::~Framebuffer() - { - if (!is_valid()) return; +Framebuffer::~Framebuffer() +{ + if (!is_valid()) + return; glDeleteFramebuffers(1, &fbo); glDeleteRenderbuffers(1, &rbo); glDeleteTextures(1, &texture); - } +} - void Framebuffer::set() - { +void Framebuffer::set() +{ glBindFramebuffer(GL_FRAMEBUFFER, fbo); glBindTexture(GL_TEXTURE_2D, texture); @@ -37,26 +38,26 @@ using namespace glm; glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); glBindFramebuffer(GL_FRAMEBUFFER, 0); - } +} - void Framebuffer::resize_check() - { +void Framebuffer::resize_check() +{ if (size != previousSize) { - set(); - previousSize = size; + set(); + previousSize = size; } - } +} - void Framebuffer::size_set(vec2 size) - { +void Framebuffer::size_set(vec2 size) +{ previousSize = this->size; this->size = size; resize_check(); - } +} - std::vector Framebuffer::pixels_get() const - { +std::vector Framebuffer::pixels_get() const +{ auto count = size.x * size.y * IMAGE_CHANNELS; std::vector pixels(count); @@ -67,18 +68,34 @@ using namespace glm; glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); return pixels; - } +} - void Framebuffer::clear(vec4 color) const - { +void Framebuffer::clear(vec4 color) const +{ glEnable(GL_BLEND); glClearColor(color.r, color.g, color.b, color.a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - if (color.a <= 0.0f) glDisable(GL_BLEND); - } + if (color.a <= 0.0f) + glDisable(GL_BLEND); +} - bool Framebuffer::is_valid() const { return fbo != 0; } - void Framebuffer::viewport_set() const { glViewport(0, 0, size.x, size.y); } - void Framebuffer::bind() const { glBindFramebuffer(GL_FRAMEBUFFER, fbo); } - void Framebuffer::unbind() const { glBindFramebuffer(GL_FRAMEBUFFER, 0); } +bool Framebuffer::is_valid() const +{ + return fbo != 0; +} + +void Framebuffer::viewport_set() const +{ + glViewport(0, 0, size.x, size.y); +} + +void Framebuffer::bind() const +{ + glBindFramebuffer(GL_FRAMEBUFFER, fbo); +} + +void Framebuffer::unbind() const +{ + glBindFramebuffer(GL_FRAMEBUFFER, 0); +} diff --git a/src/framebuffer.h b/src/framebuffer.h index 363b0f6..7896491 100644 --- a/src/framebuffer.h +++ b/src/framebuffer.h @@ -3,14 +3,14 @@ #include #include - class Framebuffer - { - public: +class Framebuffer +{ +public: enum class Type { - UNDERLAY, - LAYER, - OVERLAY, + UNDERLAY, + LAYER, + OVERLAY, }; GLuint fbo = 0; @@ -18,7 +18,7 @@ GLuint texture = 0; glm::vec2 size{}; glm::vec2 previousSize{}; - GLint filter = GL_LINEAR; // how the texture is sampled when drawn scaled; takes effect on the next resize + GLint filter = GL_LINEAR; // how the texture is sampled when drawn scaled. Takes effect on the next resize Framebuffer(); ~Framebuffer(); @@ -32,4 +32,4 @@ bool is_valid() const; void bind() const; void unbind() const; - }; +}; diff --git a/src/friends.h b/src/friends.h index f937009..41e7500 100644 --- a/src/friends.h +++ b/src/friends.h @@ -2,29 +2,29 @@ #include "embed.h" - struct FriendInfo - { +struct FriendInfo +{ const char* name = nullptr; const Embed* png = nullptr; const Embed* anm2 = nullptr; - }; +}; #define FRIENDS_LIST \ - X(FRIEND_MEAT_BOY, "Meat Boy", FRIENDS_MEAT_BOY) \ - X(FRIEND_ISAAC, "Isaac", FRIENDS_ISAAC) \ - X(FRIEND_STACY, "Stacy", FRIENDS_STACY) \ - X(FRIEND_ASH, "Ash", FRIENDS_ASH) + X(FRIEND_MEAT_BOY, "Meat Boy", FRIENDS_MEAT_BOY) \ + X(FRIEND_ISAAC, "Isaac", FRIENDS_ISAAC) \ + X(FRIEND_STACY, "Stacy", FRIENDS_STACY) \ + X(FRIEND_ASH, "Ash", FRIENDS_ASH) - enum Friend - { +enum Friend +{ #define X(symbol, name, embed) symbol, FRIENDS_LIST #undef X FRIEND_COUNT - }; +}; - constexpr FriendInfo FRIENDS[FRIEND_COUNT] = { +constexpr FriendInfo FRIENDS[FRIEND_COUNT] = { #define X(symbol, name, embed) {name, &embed##_PNG, &embed##_ANM2}, - FRIENDS_LIST + FRIENDS_LIST #undef X - }; +}; diff --git a/src/icon.h b/src/icon.h index 2157f49..7d6fb6a 100644 --- a/src/icon.h +++ b/src/icon.h @@ -2,75 +2,75 @@ #include "embed.h" #include - constexpr auto ICON_SIZE_SMALL = glm::ivec2(64, 64); - constexpr auto ICON_SIZE_NORMAL = glm::ivec2(128, 128); - constexpr auto ICON_SIZE_LARGE = glm::ivec2(256, 256); - constexpr auto ICON_SIZE_HUGE = glm::ivec2(512, 512); +constexpr auto ICON_SIZE_SMALL = glm::ivec2(64, 64); +constexpr auto ICON_SIZE_NORMAL = glm::ivec2(128, 128); +constexpr auto ICON_SIZE_LARGE = glm::ivec2(256, 256); +constexpr auto ICON_SIZE_HUGE = glm::ivec2(512, 512); #define SVG_LIST \ - X(ICON_NONE, &ICON_NONE_SVG, ICON_SIZE_SMALL) \ - X(ICON_FILE, &ICON_FILE_SVG, ICON_SIZE_NORMAL) \ - X(ICON_FOLDER, &ICON_FOLDER_SVG, ICON_SIZE_NORMAL) \ - X(ICON_FOLDER_OPEN, &ICON_FOLDER_OPEN_SVG, ICON_SIZE_NORMAL) \ - X(ICON_CLOSE, &ICON_CLOSE_SVG, ICON_SIZE_NORMAL) \ - X(ICON_ROOT, &ICON_ROOT_SVG, ICON_SIZE_NORMAL) \ - X(ICON_LAYER, &ICON_LAYER_SVG, ICON_SIZE_NORMAL) \ - X(ICON_NULL, &ICON_NULL_SVG, ICON_SIZE_NORMAL) \ - X(ICON_SOUND, &ICON_SOUND_SVG, ICON_SIZE_NORMAL) \ - X(ICON_SHADER, &ICON_SHADER_SVG, ICON_SIZE_NORMAL) \ - X(ICON_TRIGGERS, &ICON_TRIGGERS_SVG, ICON_SIZE_NORMAL) \ - X(ICON_VISIBLE, &ICON_VISIBLE_SVG, ICON_SIZE_NORMAL) \ - X(ICON_INVISIBLE, &ICON_INVISIBLE_SVG, ICON_SIZE_NORMAL) \ - X(ICON_SHOW_RECT, &ICON_SHOW_RECT_SVG, ICON_SIZE_NORMAL) \ - X(ICON_HIDE_RECT, &ICON_HIDE_RECT_SVG, ICON_SIZE_NORMAL) \ - X(ICON_SHOW_UNUSED, &ICON_SHOW_UNUSED_SVG, ICON_SIZE_NORMAL) \ - X(ICON_HIDE_UNUSED, &ICON_HIDE_UNUSED_SVG, ICON_SIZE_NORMAL) \ - X(ICON_SHOW_LAYERS, &ICON_SHOW_LAYERS_SVG, ICON_SIZE_NORMAL) \ - X(ICON_HIDE_LAYERS, &ICON_HIDE_LAYERS_SVG, ICON_SIZE_NORMAL) \ - X(ICON_OVER, &ICON_OVER_SVG, ICON_SIZE_NORMAL) \ - X(ICON_UNDER, &ICON_UNDER_SVG, ICON_SIZE_NORMAL) \ - X(ICON_PAN, &ICON_PAN_SVG, ICON_SIZE_NORMAL) \ - X(ICON_MOVE, &ICON_MOVE_SVG, ICON_SIZE_NORMAL) \ - X(ICON_ROTATE, &ICON_ROTATE_SVG, ICON_SIZE_NORMAL) \ - X(ICON_SCALE, &ICON_SCALE_SVG, ICON_SIZE_NORMAL) \ - X(ICON_SKEW, &ICON_SKEW_SVG, ICON_SIZE_NORMAL) \ - X(ICON_CROP, &ICON_CROP_SVG, ICON_SIZE_NORMAL) \ - X(ICON_DRAW, &ICON_DRAW_SVG, ICON_SIZE_NORMAL) \ - X(ICON_ERASE, &ICON_ERASE_SVG, ICON_SIZE_NORMAL) \ - X(ICON_COLOR_PICKER, &ICON_COLOR_PICKER_SVG, ICON_SIZE_NORMAL) \ - X(ICON_UNDO, &ICON_UNDO_SVG, ICON_SIZE_NORMAL) \ - X(ICON_REDO, &ICON_REDO_SVG, ICON_SIZE_NORMAL) \ - X(ICON_ANIMATION, &ICON_ANIMATION_SVG, ICON_SIZE_NORMAL) \ - X(ICON_SPRITESHEET, &ICON_SPRITESHEET_SVG, ICON_SIZE_NORMAL) \ - X(ICON_EVENT, &ICON_EVENT_SVG, ICON_SIZE_NORMAL) \ - X(ICON_INTERPOLATED, &ICON_INTERPOLATED_SVG, ICON_SIZE_NORMAL) \ - X(ICON_UNINTERPOLATED, &ICON_UNINTERPOLATED_SVG, ICON_SIZE_NORMAL) \ - X(ICON_EASE_IN, &ICON_EASE_IN_SVG, ICON_SIZE_NORMAL) \ - X(ICON_EASE_OUT, &ICON_EASE_OUT_SVG, ICON_SIZE_NORMAL) \ - X(ICON_EASE_IN_OUT, &ICON_EASE_IN_OUT_SVG, ICON_SIZE_NORMAL) \ - X(ICON_TRIGGER, &ICON_TRIGGER_SVG, ICON_SIZE_NORMAL) \ - X(ICON_PLAYHEAD, &ICON_PLAYHEAD_SVG, ICON_SIZE_NORMAL) \ - X(ICON_PIVOT, &ICON_PIVOT_SVG, ICON_SIZE_NORMAL) \ - X(ICON_POINT, &ICON_UNINTERPOLATED_SVG, ICON_SIZE_NORMAL) \ - X(ICON_TARGET, &ICON_TARGET_SVG, ICON_SIZE_HUGE) \ - X(ICON_TARGET_ALT, &ICON_TARGET_ALT_SVG, ICON_SIZE_HUGE) + X(ICON_NONE, &ICON_NONE_SVG, ICON_SIZE_SMALL) \ + X(ICON_FILE, &ICON_FILE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_FOLDER, &ICON_FOLDER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_FOLDER_OPEN, &ICON_FOLDER_OPEN_SVG, ICON_SIZE_NORMAL) \ + X(ICON_CLOSE, &ICON_CLOSE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_ROOT, &ICON_ROOT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_LAYER, &ICON_LAYER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_NULL, &ICON_NULL_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SOUND, &ICON_SOUND_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SHADER, &ICON_SHADER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_TRIGGERS, &ICON_TRIGGERS_SVG, ICON_SIZE_NORMAL) \ + X(ICON_VISIBLE, &ICON_VISIBLE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_INVISIBLE, &ICON_INVISIBLE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SHOW_RECT, &ICON_SHOW_RECT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_HIDE_RECT, &ICON_HIDE_RECT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SHOW_UNUSED, &ICON_SHOW_UNUSED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_HIDE_UNUSED, &ICON_HIDE_UNUSED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SHOW_LAYERS, &ICON_SHOW_LAYERS_SVG, ICON_SIZE_NORMAL) \ + X(ICON_HIDE_LAYERS, &ICON_HIDE_LAYERS_SVG, ICON_SIZE_NORMAL) \ + X(ICON_OVER, &ICON_OVER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_UNDER, &ICON_UNDER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_PAN, &ICON_PAN_SVG, ICON_SIZE_NORMAL) \ + X(ICON_MOVE, &ICON_MOVE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_ROTATE, &ICON_ROTATE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SCALE, &ICON_SCALE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SKEW, &ICON_SKEW_SVG, ICON_SIZE_NORMAL) \ + X(ICON_CROP, &ICON_CROP_SVG, ICON_SIZE_NORMAL) \ + X(ICON_DRAW, &ICON_DRAW_SVG, ICON_SIZE_NORMAL) \ + X(ICON_ERASE, &ICON_ERASE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_COLOR_PICKER, &ICON_COLOR_PICKER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_UNDO, &ICON_UNDO_SVG, ICON_SIZE_NORMAL) \ + X(ICON_REDO, &ICON_REDO_SVG, ICON_SIZE_NORMAL) \ + X(ICON_ANIMATION, &ICON_ANIMATION_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SPRITESHEET, &ICON_SPRITESHEET_SVG, ICON_SIZE_NORMAL) \ + X(ICON_EVENT, &ICON_EVENT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_INTERPOLATED, &ICON_INTERPOLATED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_UNINTERPOLATED, &ICON_UNINTERPOLATED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_EASE_IN, &ICON_EASE_IN_SVG, ICON_SIZE_NORMAL) \ + X(ICON_EASE_OUT, &ICON_EASE_OUT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_EASE_IN_OUT, &ICON_EASE_IN_OUT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_TRIGGER, &ICON_TRIGGER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_PLAYHEAD, &ICON_PLAYHEAD_SVG, ICON_SIZE_NORMAL) \ + X(ICON_PIVOT, &ICON_PIVOT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_POINT, &ICON_UNINTERPOLATED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_TARGET, &ICON_TARGET_SVG, ICON_SIZE_HUGE) \ + X(ICON_TARGET_ALT, &ICON_TARGET_ALT_SVG, ICON_SIZE_HUGE) - enum Icon - { +enum Icon +{ #define X(name, data, size) name, SVG_LIST #undef X ICON_COUNT - }; +}; - struct IconInfo - { +struct IconInfo +{ const Embed* svg = nullptr; glm::ivec2 size{}; - }; +}; - constexpr IconInfo ICONS[ICON_COUNT] = { +constexpr IconInfo ICONS[ICON_COUNT] = { #define X(name, data, size) {data, size}, - SVG_LIST + SVG_LIST #undef X - }; +}; diff --git a/src/image.cpp b/src/image.cpp index 3ce887a..9196e30 100644 --- a/src/image.cpp +++ b/src/image.cpp @@ -13,9 +13,9 @@ #include #if defined(__clang__) || defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wmissing-field-initializers" - #pragma GCC diagnostic ignored "-Wunused-function" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#pragma GCC diagnostic ignored "-Wunused-function" #endif #define STBI_ONLY_PNG @@ -25,7 +25,7 @@ #include #if defined(__clang__) || defined(__GNUC__) - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif #include @@ -38,267 +38,302 @@ using namespace glm; - constexpr std::size_t BASE64_GROUP_BYTES = 3; - constexpr int BASE64_DIGIT_BITS = 6; - constexpr std::uint32_t BASE64_DIGIT_MASK = 0x3F; - constexpr int BYTE_BITS = 8; - constexpr std::string_view BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - constexpr char BASE64_PADDING = '='; - constexpr auto SVG_NAMESPACE = "http://www.w3.org/2000/svg"; - constexpr auto XLINK_NAMESPACE = "http://www.w3.org/1999/xlink"; - constexpr auto SVG_ID_PREFIX = "anm2ed-source-"; - constexpr std::string_view SVG_URL_START = "url(#"; - constexpr auto SVG_INDENT = " "; - constexpr int ALPHA = 3; // a pixel's alpha channel - constexpr int SEAM_REACH = 2; - constexpr uint8_t SEAM_OPAQUE_ALPHA = 250; - // A drawing's root attributes that place it, rather than style it. - constexpr std::string_view SVG_ROOT_ONLY_ATTRIBUTES[] = {"width", "height", "viewBox", "preserveAspectRatio", - "x", "y", "version", "id"}; +constexpr std::size_t BASE64_GROUP_BYTES = 3; +constexpr int BASE64_DIGIT_BITS = 6; +constexpr std::uint32_t BASE64_DIGIT_MASK = 0x3F; +constexpr int BYTE_BITS = 8; +constexpr std::string_view BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +constexpr char BASE64_PADDING = '='; +constexpr auto SVG_NAMESPACE = "http://www.w3.org/2000/svg"; +constexpr auto XLINK_NAMESPACE = "http://www.w3.org/1999/xlink"; +constexpr auto SVG_ID_PREFIX = "anm2ed-source-"; +constexpr std::string_view SVG_URL_START = "url(#"; +constexpr auto SVG_INDENT = " "; +constexpr int ALPHA = 3; // a pixel's alpha channel +constexpr int SEAM_REACH = 2; +constexpr uint8_t SEAM_OPAQUE_ALPHA = 250; +// A drawing's root attributes that place it, rather than style it. +constexpr std::string_view SVG_ROOT_ONLY_ATTRIBUTES[] = {"width", "height", "viewBox", "preserveAspectRatio", + "x", "y", "version", "id"}; - bool Image::is_valid() const { return !pixels.empty(); } +bool Image::is_valid() const +{ + return !pixels.empty(); +} - bool Image::is_vector() const { return svg != nullptr; } +bool Image::is_vector() const +{ + return svg != nullptr; +} - glm::vec2 Image::unit_size_get() const { return glm::vec2(size) / scale; } +glm::vec2 Image::unit_size_get() const +{ + return glm::vec2(size) / scale; +} - // Closes the hairline seams an SVG's anti-aliasing leaves where two shapes meet: a partly covered pixel with opaque - // pixels on both sides of it (along any axis, within SEAM_REACH) takes their color over its own and becomes opaque. - // Outer edges, with transparency on one side, keep their anti-aliasing. - static void seams_fill(Image& image) - { +// Closes the hairline seams an SVG's anti-aliasing leaves where two shapes meet: a partly covered pixel with opaque +// pixels on both sides of it (along any axis, within SEAM_REACH) takes their color over its own and becomes opaque. +// Outer edges, with transparency on one side, keep their anti-aliasing. +static void seams_fill(Image& image) +{ constexpr glm::ivec2 AXES[] = {{1, 0}, {0, 1}, {1, 1}, {1, -1}}; // Coverage as drawn (filling only ever raises it, and only on partly covered pixels, whose colors no check reads). std::vector alphas((std::size_t)image.size.x * image.size.y); for (std::size_t i = 0; i < alphas.size(); ++i) - alphas[i] = image.pixels[i * IMAGE_CHANNELS + ALPHA]; - auto index_get = [&](glm::ivec2 point) { return (std::size_t)point.y * image.size.x + point.x; }; - auto opaque_get = [&](glm::ivec2 point, glm::ivec2 step) -> const uint8_t* - { - for (int reach = 1; reach <= SEAM_REACH; ++reach) - { - auto neighbor = point + step * reach; - if (glm::any(glm::lessThan(neighbor, glm::ivec2(0))) || glm::any(glm::greaterThanEqual(neighbor, image.size))) - return nullptr; - if (alphas[index_get(neighbor)] >= SEAM_OPAQUE_ALPHA) - return image.pixels.data() + index_get(neighbor) * IMAGE_CHANNELS; - } - return nullptr; + alphas[i] = image.pixels[i * IMAGE_CHANNELS + ALPHA]; + auto index_get = [&](glm::ivec2 point) { + return (std::size_t)point.y * image.size.x + point.x; + }; + auto opaque_get = [&](glm::ivec2 point, glm::ivec2 step) -> const uint8_t* { + for (int reach = 1; reach <= SEAM_REACH; ++reach) + { + auto neighbor = point + step * reach; + if (glm::any(glm::lessThan(neighbor, glm::ivec2(0))) || + glm::any(glm::greaterThanEqual(neighbor, image.size))) + return nullptr; + if (alphas[index_get(neighbor)] >= SEAM_OPAQUE_ALPHA) + return image.pixels.data() + index_get(neighbor) * IMAGE_CHANNELS; + } + return nullptr; }; for (int y = 0; y < image.size.y; ++y) - for (int x = 0; x < image.size.x; ++x) - { - auto alpha = alphas[index_get({x, y})]; - if (alpha == 0 || alpha == UINT8_MAX) continue; - for (auto axis : AXES) + for (int x = 0; x < image.size.x; ++x) { - auto before = opaque_get({x, y}, -axis); - auto after = before ? opaque_get({x, y}, axis) : nullptr; - if (!after) continue; - auto pixel = image.pixels.data() + index_get({x, y}) * IMAGE_CHANNELS; - auto coverage = alpha / (float)UINT8_MAX; - for (int channel = 0; channel < ALPHA; ++channel) - pixel[channel] = (uint8_t)std::round(pixel[channel] * coverage + - (before[channel] + after[channel]) * 0.5f * (1.0f - coverage)); - pixel[ALPHA] = UINT8_MAX; - break; + auto alpha = alphas[index_get({x, y})]; + if (alpha == 0 || alpha == UINT8_MAX) + continue; + for (auto axis : AXES) + { + auto before = opaque_get({x, y}, -axis); + auto after = before ? opaque_get({x, y}, axis) : nullptr; + if (!after) + continue; + auto pixel = image.pixels.data() + index_get({x, y}) * IMAGE_CHANNELS; + auto coverage = alpha / (float)UINT8_MAX; + for (int channel = 0; channel < ALPHA; ++channel) + pixel[channel] = (uint8_t)std::round(pixel[channel] * coverage + + (before[channel] + after[channel]) * 0.5f * (1.0f - coverage)); + pixel[ALPHA] = UINT8_MAX; + break; + } } - } - } +} - // An SVG drawn at about `scale` pixels per unit (exactly, after rounding to whole pixels); nothing if it won't parse. - static Image svg_render(std::shared_ptr svg, float scale) - { +// An SVG drawn at about `scale` pixels per unit (exactly, after rounding to whole pixels). Nothing if it won't parse. +static Image svg_render(std::shared_ptr svg, float scale) +{ auto document = svg ? lunasvg::Document::loadFromData(*svg) : nullptr; - if (!document || document->width() <= 0.0f) return {}; + if (!document || document->width() <= 0.0f) + return {}; auto size = glm::max(ivec2(glm::ceil(vec2(document->width(), document->height()) * scale)), ivec2(1)); auto bitmap = document->renderToBitmap(size.x, size.y); - if (bitmap.isNull()) return {}; + if (bitmap.isNull()) + return {}; bitmap.convertToRGBA(); Image image(bitmap.data(), size, true); seams_fill(image); image.svg = std::move(svg); image.scale = (float)size.x / document->width(); return image; - } +} - Image Image::vector_render(float scale) const { return svg_render(svg, scale); } +Image Image::vector_render(float scale) const +{ + return svg_render(svg, scale); +} - size_t Image::pixel_size_get() const { return size.x * size.y * IMAGE_CHANNELS; } +size_t Image::pixel_size_get() const +{ + return size.x * size.y * IMAGE_CHANNELS; +} - Image::Image(const uint8_t* data, ivec2 size, bool isLinear) : isLinear(isLinear) - { - if (!data || size.x <= 0 || size.y <= 0) return; +Image::Image(const uint8_t* data, ivec2 size, bool isLinear) : isLinear(isLinear) +{ + if (!data || size.x <= 0 || size.y <= 0) + return; this->size = size; pixels.assign(data, data + pixel_size_get()); uid = uid_next(); - } +} - Image::Image(const unsigned char* pngData, size_t pngSize) - { - if (!pngData || pngSize == 0) return; +Image::Image(const unsigned char* pngData, size_t pngSize) +{ + if (!pngData || pngSize == 0) + return; auto sizeInt = static_cast(pngSize); - if (sizeInt <= 0) return; + if (sizeInt <= 0) + return; if (auto data = stbi_load_from_memory(pngData, sizeInt, &size.x, &size.y, nullptr, IMAGE_CHANNELS); data) { - *this = Image(data, size); - stbi_image_free((void*)data); + *this = Image(data, size); + stbi_image_free((void*)data); } - } +} - // A PNG, or else an SVG (whatever the file is named, so autosaved copies load too). - Image::Image(const std::filesystem::path& path) - { +// A PNG, or else an SVG (whatever the file is named, so autosaved copies load too). +Image::Image(const std::filesystem::path& path) +{ auto text = std::make_shared(); - if (!file_text_load(path, text.get())) return; + if (!file_text_load(path, text.get())) + return; *this = Image((const unsigned char*)text->data(), text->size()); - if (!is_valid()) *this = svg_render(std::move(text), 1.0f); - } + if (!is_valid()) + *this = svg_render(std::move(text), 1.0f); +} - bool Image::write_png(const std::filesystem::path& path) const - { +bool Image::write_png(const std::filesystem::path& path) const +{ return write_pixels_png(path, size, pixels.empty() ? nullptr : pixels.data()); - } +} - bool Image::write_pixels_png(const std::filesystem::path& path, ivec2 size, const uint8_t* data) - { - if (!data || size.x <= 0 || size.y <= 0) return false; +bool Image::write_pixels_png(const std::filesystem::path& path, ivec2 size, const uint8_t* data) +{ + if (!data || size.x <= 0 || size.y <= 0) + return false; File file(path, "wb"); if (auto handle = file.get()) { - auto write_func = [](void* context, void* bytes, int count) - { fwrite(bytes, 1, count, static_cast(context)); }; - return stbi_write_png_to_func(write_func, handle, size.x, size.y, IMAGE_CHANNELS, data, size.x * IMAGE_CHANNELS) != 0; + auto write_func = [](void* context, void* bytes, int count) { + fwrite(bytes, 1, count, static_cast(context)); + }; + return stbi_write_png_to_func(write_func, handle, size.x, size.y, IMAGE_CHANNELS, data, + size.x * IMAGE_CHANNELS) != 0; } return false; - } +} - // Copies a size-sized block between images; pixels outside either image are skipped. - static void pixels_copy(const Image& from, glm::ivec2 fromMin, Image& to, glm::ivec2 toMin, glm::ivec2 size) - { +// Copies a size-sized block between images. Pixels outside either image are skipped. +static void pixels_copy(const Image& from, glm::ivec2 fromMin, Image& to, glm::ivec2 toMin, glm::ivec2 size) +{ for (int y = 0; y < size.y; ++y) - for (int x = 0; x < size.x; ++x) - { - auto source = fromMin + glm::ivec2(x, y); - auto target = toMin + glm::ivec2(x, y); - if (glm::any(glm::lessThan(source, glm::ivec2(0))) || glm::any(glm::greaterThanEqual(source, from.size)) || - glm::any(glm::lessThan(target, glm::ivec2(0))) || glm::any(glm::greaterThanEqual(target, to.size))) - continue; - std::copy_n(from.pixels.data() + ((std::size_t)source.y * from.size.x + source.x) * IMAGE_CHANNELS, - IMAGE_CHANNELS, - to.pixels.data() + ((std::size_t)target.y * to.size.x + target.x) * IMAGE_CHANNELS); - } - } + for (int x = 0; x < size.x; ++x) + { + auto source = fromMin + glm::ivec2(x, y); + auto target = toMin + glm::ivec2(x, y); + if (glm::any(glm::lessThan(source, glm::ivec2(0))) || glm::any(glm::greaterThanEqual(source, from.size)) || + glm::any(glm::lessThan(target, glm::ivec2(0))) || glm::any(glm::greaterThanEqual(target, to.size))) + continue; + std::copy_n(from.pixels.data() + ((std::size_t)source.y * from.size.x + source.x) * IMAGE_CHANNELS, + IMAGE_CHANNELS, + to.pixels.data() + ((std::size_t)target.y * to.size.x + target.x) * IMAGE_CHANNELS); + } +} - void Image::paste(const Image& source, glm::ivec2 position) { pixels_copy(source, {}, *this, position, source.size); } +void Image::paste(const Image& source, glm::ivec2 position) +{ + pixels_copy(source, {}, *this, position, source.size); +} - // A copy of a block of the image (transparent where it falls outside). - Image Image::region_get(glm::ivec2 min, glm::ivec2 regionSize) const - { +// A copy of a block of the image (transparent where it falls outside). +Image Image::region_get(glm::ivec2 min, glm::ivec2 regionSize) const +{ Image region = {}; region.size = regionSize; region.pixels.assign((std::size_t)regionSize.x * regionSize.y * IMAGE_CHANNELS, 0); pixels_copy(*this, min, region, {}, regionSize); return region; - } +} - // Base64 of bytes, for an image embedded in an SVG. - static std::string base64_get(const std::vector& bytes) - { +// Base64 of bytes, for an image embedded in an SVG. +static std::string base64_get(const std::vector& bytes) +{ std::string text; for (std::size_t i = 0; i < bytes.size(); i += BASE64_GROUP_BYTES) { - auto count = std::min(BASE64_GROUP_BYTES, bytes.size() - i); - std::uint32_t value = 0; - for (std::size_t j = 0; j < BASE64_GROUP_BYTES; ++j) - value = value << BYTE_BITS | (j < count ? bytes[i + j] : 0u); - for (std::size_t j = 0; j <= BASE64_GROUP_BYTES; ++j) - text += j <= count - ? BASE64_DIGITS[(value >> ((BASE64_GROUP_BYTES - j) * BASE64_DIGIT_BITS)) & BASE64_DIGIT_MASK] - : BASE64_PADDING; + auto count = std::min(BASE64_GROUP_BYTES, bytes.size() - i); + std::uint32_t value = 0; + for (std::size_t j = 0; j < BASE64_GROUP_BYTES; ++j) + value = value << BYTE_BITS | (j < count ? bytes[i + j] : 0u); + for (std::size_t j = 0; j <= BASE64_GROUP_BYTES; ++j) + text += j <= count + ? BASE64_DIGITS[(value >> ((BASE64_GROUP_BYTES - j) * BASE64_DIGIT_BITS)) & BASE64_DIGIT_MASK] + : BASE64_PADDING; } return text; - } +} - // Sets an attribute, adding it when the element doesn't have it yet. - template static void attribute_set(pugi::xml_node element, const char* name, const T& value) - { +// Sets an attribute, adding it when the element doesn't have it yet. +template static void attribute_set(pugi::xml_node element, const char* name, const T& value) +{ auto attribute = element.attribute(name); (attribute ? attribute : element.append_attribute(name)).set_value(value); - } +} - // An image as one SVG definition: a vector one as a symbol of its drawing (its ids prefixed with `id`, so - // several drawings can share a document), a raster one as an embedded PNG. Either draws at the image's size in - // SVG units. - static void svg_definition_add(pugi::xml_node root, pugi::xml_node defs, const Image& image, const std::string& id) - { +// An image as one SVG definition: a vector one as a symbol of its drawing (its ids prefixed with `id`, so +// several drawings can share a document), a raster one as an embedded PNG. Either draws at the image's size in +// SVG units. +static void svg_definition_add(pugi::xml_node root, pugi::xml_node defs, const Image& image, const std::string& id) +{ if (!image.is_vector()) { - std::vector png; - stbi_write_png_to_func( - [](void* context, void* data, int count) - { - static_cast*>(context)->insert(static_cast*>(context)->end(), - (uint8_t*)data, (uint8_t*)data + count); - }, - &png, image.size.x, image.size.y, IMAGE_CHANNELS, image.pixels.data(), image.size.x * IMAGE_CHANNELS); - auto element = defs.append_child("image"); - element.append_attribute("id") = id.c_str(); - element.append_attribute("width") = image.size.x; - element.append_attribute("height") = image.size.y; - element.append_attribute("xlink:href") = ("data:image/png;base64," + base64_get(png)).c_str(); - return; + std::vector png; + stbi_write_png_to_func( + [](void* context, void* data, int count) { + static_cast*>(context)->insert(static_cast*>(context)->end(), + (uint8_t*)data, (uint8_t*)data + count); + }, + &png, image.size.x, image.size.y, IMAGE_CHANNELS, image.pixels.data(), image.size.x * IMAGE_CHANNELS); + auto element = defs.append_child("image"); + element.append_attribute("id") = id.c_str(); + element.append_attribute("width") = image.size.x; + element.append_attribute("height") = image.size.y; + element.append_attribute("xlink:href") = ("data:image/png;base64," + base64_get(png)).c_str(); + return; } pugi::xml_document source; source.load_string(image.svg->c_str()); auto sourceRoot = source.document_element(); - if (!sourceRoot) return; + if (!sourceRoot) + return; // Every id in the drawing gets the prefix, and so does every reference to one (href="#id", url(#id)). std::set ids; - auto elements_each = [](pugi::xml_node element, auto&& callback, auto&& self) -> void - { - callback(element); - for (auto child : element.children()) - if (child.type() == pugi::node_element) self(child, callback, self); + auto elements_each = [](pugi::xml_node element, auto&& callback, auto&& self) -> void { + callback(element); + for (auto child : element.children()) + if (child.type() == pugi::node_element) + self(child, callback, self); }; elements_each( sourceRoot, - [&](pugi::xml_node element) - { - if (auto elementId = element.attribute("id")) ids.insert(elementId.value()); + [&](pugi::xml_node element) { + if (auto elementId = element.attribute("id")) + ids.insert(elementId.value()); }, elements_each); - auto renamed_get = [&](std::string_view sourceId) { return id + "-" + std::string(sourceId); }; + auto renamed_get = [&](std::string_view sourceId) { + return id + "-" + std::string(sourceId); + }; elements_each( sourceRoot, - [&](pugi::xml_node element) - { - for (auto attribute : element.attributes()) - { - std::string_view name = attribute.name(); - std::string value = attribute.value(); - if (name == "id") - value = renamed_get(value); - else if ((name == "href" || name == "xlink:href") && value.starts_with('#') && - ids.contains(value.substr(1))) - value = "#" + renamed_get(value.substr(1)); - else - for (auto at = value.find(SVG_URL_START); at != std::string::npos; at = value.find(SVG_URL_START, at + 1)) - { - auto start = at + SVG_URL_START.size(); - auto end = value.find(')', start); - if (end == std::string::npos) break; - if (auto reference = value.substr(start, end - start); ids.contains(reference)) - value.replace(start, end - start, renamed_get(reference)); - } - attribute.set_value(value.c_str()); - } + [&](pugi::xml_node element) { + for (auto attribute : element.attributes()) + { + std::string_view name = attribute.name(); + std::string value = attribute.value(); + if (name == "id") + value = renamed_get(value); + else if ((name == "href" || name == "xlink:href") && value.starts_with('#') && + ids.contains(value.substr(1))) + value = "#" + renamed_get(value.substr(1)); + else + for (auto at = value.find(SVG_URL_START); at != std::string::npos; + at = value.find(SVG_URL_START, at + 1)) + { + auto start = at + SVG_URL_START.size(); + auto end = value.find(')', start); + if (end == std::string::npos) + break; + if (auto reference = value.substr(start, end - start); ids.contains(reference)) + value.replace(start, end - start, renamed_get(reference)); + } + attribute.set_value(value.c_str()); + } }, elements_each); @@ -309,32 +344,32 @@ using namespace glm; symbol.append_attribute("viewBox") = viewBox ? viewBox.value() : std::format("0 0 {} {}", unitSize.x, unitSize.y).c_str(); if (auto aspect = sourceRoot.attribute("preserveAspectRatio")) - symbol.append_attribute("preserveAspectRatio") = aspect.value(); - // The drawing's root styles carry over through a group; its namespaces go on the new root. + symbol.append_attribute("preserveAspectRatio") = aspect.value(); + // The drawing's root styles carry over through a group. Its namespaces go on the new root. auto group = symbol.append_child("g"); for (auto attribute : sourceRoot.attributes()) { - std::string_view name = attribute.name(); - if (name.starts_with("xmlns")) - attribute_set(root, attribute.name(), attribute.value()); - else if (!std::ranges::contains(SVG_ROOT_ONLY_ATTRIBUTES, name)) - group.append_attribute(attribute.name()) = attribute.value(); + std::string_view name = attribute.name(); + if (name.starts_with("xmlns")) + attribute_set(root, attribute.name(), attribute.value()); + else if (!std::ranges::contains(SVG_ROOT_ONLY_ATTRIBUTES, name)) + group.append_attribute(attribute.name()) = attribute.value(); } for (auto child : sourceRoot.children()) - group.append_copy(child); - } + group.append_copy(child); +} - // Parts of images placed into one image of `size`: an SVG when `isVector` (each part a clipped view of its image's - // drawing, or of an embedded PNG), otherwise pixels. - Image Image::compose(const std::vector& parts, glm::ivec2 size, bool isVector) - { +// Parts of images placed into one image of `size`: an SVG when `isVector` (each part a clipped view of its image's +// drawing, or of an embedded PNG), otherwise pixels. +Image Image::compose(const std::vector& parts, glm::ivec2 size, bool isVector) +{ if (!isVector) { - std::vector pixels((std::size_t)size.x * size.y * IMAGE_CHANNELS, 0); - Image composed(pixels.data(), size); - for (auto& part : parts) - composed.paste(part.image->region_get(part.source, part.size), part.destination); - return composed; + std::vector pixels((std::size_t)size.x * size.y * IMAGE_CHANNELS, 0); + Image composed(pixels.data(), size); + for (auto& part : parts) + composed.paste(part.image->region_get(part.source, part.size), part.destination); + return composed; } pugi::xml_document document; @@ -349,71 +384,79 @@ using namespace glm; std::vector sources; for (auto& part : parts) { - auto source = std::ranges::find(sources, part.image); - if (source == sources.end()) - { - source = sources.insert(sources.end(), part.image); - svg_definition_add(root, defs, *part.image, std::format("{}{}", SVG_ID_PREFIX, sources.size() - 1)); - } - auto view = root.append_child("svg"); - view.append_attribute("x") = part.destination.x; - view.append_attribute("y") = part.destination.y; - view.append_attribute("width") = part.size.x; - view.append_attribute("height") = part.size.y; - view.append_attribute("viewBox") = - std::format("{} {} {} {}", part.source.x, part.source.y, part.size.x, part.size.y).c_str(); - auto use = view.append_child("use"); - auto unitSize = part.image->unit_size_get(); - use.append_attribute("xlink:href") = std::format("#{}{}", SVG_ID_PREFIX, source - sources.begin()).c_str(); - use.append_attribute("width") = unitSize.x; - use.append_attribute("height") = unitSize.y; + auto source = std::ranges::find(sources, part.image); + if (source == sources.end()) + { + source = sources.insert(sources.end(), part.image); + svg_definition_add(root, defs, *part.image, std::format("{}{}", SVG_ID_PREFIX, sources.size() - 1)); + } + auto view = root.append_child("svg"); + view.append_attribute("x") = part.destination.x; + view.append_attribute("y") = part.destination.y; + view.append_attribute("width") = part.size.x; + view.append_attribute("height") = part.size.y; + view.append_attribute("viewBox") = + std::format("{} {} {} {}", part.source.x, part.source.y, part.size.x, part.size.y).c_str(); + auto use = view.append_child("use"); + auto unitSize = part.image->unit_size_get(); + use.append_attribute("xlink:href") = std::format("#{}{}", SVG_ID_PREFIX, source - sources.begin()).c_str(); + use.append_attribute("width") = unitSize.x; + use.append_attribute("height") = unitSize.y; } std::ostringstream text; document.save(text, SVG_INDENT, pugi::format_indent | pugi::format_no_declaration); return svg_render(std::make_shared(text.str()), 1.0f); - } +} - // Writes a vector image as its SVG (unless the path asks for a PNG), and any other as a PNG. - bool Image::write(const std::filesystem::path& path) const - { - if (is_vector() && !is_path_extension(path, PNG_EXTENSION)) return file_text_save(path, *svg); +// Writes a vector image as its SVG (unless the path asks for a PNG), and any other as a PNG. +bool Image::write(const std::filesystem::path& path) const +{ + if (is_vector() && !is_path_extension(path, PNG_EXTENSION)) + return file_text_save(path, *svg); return write_png(path); - } +} - vec4 Image::pixel_read(vec2 position) const - { - if (pixels.size() < IMAGE_CHANNELS || size.x <= 0 || size.y <= 0) return vec4(0.0f); +vec4 Image::pixel_read(vec2 position) const +{ + if (pixels.size() < IMAGE_CHANNELS || size.x <= 0 || size.y <= 0) + return vec4(0.0f); int x = glm::clamp((int)(position.x), 0, size.x - 1); int y = glm::clamp((int)(position.y), 0, size.y - 1); auto index = ((size_t)(y) * (size_t)(size.x) + (size_t)(x)) * IMAGE_CHANNELS; - if (index + IMAGE_CHANNELS > pixels.size()) return vec4(0.0f); + if (index + IMAGE_CHANNELS > pixels.size()) + return vec4(0.0f); vec4 color{uint8_to_float(pixels[index + 0]), uint8_to_float(pixels[index + 1]), uint8_to_float(pixels[index + 2]), uint8_to_float(pixels[index + 3])}; - if (color.a <= 0.0f) color = vec4(0.0f); + if (color.a <= 0.0f) + color = vec4(0.0f); return color; - } +} - void Image::pixel_set(ivec2 position, vec4 color) - { - if (position.x < 0 || position.y < 0 || position.x >= size.x || position.y >= size.y) return; +void Image::pixel_set(ivec2 position, vec4 color) +{ + if (position.x < 0 || position.y < 0 || position.x >= size.x || position.y >= size.y) + return; uint8 rgba8[4] = {(uint8)float_to_uint8(color.r), (uint8)float_to_uint8(color.g), (uint8)float_to_uint8(color.b), (uint8)float_to_uint8(color.a)}; - if (pixels.size() != pixel_size_get()) return; + if (pixels.size() != pixel_size_get()) + return; size_t idx = (position.y * size.x + position.x) * IMAGE_CHANNELS; memcpy(&pixels[idx], rgba8, 4); uid = uid_next(); - } +} - void Image::pixel_line(ivec2 start, ivec2 end, vec4 color) - { - auto plot = [&](ivec2 pos) { pixel_set(pos, color); }; +void Image::pixel_line(ivec2 start, ivec2 end, vec4 color) +{ + auto plot = [&](ivec2 pos) { + pixel_set(pos, color); + }; int x0 = start.x; int y0 = start.y; @@ -428,18 +471,19 @@ using namespace glm; while (true) { - plot({x0, y0}); - if (x0 == x1 && y0 == y1) break; - int e2 = 2 * err; - if (e2 >= dy) - { - err += dy; - x0 += sx; - } - if (e2 <= dx) - { - err += dx; - y0 += sy; - } + plot({x0, y0}); + if (x0 == x1 && y0 == y1) + break; + int e2 = 2 * err; + if (e2 >= dy) + { + err += dy; + x0 += sx; + } + if (e2 <= dx) + { + err += dx; + y0 += sy; + } } - } +} diff --git a/src/image.h b/src/image.h index 32f5848..8c63fa6 100644 --- a/src/image.h +++ b/src/image.h @@ -9,26 +9,26 @@ #include - constexpr auto IMAGE_CHANNELS = 4; - constexpr auto SVG_EXTENSION = "svg"; - constexpr auto PNG_EXTENSION = "png"; +constexpr auto IMAGE_CHANNELS = 4; +constexpr auto SVG_EXTENSION = "svg"; +constexpr auto PNG_EXTENSION = "png"; - class Image; +class Image; - // A block of an image placed at `destination`, for composing images. - struct ImagePart - { +// A block of an image placed at `destination`, for composing images. +struct ImagePart +{ const Image* image = nullptr; glm::ivec2 source{}; glm::ivec2 size{}; glm::ivec2 destination{}; - }; +}; - // CPU-side RGBA pixels. uid changes whenever the pixels do, so GPU copies can be cached by it. A vector image keeps - // its SVG and is drawn at `scale` pixels per SVG unit; it can be drawn again at any scale, and isn't edited. - class Image - { - public: +// CPU-side RGBA pixels. uid changes whenever the pixels do, so GPU copies can be cached by it. A vector image keeps +// its SVG and is drawn at `scale` pixels per SVG unit. It can be drawn again at any scale, and isn't edited. +class Image +{ +public: glm::ivec2 size{}; std::vector pixels; bool isLinear = false; @@ -55,4 +55,4 @@ glm::vec4 pixel_read(glm::vec2) const; void pixel_set(glm::ivec2, glm::vec4); void pixel_line(glm::ivec2, glm::ivec2, glm::vec4); - }; +}; diff --git a/src/loader.cpp b/src/loader.cpp index af5fd24..204a7da 100644 --- a/src/loader.cpp +++ b/src/loader.cpp @@ -21,109 +21,120 @@ #include "math_util.h" #ifdef _WIN32 - #include +#include #endif - constexpr auto WINDOW_4K_SIZE = glm::ivec2(3840, 2160); - constexpr auto UI_SCALE_4K_DEFAULT = 150.0f; - constexpr auto WINDOW_DEFAULT_SIZE_MULTIPLIER = 0.90f; +constexpr auto WINDOW_4K_SIZE = glm::ivec2(3840, 2160); +constexpr auto UI_SCALE_4K_DEFAULT = 150.0f; +constexpr auto WINDOW_DEFAULT_SIZE_MULTIPLIER = 0.90f; - constexpr auto SOCKET_ADDRESS = "127.0.0.1"; - constexpr auto SOCKET_PORT = 11414; - constexpr uint32_t SOCKET_MAX_PATHS = 128; - constexpr uint32_t SOCKET_MAX_PATH_LENGTH = 32768; +constexpr auto SOCKET_ADDRESS = "127.0.0.1"; +constexpr auto SOCKET_PORT = 11414; +constexpr uint32_t SOCKET_MAX_PATHS = 128; +constexpr uint32_t SOCKET_MAX_PATH_LENGTH = 32768; #ifdef _WIN32 - constexpr int SOCKET_ERROR_ADDRESS_IN_USE = WSAEADDRINUSE; +constexpr int SOCKET_ERROR_ADDRESS_IN_USE = WSAEADDRINUSE; #else - constexpr int SOCKET_ERROR_ADDRESS_IN_USE = EADDRINUSE; +constexpr int SOCKET_ERROR_ADDRESS_IN_USE = EADDRINUSE; #endif - static bool socket_paths_send(Socket& socket, const std::vector& paths) - { +static bool socket_paths_send(Socket& socket, const std::vector& paths) +{ uint32_t count = htonl(static_cast(paths.size())); - if (!socket.send(&count, sizeof(count))) return false; + if (!socket.send(&count, sizeof(count))) + return false; for (auto& path : paths) { - uint32_t length = htonl(static_cast(path.size())); - if (!socket.send(&length, sizeof(length))) return false; - if (!path.empty() && !socket.send(path.data(), path.size())) return false; + uint32_t length = htonl(static_cast(path.size())); + if (!socket.send(&length, sizeof(length))) + return false; + if (!path.empty() && !socket.send(path.data(), path.size())) + return false; } return true; - } +} - static std::vector socket_paths_receive(Socket& socket) - { +static std::vector socket_paths_receive(Socket& socket) +{ uint32_t count = 0; - if (!socket.receive(&count, sizeof(count))) return {}; + if (!socket.receive(&count, sizeof(count))) + return {}; count = ntohl(count); - if (count > SOCKET_MAX_PATHS) return {}; + if (count > SOCKET_MAX_PATHS) + return {}; std::vector paths; paths.reserve(count); for (uint32_t i = 0; i < count; ++i) { - uint32_t length = 0; - if (!socket.receive(&length, sizeof(length))) return {}; - length = ntohl(length); - if (length > SOCKET_MAX_PATH_LENGTH) return {}; + uint32_t length = 0; + if (!socket.receive(&length, sizeof(length))) + return {}; + length = ntohl(length); + if (length > SOCKET_MAX_PATH_LENGTH) + return {}; - std::string path(length, '\0'); - if (length > 0 && !socket.receive(path.data(), length)) return {}; - paths.emplace_back(std::move(path)); + std::string path(length, '\0'); + if (length > 0 && !socket.receive(path.data(), length)) + return {}; + paths.emplace_back(std::move(path)); } return paths; - } +} - std::filesystem::path Loader::settings_path() { return preferences_directory_get() / "settings.ini"; } +std::filesystem::path Loader::settings_path() +{ + return preferences_directory_get() / "settings.ini"; +} - Loader::Loader(int argc, const char** argv) - { +Loader::Loader(int argc, const char** argv) +{ for (int i = 1; i < argc; i++) - arguments.emplace_back(argv[i]); + arguments.emplace_back(argv[i]); Socket testSocket; if (!testSocket.open(SERVER)) - logger.warning(std::format("Failed to open socket; single instancing will not work.")); + logger.warning(std::format("Failed to open socket; single instancing will not work.")); if (testSocket.bind({SOCKET_ADDRESS, SOCKET_PORT})) { - socket = std::move(testSocket); + socket = std::move(testSocket); - if (!socket.listen()) - logger.warning("Could not listen on socket; single instancing disabled."); - else - { - isSocketThread = true; - logger.info(std::format("Opened socket at {}:{}", SOCKET_ADDRESS, SOCKET_PORT)); - } + if (!socket.listen()) + logger.warning("Could not listen on socket; single instancing disabled."); + else + { + isSocketThread = true; + logger.info(std::format("Opened socket at {}:{}", SOCKET_ADDRESS, SOCKET_PORT)); + } } else { - if (testSocket.last_error() != SOCKET_ERROR_ADDRESS_IN_USE) - { - logger.fatal(std::format("Failed to bind single-instance socket (error {}).", testSocket.last_error())); + if (testSocket.last_error() != SOCKET_ERROR_ADDRESS_IN_USE) + { + logger.fatal(std::format("Failed to bind single-instance socket (error {}).", testSocket.last_error())); + isError = true; + return; + } + + logger.info(std::format("Existing instance of program exists; passing arguments...")); + Socket clientSocket; + if (!clientSocket.open(CLIENT)) + logger.warning("Could not open client socket to forward arguments."); + else if (!clientSocket.connect({SOCKET_ADDRESS, SOCKET_PORT})) + logger.warning("Could not connect to existing instance."); + else if (!socket_paths_send(clientSocket, arguments)) + logger.warning("Failed to transfer arguments to existing instance."); + else + logger.info("Sent arguments to existing instance. Exiting."); + isError = true; return; - } - - logger.info(std::format("Existing instance of program exists; passing arguments...")); - Socket clientSocket; - if (!clientSocket.open(CLIENT)) - logger.warning("Could not open client socket to forward arguments."); - else if (!clientSocket.connect({SOCKET_ADDRESS, SOCKET_PORT})) - logger.warning("Could not connect to existing instance."); - else if (!socket_paths_send(clientSocket, arguments)) - logger.warning("Failed to transfer arguments to existing instance."); - else - logger.info("Sent arguments to existing instance. Exiting."); - - isError = true; - return; } settings = Settings(settings_path()); @@ -132,9 +143,9 @@ if (!SDL_Init(SDL_INIT_VIDEO)) { - logger.fatal(std::format("Could not initialize SDL! {}", SDL_GetError())); - isError = true; - return; + logger.fatal(std::format("Could not initialize SDL! {}", SDL_GetError())); + isError = true; + return; } logger.info("Initialized SDL"); @@ -143,32 +154,33 @@ if (windowProperties == 0) { - logger.fatal(std::format("Could not initialize window properties! {}", SDL_GetError())); - isError = true; - return; + logger.fatal(std::format("Could not initialize window properties! {}", SDL_GetError())); + isError = true; + return; } if (settings.isDefault) { - if (auto display = SDL_GetPrimaryDisplay(); display != 0) - { - if (auto mode = SDL_GetCurrentDisplayMode(display)) + if (auto display = SDL_GetPrimaryDisplay(); display != 0) { - if (mode->w >= WINDOW_4K_SIZE.x || mode->h >= WINDOW_4K_SIZE.y) settings.uiScale = UI_SCALE_4K_DEFAULT; - settings.windowSize.x = mode->w * WINDOW_DEFAULT_SIZE_MULTIPLIER; - settings.windowSize.y = mode->h * WINDOW_DEFAULT_SIZE_MULTIPLIER; + if (auto mode = SDL_GetCurrentDisplayMode(display)) + { + if (mode->w >= WINDOW_4K_SIZE.x || mode->h >= WINDOW_4K_SIZE.y) + settings.uiScale = UI_SCALE_4K_DEFAULT; + settings.windowSize.x = mode->w * WINDOW_DEFAULT_SIZE_MULTIPLIER; + settings.windowSize.y = mode->h * WINDOW_DEFAULT_SIZE_MULTIPLIER; + } + else + logger.warning(std::format("Failed to query primary display mode: {}", SDL_GetError())); } else - logger.warning(std::format("Failed to query primary display mode: {}", SDL_GetError())); - } - else - logger.warning("Failed to detect primary display for UI scaling."); + logger.warning("Failed to detect primary display for UI scaling."); } if (!MIX_Init()) - logger.warning(std::format("Could not initialize SDL_mixer! {}", SDL_GetError())); + logger.warning(std::format("Could not initialize SDL_mixer! {}", SDL_GetError())); else - logger.info("Initialized SDL_mixer"); + logger.info("Initialized SDL_mixer"); SDL_SetStringProperty(windowProperties, SDL_PROP_WINDOW_CREATE_TITLE_STRING, "Anm2Ed"); SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, settings.windowSize.x); @@ -188,9 +200,9 @@ if (!window) { - logger.fatal(std::format("Could not initialize window! {}", SDL_GetError())); - isError = true; - return; + logger.fatal(std::format("Could not initialize window! {}", SDL_GetError())); + isError = true; + return; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); @@ -201,16 +213,16 @@ if (!glContext) { - logger.fatal(std::format("Could not initialize OpenGL context! {}", SDL_GetError())); - isError = true; - return; + logger.fatal(std::format("Could not initialize OpenGL context! {}", SDL_GetError())); + isError = true; + return; } if (!gladLoadGLLoader((GLADloadproc)(SDL_GL_GetProcAddress))) { - logger.fatal(std::format("Could not initialize OpenGL!")); - isError = true; - return; + logger.fatal(std::format("Could not initialize OpenGL!")); + isError = true; + return; } logger.info(std::format("Initialized OpenGL {}", (const char*)glGetString(GL_VERSION))); @@ -226,9 +238,9 @@ IMGUI_CHECKVERSION(); if (!ImGui::CreateContext()) { - logger.fatal("Could not initialize Dear ImGui!"); - isError = true; - return; + logger.fatal("Could not initialize Dear ImGui!"); + isError = true; + return; } logger.info("Initialized Dear ImGui"); @@ -241,7 +253,8 @@ ImGuiIO& io = ImGui::GetIO(); io.IniFilename = nullptr; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; - if (settings.isDetachableWindows) io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; + if (settings.isDetachableWindows) + io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; io.KeyRepeatDelay = settings.keyboardRepeatDelay; io.KeyRepeatRate = settings.keyboardRepeatRate; @@ -249,84 +262,85 @@ io.ConfigWindowsMoveFromTitleBarOnly = true; if (auto imguiData = Settings::imgui_data_load(settings_path()); !imguiData.empty()) - ImGui::LoadIniSettingsFromMemory(imguiData.c_str(), imguiData.size()); + ImGui::LoadIniSettingsFromMemory(imguiData.c_str(), imguiData.size()); if (isSocketThread) { - isSocketRunning = true; - socketThread = std::thread( - [this]() - { + isSocketRunning = true; + socketThread = std::thread([this]() { while (isSocketRunning) { - try - { - auto client = socket.accept(); - if (!client.is_valid()) + try { - if (!isSocketRunning) break; - continue; - } + auto client = socket.accept(); + if (!client.is_valid()) + { + if (!isSocketRunning) + break; + continue; + } - auto paths = socket_paths_receive(client); - for (auto& path : paths) - { - if (path.empty()) continue; - SDL_Event event = {}; - event.type = SDL_EVENT_USER; - event.user.code = 0; - event.user.data1 = SDL_strdup(path.c_str()); - event.user.data2 = nullptr; - event.user.windowID = 0; - SDL_PushEvent(&event); + auto paths = socket_paths_receive(client); + for (auto& path : paths) + { + if (path.empty()) + continue; + SDL_Event event = {}; + event.type = SDL_EVENT_USER; + event.user.code = 0; + event.user.data1 = SDL_strdup(path.c_str()); + event.user.data2 = nullptr; + event.user.windowID = 0; + SDL_PushEvent(&event); + } + } + catch (const std::exception& ex) + { + logger.error(std::format("Socket thread error: {}", ex.what())); + } + catch (...) + { + logger.error("Socket thread error: unknown exception"); } - } - catch (const std::exception& ex) - { - logger.error(std::format("Socket thread error: {}", ex.what())); - } - catch (...) - { - logger.error("Socket thread error: unknown exception"); - } } - }); + }); } - } +} - Loader::~Loader() - { +Loader::~Loader() +{ if (isSocketThread) { - isSocketRunning = false; + isSocketRunning = false; - if (socket.is_valid()) - { - Socket wakeSocket; - if (wakeSocket.open(CLIENT) && wakeSocket.connect({SOCKET_ADDRESS, SOCKET_PORT})) - socket_paths_send(wakeSocket, {}); - } + if (socket.is_valid()) + { + Socket wakeSocket; + if (wakeSocket.open(CLIENT) && wakeSocket.connect({SOCKET_ADDRESS, SOCKET_PORT})) + socket_paths_send(wakeSocket, {}); + } - socket.close(); - if (socketThread.joinable()) socketThread.join(); + socket.close(); + if (socketThread.joinable()) + socketThread.join(); } if (ImGui::GetCurrentContext()) { - settings.save(settings_path(), ImGui::SaveIniSettingsToMemory(nullptr)); - texture_garbage_collect(); + settings.save(settings_path(), ImGui::SaveIniSettingsToMemory(nullptr)); + texture_garbage_collect(); - ImGui_ImplSDL3_Shutdown(); - ImGui_ImplOpenGL3_Shutdown(); - ImGui::DestroyContext(); + ImGui_ImplSDL3_Shutdown(); + ImGui_ImplOpenGL3_Shutdown(); + ImGui::DestroyContext(); } MIX_Quit(); if (SDL_WasInit(0)) { - SDL_GL_DestroyContext(glContext); - SDL_DestroyWindow(window); - SDL_Quit(); + SDL_GL_DestroyContext(glContext); + SDL_DestroyWindow(window); + SDL_Quit(); } - } +} diff --git a/src/loader.h b/src/loader.h index bdb01ee..e881b15 100644 --- a/src/loader.h +++ b/src/loader.h @@ -10,11 +10,11 @@ #include "settings.h" #include "socket.h" - class Loader - { +class Loader +{ std::filesystem::path settings_path(); - public: +public: Socket socket = {}; std::thread socketThread; std::atomic_bool isSocketRunning = {}; @@ -27,4 +27,4 @@ Loader(int, const char**); ~Loader(); - }; +}; diff --git a/src/localization.h b/src/localization.h index 93b80c8..b4f780e 100644 --- a/src/localization.h +++ b/src/localization.h @@ -10,27 +10,27 @@ #define SELECT_KOREAN(symbol, english, spanish, russian, chinese, korean) korean, #define LANGUAGES(X) \ - X(ENGLISH, "English", SELECT_ENGLISH) \ - X(SPANISH, "Español (Latinoamérica) (Spanish (Latin America))", SELECT_SPANISH) \ - X(RUSSIAN, "Pусский (Russian)", SELECT_RUSSIAN) \ - X(CHINESE, "中文 (Chinese)", SELECT_CHINESE) \ - X(KOREAN, "한국어 (Korean)", SELECT_KOREAN) + X(ENGLISH, "English", SELECT_ENGLISH) \ + X(SPANISH, "Español (Latinoamérica) (Spanish (Latin America))", SELECT_SPANISH) \ + X(RUSSIAN, "Pусский (Russian)", SELECT_RUSSIAN) \ + X(CHINESE, "中文 (Chinese)", SELECT_CHINESE) \ + X(KOREAN, "한국어 (Korean)", SELECT_KOREAN) - enum Language - { +enum Language +{ #define X(symbol, label, selector) symbol, LANGUAGES(X) #undef X - LANGUAGE_COUNT - }; + LANGUAGE_COUNT +}; - inline constexpr const char* LANGUAGE_STRINGS[LANGUAGE_COUNT] = { +inline constexpr const char* LANGUAGE_STRINGS[LANGUAGE_COUNT] = { #define X(symbol, label, selector) label, - LANGUAGES(X) + LANGUAGES(X) #undef X - }; +}; - // clang-format off +// clang-format off #define STRINGS(X) \ X(STRING_UNDEFINED, "undefined", "undefined", "undefined", "undefined", "undefined") \ X(BASIC_ADD, "Add", "Añadir", "Добавить", "添加", "추가") \ @@ -872,26 +872,26 @@ X(TOOLTIP_WIZARD_SCAN_AND_SET_REGIONS, "Match all regionless frames in all animations in the document to a region, if a matching region exists and matches the frame's relevant values.", "Empareja todos los frames sin region de todas las animaciones del documento con una region, si existe una region coincidente y coincide con los valores relevantes del frame.", "Сопоставляет все кадры без региона во всех анимациях документа с регионом, если существует подходящий регион и его релевантные значения совпадают со значениями кадра.", "将文档中所有动画里无区域的帧与区域进行匹配;若存在匹配区域且其相关值与帧一致,则进行设置。", "문서의 모든 애니메이션에서 영역이 없는 프레임을 영역과 매칭합니다. 일치하는 영역이 있고 프레임의 관련 값이 일치하면 설정합니다.") \ X(TOOLTIP_USE_EXISTING_ITEM, "Reuse an unused item instead of creating a new one.", "Reusa un item no utilizado en vez de crear uno nuevo.", "Использовать неиспользуемый предмет, а не создавать новый.", "重用未使用的物品,而不是创建新物品。", "새로 만들지 않고 사용되지 않는 항목을 재사용합니다.") \ X(TOOLTIP_VSYNC, "Toggle vertical sync; synchronizes program update rate with monitor refresh rate.", "Alterna la Sincronizacion Vertical; Sincroniza la tasa de actualizacion del programa con la tasa de refresco del monitor.", "Переключить вертикальную синхронизацию; синхронизирует частоту обновления программы с частотой обновления монитора.", "切换垂直同步; 同步程序的更新频率与屏幕的刷新频率.", "수직 동기화를 켜거나 끕니다. 프로그램의 업데이트 속도를 모니터의 새로고침 속도와 동기화합니다.") - // clang-format on +// clang-format on - enum StringType - { +enum StringType +{ #define X(symbol, ...) symbol, STRINGS(X) #undef X - STRING_TYPE_COUNT - }; + STRING_TYPE_COUNT +}; #define DEFINE_LANGUAGE_ARRAY(symbol, label, selector) \ - inline constexpr const char* STRINGS_##symbol[] = {STRINGS(selector)}; - LANGUAGES(DEFINE_LANGUAGE_ARRAY) + inline constexpr const char* STRINGS_##symbol[] = {STRINGS(selector)}; +LANGUAGES(DEFINE_LANGUAGE_ARRAY) #undef DEFINE_LANGUAGE_ARRAY - inline constexpr const char* const* LANGUAGE_STRING_COLLECTIONS[LANGUAGE_COUNT] = { +inline constexpr const char* const* LANGUAGE_STRING_COLLECTIONS[LANGUAGE_COUNT] = { #define X(symbol, label, selector) STRINGS_##symbol, - LANGUAGES(X) + LANGUAGES(X) #undef X - }; +}; #undef SELECT_ENGLISH #undef SELECT_RUSSIAN @@ -900,23 +900,24 @@ #undef STRINGS #undef LANGUAGES - class Localizer - { - public: +class Localizer +{ +public: Language language = ENGLISH; inline const char* get(StringType type, Language setLanguage = (Language)-1) const { - auto useLanguage = (int)setLanguage == -1 ? language : setLanguage; - if (useLanguage < 0 || useLanguage >= LANGUAGE_COUNT || type < 0 || type >= STRING_TYPE_COUNT) return "undefined"; - return LANGUAGE_STRING_COLLECTIONS[useLanguage][type]; + auto useLanguage = (int)setLanguage == -1 ? language : setLanguage; + if (useLanguage < 0 || useLanguage >= LANGUAGE_COUNT || type < 0 || type >= STRING_TYPE_COUNT) + return "undefined"; + return LANGUAGE_STRING_COLLECTIONS[useLanguage][type]; } - }; +}; inline Localizer localize; - // A localized format string filled with arguments. - template std::string localize_format(StringType format, Args... args) - { +// A localized format string filled with arguments. +template std::string localize_format(StringType format, Args... args) +{ return std::vformat(localize.get(format), std::make_format_args(args...)); - } +} diff --git a/src/log.cpp b/src/log.cpp index 8f5ff0a..c45942c 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -14,210 +14,242 @@ #include "timestamp.h" #if _WIN32 - #include - #include - #include +#include +#include +#include #else - #include +#include #endif - constexpr auto SESSION_LIMIT = 10; - constexpr std::uintmax_t DIRECTORY_SIZE_LIMIT = 100ull * 1024ull * 1024ull; - constexpr std::uintmax_t SESSION_SIZE_LIMIT = 25ull * 1024ull * 1024ull; +constexpr auto SESSION_LIMIT = 10; +constexpr std::uintmax_t DIRECTORY_SIZE_LIMIT = 100ull * 1024ull * 1024ull; +constexpr std::uintmax_t SESSION_SIZE_LIMIT = 25ull * 1024ull * 1024ull; - struct SessionFile - { - std::filesystem::path path; - std::filesystem::file_time_type time; - std::uintmax_t size = 0; - }; +struct SessionFile +{ + std::filesystem::path path; + std::filesystem::file_time_type time; + std::uintmax_t size = 0; +}; - static std::uint32_t process_id_get() - { +static std::uint32_t process_id_get() +{ #if _WIN32 - return (std::uint32_t)_getpid(); + return (std::uint32_t)_getpid(); #else - return (std::uint32_t)getpid(); + return (std::uint32_t)getpid(); #endif - } +} - static std::filesystem::path session_path_get(const std::filesystem::path& directory) +static std::filesystem::path session_path_get(const std::filesystem::path& directory) +{ + auto name = std::format("anm2ed_{}_{}.log", timestamp_get("%Y-%m-%d_%H-%M-%S"), process_id_get()); + return directory / "logs" / path_from_utf8(name); +} + +static std::vector session_files_get(const std::filesystem::path& directory, + const std::filesystem::path& currentPath) +{ + std::vector files; + std::error_code ec; + if (!std::filesystem::is_directory(directory, ec)) + return files; + + for (std::filesystem::directory_iterator it(directory, ec), end{}; !ec && it != end; it.increment(ec)) { - auto name = std::format("anm2ed_{}_{}.log", timestamp_get("%Y-%m-%d_%H-%M-%S"), process_id_get()); - return directory / "logs" / path_from_utf8(name); - } - - static std::vector session_files_get(const std::filesystem::path& directory, - const std::filesystem::path& currentPath) - { - std::vector files; - std::error_code ec; - if (!std::filesystem::is_directory(directory, ec)) return files; - - for (std::filesystem::directory_iterator it(directory, ec), end{}; !ec && it != end; it.increment(ec)) - { auto path = it->path(); - if (path == currentPath || path.extension() != ".log") continue; + if (path == currentPath || path.extension() != ".log") + continue; std::error_code fileEc; - if (!std::filesystem::is_regular_file(path, fileEc)) continue; + if (!std::filesystem::is_regular_file(path, fileEc)) + continue; auto size = std::filesystem::file_size(path, fileEc); - if (fileEc) continue; + if (fileEc) + continue; auto time = std::filesystem::last_write_time(path, fileEc); if (fileEc) - { - time = std::filesystem::file_time_type::min(); - } + time = std::filesystem::file_time_type::min(); files.push_back({path, time, size}); - } - - return files; } - static void session_file_remove(const SessionFile& file, std::uintmax_t& totalSize) - { - std::error_code ec; - std::filesystem::remove(file.path, ec); - if (!ec && totalSize >= file.size) totalSize -= file.size; - } + return files; +} - static void sessions_prune(const std::filesystem::path& directory, const std::filesystem::path& currentPath) - { - auto files = session_files_get(directory, currentPath); - std::sort(files.begin(), files.end(), - [](const SessionFile& left, const SessionFile& right) { return left.time > right.time; }); +static void session_file_remove(const SessionFile& file, std::uintmax_t& totalSize) +{ + std::error_code ec; + std::filesystem::remove(file.path, ec); + if (!ec && totalSize >= file.size) + totalSize -= file.size; +} - std::uintmax_t totalSize = 0; - for (auto& file : files) +static void sessions_prune(const std::filesystem::path& directory, const std::filesystem::path& currentPath) +{ + auto files = session_files_get(directory, currentPath); + std::sort(files.begin(), files.end(), + [](const SessionFile& left, const SessionFile& right) { return left.time > right.time; }); + + std::uintmax_t totalSize = 0; + for (auto& file : files) totalSize += file.size; - while (files.size() >= SESSION_LIMIT) - { - session_file_remove(files.back(), totalSize); - files.pop_back(); - } - - while (totalSize > DIRECTORY_SIZE_LIMIT && !files.empty()) - { - session_file_remove(files.back(), totalSize); - files.pop_back(); - } - } - - static void legacy_log_remove(const std::filesystem::path& currentPath) + while (files.size() >= SESSION_LIMIT) { - auto directory = currentPath.parent_path().parent_path(); - if (directory.empty()) return; - - auto legacyPath = directory / "log.txt"; - if (legacyPath == currentPath) return; - - std::error_code ec; - std::filesystem::remove(legacyPath, ec); + session_file_remove(files.back(), totalSize); + files.pop_back(); } - void Logger::write_raw(const std::string& message) - { + while (totalSize > DIRECTORY_SIZE_LIMIT && !files.empty()) + { + session_file_remove(files.back(), totalSize); + files.pop_back(); + } +} + +static void legacy_log_remove(const std::filesystem::path& currentPath) +{ + auto directory = currentPath.parent_path().parent_path(); + if (directory.empty()) + return; + + auto legacyPath = directory / "log.txt"; + if (legacyPath == currentPath) + return; + + std::error_code ec; + std::filesystem::remove(legacyPath, ec); +} + +void Logger::write_raw(const std::string& message) +{ std::lock_guard lock(mutex); try { - std::println("{}", message); + std::println("{}", message); } catch (...) - { - } + {} if (!logPath.empty()) { - try - { - auto lineSize = (std::uintmax_t)message.size() + 1; - auto isLineWithinLimit = logSize <= SESSION_SIZE_LIMIT && lineSize <= SESSION_SIZE_LIMIT - logSize; - if (isLineWithinLimit) + try { - auto line = message + '\n'; - if (file_text_save(logPath, line, "ab")) logSize += line.size(); + auto lineSize = (std::uintmax_t)message.size() + 1; + auto isLineWithinLimit = logSize <= SESSION_SIZE_LIMIT && lineSize <= SESSION_SIZE_LIMIT - logSize; + if (isLineWithinLimit) + { + auto line = message + '\n'; + if (file_text_save(logPath, line, "ab")) + logSize += line.size(); + } + else if (!isLogLimitReached) + { + std::string line = + "[WARNING] Session log size limit reached; suppressing further file logs for this session.\n"; + if (logSize + line.size() <= SESSION_SIZE_LIMIT) + if (file_text_save(logPath, line, "ab")) + logSize += line.size(); + isLogLimitReached = true; + } } - else if (!isLogLimitReached) - { - std::string line = - "[WARNING] Session log size limit reached; suppressing further file logs for this session.\n"; - if (logSize + line.size() <= SESSION_SIZE_LIMIT) - if (file_text_save(logPath, line, "ab")) logSize += line.size(); - isLogLimitReached = true; - } - } - catch (...) - { - } + catch (...) + {} } - } +} - void Logger::write(const Level level, const std::string& message) - { - std::string formatted = std::format("{} {} {}", LEVEL_STRINGS[level], timestamp_get("(%d-%B-%Y %I:%M:%S)"), message); +void Logger::write(const Level level, const std::string& message) +{ + std::string formatted = + std::format("{} {} {}", LEVEL_STRINGS[level], timestamp_get("(%d-%B-%Y %I:%M:%S)"), message); write_raw(formatted); - } +} - void Logger::info(const std::string& message) { write(INFO, message); } - void Logger::warning(const std::string& message) { write(WARNING, message); } - void Logger::error(const std::string& message) { write(ERROR, message); } - void Logger::fatal(const std::string& message) { write(FATAL, message); } - void Logger::command(const std::string& message) { write(COMMAND, message); } +void Logger::info(const std::string& message) +{ + write(INFO, message); +} - void Logger::stderr_pump() - { +void Logger::warning(const std::string& message) +{ + write(WARNING, message); +} + +void Logger::error(const std::string& message) +{ + write(ERROR, message); +} + +void Logger::fatal(const std::string& message) +{ + write(FATAL, message); +} + +void Logger::command(const std::string& message) +{ + write(COMMAND, message); +} + +void Logger::stderr_pump() +{ std::string pending; std::array buffer = {}; while (isStderrRedirecting) { - int readBytes = 0; + int readBytes = 0; #if _WIN32 - readBytes = _read(stderrPipeReadFd, buffer.data(), (unsigned int)buffer.size()); + readBytes = _read(stderrPipeReadFd, buffer.data(), (unsigned int)buffer.size()); #else - readBytes = (int)read(stderrPipeReadFd, buffer.data(), buffer.size()); + readBytes = (int)read(stderrPipeReadFd, buffer.data(), buffer.size()); #endif - if (readBytes <= 0) break; + if (readBytes <= 0) + break; - pending.append(buffer.data(), (std::size_t)readBytes); + pending.append(buffer.data(), (std::size_t)readBytes); - std::size_t lineEnd = 0; - while ((lineEnd = pending.find('\n')) != std::string::npos) - { - auto line = pending.substr(0, lineEnd); - if (!line.empty() && line.back() == '\r') line.pop_back(); - if (!line.empty()) write_raw(line); - pending.erase(0, lineEnd + 1); - } + std::size_t lineEnd = 0; + while ((lineEnd = pending.find('\n')) != std::string::npos) + { + auto line = pending.substr(0, lineEnd); + if (!line.empty() && line.back() == '\r') + line.pop_back(); + if (!line.empty()) + write_raw(line); + pending.erase(0, lineEnd + 1); + } } - if (!pending.empty()) write_raw(pending); - } + if (!pending.empty()) + write_raw(pending); +} - void Logger::stderr_redirect_start() - { - if (isStderrRedirecting) return; +void Logger::stderr_redirect_start() +{ + if (isStderrRedirecting) + return; int pipeFds[2]{-1, -1}; #if _WIN32 - if (_pipe(pipeFds, 4096, _O_BINARY) != 0) return; + if (_pipe(pipeFds, 4096, _O_BINARY) != 0) + return; stderrOriginalFd = _dup(_fileno(stderr)); if (stderrOriginalFd < 0 || _dup2(pipeFds[1], _fileno(stderr)) != 0) { - _close(pipeFds[0]); - _close(pipeFds[1]); - return; + _close(pipeFds[0]); + _close(pipeFds[1]); + return; } _close(pipeFds[1]); #else - if (pipe(pipeFds) != 0) return; + if (pipe(pipeFds) != 0) + return; stderrOriginalFd = dup(fileno(stderr)); if (stderrOriginalFd < 0 || dup2(pipeFds[1], fileno(stderr)) < 0) { - close(pipeFds[0]); - close(pipeFds[1]); - return; + close(pipeFds[0]); + close(pipeFds[1]); + return; } close(pipeFds[1]); #endif @@ -227,90 +259,98 @@ stderrPipeReadFd = pipeFds[0]; isStderrRedirecting = true; stderrThread = std::thread([this]() { stderr_pump(); }); - } +} - void Logger::stderr_redirect_stop() - { - if (!isStderrRedirecting) return; +void Logger::stderr_redirect_stop() +{ + if (!isStderrRedirecting) + return; isStderrRedirecting = false; if (stderrOriginalFd >= 0) { #if _WIN32 - _dup2(stderrOriginalFd, _fileno(stderr)); - _close(stderrOriginalFd); + _dup2(stderrOriginalFd, _fileno(stderr)); + _close(stderrOriginalFd); #else - dup2(stderrOriginalFd, fileno(stderr)); - close(stderrOriginalFd); + dup2(stderrOriginalFd, fileno(stderr)); + close(stderrOriginalFd); #endif - stderrOriginalFd = -1; + stderrOriginalFd = -1; } if (stderrPipeReadFd >= 0) { #if _WIN32 - _close(stderrPipeReadFd); + _close(stderrPipeReadFd); #else - close(stderrPipeReadFd); + close(stderrPipeReadFd); #endif - stderrPipeReadFd = -1; + stderrPipeReadFd = -1; } - if (stderrThread.joinable()) stderrThread.join(); - } + if (stderrThread.joinable()) + stderrThread.join(); +} - void Logger::open(const std::filesystem::path& path) - { +void Logger::open(const std::filesystem::path& path) +{ logPath = path; logSize = 0; isLogLimitReached = false; if (!logPath.empty()) { - std::error_code ec; - auto directory = logPath.parent_path(); - if (!directory.empty()) std::filesystem::create_directories(directory, ec); - legacy_log_remove(logPath); - sessions_prune(directory, logPath); - logSize = std::filesystem::file_size(logPath, ec); - if (ec) logSize = 0; - isLogLimitReached = logSize >= SESSION_SIZE_LIMIT; + std::error_code ec; + auto directory = logPath.parent_path(); + if (!directory.empty()) + std::filesystem::create_directories(directory, ec); + legacy_log_remove(logPath); + sessions_prune(directory, logPath); + logSize = std::filesystem::file_size(logPath, ec); + if (ec) + logSize = 0; + isLogLimitReached = logSize >= SESSION_SIZE_LIMIT; } stderr_redirect_start(); - } +} - std::filesystem::path Logger::path() const { return logPath; } +std::filesystem::path Logger::path() const +{ + return logPath; +} - void Logger::session_open(const std::filesystem::path& directory) - { +void Logger::session_open(const std::filesystem::path& directory) +{ open(session_path_get(directory)); info(std::format("Initializing {}", localize.get(LABEL_APPLICATION_NAME, ENGLISH))); - } +} - Logger::Logger() = default; +Logger::Logger() = default; - Logger::~Logger() - { - if (logPath.empty()) return; +Logger::~Logger() +{ + if (logPath.empty()) + return; info("Exiting Anm2Ed"); stderr_redirect_stop(); - } +} - int log_exceptions(const std::function& callback) - { +int log_exceptions(const std::function& callback) +{ try { - return callback(); + return callback(); } catch (const std::exception& e) { - logger.fatal(std::format("Unhandled exception: {}", e.what())); + logger.fatal(std::format("Unhandled exception: {}", e.what())); } catch (...) { - logger.fatal("Unhandled non-standard exception"); + logger.fatal("Unhandled non-standard exception"); } return EXIT_FAILURE; - } +} Logger logger; diff --git a/src/log.h b/src/log.h index 1f936aa..7b7fdb7 100644 --- a/src/log.h +++ b/src/log.h @@ -9,41 +9,41 @@ #include #if defined(INFO) - #undef INFO +#undef INFO #endif #if defined(WARNING) - #undef WARNING +#undef WARNING #endif #if defined(ERROR) - #undef ERROR +#undef ERROR #endif #if defined(FATAL) - #undef FATAL +#undef FATAL #endif #define LEVELS \ - X(INFO, "[INFO]") \ - X(WARNING, "[WARNING]") \ - X(ERROR, "[ERROR]") \ - X(FATAL, "[FATAL]") \ - X(COMMAND, "[COMMAND]") + X(INFO, "[INFO]") \ + X(WARNING, "[WARNING]") \ + X(ERROR, "[ERROR]") \ + X(FATAL, "[FATAL]") \ + X(COMMAND, "[COMMAND]") - enum Level - { +enum Level +{ #define X(symbol, string) symbol, LEVELS #undef X - }; +}; - constexpr std::string_view LEVEL_STRINGS[] = { +constexpr std::string_view LEVEL_STRINGS[] = { #define X(symbol, string) string, - LEVELS + LEVELS #undef X - }; +}; #undef LEVELS - class Logger - { +class Logger +{ std::filesystem::path logPath; std::uintmax_t logSize = 0; std::mutex mutex; @@ -58,7 +58,7 @@ void stderr_redirect_stop(); void stderr_pump(); - public: +public: std::filesystem::path path() const; void session_open(const std::filesystem::path&); void write_raw(const std::string&); @@ -71,8 +71,8 @@ void open(const std::filesystem::path&); Logger(); ~Logger(); - }; +}; - int log_exceptions(const std::function&); +int log_exceptions(const std::function&); extern Logger logger; diff --git a/src/main.cpp b/src/main.cpp index 6fa54c5..ebc9301 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,104 +5,106 @@ #include "state.h" #ifdef _WIN32 - #define SDL_MAIN_HANDLED - #include - #include - #include - #include - #include - #include +#define SDL_MAIN_HANDLED +#include +#include +#include +#include +#include +#include #endif #ifdef _WIN32 - struct CommandLineArguments - { +struct CommandLineArguments +{ std::vector strings; std::vector pointers; - }; +}; - std::string wstring_utf8_get(std::wstring_view value) - { - if (value.empty()) return {}; +std::string wstring_utf8_get(std::wstring_view value) +{ + if (value.empty()) + return {}; auto size = WideCharToMultiByte(CP_UTF8, 0, value.data(), (int)value.size(), nullptr, 0, nullptr, nullptr); - if (size <= 0) return {}; + if (size <= 0) + return {}; std::string utf8((std::size_t)size, '\0'); WideCharToMultiByte(CP_UTF8, 0, value.data(), (int)value.size(), utf8.data(), size, nullptr, nullptr); return utf8; - } +} - CommandLineArguments command_line_arguments_get() - { +CommandLineArguments command_line_arguments_get() +{ int count = 0; auto wideArguments = CommandLineToArgvW(GetCommandLineW(), &count); - if (!wideArguments) return {}; + if (!wideArguments) + return {}; if (count <= 0) { - LocalFree(wideArguments); - return {}; + LocalFree(wideArguments); + return {}; } CommandLineArguments arguments = {}; arguments.strings.reserve((std::size_t)count); for (int i = 0; i < count; ++i) - arguments.strings.push_back(wstring_utf8_get(wideArguments[i])); + arguments.strings.push_back(wstring_utf8_get(wideArguments[i])); LocalFree(wideArguments); arguments.pointers.reserve(arguments.strings.size()); for (auto& argument : arguments.strings) - arguments.pointers.push_back(argument.c_str()); + arguments.pointers.push_back(argument.c_str()); return arguments; - } +} #endif - static int application_run(int argc, const char** argv) - { +static int application_run(int argc, const char** argv) +{ if (is_cli(argc, argv)) { #ifdef _WIN32 - // A GUI-subsystem build has no console of its own; print to the one it was started from. - if (AttachConsole(ATTACH_PARENT_PROCESS)) - { - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); - } + // A GUI-subsystem build has no console of its own. Print to the one it was started from. + if (AttachConsole(ATTACH_PARENT_PROCESS)) + { + freopen("CONOUT$", "w", stdout); + freopen("CONOUT$", "w", stderr); + } #endif - return cli_run(argc, argv); + return cli_run(argc, argv); } logger.session_open(preferences_directory_get()); - return log_exceptions( - [&]() - { - Loader loader(argc, argv); + return log_exceptions([&]() { + Loader loader(argc, argv); - if (loader.isError) return EXIT_FAILURE; + if (loader.isError) + return EXIT_FAILURE; - State state(loader.window, loader.settings, loader.arguments); + State state(loader.window, loader.settings, loader.arguments); - while (!state.isQuit) + while (!state.isQuit) state.loop(loader.window, loader.settings); - return EXIT_SUCCESS; - }); - } + return EXIT_SUCCESS; + }); +} int main(int argc, const char** argv) { #ifdef _WIN32 - auto arguments = command_line_arguments_get(); - if (!arguments.pointers.empty()) - return application_run((int)arguments.pointers.size(), arguments.pointers.data()); + auto arguments = command_line_arguments_get(); + if (!arguments.pointers.empty()) + return application_run((int)arguments.pointers.size(), arguments.pointers.data()); #endif - return application_run(argc, argv); + return application_run(argc, argv); } #ifdef _WIN32 int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { - auto arguments = command_line_arguments_get(); - return application_run((int)arguments.pointers.size(), arguments.pointers.data()); + auto arguments = command_line_arguments_get(); + return application_run((int)arguments.pointers.size(), arguments.pointers.data()); } #endif diff --git a/src/manager.cpp b/src/manager.cpp index 12343d5..91c7383 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -16,33 +16,37 @@ #include "ui/shortcut.h" #include "vector.h" - constexpr std::size_t RECENT_LIMIT = 10; +constexpr std::size_t RECENT_LIMIT = 10; - static void ensure_parent_directory_exists(const std::filesystem::path& path) - { +static void ensure_parent_directory_exists(const std::filesystem::path& path) +{ auto parent = path.parent_path(); - if (parent.empty()) return; + if (parent.empty()) + return; std::error_code ec; std::filesystem::create_directories(parent, ec); - if (ec) logger.warning(std::format("Could not create directory for {}: {}", path_to_utf8(path), ec.message())); - } + if (ec) + logger.warning(std::format("Could not create directory for {}: {}", path_to_utf8(path), ec.message())); +} - static void autosave_file_remove(const std::filesystem::path& path) - { - if (path.empty()) return; +static void autosave_file_remove(const std::filesystem::path& path) +{ + if (path.empty()) + return; std::error_code ec; std::filesystem::remove(path, ec); - if (ec) logger.warning(std::format("Could not remove autosave file {}: {}", path_to_utf8(path), ec.message())); - } + if (ec) + logger.warning(std::format("Could not remove autosave file {}: {}", path_to_utf8(path), ec.message())); +} - static std::vector path_list_load(const std::filesystem::path& path, std::string_view name) - { +static std::vector path_list_load(const std::filesystem::path& path, std::string_view name) +{ std::string fileData; if (!file_text_load(path, &fileData, "rb")) { - logger.warning(std::format("Could not load {} from: {}. Skipping...", name, path_to_utf8(path))); - return {}; + logger.warning(std::format("Could not load {} from: {}. Skipping...", name, path_to_utf8(path))); + return {}; } logger.info(std::format("Loading {} from: {}", name, path_to_utf8(path))); @@ -50,86 +54,102 @@ std::istringstream file(fileData); for (std::string line{}; std::getline(file, line);) { - if (!line.empty() && line.back() == '\r') line.pop_back(); - auto entry = path_from_utf8(line); - if (!line.empty() && std::ranges::find(result, entry) == result.end()) result.push_back(entry); + if (!line.empty() && line.back() == '\r') + line.pop_back(); + auto entry = path_from_utf8(line); + if (!line.empty() && std::ranges::find(result, entry) == result.end()) + result.push_back(entry); } return result; - } +} - static void path_list_save(const std::filesystem::path& path, const std::vector& entries, - std::string_view name) - { +static void path_list_save(const std::filesystem::path& path, const std::vector& entries, + std::string_view name) +{ ensure_parent_directory_exists(path); std::ostringstream file; for (auto& entry : entries) - file << path_to_utf8(entry) << '\n'; + file << path_to_utf8(entry) << '\n'; if (!file_text_save(path, file.str(), "wb")) - logger.warning(std::format("Could not write {} to: {}. Skipping...", name, path_to_utf8(path))); - } + logger.warning(std::format("Could not write {} to: {}. Skipping...", name, path_to_utf8(path))); +} - void Manager::selection_history_push(int index) - { - if (index < 0 || index >= (int)documents.size()) return; +void Manager::selection_history_push(int index) +{ + if (index < 0 || index >= (int)documents.size()) + return; selectionHistory.erase(std::remove(selectionHistory.begin(), selectionHistory.end(), index), selectionHistory.end()); selectionHistory.push_back(index); - } +} - void Manager::selection_history_cleanup(int removedIndex) - { +void Manager::selection_history_cleanup(int removedIndex) +{ if (removedIndex >= 0) { - for (auto& entry : selectionHistory) - { - if (entry == removedIndex) - entry = -1; - else if (entry > removedIndex) - --entry; - } + for (auto& entry : selectionHistory) + if (entry == removedIndex) + entry = -1; + else if (entry > removedIndex) + --entry; } selectionHistory.erase(std::remove_if(selectionHistory.begin(), selectionHistory.end(), [&](int idx) { return idx < 0 || idx >= (int)documents.size(); }), selectionHistory.end()); - if (documents.empty()) selectionHistory.clear(); - } + if (documents.empty()) + selectionHistory.clear(); +} - std::filesystem::path Manager::recent_files_path_get() { return preferences_directory_get() / "recent.txt"; } - std::filesystem::path Manager::autosave_path_get() { return preferences_directory_get() / "autosave.txt"; } +std::filesystem::path Manager::recent_files_path_get() +{ + return preferences_directory_get() / "recent.txt"; +} - Manager::Manager() - { +std::filesystem::path Manager::autosave_path_get() +{ + return preferences_directory_get() / "autosave.txt"; +} + +Manager::Manager() +{ recent_files_load(); autosave_files_load(); - } +} - Document* Manager::get(int index) { return vector_find(documents, index > -1 ? index : selected); } +Document* Manager::get(int index) +{ + return vector_find(documents, index > -1 ? index : selected); +} - void Manager::command_push(Command command) - { - if (command.documentIndex == -1) command.documentIndex = selected; +void Manager::command_push(Command command) +{ + if (command.documentIndex == -1) + command.documentIndex = selected; commands.push_back(std::move(command)); - } +} - void Manager::commands_run() - { +void Manager::commands_run() +{ auto queued = std::move(commands); commands.clear(); for (auto& command : queued) { - if (command.runManager) continue; + if (command.runManager) + continue; - if (auto document = get(command.documentIndex); document) document->command_run(*this, command); + if (auto document = get(command.documentIndex); document) + document->command_run(*this, command); } for (auto& command : queued) - if (command.runManager) command.runManager(*this); - } + if (command.runManager) + command.runManager(*this); +} - Document* Manager::open(const std::filesystem::path& path, bool isNew, bool isRecent) - { +Document* Manager::open(const std::filesystem::path& path, bool isNew, bool isRecent) +{ std::string errorString; documents.emplace_back(path, isNew, &errorString); auto pathString = path_to_utf8(path); @@ -137,160 +157,179 @@ auto& document = documents.back(); if (!document.is_valid()) { - documents.pop_back(); - toast_log(Level::ERROR, TOAST_OPEN_DOCUMENT_FAILED, pathString, errorString); - return nullptr; + documents.pop_back(); + toast_log(Level::ERROR, TOAST_OPEN_DOCUMENT_FAILED, pathString, errorString); + return nullptr; } - if (isRecent) recent_file_add(path); + if (isRecent) + recent_file_add(path); selected = (int)documents.size() - 1; pendingSelected = selected; selection_history_push(selected); toast_log(Level::INFO, TOAST_OPEN_DOCUMENT, pathString); // A JSON document that opened lists what it couldn't read. - if (!errorString.empty()) toast_log(Level::WARNING, TOAST_OPEN_DOCUMENT_ISSUES, pathString, errorString); + if (!errorString.empty()) + toast_log(Level::WARNING, TOAST_OPEN_DOCUMENT_ISSUES, pathString, errorString); return &document; - } +} - void Manager::new_(const std::filesystem::path& path) { open(path, true, true); } +void Manager::new_(const std::filesystem::path& path) +{ + open(path, true, true); +} - bool Manager::save(int index, const std::filesystem::path& path) - { +bool Manager::save(int index, const std::filesystem::path& path) +{ if (auto document = get(index); document) { - std::string errorString; - auto previousAutosavePath = document->autosave_path_get(); - auto savePath = !path.empty() ? path : document->path; - savePath.replace_extension(".anm2"); - ensure_parent_directory_exists(savePath); + std::string errorString; + auto previousAutosavePath = document->autosave_path_get(); + auto savePath = !path.empty() ? path : document->path; + savePath.replace_extension(".anm2"); + ensure_parent_directory_exists(savePath); - if (!document->save(savePath, &errorString, saveOptions)) return false; + if (!document->save(savePath, &errorString, saveOptions)) + return false; - auto autosavePath = document->autosave_path_get(); - autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), previousAutosavePath), - autosaveFiles.end()); - if (autosavePath != previousAutosavePath) - autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), autosavePath), autosaveFiles.end()); - autosave_file_remove(previousAutosavePath); - autosave_file_remove(autosavePath); - autosave_files_write(); - recent_file_add(document->path); - return true; + auto autosavePath = document->autosave_path_get(); + autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), previousAutosavePath), + autosaveFiles.end()); + if (autosavePath != previousAutosavePath) + autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), autosavePath), + autosaveFiles.end()); + autosave_file_remove(previousAutosavePath); + autosave_file_remove(autosavePath); + autosave_files_write(); + recent_file_add(document->path); + return true; } return false; - } +} - bool Manager::save(const std::filesystem::path& path) { return save(selected, path); } +bool Manager::save(const std::filesystem::path& path) +{ + return save(selected, path); +} - void Manager::autosave(Document& document) - { +void Manager::autosave(Document& document) +{ std::string errorString; auto autosavePath = document.autosave_path_get(); - if (!document.autosave(&errorString, saveOptions)) return; + if (!document.autosave(&errorString, saveOptions)) + return; autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), autosavePath), autosaveFiles.end()); autosaveFiles.insert(autosaveFiles.begin(), autosavePath); autosave_files_write(); - } +} - void Manager::autosave_file_clear(int index) - { +void Manager::autosave_file_clear(int index) +{ auto document = get(index); - if (!document) return; + if (!document) + return; auto autosavePath = document->autosave_path_get(); autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), autosavePath), autosaveFiles.end()); autosave_file_remove(autosavePath); document->spritesheets_autosave_clear(); autosave_files_write(); - } +} - void Manager::close(int index) - { - if (!is_vector_in_bounds(documents, index)) return; +void Manager::close(int index) +{ + if (!is_vector_in_bounds(documents, index)) + return; documents.erase(documents.begin() + index); selection_history_cleanup(index); if (documents.empty()) { - selected = -1; - pendingSelected = -1; - return; + selected = -1; + pendingSelected = -1; + return; } if (!selectionHistory.empty()) { - selected = selectionHistory.back(); - selectionHistory.pop_back(); + selected = selectionHistory.back(); + selectionHistory.pop_back(); } else if (selected >= index) - selected = std::max(0, selected - 1); + selected = std::max(0, selected - 1); selected = std::clamp(selected, 0, (int)documents.size() - 1); pendingSelected = selected; - if (selected >= 0 && selected < (int)documents.size()) documents[selected].change(); - } + if (selected >= 0 && selected < (int)documents.size()) + documents[selected].change(); +} - void Manager::set(int index) - { +void Manager::set(int index) +{ if (documents.empty()) { - selected = -1; - pendingSelected = -1; - return; + selected = -1; + pendingSelected = -1; + return; } index = std::clamp(index, 0, (int)documents.size() - 1); selected = index; selection_history_push(selected); - if (auto document = get()) document->change(); - } + if (auto document = get()) + document->change(); +} - int Manager::tab_index_get(std::uint64_t tabId) const - { +int Manager::tab_index_get(std::uint64_t tabId) const +{ for (int i = 0; i < (int)documents.size(); ++i) - if (documents[i].tabId == tabId) return i; + if (documents[i].tabId == tabId) + return i; return -1; - } +} - // The open document saved at `path`, or -1. - int Manager::path_index_get(const std::filesystem::path& path) const - { +// The open document saved at `path`, or -1. +int Manager::path_index_get(const std::filesystem::path& path) const +{ for (int i = 0; i < (int)documents.size(); ++i) { - std::error_code ec; - if (std::filesystem::equivalent(documents[i].path, path, ec)) return i; + std::error_code ec; + if (std::filesystem::equivalent(documents[i].path, path, ec)) + return i; } return -1; - } +} - // Switches to a document's tab. - void Manager::tab_select(int index) - { +// Switches to a document's tab. +void Manager::tab_select(int index) +{ pendingSelected = index; set(index); - } +} - // Edits the child of an animation layer track: its animation in this tab, or in its library's tab (opened if need - // be), at the time the parent plays it now. The step is remembered, so the breadcrumb can lead back. - void Manager::child_step_in(int index, Reference layerTrack) - { +// Edits the child of an animation layer track: its animation in this tab, or in its library's tab (opened if need +// be), at the time the parent plays it now. The step is remembered, so the breadcrumb can lead back. +void Manager::child_step_in(int index, Reference layerTrack) +{ auto parent = get(index); auto animation = parent ? parent->model.animation_get(layerTrack.animationIndex) : nullptr; auto track = parent ? parent->model.track_get(layerTrack) : nullptr; auto layer = parent ? item_get(parent->model.content.layers, layerTrack.itemID) : nullptr; - if (!animation || !track || !layer || !layer->is_animation()) return; + if (!animation || !track || !layer || !layer->is_animation()) + return; auto time = parent->frameTime > -1 && !parent->playback.isPlaying ? parent->frameTime : parent->playback.time; auto [childModel, childAnimation] = child_get(parent->model, *layer, frame_generate(*track, time), parent->library_resolver_get()); - if (!childAnimation) return; + if (!childAnimation) + return; auto steps = parent->childSteps; steps.push_back({.tabId = parent->tabId, @@ -305,35 +344,40 @@ auto targetIndex = index; if (childModel != &parent->model) { - auto path = parent->library_path_get(layer->libraryId); - targetIndex = path_index_get(path); - if (targetIndex == -1) - { - if (!open(path)) return; - targetIndex = (int)documents.size() - 1; - } + auto path = parent->library_path_get(layer->libraryId); + targetIndex = path_index_get(path); + if (targetIndex == -1) + { + if (!open(path)) + return; + targetIndex = (int)documents.size() - 1; + } } auto& target = documents[targetIndex]; for (auto [childIndex, candidate] : target.model.animations_get()) - if (candidate->name == childName) steps.back().childAnimationIndex = childIndex; + if (candidate->name == childName) + steps.back().childAnimationIndex = childIndex; target.childSteps = steps; target.reference_set({steps.back().childAnimationIndex}); target.frame_references_clear(); target.frameTime = target.playback.time = childTime; tab_select(targetIndex); - } +} - // Goes back to where step `stepIndex` of a document's breadcrumb was taken, keeping the steps before it. - void Manager::child_step_out(int index, int stepIndex) - { +// Goes back to where step `stepIndex` of a document's breadcrumb was taken, keeping the steps before it. +void Manager::child_step_out(int index, int stepIndex) +{ auto document = get(index); - if (!document || stepIndex < 0 || stepIndex >= (int)document->childSteps.size()) return; + if (!document || stepIndex < 0 || stepIndex >= (int)document->childSteps.size()) + return; auto steps = document->childSteps; auto step = steps[stepIndex]; auto targetIndex = tab_index_get(step.tabId); - if (targetIndex == -1) return; - if (targetIndex != index) document->childSteps.clear(); + if (targetIndex == -1) + return; + if (targetIndex != index) + document->childSteps.clear(); auto& target = documents[targetIndex]; target.childSteps.assign(steps.begin(), steps.begin() + stepIndex); @@ -341,17 +385,19 @@ target.frame_references_clear(); target.frameTime = target.playback.time = step.frameTime; tab_select(targetIndex); - } +} - void Manager::item_properties_open(ElementType type, int id) - { +void Manager::item_properties_open(ElementType type, int id) +{ auto document = get(); - if (!document || (type != ElementType::LAYER_ELEMENT && type != ElementType::NULL_ELEMENT)) return; + if (!document || (type != ElementType::LAYER_ELEMENT && type != ElementType::NULL_ELEMENT)) + return; auto isLayer = type == ElementType::LAYER_ELEMENT; auto& content = document->model.content; auto layer = isLayer ? item_get(content.layers, id) : nullptr; auto null = isLayer ? nullptr : item_get(content.nulls, id); - if (id != -1 && !layer && !null) return; + if (id != -1 && !layer && !null) + return; itemEdit = layer ? ItemEdit{.id = id, .name = layer->name, .spritesheetId = layer->spritesheetId, @@ -361,21 +407,22 @@ : null ? ItemEdit{.id = id, .name = null->name, .isShowRect = null->isShowRect} : ItemEdit{}; itemPropertiesPopups[isLayer ? 0 : 1].open(); - } +} - void Manager::recent_files_trim() - { +void Manager::recent_files_trim() +{ while (recentFiles.size() > RECENT_LIMIT) { - auto oldest = std::min_element(recentFiles.begin(), recentFiles.end(), - [](const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; }); - if (oldest == recentFiles.end()) break; - recentFiles.erase(oldest); + auto oldest = std::min_element(recentFiles.begin(), recentFiles.end(), + [](const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; }); + if (oldest == recentFiles.end()) + break; + recentFiles.erase(oldest); } - } +} - std::vector Manager::recent_files_ordered() const - { +std::vector Manager::recent_files_ordered() const +{ std::vector> orderedEntries(recentFiles.begin(), recentFiles.end()); std::sort(orderedEntries.begin(), orderedEntries.end(), [](const auto& lhs, const auto& rhs) { return lhs.second > rhs.second; }); @@ -383,91 +430,96 @@ std::vector ordered; ordered.reserve(orderedEntries.size()); for (auto& [pathString, _] : orderedEntries) - ordered.emplace_back(path_from_utf8(pathString)); + ordered.emplace_back(path_from_utf8(pathString)); return ordered; - } +} - void Manager::recent_file_add(const std::filesystem::path& path) - { - if (path.empty()) return; +void Manager::recent_file_add(const std::filesystem::path& path) +{ + if (path.empty()) + return; std::error_code ec; if (!std::filesystem::exists(path, ec)) { - logger.warning(std::format("Skipping missing recent file: {}", path_to_utf8(path))); - return; + logger.warning(std::format("Skipping missing recent file: {}", path_to_utf8(path))); + return; } recentFiles[path_to_utf8(path)] = ++recentFilesCounter; recent_files_trim(); recent_files_write(); - } +} - void Manager::recent_files_load() - { +void Manager::recent_files_load() +{ recentFiles.clear(); recentFilesCounter = 0; auto loaded = path_list_load(recent_files_path_get(), "recent files"); for (auto it = loaded.rbegin(); it != loaded.rend(); ++it) { - std::error_code ec; - if (std::filesystem::exists(*it, ec)) - recentFiles[path_to_utf8(*it)] = ++recentFilesCounter; - else - logger.warning(std::format("Skipping missing recent file: {}", path_to_utf8(*it))); + std::error_code ec; + if (std::filesystem::exists(*it, ec)) + recentFiles[path_to_utf8(*it)] = ++recentFilesCounter; + else + logger.warning(std::format("Skipping missing recent file: {}", path_to_utf8(*it))); } recent_files_trim(); - } +} - void Manager::recent_files_write() - { +void Manager::recent_files_write() +{ path_list_save(recent_files_path_get(), recent_files_ordered(), "recent files"); - } +} - void Manager::recent_files_clear() - { +void Manager::recent_files_clear() +{ recentFiles.clear(); recentFilesCounter = 0; recent_files_write(); - } +} - void Manager::autosave_files_open() - { +void Manager::autosave_files_open() +{ for (auto& path : autosaveFiles) { - if (auto document = open(path, false, false)) - { - document->isForceDirty = true; - document->path = document->path_from_autosave_get(path); - document->spritesheets_autosave_restore(); - document->change(); - } + if (auto document = open(path, false, false)) + { + document->isForceDirty = true; + document->path = document->path_from_autosave_get(path); + document->spritesheets_autosave_restore(); + document->change(); + } } - } +} - void Manager::autosave_files_load() - { +void Manager::autosave_files_load() +{ for (auto& entry : path_list_load(autosave_path_get(), "autosave files")) - if (std::ranges::find(autosaveFiles, entry) == autosaveFiles.end()) autosaveFiles.push_back(entry); - } + if (std::ranges::find(autosaveFiles, entry) == autosaveFiles.end()) + autosaveFiles.push_back(entry); +} - void Manager::autosave_files_write() { path_list_save(autosave_path_get(), autosaveFiles, "autosave files"); } +void Manager::autosave_files_write() +{ + path_list_save(autosave_path_get(), autosaveFiles, "autosave files"); +} - void Manager::autosave_files_clear(bool removeFiles) - { +void Manager::autosave_files_clear(bool removeFiles) +{ if (removeFiles) - for (auto& path : autosaveFiles) - autosave_file_remove(path); + for (auto& path : autosaveFiles) + autosave_file_remove(path); autosaveFiles.clear(); autosave_files_write(); - } +} - // What the manager keeps from the settings: shortcuts, and how documents save. - void Manager::settings_apply(Settings& settings) - { +// What the manager keeps from the settings: shortcuts, and how documents save. +void Manager::settings_apply(Settings& settings) +{ saveOptions = {.isJson = settings.fileIsJson}; for (int i = 0; i < SHORTCUT_COUNT; i++) - chords[i] = string_to_chord(settings.*SHORTCUT_MEMBERS[i]); - } + chords[i] = string_to_chord(settings.*SHORTCUT_MEMBERS[i]); +} - Manager::~Manager() = default; +Manager::~Manager() = default; diff --git a/src/manager.h b/src/manager.h index 6b87b51..bbb28bf 100644 --- a/src/manager.h +++ b/src/manager.h @@ -13,26 +13,26 @@ #include "localization.h" #include "ui/popup.h" - constexpr auto FILE_LABEL_FORMAT = "{} [{}]"; +constexpr auto FILE_LABEL_FORMAT = "{} [{}]"; - class Manager; +class Manager; - struct Command - { +struct Command +{ int documentIndex = -1; std::function run{}; std::function runManager{}; - }; +}; - class Manager - { +class Manager +{ std::filesystem::path recent_files_path_get(); std::filesystem::path autosave_path_get(); void selection_history_push(int); void selection_history_cleanup(int removedIndex); void recent_files_trim(); - public: +public: std::vector documents; std::vector commands; std::map> recentFiles; @@ -55,34 +55,30 @@ std::vector anm2DragDropPaths; bool isAnm2DragDrop = false; int anm2DragDropMergePreset = FILE_MERGE_PRESET_MERGE_BY_NAME; - PopupHelper anm2DragDropPopup{ - PopupHelper(LABEL_MANAGER_ANM2_DRAG_DROP, POPUP_NORMAL, POPUP_BY_CURSOR)}; - PopupHelper anm2DragDropMergePopup{ - PopupHelper(LABEL_DOCUMENTS_MERGE_INTO_CURRENT, POPUP_SMALL_NO_HEIGHT)}; + PopupHelper anm2DragDropPopup{PopupHelper(LABEL_MANAGER_ANM2_DRAG_DROP, POPUP_NORMAL, POPUP_BY_CURSOR)}; + PopupHelper anm2DragDropMergePopup{PopupHelper(LABEL_DOCUMENTS_MERGE_INTO_CURRENT, POPUP_SMALL_NO_HEIGHT)}; std::filesystem::path spritesheetDragDropPath; bool isSpritesheetDragDrop = false; struct ItemEdit { - int id = -1; - std::string name; - int spritesheetId = 0; - bool isShowRect = false; - bool isAnimation = false; - int libraryId = -1; - std::string animation; + int id = -1; + std::string name; + int spritesheetId = 0; + bool isShowRect = false; + bool isAnimation = false; + int libraryId = -1; + std::string animation; } itemEdit{}; - PopupHelper itemPropertiesPopups[2]{ - PopupHelper(LABEL_MANAGER_LAYER_PROPERTIES, POPUP_SMALL_NO_HEIGHT), - PopupHelper(LABEL_MANAGER_NULL_PROPERTIES, POPUP_SMALL_NO_HEIGHT)}; + PopupHelper itemPropertiesPopups[2]{PopupHelper(LABEL_MANAGER_LAYER_PROPERTIES, POPUP_SMALL_NO_HEIGHT), + PopupHelper(LABEL_MANAGER_NULL_PROPERTIES, POPUP_SMALL_NO_HEIGHT)}; Region makeRegion = {}; int makeRegionSpritesheetId = -1; bool isMakeRegionRequested = false; - PopupHelper progressPopup{ - PopupHelper(LABEL_MANAGER_RENDERING_PROGRESS, POPUP_SMALL_NO_HEIGHT)}; + PopupHelper progressPopup{PopupHelper(LABEL_MANAGER_RENDERING_PROGRESS, POPUP_SMALL_NO_HEIGHT)}; std::vector selectionHistory; @@ -119,4 +115,4 @@ void autosave_files_clear(bool removeFiles = false); void settings_apply(Settings&); - }; +}; diff --git a/src/math_util.cpp b/src/math_util.cpp index 5d4c378..141f50a 100644 --- a/src/math_util.cpp +++ b/src/math_util.cpp @@ -6,49 +6,50 @@ using namespace glm; - constexpr auto FLOAT_FORMAT_MAX_DECIMALS = 7; - constexpr auto FLOAT_FORMAT_EPSILON = 1e-7f; - constexpr float FLOAT_FORMAT_POW10[] = {1.f, 10.f, 100.f, 1000.f, 10000.f, 100000.f, 1000000.f, 10000000.f}; +constexpr auto FLOAT_FORMAT_MAX_DECIMALS = 7; +constexpr auto FLOAT_FORMAT_EPSILON = 1e-7f; +constexpr float FLOAT_FORMAT_POW10[] = {1.f, 10.f, 100.f, 1000.f, 10000.f, 100000.f, 1000000.f, 10000000.f}; - int float_decimals_needed(float value) - { +int float_decimals_needed(float value) +{ for (int decimalCount = 0; decimalCount <= FLOAT_FORMAT_MAX_DECIMALS; ++decimalCount) { - auto scale = FLOAT_FORMAT_POW10[decimalCount]; - auto rounded = roundf(value * scale) / scale; - if (fabsf(value - rounded) < FLOAT_FORMAT_EPSILON) return decimalCount; + auto scale = FLOAT_FORMAT_POW10[decimalCount]; + auto rounded = roundf(value * scale) / scale; + if (fabsf(value - rounded) < FLOAT_FORMAT_EPSILON) + return decimalCount; } return FLOAT_FORMAT_MAX_DECIMALS; - } +} - const char* float_format_get(float value) - { +const char* float_format_get(float value) +{ static std::string formatString; int decimalCount = float_decimals_needed(value); formatString = (decimalCount == 0) ? "%.0f" : ("%." + std::to_string(decimalCount) + "f"); return formatString.c_str(); - } +} - const char* vec2_format_get(const vec2& value) - { +const char* vec2_format_get(const vec2& value) +{ static std::string formatString; int decimalCountX = float_decimals_needed(value.x); int decimalCountY = float_decimals_needed(value.y); int decimalCount = (decimalCountX > decimalCountY) ? decimalCountX : decimalCountY; formatString = (decimalCount == 0) ? "%.0f" : ("%." + std::to_string(decimalCount) + "f"); return formatString.c_str(); - } +} - static mat4 skew_get(vec2 skew) - { +static mat4 skew_get(vec2 skew) +{ mat4 result(1.0f); result[1][0] = skew.x; result[0][1] = skew.y; return result; - } +} - mat4 quad_model_get(vec2 size, vec2 position, vec2 pivot, vec2 scale, float rotation, vec2 skew) - { +mat4 quad_model_get(vec2 size, vec2 position, vec2 pivot, vec2 scale, float rotation, vec2 skew) +{ vec2 scaleAbsolute = glm::abs(scale); vec2 scaleSign = glm::sign(scale); vec2 pivotScaled = pivot * scaleAbsolute; @@ -64,10 +65,10 @@ using namespace glm; model = glm::translate(model, vec3(-pivotScaled, 0.0f)); model = glm::scale(model, vec3(sizeScaled, 1.0f)); return model; - } +} - mat4 quad_model_parent_get(vec2 position, vec2 pivot, vec2 scale, float rotation, vec2 skew) - { +mat4 quad_model_parent_get(vec2 position, vec2 pivot, vec2 scale, float rotation, vec2 skew) +{ vec2 scaleSign = glm::sign(scale); vec2 scaleAbsolute = glm::abs(scale); float handedness = (scaleSign.x * scaleSign.y) < 0.0f ? -1.0f : 1.0f; @@ -81,8 +82,19 @@ using namespace glm; local = glm::scale(local, vec3(scaleAbsolute, 1.0f)); return glm::translate(mat4(1.0f), vec3(position, 0.0f)) * local; - } +} - float random_unit_get() { return (float)rand() / RAND_MAX; } - float random_in_range(float min, float max) { return min + random_unit_get() * (max - min); } - void random_seed_set() { srand(std::time(nullptr)); } +float random_unit_get() +{ + return (float)rand() / RAND_MAX; +} + +float random_in_range(float min, float max) +{ + return min + random_unit_get() * (max - min); +} + +void random_seed_set() +{ + srand(std::time(nullptr)); +} diff --git a/src/math_util.h b/src/math_util.h index 5d33dca..296b2f5 100644 --- a/src/math_util.h +++ b/src/math_util.h @@ -3,31 +3,43 @@ #include #include - template constexpr T percent_to_unit(T value) { return value / 100.0f; } +template constexpr T percent_to_unit(T value) +{ + return value / 100.0f; +} - template constexpr T unit_to_percent(T value) { return value * 100.0f; } +template constexpr T unit_to_percent(T value) +{ + return value * 100.0f; +} - constexpr float uint8_to_float(int value) { return (float)(value / 255.0f); } +constexpr float uint8_to_float(int value) +{ + return (float)(value / 255.0f); +} - constexpr int float_to_uint8(float value) { return (int)(value * 255); } +constexpr int float_to_uint8(float value) +{ + return (int)(value * 255); +} - constexpr std::array uv_vertices_get(glm::vec2 uvMin, glm::vec2 uvMax) - { +constexpr std::array uv_vertices_get(glm::vec2 uvMin, glm::vec2 uvMax) +{ return {0.0f, 0.0f, uvMin.x, uvMin.y, 1.0f, 0.0f, uvMax.x, uvMin.y, 1.0f, 1.0f, uvMax.x, uvMax.y, 0.0f, 1.0f, uvMin.x, uvMax.y}; - } +} - int float_decimals_needed(float); +int float_decimals_needed(float); - const char* float_format_get(float); +const char* float_format_get(float); - const char* vec2_format_get(const glm::vec2&); +const char* vec2_format_get(const glm::vec2&); - glm::mat4 quad_model_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {}, - glm::vec2 = {}); - glm::mat4 quad_model_parent_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {}, - glm::vec2 = {}); +glm::mat4 quad_model_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {}, + glm::vec2 = {}); +glm::mat4 quad_model_parent_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {}, + glm::vec2 = {}); - float random_unit_get(); - float random_in_range(float min, float max); - void random_seed_set(); +float random_unit_get(); +float random_in_range(float min, float max); +void random_seed_set(); diff --git a/src/model/common.h b/src/model/common.h index 54c6ffe..e9729d5 100644 --- a/src/model/common.h +++ b/src/model/common.h @@ -9,137 +9,137 @@ #include "types.h" #define ANM2_ELEMENT_TYPES \ - X(UNKNOWN, "") \ - X(ANIMATED_ACTOR, "AnimatedActor") \ - X(INFO, "Info") \ - X(CONTENT, "Content") \ - X(SPRITESHEETS, "Spritesheets") \ - X(SPRITESHEET, "Spritesheet") \ - X(SHADERS, "Shaders") \ - X(SHADER, "Shader") \ - X(UNIFORM, "Uniform") \ - X(COMPONENT, "Component") \ - X(REGION, "Region") \ - X(LAYERS, "Layers") \ - X(LAYER_ELEMENT, "Layer") \ - X(NULLS, "Nulls") \ - X(NULL_ELEMENT, "Null") \ - X(EVENTS, "Events") \ - X(EVENT_ELEMENT, "Event") \ - X(SOUNDS, "Sounds") \ - X(SOUND_ELEMENT, "Sound") \ - X(LIBRARIES, "Libraries") \ - X(LIBRARY, "Library") \ - X(ANIMATIONS, "Animations") \ - X(ANIMATION, "Animation") \ - X(ROOT_ANIMATION, "RootAnimation") \ - X(LAYER_ANIMATIONS, "LayerAnimations") \ - X(LAYER_ANIMATION_GROUPS, "LayerAnimationGroups") \ - X(LAYER_ANIMATION, "LayerAnimation") \ - X(NULL_ANIMATIONS, "NullAnimations") \ - X(NULL_ANIMATION_GROUPS, "NullAnimationGroups") \ - X(NULL_ANIMATION, "NullAnimation") \ - X(GROUP, "Group") \ - X(TRIGGERS, "Triggers") \ - X(FRAME, "Frame") \ - X(TRIGGER, "Trigger") + X(UNKNOWN, "") \ + X(ANIMATED_ACTOR, "AnimatedActor") \ + X(INFO, "Info") \ + X(CONTENT, "Content") \ + X(SPRITESHEETS, "Spritesheets") \ + X(SPRITESHEET, "Spritesheet") \ + X(SHADERS, "Shaders") \ + X(SHADER, "Shader") \ + X(UNIFORM, "Uniform") \ + X(COMPONENT, "Component") \ + X(REGION, "Region") \ + X(LAYERS, "Layers") \ + X(LAYER_ELEMENT, "Layer") \ + X(NULLS, "Nulls") \ + X(NULL_ELEMENT, "Null") \ + X(EVENTS, "Events") \ + X(EVENT_ELEMENT, "Event") \ + X(SOUNDS, "Sounds") \ + X(SOUND_ELEMENT, "Sound") \ + X(LIBRARIES, "Libraries") \ + X(LIBRARY, "Library") \ + X(ANIMATIONS, "Animations") \ + X(ANIMATION, "Animation") \ + X(ROOT_ANIMATION, "RootAnimation") \ + X(LAYER_ANIMATIONS, "LayerAnimations") \ + X(LAYER_ANIMATION_GROUPS, "LayerAnimationGroups") \ + X(LAYER_ANIMATION, "LayerAnimation") \ + X(NULL_ANIMATIONS, "NullAnimations") \ + X(NULL_ANIMATION_GROUPS, "NullAnimationGroups") \ + X(NULL_ANIMATION, "NullAnimation") \ + X(GROUP, "Group") \ + X(TRIGGERS, "Triggers") \ + X(FRAME, "Frame") \ + X(TRIGGER, "Trigger") - enum class ElementType - { +enum class ElementType +{ #define X(symbol, tag) symbol, ANM2_ELEMENT_TYPES #undef X COUNT - }; +}; - enum class Interpolation - { +enum class Interpolation +{ NONE, LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT, COUNT - }; +}; - enum class Origin - { +enum class Origin +{ CUSTOM, TOP_LEFT, CENTER, COUNT - }; +}; - // How an animation layer's child animation plays through a keyframe: looping, once (then holding its last frame), - // or held at the keyframe's start frame. - enum class ChildMode - { +// How an animation layer's child animation plays through a keyframe: looping, once (then holding its last frame), +// or held at the keyframe's start frame. +enum class ChildMode +{ LOOP, ONCE, HOLD, COUNT - }; +}; - enum class ItemType - { +enum class ItemType +{ NONE, ROOT, LAYER, NULL_, TRIGGER, COUNT - }; +}; - inline constexpr int NONE = (int)ItemType::NONE; - inline constexpr int ROOT = (int)ItemType::ROOT; - inline constexpr int LAYER = (int)ItemType::LAYER; - inline constexpr int NULL_ = (int)ItemType::NULL_; - inline constexpr int TRIGGER = (int)ItemType::TRIGGER; +inline constexpr int NONE = (int)ItemType::NONE; +inline constexpr int ROOT = (int)ItemType::ROOT; +inline constexpr int LAYER = (int)ItemType::LAYER; +inline constexpr int NULL_ = (int)ItemType::NULL_; +inline constexpr int TRIGGER = (int)ItemType::TRIGGER; - inline constexpr int FRAME_DURATION_MIN = 1; - inline constexpr int FRAME_DURATION_MAX = 1000000; - inline constexpr int FRAME_NUM_MIN = 1; - inline constexpr int FRAME_NUM_MAX = FRAME_DURATION_MAX; - inline constexpr int FPS_MIN = 1; - inline constexpr int FPS_MAX = 120; - inline constexpr int FRAME_DEPTH_MAX = 100; - inline constexpr float FRAME_BLUR_MAX = 255.0f; // Flash's BlurFilter limit +inline constexpr int FRAME_DURATION_MIN = 1; +inline constexpr int FRAME_DURATION_MAX = 1000000; +inline constexpr int FRAME_NUM_MIN = 1; +inline constexpr int FRAME_NUM_MAX = FRAME_DURATION_MAX; +inline constexpr int FPS_MIN = 1; +inline constexpr int FPS_MAX = 120; +inline constexpr int FRAME_DEPTH_MAX = 100; +inline constexpr float FRAME_BLUR_MAX = 255.0f; // Flash's BlurFilter limit - enum class SpritesheetMergeOrigin - { +enum class SpritesheetMergeOrigin +{ APPEND_RIGHT, APPEND_BOTTOM, COUNT - }; +}; - inline constexpr int APPEND_RIGHT = (int)SpritesheetMergeOrigin::APPEND_RIGHT; - inline constexpr int APPEND_BOTTOM = (int)SpritesheetMergeOrigin::APPEND_BOTTOM; +inline constexpr int APPEND_RIGHT = (int)SpritesheetMergeOrigin::APPEND_RIGHT; +inline constexpr int APPEND_BOTTOM = (int)SpritesheetMergeOrigin::APPEND_BOTTOM; - enum class RegionFrameMapping - { +enum class RegionFrameMapping +{ PRESERVE, SET - }; +}; - enum FileMergePreset - { +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, ADD, SUBTRACT, MULTIPLY, DIVIDE - }; +}; - enum Flag - { +enum Flag +{ SERIALIZE_GROUPS = 1 << 0, SERIALIZE_REGIONS = 1 << 1, SERIALIZE_SOUNDS = 1 << 2, @@ -150,56 +150,60 @@ SERIALIZE_EXTENSIONS = 1 << 7, SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES = 1 << 8, SERIALIZE_PURGE_DEFAULT_COLORS = 1 << 9 - }; +}; - using Flags = int; +using Flags = int; - constexpr bool has_flag(Flags flags, Flag flag) { return (flags & flag) != 0; } - constexpr Flags SERIALIZE_EDITOR_DEFAULT = SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | - SERIALIZE_REDUNDANT_FRAME_REGION_VALUES | SERIALIZE_EXTENSIONS; - constexpr Flags SERIALIZE_DEFAULT = - SERIALIZE_EDITOR_DEFAULT | SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES | SERIALIZE_BAKE_GROUP_FRAMES; - constexpr Flags SERIALIZE_ISAAC_DEFAULT = SERIALIZE_BAKE_GROUP_FRAMES | SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES; - constexpr Flags SERIALIZE_ANM2ED_DEFAULT = - SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | SERIALIZE_NESTED_GROUPS | SERIALIZE_EXTENSIONS; +constexpr bool has_flag(Flags flags, Flag flag) +{ + return (flags & flag) != 0; +} - class Model; +constexpr Flags SERIALIZE_EDITOR_DEFAULT = SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | + SERIALIZE_REDUNDANT_FRAME_REGION_VALUES | SERIALIZE_EXTENSIONS; +constexpr Flags SERIALIZE_DEFAULT = + SERIALIZE_EDITOR_DEFAULT | SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES | SERIALIZE_BAKE_GROUP_FRAMES; +constexpr Flags SERIALIZE_ISAAC_DEFAULT = SERIALIZE_BAKE_GROUP_FRAMES | SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES; +constexpr Flags SERIALIZE_ANM2ED_DEFAULT = + SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | SERIALIZE_NESTED_GROUPS | SERIALIZE_EXTENSIONS; - // How a document saves: the game's copy with the editor's embedded, or the editor's own JSON; `gameModel` is the - // game's copy when it differs from the document (animation layers flattened). - struct Options - { - bool isJson = false; // the editor's own JSON document instead +class Model; + +// How a document saves: the game's copy with the editor's embedded, or the editor's own JSON. `gameModel` is the +// game's copy when it differs from the document (animation layers flattened). +struct Options +{ + bool isJson = false; // the editor's own JSON document instead bool isPixelBaked = true; // what the game can't draw is baked into a spritesheet beside the file const Model* gameModel = nullptr; - }; +}; #define FRAME_CHANGE_SCALARS \ - X(cropX, crop.x, true, false, changeIsCropX, changeCrop.x) \ - X(cropY, crop.y, true, false, changeIsCropY, changeCrop.y) \ - X(sizeX, size.x, true, false, changeIsSizeX, changeSize.x) \ - X(sizeY, size.y, true, false, changeIsSizeY, changeSize.y) \ - X(pivotX, pivot.x, true, false, changeIsPivotX, changePivot.x) \ - X(pivotY, pivot.y, true, false, changeIsPivotY, changePivot.y) \ - X(positionX, position.x, false, false, changeIsPositionX, changePosition.x) \ - X(positionY, position.y, false, false, changeIsPositionY, changePosition.y) \ - X(scaleX, scale.x, false, false, changeIsScaleX, changeScale.x) \ - X(scaleY, scale.y, false, false, changeIsScaleY, changeScale.y) \ - X(skewX, skew.x, false, false, changeIsSkewX, changeSkew.x) \ - X(skewY, skew.y, false, false, changeIsSkewY, changeSkew.y) \ - X(rotation, rotation, false, false, changeIsRotation, changeRotation) \ - X(tintR, tint.r, false, true, changeIsTintR, changeTint.r) \ - X(tintG, tint.g, false, true, changeIsTintG, changeTint.g) \ - X(tintB, tint.b, false, true, changeIsTintB, changeTint.b) \ - X(tintA, tint.a, false, true, changeIsTintA, changeTint.a) \ - X(colorOffsetR, colorOffset.r, false, true, changeIsColorOffsetR, changeColorOffset.r) \ - X(colorOffsetG, colorOffset.g, false, true, changeIsColorOffsetG, changeColorOffset.g) \ - X(colorOffsetB, colorOffset.b, false, true, changeIsColorOffsetB, changeColorOffset.b) \ - X(colorOffsetA, colorOffset.a, false, true, changeIsColorOffsetA, changeColorOffset.a) \ - X(blur, blur, true, false, changeIsBlur, changeBlur) + X(cropX, crop.x, true, false, changeIsCropX, changeCrop.x) \ + X(cropY, crop.y, true, false, changeIsCropY, changeCrop.y) \ + X(sizeX, size.x, true, false, changeIsSizeX, changeSize.x) \ + X(sizeY, size.y, true, false, changeIsSizeY, changeSize.y) \ + X(pivotX, pivot.x, true, false, changeIsPivotX, changePivot.x) \ + X(pivotY, pivot.y, true, false, changeIsPivotY, changePivot.y) \ + X(positionX, position.x, false, false, changeIsPositionX, changePosition.x) \ + X(positionY, position.y, false, false, changeIsPositionY, changePosition.y) \ + X(scaleX, scale.x, false, false, changeIsScaleX, changeScale.x) \ + X(scaleY, scale.y, false, false, changeIsScaleY, changeScale.y) \ + X(skewX, skew.x, false, false, changeIsSkewX, changeSkew.x) \ + X(skewY, skew.y, false, false, changeIsSkewY, changeSkew.y) \ + X(rotation, rotation, false, false, changeIsRotation, changeRotation) \ + X(tintR, tint.r, false, true, changeIsTintR, changeTint.r) \ + X(tintG, tint.g, false, true, changeIsTintG, changeTint.g) \ + X(tintB, tint.b, false, true, changeIsTintB, changeTint.b) \ + X(tintA, tint.a, false, true, changeIsTintA, changeTint.a) \ + X(colorOffsetR, colorOffset.r, false, true, changeIsColorOffsetR, changeColorOffset.r) \ + X(colorOffsetG, colorOffset.g, false, true, changeIsColorOffsetG, changeColorOffset.g) \ + X(colorOffsetB, colorOffset.b, false, true, changeIsColorOffsetB, changeColorOffset.b) \ + X(colorOffsetA, colorOffset.a, false, true, changeIsColorOffsetA, changeColorOffset.a) \ + X(blur, blur, true, false, changeIsBlur, changeBlur) - struct FrameChange - { +struct FrameChange +{ std::optional regionId; #define X(name, member, isLayerOnly, isColor, isEnabled, value) std::optional name{}; FRAME_CHANGE_SCALARS @@ -211,16 +215,16 @@ std::optional interpolation; std::optional isFlipX; std::optional isFlipY; - // An animation layer's child; a spritesheet layer's frames keep theirs. + // An animation layer's child. A spritesheet layer's frames keep theirs. std::optional childAnimation; std::optional childMode; std::optional childStart; std::optional isChildStartRandom; std::optional isChildRestart; - }; +}; - struct Reference - { +struct Reference +{ int animationIndex = -1; int itemType = (int)ItemType::NONE; int itemID = -1; @@ -229,25 +233,28 @@ int groupId = -1; auto operator<=>(const Reference&) const = default; - }; +}; - // A Reference expressed by runtime uids, so it survives inserts, deletes and moves. - struct Handle - { +// A Reference expressed by runtime uids, so it survives inserts, deletes and moves. +struct Handle +{ std::uint64_t animation = 0; std::uint64_t item = 0; std::uint64_t frame = 0; auto operator<=>(const Handle&) const = default; - }; +}; - inline float interpolation_factor(Interpolation interpolation, float value) - { +inline float interpolation_factor(Interpolation interpolation, float value) +{ value = glm::clamp(value, 0.0f, 1.0f); - if (interpolation == Interpolation::LINEAR) return value; - if (interpolation == Interpolation::EASE_IN) return value * value; - if (interpolation == Interpolation::EASE_OUT) return 1.0f - ((1.0f - value) * (1.0f - value)); + if (interpolation == Interpolation::LINEAR) + return value; + if (interpolation == Interpolation::EASE_IN) + return value * value; + if (interpolation == Interpolation::EASE_OUT) + return 1.0f - ((1.0f - value) * (1.0f - value)); if (interpolation == Interpolation::EASE_IN_OUT) - return value < 0.5f ? (2.0f * value * value) : (1.0f - std::pow(-2.0f * value + 2.0f, 2.0f) * 0.5f); + return value < 0.5f ? (2.0f * value * value) : (1.0f - std::pow(-2.0f * value + 2.0f, 2.0f) * 0.5f); return 0.0f; - } +} diff --git a/src/model/draw.cpp b/src/model/draw.cpp index a1b0d3e..5858a1c 100644 --- a/src/model/draw.cpp +++ b/src/model/draw.cpp @@ -6,280 +6,295 @@ #include "model/frames.h" #include "math_util.h" - constexpr unsigned RANDOM_MULTIPLIER_A = 73856093u; - constexpr unsigned RANDOM_MULTIPLIER_B = 19349663u; +constexpr unsigned RANDOM_MULTIPLIER_A = 73856093u; +constexpr unsigned RANDOM_MULTIPLIER_B = 19349663u; - glm::mat4 draw_quad_model_get(const Draw& draw) - { +glm::mat4 draw_quad_model_get(const Draw& draw) +{ auto& frame = draw.frame; - return quad_model_get(frame.size, frame.position, frame.pivot, percent_to_unit(frame.scale), - frame.rotation, percent_to_unit(frame.skew)); - } + return quad_model_get(frame.size, frame.position, frame.pivot, percent_to_unit(frame.scale), frame.rotation, + percent_to_unit(frame.skew)); +} - // Where an animation layer's frame puts its child: the frame's transform, with its pivot as the child's origin. - glm::mat4 frame_child_model_get(const Frame& frame) - { - return quad_model_get(glm::vec2(1.0f), frame.position, frame.pivot, percent_to_unit(frame.scale), - frame.rotation, percent_to_unit(frame.skew)); - } +// Where an animation layer's frame puts its child: the frame's transform, with its pivot as the child's origin. +glm::mat4 frame_child_model_get(const Frame& frame) +{ + return quad_model_get(glm::vec2(1.0f), frame.position, frame.pivot, percent_to_unit(frame.scale), frame.rotation, + percent_to_unit(frame.skew)); +} - // How many canvas pixels one spritesheet pixel of a layer draw covers (along its longer axis). - float draw_scale_get(const Draw& draw) - { +// How many canvas pixels one spritesheet pixel of a layer draw covers (along its longer axis). +float draw_scale_get(const Draw& draw) +{ auto model = draw.parent * draw_quad_model_get(draw); auto size = glm::max(draw.frame.size, glm::vec2(1.0f)); return std::max(glm::length(glm::vec2(model[0])) / size.x, glm::length(glm::vec2(model[1])) / size.y); - } +} - // When an item is drawn: now, and for each sample its time if the track has a frame there. - static std::vector> draw_times_get(const Animation& animation, const Track& track, - const DrawOptions& options) - { +// When an item is drawn: now, and for each sample its time if the track has a frame there. +static std::vector> draw_times_get(const Animation& animation, const Track& track, + const DrawOptions& options) +{ std::vector> times; for (int i = 0; i < (int)options.samples.size(); ++i) { - auto& sample = options.samples[i]; - if (!options.isIndexSampled) - { - auto time = options.time + sample.timeOffset; - if (time >= 0.0f && time <= (float)animation.frameNum) times.emplace_back(i, time); - continue; - } - auto index = track.frames.empty() ? -1 : frame_index_from_time_get(track, options.time); - if (index < 0 || index + sample.indexOffset < 0 || index + sample.indexOffset >= (int)track.frames.size()) - continue; - times.emplace_back(i, frame_time_from_index_get(track, index + sample.indexOffset)); + auto& sample = options.samples[i]; + if (!options.isIndexSampled) + { + auto time = options.time + sample.timeOffset; + if (time >= 0.0f && time <= (float)animation.frameNum) + times.emplace_back(i, time); + continue; + } + auto index = track.frames.empty() ? -1 : frame_index_from_time_get(track, options.time); + if (index < 0 || index + sample.indexOffset < 0 || index + sample.indexOffset >= (int)track.frames.size()) + continue; + times.emplace_back(i, frame_time_from_index_get(track, index + sample.indexOffset)); } times.emplace_back(-1, options.time); return times; - } +} - // A keyframe's start frame in its child animation; a random start is fixed per layer and keyframe. - static float child_start_get(const Frame& frame, int length, int seed, int index) - { - if (!frame.isChildStartRandom) return (float)frame.childStart; +// A keyframe's start frame in its child animation. A random start is fixed per layer and keyframe. +static float child_start_get(const Frame& frame, int length, int seed, int index) +{ + if (!frame.isChildStartRandom) + return (float)frame.childStart; return (float)((((unsigned)seed * RANDOM_MULTIPLIER_A) ^ ((unsigned)index * RANDOM_MULTIPLIER_B)) % (unsigned)length); - } +} - // Where an animation layer's child animation is at `time`. Its clock runs from the last keyframe that restarted it - // (the first, one set to restart, or one that changes the animation), from that keyframe's start frame; the keyframe - // playing then loops the child, stops it at its end, or holds its own start frame. - float child_time_get(const Track& track, float time, int length, int seed) - { +// Where an animation layer's child animation is at `time`. Its clock runs from the last keyframe that restarted it +// (the first, one set to restart, or one that changes the animation), from that keyframe's start frame. The keyframe +// playing then loops the child, stops it at its end, or holds its own start frame. +float child_time_get(const Track& track, float time, int length, int seed) +{ float start = 0; float clockStart = 0; float clockOffset = 0; for (int i = 0; i < (int)track.frames.size(); ++i) { - auto& frame = track.frames[i]; - if (i == 0 || frame.isChildRestart || frame.childAnimation != track.frames[i - 1].childAnimation) - { - clockStart = start; - clockOffset = child_start_get(frame, length, seed, i); - } - start += frame.duration; - if (time >= start && i + 1 < (int)track.frames.size()) continue; - if (frame.childMode == ChildMode::HOLD) return child_start_get(frame, length, seed, i); - auto childTime = clockOffset + std::max(time, 0.0f) - clockStart; - if (frame.childMode == ChildMode::ONCE) return std::min(childTime, (float)(length - 1)); - return std::fmod(childTime, (float)length); + auto& frame = track.frames[i]; + if (i == 0 || frame.isChildRestart || frame.childAnimation != track.frames[i - 1].childAnimation) + { + clockStart = start; + clockOffset = child_start_get(frame, length, seed, i); + } + start += frame.duration; + if (time >= start && i + 1 < (int)track.frames.size()) + continue; + if (frame.childMode == ChildMode::HOLD) + return child_start_get(frame, length, seed, i); + auto childTime = clockOffset + std::max(time, 0.0f) - clockStart; + if (frame.childMode == ChildMode::ONCE) + return std::min(childTime, (float)(length - 1)); + return std::fmod(childTime, (float)length); } return 0.0f; - } +} - // The child animation an animation layer's frame plays: its own, or the layer's, from this file or a library. - std::pair child_get(const Model& model, const Layer& layer, const Frame& frame, - const LibraryGet& library_get) - { +// The child animation an animation layer's frame plays: its own, or the layer's, from this file or a library. +std::pair child_get(const Model& model, const Layer& layer, const Frame& frame, + const LibraryGet& library_get) +{ auto childModel = layer.libraryId == -1 ? &model : library_get ? library_get(model, layer.libraryId) : nullptr; auto childAnimation = childModel ? childModel->animation_named_get(frame.childAnimation.empty() ? layer.animation : frame.childAnimation) : nullptr; - if (childAnimation && childAnimation->frameNum < FRAME_NUM_MIN) childAnimation = nullptr; + if (childAnimation && childAnimation->frameNum < FRAME_NUM_MIN) + childAnimation = nullptr; return {childModel, childAnimation}; - } +} - static void animation_triggers_add(std::vector& fires, const Model& model, const Animation& animation, int time, - const LibraryGet& library_get, std::vector& playing, int layerId = -1) - { +static void animation_triggers_add(std::vector& fires, const Model& model, const Animation& animation, + int time, const LibraryGet& library_get, std::vector& playing, + int layerId = -1) +{ if (animation.triggers.isVisible) - if (auto trigger = frame_generate(animation.triggers, (float)time); trigger.isVisible) - fires.push_back({&model, std::move(trigger), layerId}); + if (auto trigger = frame_generate(animation.triggers, (float)time); trigger.isVisible) + fires.push_back({&model, std::move(trigger), layerId}); // A child fires the trigger of each frame it reaches: when its frame (or animation) changes from the parent's last. - tracks_each( - animation.layers, - [&](const Track& track, const TrackGroup* group) + tracks_each(animation.layers, [&](const Track& track, const TrackGroup* group) { + auto layer = item_get(model.content.layers, track.id); + if (!layer || !layer->is_animation() || !track.isVisible || (group && !group->isVisible)) + return; + auto frame = frame_generate(track, (float)time); + auto [childModel, childAnimation] = child_get(model, *layer, frame, library_get); + if (!frame.isVisible || !childAnimation || std::ranges::contains(playing, childAnimation)) + return; + auto childTime = (int)child_time_get(track, (float)time, childAnimation->frameNum, layer->id); + if (time > 0) { - auto layer = item_get(model.content.layers, track.id); - if (!layer || !layer->is_animation() || !track.isVisible || (group && !group->isVisible)) return; - auto frame = frame_generate(track, (float)time); - auto [childModel, childAnimation] = child_get(model, *layer, frame, library_get); - if (!frame.isVisible || !childAnimation || std::ranges::contains(playing, childAnimation)) return; - auto childTime = (int)child_time_get(track, (float)time, childAnimation->frameNum, layer->id); - if (time > 0) - { auto previous = frame_generate(track, (float)(time - 1)); auto previousTime = (int)child_time_get(track, (float)(time - 1), childAnimation->frameNum, layer->id); if (previous.isVisible && child_get(model, *layer, previous, library_get).second == childAnimation && previousTime == childTime) - return; - } - playing.push_back(childAnimation); - animation_triggers_add(fires, *childModel, *childAnimation, childTime, library_get, playing, - layerId == -1 ? layer->id : layerId); - playing.pop_back(); - }); - } + return; + } + playing.push_back(childAnimation); + animation_triggers_add(fires, *childModel, *childAnimation, childTime, library_get, playing, + layerId == -1 ? layer->id : layerId); + playing.pop_back(); + }); +} - // The triggers that fire on an animation's frame: its own, and those its animation layers' children reach then. - std::vector animation_triggers_get(const Model& model, const Animation& animation, int time, - const LibraryGet& library_get) - { +// The triggers that fire on an animation's frame: its own, and those its animation layers' children reach then. +std::vector animation_triggers_get(const Model& model, const Animation& animation, int time, + const LibraryGet& library_get) +{ std::vector fires; std::vector playing{&animation}; animation_triggers_add(fires, model, animation, time, library_get, playing); return fires; - } +} - // Where an animation layer track (`layerId`) puts its child at a time, in the animation's space. - std::optional layer_child_transform_get(const Animation& animation, int layerId, float time, - bool isRootTransform) - { +// Where an animation layer track (`layerId`) puts its child at a time, in the animation's space. +std::optional layer_child_transform_get(const Animation& animation, int layerId, float time, + bool isRootTransform) +{ std::optional transform{}; - tracks_each(animation.layers, - [&](const Track& track, const TrackGroup* group) - { - if (track.id != layerId || transform) return; - glm::mat4 parent(1.0f); - if (isRootTransform) - { - parent *= frame_parent_model_get(frame_generate(animation.root, time)); - if (group) parent *= frame_parent_model_get(frame_generate(group->root, time)); - } - transform = parent * frame_child_model_get(frame_generate(track, time)); - }); + tracks_each(animation.layers, [&](const Track& track, const TrackGroup* group) { + if (track.id != layerId || transform) + return; + glm::mat4 parent(1.0f); + if (isRootTransform) + { + parent *= frame_parent_model_get(frame_generate(animation.root, time)); + if (group) + parent *= frame_parent_model_get(frame_generate(group->root, time)); + } + transform = parent * frame_child_model_get(frame_generate(track, time)); + }); return transform; - } +} - // `playing` holds the animations being drawn into one another, so an animation never draws itself. - static std::vector animation_draws_get(const Model& model, const Animation& animation, const DrawOptions& options, - std::vector& playing) - { +// `playing` holds the animations being drawn into one another, so an animation never draws itself. +static std::vector animation_draws_get(const Model& model, const Animation& animation, const DrawOptions& options, + std::vector& playing) +{ std::vector draws; - // Each layer draw's place in the drawing order: its track's position among the layers plus its frame's depth; a + // Each layer draw's place in the drawing order: its track's position among the layers plus its frame's depth. A // moved layer lands past the one already at that place (below it when moved down, above it when moved up). std::vector> layerOrders; int layerOrder = 0; - auto parent_get = [&](float time, const TrackGroup* group) - { - glm::mat4 parent(1.0f); - if (!options.isRootTransform) return parent; - parent *= frame_parent_model_get(frame_generate(animation.root, time)); - if (group) parent *= frame_parent_model_get(frame_generate(group->root, time)); - return parent; + auto parent_get = [&](float time, const TrackGroup* group) { + glm::mat4 parent(1.0f); + if (!options.isRootTransform) + return parent; + parent *= frame_parent_model_get(frame_generate(animation.root, time)); + if (group) + parent *= frame_parent_model_get(frame_generate(group->root, time)); + return parent; }; // An animation layer's child animation, placed by the layer's frame (its pivot is the child's origin). - auto child_draws_add = - [&](const Track& track, const Layer& layer, int sample, float time, const Frame& frame, const glm::mat4& parent) - { - auto [childModel, childAnimation] = child_get(model, layer, frame, options.library_get); - if (!childAnimation || std::ranges::contains(playing, childAnimation)) return; - playing.push_back(childAnimation); - auto transform = parent * frame_child_model_get(frame); - DrawOptions childOptions{.time = child_time_get(track, time, childAnimation->frameNum, layer.id), - .isRootTransform = true, - .library_get = options.library_get}; - for (auto child : animation_draws_get(*childModel, *childAnimation, childOptions, playing)) - { - if (child.type != DrawType::LAYER) continue; - child.id = layer.id; - child.sample = sample; - child.time = time; - child.parent = transform * child.parent; - child.frame.tint *= frame.tint; - child.frame.colorOffset += frame.colorOffset; - child.frame.blur = std::max(child.frame.blur, frame.blur); // Each part blurs on its own, as the game draws it. - if (child.source != &model) child.frame.shaderId = -1; - layerOrders.emplace_back(layerOrder + frame.depth, frame.depth); - draws.push_back(std::move(child)); - } - playing.pop_back(); - }; - auto track_draws_add = [&](const Track& track, DrawType type, int id, int groupType, const TrackGroup* group) - { - auto layer = type == DrawType::LAYER ? item_get(model.content.layers, id) : nullptr; - for (auto [sample, time] : draw_times_get(animation, track, options)) - { - auto frame = frame_generate(track, time); - if (!frame.isVisible) continue; - auto parent = parent_get(time, type == DrawType::ROOT ? nullptr : group); - if (layer) + auto child_draws_add = [&](const Track& track, const Layer& layer, int sample, float time, const Frame& frame, + const glm::mat4& parent) { + auto [childModel, childAnimation] = child_get(model, layer, frame, options.library_get); + if (!childAnimation || std::ranges::contains(playing, childAnimation)) + return; + playing.push_back(childAnimation); + auto transform = parent * frame_child_model_get(frame); + DrawOptions childOptions{.time = child_time_get(track, time, childAnimation->frameNum, layer.id), + .isRootTransform = true, + .library_get = options.library_get}; + for (auto child : animation_draws_get(*childModel, *childAnimation, childOptions, playing)) { - frame = model.frame_effective(id, frame); - if (options.isRootTransform) - for (auto* root : {&animation.root, group ? &group->root : nullptr}) - if (root) - { - auto rootFrame = frame_generate(*root, time); - frame.tint *= rootFrame.tint; - frame.colorOffset += rootFrame.colorOffset; - } - if (layer->is_animation()) - { - child_draws_add(track, *layer, sample, time, frame, parent); - continue; - } + if (child.type != DrawType::LAYER) + continue; + child.id = layer.id; + child.sample = sample; + child.time = time; + child.parent = transform * child.parent; + child.frame.tint *= frame.tint; + child.frame.colorOffset += frame.colorOffset; + child.frame.blur = + std::max(child.frame.blur, frame.blur); // Each part blurs on its own, as the game draws it. + if (child.source != &model) + child.frame.shaderId = -1; + layerOrders.emplace_back(layerOrder + frame.depth, frame.depth); + draws.push_back(std::move(child)); } - layerOrders.emplace_back(layerOrder + frame.depth, frame.depth); - draws.push_back( - {type, id, groupType, sample, time, frame, parent, &model, layer ? layer->spritesheetId : -1, id}); - } + playing.pop_back(); }; - if (animation.root.isVisible) track_draws_add(animation.root, DrawType::ROOT, -1, NONE, nullptr); + auto track_draws_add = [&](const Track& track, DrawType type, int id, int groupType, const TrackGroup* group) { + auto layer = type == DrawType::LAYER ? item_get(model.content.layers, id) : nullptr; + for (auto [sample, time] : draw_times_get(animation, track, options)) + { + auto frame = frame_generate(track, time); + if (!frame.isVisible) + continue; + auto parent = parent_get(time, type == DrawType::ROOT ? nullptr : group); + if (layer) + { + frame = model.frame_effective(id, frame); + if (options.isRootTransform) + for (auto* root : {&animation.root, group ? &group->root : nullptr}) + if (root) + { + auto rootFrame = frame_generate(*root, time); + frame.tint *= rootFrame.tint; + frame.colorOffset += rootFrame.colorOffset; + } + if (layer->is_animation()) + { + child_draws_add(track, *layer, sample, time, frame, parent); + continue; + } + } + layerOrders.emplace_back(layerOrder + frame.depth, frame.depth); + draws.push_back( + {type, id, groupType, sample, time, frame, parent, &model, layer ? layer->spritesheetId : -1, id}); + } + }; + if (animation.root.isVisible) + track_draws_add(animation.root, DrawType::ROOT, -1, NONE, nullptr); for (auto [type, entries] : {std::pair{LAYER, &animation.layers}, std::pair{NULL_, &animation.nulls}}) { - auto drawType = type == LAYER ? DrawType::LAYER : DrawType::NULL_; - auto track_add = [&](const Track& track, const TrackGroup* group) - { - auto isFound = type == LAYER ? item_get(model.content.layers, track.id) != nullptr - : item_get(model.content.nulls, track.id) != nullptr; - if (track.isVisible && isFound) track_draws_add(track, drawType, track.id, NONE, group); - if (type == LAYER) ++layerOrder; - }; - for (auto& entry : *entries) - { - if (auto track = std::get_if(&entry)) + auto drawType = type == LAYER ? DrawType::LAYER : DrawType::NULL_; + auto track_add = [&](const Track& track, const TrackGroup* group) { + auto isFound = type == LAYER ? item_get(model.content.layers, track.id) != nullptr + : item_get(model.content.nulls, track.id) != nullptr; + if (track.isVisible && isFound) + track_draws_add(track, drawType, track.id, NONE, group); + if (type == LAYER) + ++layerOrder; + }; + for (auto& entry : *entries) { - track_add(*track, nullptr); - continue; + if (auto track = std::get_if(&entry)) + { + track_add(*track, nullptr); + continue; + } + auto& group = std::get(entry); + if (!group.isVisible) + continue; + if (group.root.isVisible) + track_draws_add(group.root, DrawType::GROUP_ROOT, group.id, type, &group); + for (auto& groupTrack : group.tracks) + track_add(groupTrack, &group); } - auto& group = std::get(entry); - if (!group.isVisible) continue; - if (group.root.isVisible) track_draws_add(group.root, DrawType::GROUP_ROOT, group.id, type, &group); - for (auto& groupTrack : group.tracks) - track_add(groupTrack, &group); - } } // Layers draw one after another, so reordering them by depth only moves them among each other. std::vector layerIndices; for (std::size_t i = 0; i < draws.size(); ++i) - if (draws[i].type == DrawType::LAYER) layerIndices.push_back(i); + if (draws[i].type == DrawType::LAYER) + layerIndices.push_back(i); auto sorted = layerIndices; std::ranges::stable_sort(sorted, {}, [&](std::size_t i) { return layerOrders[i]; }); std::vector layerDraws; for (auto i : sorted) - layerDraws.push_back(draws[i]); + layerDraws.push_back(draws[i]); for (std::size_t i = 0; i < layerIndices.size(); ++i) - draws[layerIndices[i]] = std::move(layerDraws[i]); + draws[layerIndices[i]] = std::move(layerDraws[i]); return draws; - } +} - std::vector animation_draws_get(const Model& model, const Animation& animation, const DrawOptions& options) - { +std::vector animation_draws_get(const Model& model, const Animation& animation, const DrawOptions& options) +{ std::vector playing{&animation}; return animation_draws_get(model, animation, options, playing); - } +} diff --git a/src/model/draw.h b/src/model/draw.h index 779ebc5..5163f0d 100644 --- a/src/model/draw.h +++ b/src/model/draw.h @@ -7,39 +7,39 @@ #include "model/model.h" // What an animation draws at a time, as plain data: every canvas (preview, render, about) draws from this list. - enum class DrawType - { +enum class DrawType +{ ROOT, GROUP_ROOT, LAYER, NULL_ - }; +}; - // An onion-skin sample: a time offset, or (when sampling by index) an offset in each track's frames. - struct DrawSample - { +// An onion-skin sample: a time offset, or (when sampling by index) an offset in each track's frames. +struct DrawSample +{ float timeOffset = 0; int indexOffset = 0; - }; +}; - // The document a library id of a document (the one drawn, or a library) points at; nullptr when not loaded. - using LibraryGet = std::function; +// The document a library id of a document (the one drawn, or a library) points at. Nullptr when not loaded. +using LibraryGet = std::function; - struct DrawOptions - { +struct DrawOptions +{ float time = 0; bool isRootTransform = false; bool isIndexSampled = false; std::vector samples; LibraryGet library_get = {}; - }; +}; - // An item's frame at a time; `parent` is the transform of its root and group root when root transforms are shown - // (whose tint and color offset are then folded into a layer's frame). `sample` indexes the samples, -1 for now. - // A layer draw shows spritesheet `spritesheetId` of `source`; an animation layer's child animation draws as its - // layers' draws, with the animation layer's id and transform. - struct Draw - { +// An item's frame at a time. `parent` is the transform of its root and group root when root transforms are shown +// (whose tint and color offset are then folded into a layer's frame). `sample` indexes the samples, -1 for now. +// A layer draw shows spritesheet `spritesheetId` of `source`. An animation layer's child animation draws as its +// layers' draws, with the animation layer's id and transform. +struct Draw +{ DrawType type = {}; int id = -1; int groupType = NONE; @@ -50,21 +50,21 @@ const Model* source = nullptr; int spritesheetId = -1; int sourceId = -1; // the layer of `source` drawn (a child's, for an animation layer's draws) - }; +}; - // A trigger that fires, from the animation played or a child animation (whose ids belong to `source`). - struct TriggerFire - { +// A trigger that fires, from the animation played or a child animation (whose ids belong to `source`). +struct TriggerFire +{ const Model* source = nullptr; Frame trigger = {}; - int layerId = -1; // the animation's layer whose child fired it; -1 for the animation's own - }; + int layerId = -1; // the animation's layer whose child fired it. -1 for the animation's own +}; - glm::mat4 draw_quad_model_get(const Draw&); - glm::mat4 frame_child_model_get(const Frame&); - std::pair child_get(const Model&, const Layer&, const Frame&, const LibraryGet&); - float child_time_get(const Track&, float, int, int); - std::optional layer_child_transform_get(const Animation&, int, float, bool); - float draw_scale_get(const Draw&); - std::vector animation_draws_get(const Model&, const Animation&, const DrawOptions&); - std::vector animation_triggers_get(const Model&, const Animation&, int, const LibraryGet& = {}); +glm::mat4 draw_quad_model_get(const Draw&); +glm::mat4 frame_child_model_get(const Frame&); +std::pair child_get(const Model&, const Layer&, const Frame&, const LibraryGet&); +float child_time_get(const Track&, float, int, int); +std::optional layer_child_transform_get(const Animation&, int, float, bool); +float draw_scale_get(const Draw&); +std::vector animation_draws_get(const Model&, const Animation&, const DrawOptions&); +std::vector animation_triggers_get(const Model&, const Animation&, int, const LibraryGet& = {}); diff --git a/src/model/frames.cpp b/src/model/frames.cpp index d348090..83d9a73 100644 --- a/src/model/frames.cpp +++ b/src/model/frames.cpp @@ -6,8 +6,8 @@ #include "model/draw.h" #include "math_util.h" - void frame_mix(Frame& frame, const Frame& next, float amount) - { +void frame_mix(Frame& frame, const Frame& next, float amount) +{ frame.rotation = glm::mix(frame.rotation, next.rotation, amount); frame.position = glm::mix(frame.position, next.position, amount); frame.scale = glm::mix(frame.scale, next.scale, amount); @@ -15,36 +15,38 @@ frame.colorOffset = glm::mix(frame.colorOffset, next.colorOffset, amount); frame.tint = glm::mix(frame.tint, next.tint, amount); frame.blur = glm::mix(frame.blur, next.blur, amount); - } +} - // Splits an interpolated frame into uninterpolated frames of at most `interval`; the first keeps the frame's uid. - std::vector frame_bake_split(const Frame& original, const Frame& next, int interval, bool isRoundScale, - bool isRoundRotation) - { +// Splits an interpolated frame into uninterpolated frames of at most `interval`. The first keeps the frame's uid. +std::vector frame_bake_split(const Frame& original, const Frame& next, int interval, bool isRoundScale, + bool isRoundRotation) +{ auto total = std::max(original.duration, FRAME_DURATION_MIN); interval = std::max(interval, FRAME_DURATION_MIN); std::vector frames; for (int duration = 0; duration < total; duration += interval) { - auto& baked = frames.emplace_back(duration == 0 ? original : frame_clone(original)); - frame_mix(baked, next, interpolation_factor(original.interpolation, (float)duration / total)); - baked.duration = std::min(interval, total - duration); - baked.interpolation = Interpolation::NONE; - if (isRoundScale) baked.scale = glm::round(baked.scale); - if (isRoundRotation) baked.rotation = std::round(baked.rotation); + auto& baked = frames.emplace_back(duration == 0 ? original : frame_clone(original)); + frame_mix(baked, next, interpolation_factor(original.interpolation, (float)duration / total)); + baked.duration = std::min(interval, total - duration); + baked.interpolation = Interpolation::NONE; + if (isRoundScale) + baked.scale = glm::round(baked.scale); + if (isRoundRotation) + baked.rotation = std::round(baked.rotation); } return frames; - } +} - glm::mat4 frame_parent_model_get(const Frame& frame) - { +glm::mat4 frame_parent_model_get(const Frame& frame) +{ return quad_model_parent_get(frame.position, {}, percent_to_unit(frame.scale), frame.rotation, - percent_to_unit(frame.skew)); - } + percent_to_unit(frame.skew)); +} - void frame_root_transform_apply(Frame& frame, const Frame& rootFrame, bool isRoundScale, bool isRoundRotation, - bool isUseRootPivot) - { +void frame_root_transform_apply(Frame& frame, const Frame& rootFrame, bool isRoundScale, bool isRoundRotation, + bool isUseRootPivot) +{ auto rootScale = percent_to_unit(rootFrame.scale); auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2(); auto offset = (frame.position - pivot) * rootScale; @@ -58,41 +60,46 @@ frame.tint *= rootFrame.tint; frame.colorOffset += rootFrame.colorOffset; - if (isRoundScale) frame.scale = glm::round(frame.scale); - if (isRoundRotation) frame.rotation = std::round(frame.rotation); - } + if (isRoundScale) + frame.scale = glm::round(frame.scale); + if (isRoundRotation) + frame.rotation = std::round(frame.rotation); +} - // For the game, a group root's transform is baked into its tracks one frame at a time. - void track_group_root_bake(Track& track, const Track& root, int frameNum) - { +// For the game, a group root's transform is baked into its tracks one frame at a time. +void track_group_root_bake(Track& track, const Track& root, int frameNum) +{ auto trackLength = track_length_get(track); - if (trackLength <= 0) return; + if (trackLength <= 0) + return; auto length = std::max({trackLength, track_length_get(root), frameNum, FRAME_DURATION_MIN}); std::vector frames; for (int time = 0; time < length; ++time) { - auto& frame = frames.emplace_back(frame_generate(track, (float)time)); - frame_root_transform_apply(frame, frame_generate(root, (float)time), false, false, false); - frame.duration = FRAME_DURATION_MIN; - frame.interpolation = Interpolation::NONE; + auto& frame = frames.emplace_back(frame_generate(track, (float)time)); + frame_root_transform_apply(frame, frame_generate(root, (float)time), false, false, false); + frame.duration = FRAME_DURATION_MIN; + frame.interpolation = Interpolation::NONE; } track.frames = std::move(frames); - } +} - // The track's state at a time: the frame playing then, mixed toward the next one when interpolated. A trigger is - // returned only on its exact frame; otherwise the result is invisible. - Frame frame_generate(const Track& track, float time) - { +// The track's state at a time: the frame playing then, mixed toward the next one when interpolated. A trigger is +// returned only on its exact frame. Otherwise the result is invisible. +Frame frame_generate(const Track& track, float time) +{ Frame frame = {}; frame.isVisible = false; - if (track.frames.empty()) return frame; + if (track.frames.empty()) + return frame; time = std::max(time, 0.0f); if (track.type == ItemType::TRIGGER) { - for (auto& trigger : track.frames) - if ((int)time == trigger.atFrame) return trigger; - return frame; + for (auto& trigger : track.frames) + if ((int)time == trigger.atFrame) + return trigger; + return frame; } const Frame* next = nullptr; @@ -100,160 +107,191 @@ int durationNext = 0; for (int i = 0; i < (int)track.frames.size(); ++i) { - frame = track.frames[i]; - durationNext += frame.duration; - if (time >= durationCurrent && time < durationNext) - { - if (i + 1 < (int)track.frames.size()) next = &track.frames[i + 1]; - break; - } - durationCurrent += frame.duration; + frame = track.frames[i]; + durationNext += frame.duration; + if (time >= durationCurrent && time < durationNext) + { + if (i + 1 < (int)track.frames.size()) + next = &track.frames[i + 1]; + break; + } + durationCurrent += frame.duration; } if (frame.interpolation != Interpolation::NONE && next && frame.duration > 1) - frame_mix(frame, *next, - interpolation_factor(frame.interpolation, (time - durationCurrent) / (durationNext - durationCurrent))); + frame_mix( + frame, *next, + interpolation_factor(frame.interpolation, (time - durationCurrent) / (durationNext - durationCurrent))); return frame; - } +} - int frame_index_from_at_frame_get(const Track& track, int atFrame) - { +int frame_index_from_at_frame_get(const Track& track, int atFrame) +{ for (int i = 0; i < (int)track.frames.size(); ++i) - if (track.frames[i].atFrame == atFrame) return i; + if (track.frames[i].atFrame == atFrame) + return i; return -1; - } +} - int frame_index_from_time_get(const Track& track, float time) - { - if (track.type == ItemType::TRIGGER) return frame_index_from_at_frame_get(track, (int)time); - if (track.frames.empty()) return -1; - if (time <= 0.0f) return 0; +int frame_index_from_time_get(const Track& track, float time) +{ + if (track.type == ItemType::TRIGGER) + return frame_index_from_at_frame_get(track, (int)time); + if (track.frames.empty()) + return -1; + if (time <= 0.0f) + return 0; float duration = 0; for (int i = 0; i < (int)track.frames.size(); ++i) { - duration += track.frames[i].duration; - if (time < duration) return i; + duration += track.frames[i].duration; + if (time < duration) + return i; } return (int)track.frames.size() - 1; - } +} - float frame_time_from_index_get(const Track& track, int index) - { - if (index < 0 || index >= (int)track.frames.size()) return 0.0f; - if (track.type == ItemType::TRIGGER) return (float)track.frames[index].atFrame; +float frame_time_from_index_get(const Track& track, int index) +{ + if (index < 0 || index >= (int)track.frames.size()) + return 0.0f; + if (track.type == ItemType::TRIGGER) + return (float)track.frames[index].atFrame; float time = 0; for (int i = 0; i < index; ++i) - time += track.frames[i].duration; + time += track.frames[i].duration; return time; - } +} - void frame_bake(Track& track, int index, int interval, bool isRoundScale, bool isRoundRotation) - { - if (index < 0 || index >= (int)track.frames.size()) return; +void frame_bake(Track& track, int index, int interval, bool isRoundScale, bool isRoundRotation) +{ + if (index < 0 || index >= (int)track.frames.size()) + return; auto original = track.frames[index]; if (original.duration <= FRAME_DURATION_MIN) { - track.frames[index].interpolation = Interpolation::NONE; - return; + track.frames[index].interpolation = Interpolation::NONE; + return; } auto next = index + 1 < (int)track.frames.size() ? track.frames[index + 1] : original; auto baked = frame_bake_split(original, next, interval, isRoundScale, isRoundRotation); track.frames.erase(track.frames.begin() + index); track.frames.insert(track.frames.begin() + index, baked.begin(), baked.end()); - } +} - void frames_generate_from_grid(Track& track, glm::ivec2 startPosition, glm::ivec2 size, glm::vec2 pivot, int columns, - int count, int duration) - { +void frames_generate_from_grid(Track& track, glm::ivec2 startPosition, glm::ivec2 size, glm::vec2 pivot, int columns, + int count, int duration) +{ for (int i = 0; i < count; ++i) { - auto& frame = track.frames.emplace_back(); - frame.duration = duration; - frame.pivot = pivot; - frame.size = size; - frame.crop = startPosition + glm::ivec2(size.x * (i % columns), size.y * (i / columns)); + auto& frame = track.frames.emplace_back(); + frame.duration = duration; + frame.pivot = pivot; + frame.size = size; + frame.crop = startPosition + glm::ivec2(size.x * (i % columns), size.y * (i / columns)); } - } +} - void frames_sort_by_at_frame(Track& track) - { +void frames_sort_by_at_frame(Track& track) +{ std::stable_sort(track.frames.begin(), track.frames.end(), [](const Frame& a, const Frame& b) { return a.atFrame < b.atFrame; }); - } +} - void frames_change(Track& track, FrameChange change, ItemType itemType, ChangeType changeType, - const std::set& selection, bool isAnimationLayer) - { - auto apply = [&](auto& target, const auto& optionalValue) - { - if (!optionalValue) return; - auto value = *optionalValue; - if (changeType == ChangeType::ADJUST) target = value; - if (changeType == ChangeType::ADD) target += value; - if (changeType == ChangeType::SUBTRACT) target -= value; - if (changeType == ChangeType::MULTIPLY) target *= value; - if (changeType == ChangeType::DIVIDE && value != decltype(value){}) target /= value; +void frames_change(Track& track, FrameChange change, ItemType itemType, ChangeType changeType, + const std::set& selection, bool isAnimationLayer) +{ + auto apply = [&](auto& target, const auto& optionalValue) { + if (!optionalValue) + return; + auto value = *optionalValue; + if (changeType == ChangeType::ADJUST) + target = value; + if (changeType == ChangeType::ADD) + target += value; + if (changeType == ChangeType::SUBTRACT) + target -= value; + if (changeType == ChangeType::MULTIPLY) + target *= value; + if (changeType == ChangeType::DIVIDE && value != decltype(value){}) + target /= value; }; for (auto index : selection) { - if (index < 0 || index >= (int)track.frames.size()) continue; - auto& frame = track.frames[index]; - if (change.isVisible) frame.isVisible = *change.isVisible; - if (change.interpolation) frame.interpolation = *change.interpolation; - if (change.isFlipX) frame.scale.x = -frame.scale.x; - if (change.isFlipY) frame.scale.y = -frame.scale.y; + if (index < 0 || index >= (int)track.frames.size()) + continue; + auto& frame = track.frames[index]; + if (change.isVisible) + frame.isVisible = *change.isVisible; + if (change.interpolation) + frame.interpolation = *change.interpolation; + if (change.isFlipX) + frame.scale.x = -frame.scale.x; + if (change.isFlipY) + frame.scale.y = -frame.scale.y; - apply(frame.duration, change.duration); - if (change.duration) frame.duration = std::max(FRAME_DURATION_MIN, frame.duration); - if (itemType == ItemType::LAYER && change.regionId) frame.regionId = *change.regionId; - if (itemType == ItemType::LAYER && change.shaderId) frame.shaderId = *change.shaderId; - if (itemType == ItemType::LAYER && change.depth) - { - apply(frame.depth, change.depth); - frame.depth = std::clamp(frame.depth, -FRAME_DEPTH_MAX, FRAME_DEPTH_MAX); - } + apply(frame.duration, change.duration); + if (change.duration) + frame.duration = std::max(FRAME_DURATION_MIN, frame.duration); + if (itemType == ItemType::LAYER && change.regionId) + frame.regionId = *change.regionId; + if (itemType == ItemType::LAYER && change.shaderId) + frame.shaderId = *change.shaderId; + if (itemType == ItemType::LAYER && change.depth) + { + apply(frame.depth, change.depth); + frame.depth = std::clamp(frame.depth, -FRAME_DEPTH_MAX, FRAME_DEPTH_MAX); + } #define X(name, member, isLayerOnly, isColor, isEnabled, value) \ - if (!isLayerOnly || itemType == ItemType::LAYER) apply(frame.member, change.name); - FRAME_CHANGE_SCALARS + if (!isLayerOnly || itemType == ItemType::LAYER) \ + apply(frame.member, change.name); + FRAME_CHANGE_SCALARS #undef X - frame.blur = std::clamp(frame.blur, 0.0f, FRAME_BLUR_MAX); - if (!isAnimationLayer) continue; - if (change.childAnimation) frame.childAnimation = *change.childAnimation; - if (change.childMode) frame.childMode = *change.childMode; - if (change.isChildStartRandom) frame.isChildStartRandom = *change.isChildStartRandom; - if (change.isChildRestart) frame.isChildRestart = *change.isChildRestart; - apply(frame.childStart, change.childStart); - frame.childStart = std::clamp(frame.childStart, 0, FRAME_NUM_MAX); + frame.blur = std::clamp(frame.blur, 0.0f, FRAME_BLUR_MAX); + if (!isAnimationLayer) + continue; + if (change.childAnimation) + frame.childAnimation = *change.childAnimation; + if (change.childMode) + frame.childMode = *change.childMode; + if (change.isChildStartRandom) + frame.isChildStartRandom = *change.isChildStartRandom; + if (change.isChildRestart) + frame.isChildRestart = *change.isChildRestart; + apply(frame.childStart, change.childStart); + frame.childStart = std::clamp(frame.childStart, 0, FRAME_NUM_MAX); } - } +} - // Bounds of all visible layer frames over the animation's length, or -1 when nothing is drawn. - glm::vec4 animation_rect(const Model& model, const Animation& animation, bool isRootTransform, - const LibraryGet& library_get) - { +// Bounds of all visible layer frames over the animation's length, or -1 when nothing is drawn. +glm::vec4 animation_rect(const Model& model, const Animation& animation, bool isRootTransform, + const LibraryGet& library_get) +{ constexpr glm::ivec2 CORNERS[4] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; glm::vec2 min{std::numeric_limits::infinity()}; glm::vec2 max{-std::numeric_limits::infinity()}; bool isAny = false; for (float time = 0.0f; time < (float)animation.frameNum; time += 1.0f) - for (auto& draw : animation_draws_get( - model, animation, {.time = time, .isRootTransform = isRootTransform, .library_get = library_get})) - { - if (draw.type != DrawType::LAYER || draw.frame.size == glm::vec2()) continue; - auto transform = draw.parent * draw_quad_model_get(draw); - for (auto& corner : CORNERS) + for (auto& draw : animation_draws_get( + model, animation, {.time = time, .isRootTransform = isRootTransform, .library_get = library_get})) { - auto world = glm::vec2(transform * glm::vec4(corner, 0.0f, 1.0f)); - min = glm::min(min, world); - max = glm::max(max, world); - isAny = true; + if (draw.type != DrawType::LAYER || draw.frame.size == glm::vec2()) + continue; + auto transform = draw.parent * draw_quad_model_get(draw); + for (auto& corner : CORNERS) + { + auto world = glm::vec2(transform * glm::vec4(corner, 0.0f, 1.0f)); + min = glm::min(min, world); + max = glm::max(max, world); + isAny = true; + } } - } - if (!isAny) return glm::vec4(-1.0f); + if (!isAny) + return glm::vec4(-1.0f); return {min.x, min.y, max.x - min.x, max.y - min.y}; - } +} diff --git a/src/model/frames.h b/src/model/frames.h index efa81f2..9ae6a88 100644 --- a/src/model/frames.h +++ b/src/model/frames.h @@ -5,17 +5,17 @@ #include "model/draw.h" - void frame_mix(Frame&, const Frame&, float); - std::vector frame_bake_split(const Frame&, const Frame&, int, bool, bool); - glm::mat4 frame_parent_model_get(const Frame&); - void frame_root_transform_apply(Frame&, const Frame&, bool, bool, bool); - Frame frame_generate(const Track&, float); - void track_group_root_bake(Track&, const Track&, int); - int frame_index_from_at_frame_get(const Track&, int); - int frame_index_from_time_get(const Track&, float); - float frame_time_from_index_get(const Track&, int); - void frame_bake(Track&, int, int, bool, bool); - void frames_generate_from_grid(Track&, glm::ivec2, glm::ivec2, glm::vec2, int, int, int); - void frames_sort_by_at_frame(Track&); - void frames_change(Track&, FrameChange, ItemType, ChangeType, const std::set&, bool isAnimationLayer = false); - glm::vec4 animation_rect(const Model&, const Animation&, bool, const LibraryGet& = {}); +void frame_mix(Frame&, const Frame&, float); +std::vector frame_bake_split(const Frame&, const Frame&, int, bool, bool); +glm::mat4 frame_parent_model_get(const Frame&); +void frame_root_transform_apply(Frame&, const Frame&, bool, bool, bool); +Frame frame_generate(const Track&, float); +void track_group_root_bake(Track&, const Track&, int); +int frame_index_from_at_frame_get(const Track&, int); +int frame_index_from_time_get(const Track&, float); +float frame_time_from_index_get(const Track&, int); +void frame_bake(Track&, int, int, bool, bool); +void frames_generate_from_grid(Track&, glm::ivec2, glm::ivec2, glm::vec2, int, int, int); +void frames_sort_by_at_frame(Track&); +void frames_change(Track&, FrameChange, ItemType, ChangeType, const std::set&, bool isAnimationLayer = false); +glm::vec4 animation_rect(const Model&, const Animation&, bool, const LibraryGet& = {}); diff --git a/src/model/json.cpp b/src/model/json.cpp index fc83ee5..3dcb8cb 100644 --- a/src/model/json.cpp +++ b/src/model/json.cpp @@ -14,87 +14,85 @@ using namespace simdjson; - constexpr std::string_view INDENT = " "; - constexpr std::size_t LINE_WIDTH_MAX = 100; - constexpr std::string_view WHITESPACE = " \t\r\n"; - constexpr std::size_t NUMBER_BUFFER_SIZE = 64; - constexpr std::pair ESCAPES[] = { - {'"', "\\\""}, {'\\', "\\\\"}, {'\n', "\\n"}, {'\r', "\\r"}, {'\t', "\\t"}}; - constexpr std::string_view INTERPOLATION_NAMES[] = {"", "lerp", "in", "out", "inOut"}; - constexpr std::string_view CHILD_MODE_NAMES[] = {"loop", "once", "hold"}; - constexpr std::string_view ORIGIN_NAMES[] = {"", "topLeft", "center"}; - constexpr std::size_t ISSUES_SHOWN_MAX = 5; - constexpr int HOURS_HALF_DAY = 12; - constexpr int DATE_FIELDS = 6; - constexpr int DATE_MERIDIEM_SIZE = 3; - const std::vector REGIONS_NONE; +constexpr std::string_view INDENT = " "; +constexpr std::size_t LINE_WIDTH_MAX = 100; +constexpr std::string_view WHITESPACE = " \t\r\n"; +constexpr std::size_t NUMBER_BUFFER_SIZE = 64; +constexpr std::pair ESCAPES[] = { + {'"', "\\\""}, {'\\', "\\\\"}, {'\n', "\\n"}, {'\r', "\\r"}, {'\t', "\\t"}}; +constexpr std::string_view INTERPOLATION_NAMES[] = {"", "lerp", "in", "out", "inOut"}; +constexpr std::string_view CHILD_MODE_NAMES[] = {"loop", "once", "hold"}; +constexpr std::string_view ORIGIN_NAMES[] = {"", "topLeft", "center"}; +constexpr std::size_t ISSUES_SHOWN_MAX = 5; +constexpr int HOURS_HALF_DAY = 12; +constexpr int DATE_FIELDS = 6; +constexpr int DATE_MERIDIEM_SIZE = 3; +const std::vector REGIONS_NONE; - bool is_json(std::string_view text) - { +bool is_json(std::string_view text) +{ auto start = text.find_first_not_of(WHITESPACE); return start != std::string_view::npos && text[start] == '{'; - } +} - template static int index_get(const Items& items, int id) - { +template static int index_get(const Items& items, int id) +{ auto it = std::ranges::find(items, id, &std::ranges::range_value_t::id); return it == items.end() ? -1 : (int)(it - items.begin()); - } +} - static glm::ivec4 color_to_bytes(const glm::vec4& color) - { - return {float_to_uint8(color.r), float_to_uint8(color.g), float_to_uint8(color.b), - float_to_uint8(color.a)}; - } +static glm::ivec4 color_to_bytes(const glm::vec4& color) +{ + return {float_to_uint8(color.r), float_to_uint8(color.g), float_to_uint8(color.b), float_to_uint8(color.a)}; +} - static glm::vec4 color_from_bytes(const glm::ivec4& bytes) - { - return {uint8_to_float(bytes.r), uint8_to_float(bytes.g), uint8_to_float(bytes.b), - uint8_to_float(bytes.a)}; - } +static glm::vec4 color_from_bytes(const glm::ivec4& bytes) +{ + return {uint8_to_float(bytes.r), uint8_to_float(bytes.g), uint8_to_float(bytes.b), uint8_to_float(bytes.a)}; +} - // The editor keeps dates as "MM/DD/YYYY hh:mm:ss AM"; JSON has them as ISO 8601. Anything else is kept as it is. - static std::string date_to_iso(const std::string& date) - { +// The editor keeps dates as "MM/DD/YYYY hh:mm:ss AM". JSON has them as ISO 8601. Anything else is kept as it is. +static std::string date_to_iso(const std::string& date) +{ int month{}, day{}, year{}, hour{}, minute{}, second{}; char meridiem[DATE_MERIDIEM_SIZE]{}; if (std::sscanf(date.c_str(), "%d/%d/%d %d:%d:%d %2s", &month, &day, &year, &hour, &minute, &second, meridiem) != DATE_FIELDS + 1) - return date; + return date; hour = hour % HOURS_HALF_DAY + (std::string_view(meridiem) == "PM" ? HOURS_HALF_DAY : 0); return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", year, month, day, hour, minute, second); - } +} - static std::string date_from_iso(const std::string& date) - { +static std::string date_from_iso(const std::string& date) +{ int year{}, month{}, day{}, hour{}, minute{}, second{}; if (std::sscanf(date.c_str(), "%d-%d-%dT%d:%d:%d", &year, &month, &day, &hour, &minute, &second) != DATE_FIELDS) - return date; + return date; auto hour12 = hour % HOURS_HALF_DAY == 0 ? HOURS_HALF_DAY : hour % HOURS_HALF_DAY; return std::format("{:02}/{:02}/{:04} {:02}:{:02}:{:02} {}", month, day, year, hour12, minute, second, hour < HOURS_HALF_DAY ? "AM" : "PM"); - } +} - static void line_break(std::string& text, int depth) - { +static void line_break(std::string& text, int depth) +{ text += '\n'; for (int i = 0; i < depth; ++i) - text += INDENT; - } + text += INDENT; +} - // Writing: defaults are left out and ids become indices. Containers opened inline (and everything inside them) stay - // on one line; any other that fits within LINE_WIDTH_MAX is joined onto one when it closes, unless it keeps its items - // a line each (frames and content items). - struct JsonWriter - { +// Writing: defaults are left out and ids become indices. Containers opened inline (and everything inside them) stay +// on one line. Any other that fits within LINE_WIDTH_MAX is joined onto one when it closes, unless it keeps its items +// a line each (frames and content items). +struct JsonWriter +{ static constexpr bool IS_READING = false; struct Scope { - bool isInline = false; - bool isJoinable = true; - std::size_t start = 0; - bool isEmpty = true; + bool isInline = false; + bool isJoinable = true; + std::size_t start = 0; + bool isEmpty = true; }; const Model& model; @@ -103,240 +101,281 @@ using namespace simdjson; void separate() { - if (scopes.empty()) return; - auto& scope = scopes.back(); - if (!scope.isEmpty) text += scope.isInline ? ", " : ","; - if (!scope.isInline) line_break(text, (int)scopes.size()); - scope.isEmpty = false; + if (scopes.empty()) + return; + auto& scope = scopes.back(); + if (!scope.isEmpty) + text += scope.isInline ? ", " : ","; + if (!scope.isInline) + line_break(text, (int)scopes.size()); + scope.isEmpty = false; } void open(char bracket, bool isInline, bool isJoinable = true) { - scopes.push_back({isInline || (!scopes.empty() && scopes.back().isInline), isJoinable, text.size()}); - text += bracket; + scopes.push_back({isInline || (!scopes.empty() && scopes.back().isInline), isJoinable, text.size()}); + text += bracket; } // Line breaks become nothing, or a space after a comma. void join(const Scope& scope) { - std::string joined; - for (auto i = scope.start; i < text.size(); ++i) - if (text[i] != '\n') - joined += text[i]; - else - { - i = text.find_first_not_of(' ', i + 1) - 1; - if (joined.back() == ',') joined += ' '; - } - auto column = scope.start - (text.rfind('\n', scope.start) + 1); - if (column + joined.size() <= LINE_WIDTH_MAX) text.replace(scope.start, std::string::npos, joined); + std::string joined; + for (auto i = scope.start; i < text.size(); ++i) + if (text[i] != '\n') + joined += text[i]; + else + { + i = text.find_first_not_of(' ', i + 1) - 1; + if (joined.back() == ',') + joined += ' '; + } + auto column = scope.start - (text.rfind('\n', scope.start) + 1); + if (column + joined.size() <= LINE_WIDTH_MAX) + text.replace(scope.start, std::string::npos, joined); } void close(char bracket) { - auto scope = scopes.back(); - scopes.pop_back(); - if (!scope.isEmpty && !scope.isInline) line_break(text, (int)scopes.size()); - text += bracket; - if (!scope.isInline && scope.isJoinable) join(scope); + auto scope = scopes.back(); + scopes.pop_back(); + if (!scope.isEmpty && !scope.isInline) + line_break(text, (int)scopes.size()); + text += bracket; + if (!scope.isInline && scope.isJoinable) + join(scope); } void key(std::string_view name) { - separate(); - value(name); - text += ": "; + separate(); + value(name); + text += ": "; } template void number(T number) { - char buffer[NUMBER_BUFFER_SIZE]{}; - text.append(buffer, std::to_chars(buffer, buffer + sizeof(buffer), number).ptr); + char buffer[NUMBER_BUFFER_SIZE]{}; + text.append(buffer, std::to_chars(buffer, buffer + sizeof(buffer), number).ptr); } - void value(bool value) { text += value ? "true" : "false"; } - void value(int value) { number(value); } - void value(float value) { number(value); } - void value(const std::string& value) { this->value(std::string_view(value)); } - void value(const std::filesystem::path& value) { this->value(path_to_utf8(value)); } + void value(bool value) + { + text += value ? "true" : "false"; + } + void value(int value) + { + number(value); + } + void value(float value) + { + number(value); + } + void value(const std::string& value) + { + this->value(std::string_view(value)); + } + void value(const std::filesystem::path& value) + { + this->value(path_to_utf8(value)); + } void value(std::string_view value) { - text += '"'; - for (auto character : value) - { - auto escape = std::ranges::find(ESCAPES, character, &std::pair::first); - if (escape != std::end(ESCAPES)) - text += escape->second; - else if ((unsigned char)character < ' ') - text += std::format("\\u{:04x}", (unsigned char)character); - else - text += character; - } - text += '"'; + text += '"'; + for (auto character : value) + { + auto escape = std::ranges::find(ESCAPES, character, &std::pair::first); + if (escape != std::end(ESCAPES)) + text += escape->second; + else if ((unsigned char)character < ' ') + text += std::format("\\u{:04x}", (unsigned char)character); + else + text += character; + } + text += '"'; } template void array(const Values& values, int count) { - open('[', true); - for (int i = 0; i < count; ++i) - { - separate(); - value(values[i]); - } - close(']'); + open('[', true); + for (int i = 0; i < count; ++i) + { + separate(); + value(values[i]); + } + close(']'); } - template void value(const glm::vec& value) { array(value, L); } - template void value(const std::vector& value) { array(value, (int)value.size()); } + template void value(const glm::vec& value) + { + array(value, L); + } + template void value(const std::vector& value) + { + array(value, (int)value.size()); + } template void field(std::string_view name, const T& value) { - key(name); - this->value(value); + key(name); + this->value(value); } template void field(std::string_view name, const T& value, const std::type_identity_t& defaultValue) { - if (value != defaultValue) field(name, value); + if (value != defaultValue) + field(name, value); } // Written as `to` makes it (and read back through `from`). template void field(std::string_view name, const T& value, const T& defaultValue, To&& to, From&&) { - field(name, to(value), to(defaultValue)); + field(name, to(value), to(defaultValue)); } template int reference(std::string_view name, int id, const Items& items, int defaultIndex = -1) { - auto index = index_get(items, id); - field(name, index, defaultIndex); - return index; + auto index = index_get(items, id); + field(name, index, defaultIndex); + return index; } template void references(std::string_view name, const std::vector& ids, const Items& items) { - std::vector indices; - for (auto id : ids) - if (auto index = index_get(items, id); index != -1) indices.push_back(index); - field(name, indices, {}); + std::vector indices; + for (auto id : ids) + if (auto index = index_get(items, id); index != -1) + indices.push_back(index); + field(name, indices, {}); } template void choice(std::string_view name, E value, const std::string_view (&names)[N], E defaultValue) { - if (value != defaultValue) field(name, names[(int)value]); + if (value != defaultValue) + field(name, names[(int)value]); } // An object with nothing in it is left out when `isOmittedEmpty`. template void object(std::string_view name, Fn&& fn, bool isInline, bool isOmittedEmpty = false) { - auto size = text.size(); - auto isParentEmpty = scopes.back().isEmpty; - key(name); - open('{', isInline); - fn(*this); - if (!isOmittedEmpty || !scopes.back().isEmpty) return close('}'); - scopes.pop_back(); - text.resize(size); - scopes.back().isEmpty = isParentEmpty; + auto size = text.size(); + auto isParentEmpty = scopes.back().isEmpty; + key(name); + open('{', isInline); + fn(*this); + if (!isOmittedEmpty || !scopes.back().isEmpty) + return close('}'); + scopes.pop_back(); + text.resize(size); + scopes.back().isEmpty = isParentEmpty; } template void list(std::string_view name, const std::vector& items, Fn&& fn, bool isInline, bool isJoinable = true) { - if (items.empty()) return; - key(name); - open('[', false, isJoinable); - for (auto& item : items) - { - separate(); - open('{', isInline); - fn(*this, item); - close('}'); - } - close(']'); + if (items.empty()) + return; + key(name); + open('[', false, isJoinable); + for (auto& item : items) + { + separate(); + open('{', isInline); + fn(*this, item); + close('}'); + } + close(']'); } template void values(std::string_view name, const std::vector& items, Get&& get) { - if (items.empty()) return; - key(name); - open('[', false, false); - for (auto& item : items) - { - separate(); - value(get(item)); - } - close(']'); + if (items.empty()) + return; + key(name); + open('[', false, false); + for (auto& item : items) + { + separate(); + value(get(item)); + } + close(']'); } - }; +}; - // Each returns what it expected when the value is the wrong kind (and leaves the value as it was). - static std::string_view value_read(dom::element element, bool& value) - { +// Each returns what it expected when the value is the wrong kind (and leaves the value as it was). +static std::string_view value_read(dom::element element, bool& value) +{ bool read = false; - if (element.get(read)) return "true or false"; + if (element.get(read)) + return "true or false"; value = read; return {}; - } +} - template +template requires std::is_same_v || std::is_same_v - std::string_view value_read(dom::element element, T& value) - { +std::string_view value_read(dom::element element, T& value) +{ double read = 0; - if (element.get(read)) return "a number"; + if (element.get(read)) + return "a number"; value = (T)read; return {}; - } +} - static std::string_view value_read(dom::element element, std::string& value) - { +static std::string_view value_read(dom::element element, std::string& value) +{ std::string_view read; - if (element.get(read)) return "a string"; + if (element.get(read)) + return "a string"; value = read; return {}; - } +} - static std::string_view value_read(dom::element element, std::filesystem::path& value) - { +static std::string_view value_read(dom::element element, std::filesystem::path& value) +{ std::string read; auto expected = value_read(element, read); - if (expected.empty()) value = path_from_utf8(read); + if (expected.empty()) + value = path_from_utf8(read); return expected; - } +} - template - std::string_view value_read(dom::element element, glm::vec& value) - { +template std::string_view value_read(dom::element element, glm::vec& value) +{ static const auto EXPECTED = std::format("an array of {} numbers", L); dom::array array; - if (element.get(array) || array.size() != L) return EXPECTED; + if (element.get(array) || array.size() != L) + return EXPECTED; auto read = value; int i = 0; for (auto item : array) - if (!value_read(item, read[i++]).empty()) return EXPECTED; + if (!value_read(item, read[i++]).empty()) + return EXPECTED; value = read; return {}; - } +} - template static std::string_view value_read(dom::element element, std::vector& value) - { +template static std::string_view value_read(dom::element element, std::vector& value) +{ dom::array array; - if (element.get(array)) return "an array"; + if (element.get(array)) + return "an array"; std::vector read; for (auto item : array) - if (auto expected = value_read(item, read.emplace_back()); !expected.empty()) return expected; + if (auto expected = value_read(item, read.emplace_back()); !expected.empty()) + return expected; value = std::move(read); return {}; - } +} - // Reading: only the keys present change the model, and an item's id is its index. Whatever can't be read (and any - // key it doesn't know) is noted in `issues` by where it is, e.g. "animations.Idle.layers[0].frames[2].pos". - struct JsonReader - { +// Reading: only the keys present change the model, and an item's id is its index. Whatever can't be read (and any +// key it doesn't know) is noted in `issues` by where it is, e.g. "animations.Idle.layers[0].frames[2].pos". +struct JsonReader +{ static constexpr bool IS_READING = true; const Model& model; @@ -348,150 +387,164 @@ using namespace simdjson; void issue_add(std::string_view name, std::string_view message) { - issues->push_back(std::format("{}{}: {}", path, name, message)); + issues->push_back(std::format("{}{}: {}", path, name, message)); } bool element_get(std::string_view name, dom::element& element) { - used.insert(name); - return !fields[name].get(element); + used.insert(name); + return !fields[name].get(element); } bool has(std::string_view name) { - dom::element element; - return element_get(name, element); + dom::element element; + return element_get(name, element); } template bool field(std::string_view name, T& value, const std::type_identity_t& = {}) { - dom::element element; - if (!element_get(name, element)) return false; - if (auto expected = value_read(element, value); !expected.empty()) - issue_add(name, std::format("expected {}", expected)); - return true; + dom::element element; + if (!element_get(name, element)) + return false; + if (auto expected = value_read(element, value); !expected.empty()) + issue_add(name, std::format("expected {}", expected)); + return true; } template void field(std::string_view name, T& value, const T&, To&& to, From&& from) { - auto converted = to(value); - if (field(name, converted)) value = from(converted); + auto converted = to(value); + if (field(name, converted)) + value = from(converted); } template bool is_index_valid(const Items& items, int index) { - return index >= -1 && index < (int)items.size(); + return index >= -1 && index < (int)items.size(); } template int reference(std::string_view name, int& id, const Items& items, int = -1) { - if (field(name, id) && !is_index_valid(items, id)) issue_add(name, std::format("no item at index {}", id)); - return id; + if (field(name, id) && !is_index_valid(items, id)) + issue_add(name, std::format("no item at index {}", id)); + return id; } template void references(std::string_view name, std::vector& ids, const Items& items) { - if (!field(name, ids)) return; - for (auto id : ids) - if (!is_index_valid(items, id)) issue_add(name, std::format("no item at index {}", id)); + if (!field(name, ids)) + return; + for (auto id : ids) + if (!is_index_valid(items, id)) + issue_add(name, std::format("no item at index {}", id)); } template void choice(std::string_view name, E& value, const std::string_view (&names)[N], E) { - std::string read; - if (!field(name, read)) return; - auto it = std::ranges::find(names, read); - if (read.empty() || it == std::end(names)) - issue_add(name, std::format("unknown value \"{}\"", read)); - else - value = (E)(it - std::begin(names)); + std::string read; + if (!field(name, read)) + return; + auto it = std::ranges::find(names, read); + if (read.empty() || it == std::end(names)) + issue_add(name, std::format("unknown value \"{}\"", read)); + else + value = (E)(it - std::begin(names)); } void unknown_keys_check() { - if (isKeyed) return; - for (auto [key, value] : fields) - if (!used.contains(key)) issue_add(key, "unknown key"); + if (isKeyed) + return; + for (auto [key, value] : fields) + if (!used.contains(key)) + issue_add(key, "unknown key"); } // Reads `element` as an object at `childPath` (ending in '.'), then notes the keys it never asked for. template void object_each(dom::element element, std::string childPath, Fn&& fn) { - JsonReader reader = {model, issues, std::move(childPath)}; - if (element.get(reader.fields)) - { - issues->push_back(std::format("{}: expected an object", reader.path.substr(0, reader.path.size() - 1))); - return; - } - fn(reader); - reader.unknown_keys_check(); + JsonReader reader = {model, issues, std::move(childPath)}; + if (element.get(reader.fields)) + { + issues->push_back(std::format("{}: expected an object", reader.path.substr(0, reader.path.size() - 1))); + return; + } + fn(reader); + reader.unknown_keys_check(); } template void object(std::string_view name, Fn&& fn, bool, bool = false) { - dom::element element; - if (element_get(name, element)) object_each(element, std::format("{}{}.", path, name), fn); + dom::element element; + if (element_get(name, element)) + object_each(element, std::format("{}{}.", path, name), fn); } bool array_get(std::string_view name, dom::array& array) { - dom::element element; - if (!element_get(name, element)) return false; - if (!element.get(array)) return true; - issue_add(name, "expected an array"); - return false; + dom::element element; + if (!element_get(name, element)) + return false; + if (!element.get(array)) + return true; + issue_add(name, "expected an array"); + return false; } template void list(std::string_view name, std::vector& items, Fn&& fn, bool, bool = true) { - dom::array array; - if (!array_get(name, array)) return; - items.clear(); - for (auto element : array) - { - auto& item = items.emplace_back(); - auto index = (int)items.size() - 1; - if constexpr (requires { item.id; }) item.id = index; - object_each(element, std::format("{}{}[{}].", path, name, index), - [&](JsonReader& reader) { fn(reader, item); }); - } + dom::array array; + if (!array_get(name, array)) + return; + items.clear(); + for (auto element : array) + { + auto& item = items.emplace_back(); + auto index = (int)items.size() - 1; + if constexpr (requires { item.id; }) + item.id = index; + object_each(element, std::format("{}{}[{}].", path, name, index), + [&](JsonReader& reader) { fn(reader, item); }); + } } template void values(std::string_view name, std::vector& items, Get&& get) { - dom::array array; - if (!array_get(name, array)) return; - items.clear(); - for (auto element : array) - { - auto& item = items.emplace_back(); - item.id = (int)items.size() - 1; - if (auto expected = value_read(element, get(item)); !expected.empty()) - issue_add(std::format("{}[{}]", name, item.id), std::format("expected {}", expected)); - } + dom::array array; + if (!array_get(name, array)) + return; + items.clear(); + for (auto element : array) + { + auto& item = items.emplace_back(); + item.id = (int)items.size() - 1; + if (auto expected = value_read(element, get(item)); !expected.empty()) + issue_add(std::format("{}[{}]", name, item.id), std::format("expected {}", expected)); + } } - }; +}; - // Each part of the document is described once; with a JsonWriter it is written, with a JsonReader read. +// Each part of the document is described once. With a JsonWriter it is written, with a JsonReader read. - template static void frame_io(Io& io, F& frame, ItemType type, const std::vector& regions) - { +template static void frame_io(Io& io, F& frame, ItemType type, const std::vector& regions) +{ static const Frame FRAME_DEFAULT = {}; auto& content = io.model.content; if (type == ItemType::TRIGGER) { - io.field("at", frame.atFrame, FRAME_DEFAULT.atFrame); - io.references("events", frame.eventIds, content.events); - io.references("sounds", frame.soundIds, content.sounds); - return; + io.field("at", frame.atFrame, FRAME_DEFAULT.atFrame); + io.references("events", frame.eventIds, content.events); + io.references("sounds", frame.soundIds, content.sounds); + return; } // A frame on a region takes the region's rectangle. if (type == ItemType::LAYER && io.reference("region", frame.regionId, regions) == -1) { - io.field("crop", frame.crop, FRAME_DEFAULT.crop); - io.field("size", frame.size, FRAME_DEFAULT.size); - io.field("pivot", frame.pivot, FRAME_DEFAULT.pivot); + io.field("crop", frame.crop, FRAME_DEFAULT.crop); + io.field("size", frame.size, FRAME_DEFAULT.size); + io.field("pivot", frame.pivot, FRAME_DEFAULT.pivot); } io.field("pos", frame.position, FRAME_DEFAULT.position); io.field("scale", frame.scale, FRAME_DEFAULT.scale); @@ -503,315 +556,304 @@ using namespace simdjson; io.field("visible", frame.isVisible, FRAME_DEFAULT.isVisible); io.choice("ease", frame.interpolation, INTERPOLATION_NAMES, FRAME_DEFAULT.interpolation); io.reference("shader", frame.shaderId, content.shaders); - if (type != ItemType::LAYER) return; + if (type != ItemType::LAYER) + return; io.field("depth", frame.depth, FRAME_DEFAULT.depth); io.field("blur", frame.blur, FRAME_DEFAULT.blur); io.object( "child", - [&](auto& childIo) - { - childIo.field("name", frame.childAnimation, FRAME_DEFAULT.childAnimation); - childIo.choice("mode", frame.childMode, CHILD_MODE_NAMES, FRAME_DEFAULT.childMode); - childIo.field("start", frame.childStart, FRAME_DEFAULT.childStart); - childIo.field("random", frame.isChildStartRandom, FRAME_DEFAULT.isChildStartRandom); - childIo.field("restart", frame.isChildRestart, FRAME_DEFAULT.isChildRestart); + [&](auto& childIo) { + childIo.field("name", frame.childAnimation, FRAME_DEFAULT.childAnimation); + childIo.choice("mode", frame.childMode, CHILD_MODE_NAMES, FRAME_DEFAULT.childMode); + childIo.field("start", frame.childStart, FRAME_DEFAULT.childStart); + childIo.field("random", frame.isChildStartRandom, FRAME_DEFAULT.isChildStartRandom); + childIo.field("restart", frame.isChildRestart, FRAME_DEFAULT.isChildRestart); }, true, true); - } +} - template - void frames_io(Io& io, std::string_view name, Frames& frames, ItemType type, - const std::vector& regions = REGIONS_NONE) - { +template +void frames_io(Io& io, std::string_view name, Frames& frames, ItemType type, + const std::vector& regions = REGIONS_NONE) +{ // Each frame keeps a line of its own. io.list(name, frames, [&](auto& frameIo, auto& frame) { frame_io(frameIo, frame, type, regions); }, true, false); - } +} - template static void track_io(Io& io, T& track, ItemType type) - { +template static void track_io(Io& io, T& track, ItemType type) +{ auto isLayer = type == ItemType::LAYER; - if constexpr (Io::IS_READING) track.type = type; + if constexpr (Io::IS_READING) + track.type = type; if (isLayer) - io.reference("layer", track.id, io.model.content.layers); + io.reference("layer", track.id, io.model.content.layers); else - io.reference("null", track.id, io.model.content.nulls); + io.reference("null", track.id, io.model.content.nulls); io.field("visible", track.isVisible, true); auto spritesheet = isLayer ? io.model.layer_spritesheet_get(track.id) : nullptr; frames_io(io, "frames", track.frames, type, spritesheet ? spritesheet->regions : REGIONS_NONE); if constexpr (Io::IS_READING) - if (isLayer) - for (auto& frame : track.frames) - frame = io.model.frame_effective(track.id, frame); - } + if (isLayer) + for (auto& frame : track.frames) + frame = io.model.frame_effective(track.id, frame); +} - // A group is an entry with a "group" name, its root and its own tracks. - template static void entries_io(Io& io, std::string_view name, Entries& entries, ItemType type) - { +// A group is an entry with a "group" name, its root and its own tracks. +template +static void entries_io(Io& io, std::string_view name, Entries& entries, ItemType type) +{ io.list( name, entries, - [&](auto& entryIo, auto& entry) - { - if constexpr (Io::IS_READING) - if (entryIo.has("group")) entry = TrackGroup{}; - std::visit( - [&](auto& item) - { - if constexpr (std::is_same_v, Track>) - return track_io(entryIo, item, type); - else - { - entryIo.field("group", item.name); - entryIo.field("expanded", item.isExpanded, true); - entryIo.field("visible", item.isVisible, true); - frames_io(entryIo, "root", item.root.frames, ItemType::ROOT); - entryIo.list( - name, item.tracks, [&](auto& trackIo, auto& track) { track_io(trackIo, track, type); }, false); - } - }, - entry); + [&](auto& entryIo, auto& entry) { + if constexpr (Io::IS_READING) + if (entryIo.has("group")) + entry = TrackGroup{}; + std::visit( + [&](auto& item) { + if constexpr (std::is_same_v, Track>) + return track_io(entryIo, item, type); + else + { + entryIo.field("group", item.name); + entryIo.field("expanded", item.isExpanded, true); + entryIo.field("visible", item.isVisible, true); + frames_io(entryIo, "root", item.root.frames, ItemType::ROOT); + entryIo.list( + name, item.tracks, [&](auto& trackIo, auto& track) { track_io(trackIo, track, type); }, + false); + } + }, + entry); }, false); if constexpr (Io::IS_READING) { - int id = 0; - groups_each(entries, [&](TrackGroup& group) { group.id = id++; }); + int id = 0; + groups_each(entries, [&](TrackGroup& group) { group.id = id++; }); } - } +} - template static void animation_io(Io& io, A& animation) - { +template static void animation_io(Io& io, A& animation) +{ io.field("length", animation.frameNum, 1); io.field("loop", animation.isLoop, true); glm::ivec2 markers{animation.startMarker, animation.endMarker}; io.field("markers", markers, glm::ivec2{-1}); - if constexpr (Io::IS_READING) std::tie(animation.startMarker, animation.endMarker) = std::tie(markers.x, markers.y); + if constexpr (Io::IS_READING) + std::tie(animation.startMarker, animation.endMarker) = std::tie(markers.x, markers.y); frames_io(io, "root", animation.root.frames, ItemType::ROOT); entries_io(io, "layers", animation.layers, ItemType::LAYER); entries_io(io, "nulls", animation.nulls, ItemType::NULL_); frames_io(io, "triggers", animation.triggers.frames, ItemType::TRIGGER); - } +} - // Animations (and groups, which hold an "animations" object) are keyed by name; a repeated name is renumbered. - // Animation names are unique document-wide (default names one); a group's only among the top-level keys. - static void animations_write(JsonWriter& io, const Model& model) - { +// Animations (and groups, which hold an "animations" object) are keyed by name. A repeated name is renumbered. +// Animation names are unique document-wide (default names one). A group's only among the top-level keys. +static void animations_write(JsonWriter& io, const Model& model) +{ std::set animationNames; std::set keys; - auto name_unique_get = [](const std::string& name, std::initializer_list*> sets) - { - auto candidate = name; - for (int i = 2; std::ranges::any_of(sets, [&](auto* names) { return names->contains(candidate); }); ++i) - candidate = std::format("{} {}", name, i); - for (auto* names : sets) - names->insert(candidate); - return candidate; + auto name_unique_get = [](const std::string& name, std::initializer_list*> sets) { + auto candidate = name; + for (int i = 2; std::ranges::any_of(sets, [&](auto* names) { return names->contains(candidate); }); ++i) + candidate = std::format("{} {}", name, i); + for (auto* names : sets) + names->insert(candidate); + return candidate; }; - auto animation_write = [&](const Animation& animation, bool isTopLevel) - { - auto name = isTopLevel ? name_unique_get(animation.name, {&animationNames, &keys}) - : name_unique_get(animation.name, {&animationNames}); - io.object(name, [&](JsonWriter&) { animation_io(io, animation); }, false); + auto animation_write = [&](const Animation& animation, bool isTopLevel) { + auto name = isTopLevel ? name_unique_get(animation.name, {&animationNames, &keys}) + : name_unique_get(animation.name, {&animationNames}); + io.object(name, [&](JsonWriter&) { animation_io(io, animation); }, false); }; io.object( "animations", - [&](JsonWriter&) - { - for (auto& entry : model.animations.entries) - { - if (auto animation = std::get_if>(&entry)) + [&](JsonWriter&) { + for (auto& entry : model.animations.entries) { - animation_write(**animation, true); - continue; - } - auto& group = std::get(entry); - io.object( - name_unique_get(group.name, {&keys}), - [&](JsonWriter&) + if (auto animation = std::get_if>(&entry)) { - io.field("expanded", group.isExpanded, true); - io.field("visible", group.isVisible, true); - io.object( - "animations", - [&](JsonWriter&) - { - for (auto& animation : group.animations) - animation_write(*animation, false); - }, - false); - }, - false); - } + animation_write(**animation, true); + continue; + } + auto& group = std::get(entry); + io.object( + name_unique_get(group.name, {&keys}), + [&](JsonWriter&) { + io.field("expanded", group.isExpanded, true); + io.field("visible", group.isVisible, true); + io.object( + "animations", + [&](JsonWriter&) { + for (auto& animation : group.animations) + animation_write(*animation, false); + }, + false); + }, + false); + } }, false); - } +} - static void animations_read(JsonReader& io, Model& model) - { - auto animation_read = [&](std::string_view name, JsonReader& animationIo) - { - Animation animation = {.name = std::string(name), .root = {.type = ItemType::ROOT}}; - animation_io(animationIo, animation); - return std::make_shared(std::move(animation)); +static void animations_read(JsonReader& io, Model& model) +{ + auto animation_read = [&](std::string_view name, JsonReader& animationIo) { + Animation animation = {.name = std::string(name), .root = {.type = ItemType::ROOT}}; + animation_io(animationIo, animation); + return std::make_shared(std::move(animation)); }; int groupId = 0; io.object( "animations", - [&](JsonReader& animationsIo) - { - animationsIo.isKeyed = true; - for (auto [name, value] : animationsIo.fields) - io.object_each(value, std::format("{}{}.", animationsIo.path, name), - [&](JsonReader& entryIo) - { - if (!entryIo.has("animations")) - { - model.animations.entries.emplace_back(animation_read(name, entryIo)); - return; - } - AnimationGroup group = {.id = groupId++, .name = std::string(name)}; - entryIo.field("expanded", group.isExpanded); - entryIo.field("visible", group.isVisible); - entryIo.object( - "animations", - [&](JsonReader& membersIo) - { - membersIo.isKeyed = true; - for (auto [memberName, member] : membersIo.fields) - io.object_each( - member, std::format("{}{}.", membersIo.path, memberName), - [&](JsonReader& animationIo) - { group.animations.push_back(animation_read(memberName, animationIo)); }); - }, - false); - model.animations.entries.emplace_back(std::move(group)); - }); + [&](JsonReader& animationsIo) { + animationsIo.isKeyed = true; + for (auto [name, value] : animationsIo.fields) + io.object_each(value, std::format("{}{}.", animationsIo.path, name), [&](JsonReader& entryIo) { + if (!entryIo.has("animations")) + { + model.animations.entries.emplace_back(animation_read(name, entryIo)); + return; + } + AnimationGroup group = {.id = groupId++, .name = std::string(name)}; + entryIo.field("expanded", group.isExpanded); + entryIo.field("visible", group.isVisible); + entryIo.object( + "animations", + [&](JsonReader& membersIo) { + membersIo.isKeyed = true; + for (auto [memberName, member] : membersIo.fields) + io.object_each(member, std::format("{}{}.", membersIo.path, memberName), + [&](JsonReader& animationIo) { + group.animations.push_back(animation_read(memberName, animationIo)); + }); + }, + false); + model.animations.entries.emplace_back(std::move(group)); + }); }, false); - } +} - // Content comes before animations, which read it (and anything named comes before what names it). - template static void model_io(Io& io, M& model) - { +// Content comes before animations, which read it (and anything named comes before what names it). +template static void model_io(Io& io, M& model) +{ auto& content = model.content; io.object( "info", - [&](auto& infoIo) - { - infoIo.field("createdBy", model.info.createdBy, Info{}.createdBy); - infoIo.field("createdOn", model.info.createdOn, {}, date_to_iso, date_from_iso); - infoIo.field("fps", model.info.fps, Info{}.fps); - infoIo.field("version", model.info.version, Info{}.version); - infoIo.field("isaacIgnored", model.info.isIsaacIgnored, false); + [&](auto& infoIo) { + infoIo.field("createdBy", model.info.createdBy, Info{}.createdBy); + infoIo.field("createdOn", model.info.createdOn, {}, date_to_iso, date_from_iso); + infoIo.field("fps", model.info.fps, Info{}.fps); + infoIo.field("version", model.info.version, Info{}.version); + infoIo.field("isaacIgnored", model.info.isIsaacIgnored, false); }, true); io.list( "sheets", content.spritesheets, - [](auto& spritesheetIo, auto& spritesheet) - { - spritesheetIo.field("path", spritesheet.path, {}); - spritesheetIo.list( - "regions", spritesheet.regions, - [](auto& regionIo, auto& region) - { - regionIo.field("name", region.name, {}); - regionIo.field("crop", region.crop, {}); - regionIo.field("size", region.size, {}); - regionIo.field("pivot", region.pivot, {}); - regionIo.choice("origin", region.origin, ORIGIN_NAMES, Origin::CUSTOM); - }, - true, false); + [](auto& spritesheetIo, auto& spritesheet) { + spritesheetIo.field("path", spritesheet.path, {}); + spritesheetIo.list( + "regions", spritesheet.regions, + [](auto& regionIo, auto& region) { + regionIo.field("name", region.name, {}); + regionIo.field("crop", region.crop, {}); + regionIo.field("size", region.size, {}); + regionIo.field("pivot", region.pivot, {}); + regionIo.choice("origin", region.origin, ORIGIN_NAMES, Origin::CUSTOM); + }, + true, false); }, false, false); io.list( "shaders", content.shaders, - [](auto& shaderIo, auto& shader) - { - shaderIo.field("name", shader.name, {}); - shaderIo.field("vertex", shader.vertex, {}); - shaderIo.field("fragment", shader.fragment, {}); - shaderIo.list( - "uniforms", shader.uniforms, - [](auto& uniformIo, auto& uniform) - { - uniformIo.field("name", uniform.name, {}); - uniformIo.field("binding", uniform.binding, {}); - uniformIo.field("value", uniform.value, {}); - uniformIo.list( - "components", uniform.components, - [](auto& componentIo, auto& component) - { - componentIo.field("index", component.index); - componentIo.field("binding", component.binding, {}); - componentIo.field("value", component.value, {}); - }, - true); - }, - true); + [](auto& shaderIo, auto& shader) { + shaderIo.field("name", shader.name, {}); + shaderIo.field("vertex", shader.vertex, {}); + shaderIo.field("fragment", shader.fragment, {}); + shaderIo.list( + "uniforms", shader.uniforms, + [](auto& uniformIo, auto& uniform) { + uniformIo.field("name", uniform.name, {}); + uniformIo.field("binding", uniform.binding, {}); + uniformIo.field("value", uniform.value, {}); + uniformIo.list( + "components", uniform.components, + [](auto& componentIo, auto& component) { + componentIo.field("index", component.index); + componentIo.field("binding", component.binding, {}); + componentIo.field("value", component.value, {}); + }, + true); + }, + true); }, false, false); // Libraries come before the layers that name them. io.values("libraries", content.libraries, [](auto& library) -> auto& { return library.path; }); io.list( "layers", content.layers, - [&](auto& layerIo, auto& layer) - { - layerIo.field("name", layer.name, {}); - layerIo.reference("sheet", layer.spritesheetId, content.spritesheets, Layer{}.spritesheetId); - layerIo.reference("library", layer.libraryId, content.libraries); - layerIo.field("animation", layer.animation, {}); + [&](auto& layerIo, auto& layer) { + layerIo.field("name", layer.name, {}); + layerIo.reference("sheet", layer.spritesheetId, content.spritesheets, Layer{}.spritesheetId); + layerIo.reference("library", layer.libraryId, content.libraries); + layerIo.field("animation", layer.animation, {}); }, true, false); io.list( "nulls", content.nulls, - [](auto& nullIo, auto& null) - { - nullIo.field("name", null.name, {}); - nullIo.field("showRect", null.isShowRect, false); + [](auto& nullIo, auto& null) { + nullIo.field("name", null.name, {}); + nullIo.field("showRect", null.isShowRect, false); }, true, false); io.values("events", content.events, [](auto& event) -> auto& { return event.name; }); io.values("sounds", content.sounds, [](auto& sound) -> auto& { return sound.path; }); io.field("default", model.animations.defaultAnimation, {}); if constexpr (Io::IS_READING) - animations_read(io, model); + animations_read(io, model); else - animations_write(io, model); - } + animations_write(io, model); +} - std::string model_to_json(const Model& model) - { +std::string model_to_json(const Model& model) +{ JsonWriter io{model}; io.open('{', false); model_io(io, model); io.close('}'); io.text += '\n'; return std::move(io.text); - } +} - // Fails only when the text isn't a JSON object; anything it couldn't read is listed in `errorString`. - bool model_from_json(Model& model, std::string_view text, std::string* errorString) - { +// Fails only when the text isn't a JSON object. Anything it couldn't read is listed in `errorString`. +bool model_from_json(Model& model, std::string_view text, std::string* errorString) +{ dom::parser parser; padded_string json(text); dom::element root; std::vector issues; JsonReader io = {model, &issues}; auto error = parser.parse(json).get(root); - if (!error) error = root.get(io.fields); + if (!error) + error = root.get(io.fields); if (error) { - if (errorString) *errorString = error_message(error); - return false; + if (errorString) + *errorString = error_message(error); + return false; } model = Model{}; model_io(io, model); io.unknown_keys_check(); model_repair(model); - if (!errorString || issues.empty()) return true; + if (!errorString || issues.empty()) + return true; errorString->clear(); for (std::size_t i = 0; i < std::min(issues.size(), ISSUES_SHOWN_MAX); ++i) - *errorString += (i ? "\n" : "") + issues[i]; - if (issues.size() > ISSUES_SHOWN_MAX) *errorString += std::format("\n({} more)", issues.size() - ISSUES_SHOWN_MAX); + *errorString += (i ? "\n" : "") + issues[i]; + if (issues.size() > ISSUES_SHOWN_MAX) + *errorString += std::format("\n({} more)", issues.size() - ISSUES_SHOWN_MAX); return true; - } +} diff --git a/src/model/json.h b/src/model/json.h index b9dd423..43c7807 100644 --- a/src/model/json.h +++ b/src/model/json.h @@ -7,6 +7,6 @@ // The editor's own JSON document: content items in arrays (an item's index is its id), animations keyed by their // unique name, and every value left out when it is the default. Unknown XML (extras) is not kept. - bool is_json(std::string_view); - std::string model_to_json(const Model&); - bool model_from_json(Model&, std::string_view, std::string* = nullptr); +bool is_json(std::string_view); +std::string model_to_json(const Model&); +bool model_from_json(Model&, std::string_view, std::string* = nullptr); diff --git a/src/model/model.cpp b/src/model/model.cpp index cc909ec..6de8dde 100644 --- a/src/model/model.cpp +++ b/src/model/model.cpp @@ -6,522 +6,557 @@ #include "image.h" #include "path.h" - // The slot holding the animation at a flat index (animations inside groups count in order), or nullptr. - template static auto animation_slot_get(Entries& entries, int index) -> decltype(&std::get<0>(entries[0])) - { - if (index < 0) return nullptr; +// The slot holding the animation at a flat index (animations inside groups count in order), or nullptr. +template +static auto animation_slot_get(Entries& entries, int index) -> decltype(&std::get<0>(entries[0])) +{ + if (index < 0) + return nullptr; for (auto& entry : entries) { - if (auto animation = std::get_if>(&entry)) - { - if (index-- == 0) return animation; - continue; - } - auto& group = std::get(entry); - if (index < (int)group.animations.size()) return &group.animations[index]; - index -= (int)group.animations.size(); + if (auto animation = std::get_if>(&entry)) + { + if (index-- == 0) + return animation; + continue; + } + auto& group = std::get(entry); + if (index < (int)group.animations.size()) + return &group.animations[index]; + index -= (int)group.animations.size(); } return nullptr; - } +} - int Model::animations_count_get() const - { +int Model::animations_count_get() const +{ int count = 0; for (auto& entry : animations.entries) - count += - std::holds_alternative(entry) ? (int)std::get(entry).animations.size() : 1; + count += + std::holds_alternative(entry) ? (int)std::get(entry).animations.size() : 1; return count; - } +} - const Animation* Model::animation_get(int index) const - { +const Animation* Model::animation_get(int index) const +{ auto slot = animation_slot_get(animations.entries, index); return slot ? slot->get() : nullptr; - } +} - // Copy-on-write: an animation shared with undo history is cloned before it is changed. - Animation* Model::animation_edit(int index) - { +// Copy-on-write: an animation shared with undo history is cloned before it is changed. +Animation* Model::animation_edit(int index) +{ auto slot = animation_slot_get(animations.entries, index); - if (!slot || !*slot) return nullptr; - if (slot->use_count() > 1) *slot = std::make_shared(**slot); + if (!slot || !*slot) + return nullptr; + if (slot->use_count() > 1) + *slot = std::make_shared(**slot); return const_cast(slot->get()); - } +} - const Animation* Model::animation_named_get(std::string_view name) const - { +const Animation* Model::animation_named_get(std::string_view name) const +{ for (auto [index, animation] : animations_get()) - if (animation->name == name) return animation; + if (animation->name == name) + return animation; return nullptr; - } +} - std::vector> Model::animations_get() const - { +std::vector> Model::animations_get() const +{ std::vector> result; for (int i = 0; i < animations_count_get(); ++i) - result.emplace_back(i, animation_get(i)); + result.emplace_back(i, animation_get(i)); return result; - } +} - template static auto animation_group_find(Self& self, int index) - { +template static auto animation_group_find(Self& self, int index) +{ using Group = std::conditional_t, const AnimationGroup, AnimationGroup>; Group* result = nullptr; - if (index < 0) return result; + if (index < 0) + return result; for (auto& entry : self.animations.entries) { - if (std::holds_alternative>(entry)) - { - if (index-- == 0) return result; - continue; - } - auto& group = std::get(entry); - if (index < (int)group.animations.size()) return &group; - index -= (int)group.animations.size(); + if (std::holds_alternative>(entry)) + { + if (index-- == 0) + return result; + continue; + } + auto& group = std::get(entry); + if (index < (int)group.animations.size()) + return &group; + index -= (int)group.animations.size(); } return result; - } +} - const AnimationGroup* Model::animation_group_get(int index) const { return animation_group_find(*this, index); } - AnimationGroup* Model::animation_group_edit(int index) { return animation_group_find(*this, index); } +const AnimationGroup* Model::animation_group_get(int index) const +{ + return animation_group_find(*this, index); +} - int Model::animation_group_id_get(int index) const - { +AnimationGroup* Model::animation_group_edit(int index) +{ + return animation_group_find(*this, index); +} + +int Model::animation_group_id_get(int index) const +{ auto group = animation_group_get(index); return group ? group->id : -1; - } +} - template static auto animation_track_group_find(A& animation, int groupType, int groupId) - { +template static auto animation_track_group_find(A& animation, int groupType, int groupId) +{ using Group = std::conditional_t, const TrackGroup, TrackGroup>; Group* result = nullptr; - if (groupId < 0 || (groupType != LAYER && groupType != NULL_)) return result; - groups_each(animation_entries_get(animation, groupType), - [&](auto& group) - { - if (!result && group.id == groupId) result = &group; - }); + if (groupId < 0 || (groupType != LAYER && groupType != NULL_)) + return result; + groups_each(animation_entries_get(animation, groupType), [&](auto& group) { + if (!result && group.id == groupId) + result = &group; + }); return result; - } +} - TrackGroup* animation_track_group_get(Animation& animation, int groupType, int groupId) - { +TrackGroup* animation_track_group_get(Animation& animation, int groupType, int groupId) +{ return animation_track_group_find(animation, groupType, groupId); - } +} - const TrackGroup* animation_track_group_get(const Animation& animation, int groupType, int groupId) - { +const TrackGroup* animation_track_group_get(const Animation& animation, int groupType, int groupId) +{ return animation_track_group_find(animation, groupType, groupId); - } +} - // A track by item type and id; a group root when the item is ROOT with a group, and grouped tracks only match their - // own group when one is given. - template static auto animation_track_find(A& animation, int itemType, int id, int groupType, int groupId) - { +// A track by item type and id. A group root when the item is ROOT with a group, and grouped tracks only match their +// own group when one is given. +template static auto animation_track_find(A& animation, int itemType, int id, int groupType, int groupId) +{ using T = std::conditional_t, const Track, Track>; T* result = nullptr; auto isGrouped = groupType != NONE && groupId != -1; if (itemType == ROOT) { - if (!isGrouped) return &animation.root; - auto group = animation_track_group_find(animation, groupType, groupId); - return group ? &group->root : result; + if (!isGrouped) + return &animation.root; + auto group = animation_track_group_find(animation, groupType, groupId); + return group ? &group->root : result; } - if (itemType == TRIGGER) return &animation.triggers; - if (itemType != LAYER && itemType != NULL_) return result; + if (itemType == TRIGGER) + return &animation.triggers; + if (itemType != LAYER && itemType != NULL_) + return result; - tracks_each(animation_entries_get(animation, itemType), - [&](auto& track, auto* group) - { - if (result || track.id != id) return; - if (isGrouped && (!group || group->id != groupId)) return; - result = &track; - }); + tracks_each(animation_entries_get(animation, itemType), [&](auto& track, auto* group) { + if (result || track.id != id) + return; + if (isGrouped && (!group || group->id != groupId)) + return; + result = &track; + }); return result; - } +} - const Track* animation_track_get(const Animation& animation, int itemType, int id, int groupType, int groupId) - { +const Track* animation_track_get(const Animation& animation, int itemType, int id, int groupType, int groupId) +{ return animation_track_find(animation, itemType, id, groupType, groupId); - } +} - Track* animation_track_get(Animation& animation, int itemType, int id, int groupType, int groupId) - { +Track* animation_track_get(Animation& animation, int itemType, int id, int groupType, int groupId) +{ return animation_track_find(animation, itemType, id, groupType, groupId); - } +} - const Track* Model::track_get(Reference reference) const - { +const Track* Model::track_get(Reference reference) const +{ auto animation = animation_get(reference.animationIndex); return animation ? animation_track_get(*animation, reference.itemType, reference.itemID, reference.groupType, reference.groupId) : nullptr; - } +} - Track* Model::track_edit(Reference reference) - { - if (!track_get(reference)) return nullptr; +Track* Model::track_edit(Reference reference) +{ + if (!track_get(reference)) + return nullptr; auto animation = animation_edit(reference.animationIndex); return animation_track_get(*animation, reference.itemType, reference.itemID, reference.groupType, reference.groupId); - } +} - const TrackGroup* Model::track_group_get(int animationIndex, int groupType, int groupId) const - { +const TrackGroup* Model::track_group_get(int animationIndex, int groupType, int groupId) const +{ auto animation = animation_get(animationIndex); return animation ? animation_track_group_get(*animation, groupType, groupId) : nullptr; - } +} - TrackGroup* Model::track_group_edit(int animationIndex, int groupType, int groupId) - { - if (!track_group_get(animationIndex, groupType, groupId)) return nullptr; +TrackGroup* Model::track_group_edit(int animationIndex, int groupType, int groupId) +{ + if (!track_group_get(animationIndex, groupType, groupId)) + return nullptr; return animation_track_group_get(*animation_edit(animationIndex), groupType, groupId); - } +} - const Frame* Model::frame_get(Reference reference) const - { +const Frame* Model::frame_get(Reference reference) const +{ auto track = track_get(reference); - if (!track || reference.frameIndex < 0 || reference.frameIndex >= (int)track->frames.size()) return nullptr; + if (!track || reference.frameIndex < 0 || reference.frameIndex >= (int)track->frames.size()) + return nullptr; return &track->frames[reference.frameIndex]; - } +} - Frame* Model::frame_edit(Reference reference) - { - if (!frame_get(reference)) return nullptr; +Frame* Model::frame_edit(Reference reference) +{ + if (!frame_get(reference)) + return nullptr; return &track_edit(reference)->frames[reference.frameIndex]; - } +} - const Spritesheet* Model::layer_spritesheet_get(int layerId) const - { +const Spritesheet* Model::layer_spritesheet_get(int layerId) const +{ auto layer = item_get(content.layers, layerId); return layer ? item_get(content.spritesheets, layer->spritesheetId) : nullptr; - } +} - // The frame with its region's crop/size/pivot applied, as it is drawn. - Frame Model::frame_effective(int layerId, const Frame& frame) const - { +// The frame with its region's crop/size/pivot applied, as it is drawn. +Frame Model::frame_effective(int layerId, const Frame& frame) const +{ auto resolved = frame; auto spritesheet = frame.regionId == -1 ? nullptr : layer_spritesheet_get(layerId); auto region = spritesheet ? item_get(spritesheet->regions, frame.regionId) : nullptr; - if (!region) return resolved; + if (!region) + return resolved; resolved.crop = region->crop; resolved.size = region->size; resolved.pivot = region->pivot; return resolved; - } +} - template static std::set unused_ids_get(const Items& items, const std::set& used) - { +template static std::set unused_ids_get(const Items& items, const std::set& used) +{ std::set unused; for (auto& item : items) - if (!used.contains(item.id)) unused.insert(item.id); + if (!used.contains(item.id)) + unused.insert(item.id); return unused; - } +} - // Each reference to a content item of `type`, as the id it holds: a plain layer's spritesheet or a layer's library, a - // track's layer or null, a trigger's events or sounds, a frame's shader, or (from layers on spritesheet - // `spritesheetId`) a frame's region. With `only`, those in that animation (layers name spritesheets and libraries - // either way). - template - void references_each(const Model& model, ElementType type, int spritesheetId, const Animation* only, - Callback&& callback) - { +// Each reference to a content item of `type`, as the id it holds: a plain layer's spritesheet or a layer's library, a +// track's layer or null, a trigger's events or sounds, a frame's shader, or (from layers on spritesheet +// `spritesheetId`) a frame's region. With `only`, those in that animation (layers name spritesheets and libraries +// either way). +template +void references_each(const Model& model, ElementType type, int spritesheetId, const Animation* only, + Callback&& callback) +{ auto& content = model.content; if (type == ElementType::SPRITESHEET || type == ElementType::LIBRARY) { - // An animation layer's spritesheet isn't drawn. - for (auto& layer : content.layers) - if (type == ElementType::LIBRARY) - callback(layer.libraryId); - else if (!layer.is_animation()) - callback(layer.spritesheetId); - return; + // An animation layer's spritesheet isn't drawn. + for (auto& layer : content.layers) + if (type == ElementType::LIBRARY) + callback(layer.libraryId); + else if (!layer.is_animation()) + callback(layer.spritesheetId); + return; } - auto animation_references_each = [&](const Animation& animation) - { - if (type == ElementType::LAYER_ELEMENT || type == ElementType::NULL_ELEMENT) - tracks_each(type == ElementType::LAYER_ELEMENT ? animation.layers : animation.nulls, - [&](const Track& track, auto*) { callback(track.id); }); - if (type == ElementType::EVENT_ELEMENT || type == ElementType::SOUND_ELEMENT) - for (auto& trigger : animation.triggers.frames) - for (auto id : type == ElementType::EVENT_ELEMENT ? trigger.eventIds : trigger.soundIds) - callback(id); - if (type == ElementType::SHADER) - animation_tracks_each(animation, - [&](const Track& track) - { - for (auto& frame : track.frames) - callback(frame.shaderId); - }); - if (type == ElementType::REGION) - tracks_each(animation.layers, - [&](const Track& track, auto*) - { - auto layer = item_get(content.layers, track.id); - if (!layer || layer->spritesheetId != spritesheetId) return; - for (auto& frame : track.frames) - callback(frame.regionId); - }); + auto animation_references_each = [&](const Animation& animation) { + if (type == ElementType::LAYER_ELEMENT || type == ElementType::NULL_ELEMENT) + tracks_each(type == ElementType::LAYER_ELEMENT ? animation.layers : animation.nulls, + [&](const Track& track, auto*) { callback(track.id); }); + if (type == ElementType::EVENT_ELEMENT || type == ElementType::SOUND_ELEMENT) + for (auto& trigger : animation.triggers.frames) + for (auto id : type == ElementType::EVENT_ELEMENT ? trigger.eventIds : trigger.soundIds) + callback(id); + if (type == ElementType::SHADER) + animation_tracks_each(animation, [&](const Track& track) { + for (auto& frame : track.frames) + callback(frame.shaderId); + }); + if (type == ElementType::REGION) + tracks_each(animation.layers, [&](const Track& track, auto*) { + auto layer = item_get(content.layers, track.id); + if (!layer || layer->spritesheetId != spritesheetId) + return; + for (auto& frame : track.frames) + callback(frame.regionId); + }); }; - if (only) return animation_references_each(*only); + if (only) + return animation_references_each(*only); for (auto [index, animation] : model.animations_get()) - animation_references_each(*animation); - } + animation_references_each(*animation); +} - std::set Model::unused_get(ElementType type, const Animation* only) const - { +std::set Model::unused_get(ElementType type, const Animation* only) const +{ std::set used; references_each(*this, type, -1, only, [&](int id) { used.insert(id); }); switch (type) { - case ElementType::SPRITESHEET: - return unused_ids_get(content.spritesheets, used); - case ElementType::SHADER: - return unused_ids_get(content.shaders, used); - case ElementType::LAYER_ELEMENT: - return unused_ids_get(content.layers, used); - case ElementType::NULL_ELEMENT: - return unused_ids_get(content.nulls, used); - case ElementType::EVENT_ELEMENT: - return unused_ids_get(content.events, used); - case ElementType::SOUND_ELEMENT: - return unused_ids_get(content.sounds, used); - case ElementType::LIBRARY: - return unused_ids_get(content.libraries, used); - default: - return {}; + case ElementType::SPRITESHEET: + return unused_ids_get(content.spritesheets, used); + case ElementType::SHADER: + return unused_ids_get(content.shaders, used); + case ElementType::LAYER_ELEMENT: + return unused_ids_get(content.layers, used); + case ElementType::NULL_ELEMENT: + return unused_ids_get(content.nulls, used); + case ElementType::EVENT_ELEMENT: + return unused_ids_get(content.events, used); + case ElementType::SOUND_ELEMENT: + return unused_ids_get(content.sounds, used); + case ElementType::LIBRARY: + return unused_ids_get(content.libraries, used); + default: + return {}; } - } +} - // How many references there are to the items `ids` (see references_each). - int Model::uses_count(ElementType type, const std::set& ids, int spritesheetId, const Animation* only) const - { +// How many references there are to the items `ids` (see references_each). +int Model::uses_count(ElementType type, const std::set& ids, int spritesheetId, const Animation* only) const +{ int count = 0; references_each(*this, type, spritesheetId, only, [&](int id) { count += ids.contains(id); }); return count; - } +} - Handle Model::handle_get(Reference reference, bool isGroup) const - { +Handle Model::handle_get(Reference reference, bool isGroup) const +{ Handle handle = {}; auto animation = animation_get(reference.animationIndex); - if (!animation) return handle; + if (!animation) + return handle; handle.animation = animation->uid; if (isGroup) { - if (auto group = animation_track_group_get(*animation, reference.itemType, reference.itemID)) - handle.item = group->uid; - return handle; + if (auto group = animation_track_group_get(*animation, reference.itemType, reference.itemID)) + handle.item = group->uid; + return handle; } auto track = animation_track_get(*animation, reference.itemType, reference.itemID, reference.groupType, reference.groupId); - if (!track) return handle; + if (!track) + return handle; handle.item = track->uid; if (reference.frameIndex >= 0 && reference.frameIndex < (int)track->frames.size()) - handle.frame = track->frames[reference.frameIndex].uid; + handle.frame = track->frames[reference.frameIndex].uid; return handle; - } +} - std::uint64_t Model::uid_get(Reference reference, bool isGroup) const - { +std::uint64_t Model::uid_get(Reference reference, bool isGroup) const +{ auto handle = handle_get(reference, isGroup); return handle.frame ? handle.frame : handle.item ? handle.item : handle.animation; - } +} - template static void animation_uids_each(Animation& animation, Callback&& callback) - { +template static void animation_uids_each(Animation& animation, Callback&& callback) +{ callback(animation.uid); for (auto* entries : {&animation.layers, &animation.nulls}) - groups_each(*entries, [&](TrackGroup& group) { callback(group.uid); }); - animation_tracks_each(animation, - [&](Track& track) - { - callback(track.uid); - for (auto& frame : track.frames) - callback(frame.uid); - }); - } + groups_each(*entries, [&](TrackGroup& group) { callback(group.uid); }); + animation_tracks_each(animation, [&](Track& track) { + callback(track.uid); + for (auto& frame : track.frames) + callback(frame.uid); + }); +} - // Gives any element that shares a uid with an earlier one a fresh uid (copies made without cloning). - void Model::uids_repair() - { +// Gives any element that shares a uid with an earlier one a fresh uid (copies made without cloning). +void Model::uids_repair() +{ std::unordered_set seen; - auto repair = [&](std::uint64_t& uid) - { - if (!uid || !seen.insert(uid).second) uid = uid_next(); + auto repair = [&](std::uint64_t& uid) { + if (!uid || !seen.insert(uid).second) + uid = uid_next(); }; for (int i = 0; i < animations_count_get(); ++i) { - auto seenBefore = seen; - bool isDuplicate = false; - animation_uids_each(const_cast(*animation_get(i)), - [&](std::uint64_t& uid) { isDuplicate |= !uid || !seen.insert(uid).second; }); - if (!isDuplicate) continue; - seen = std::move(seenBefore); - animation_uids_each(*animation_edit(i), repair); + auto seenBefore = seen; + bool isDuplicate = false; + animation_uids_each(const_cast(*animation_get(i)), + [&](std::uint64_t& uid) { isDuplicate |= !uid || !seen.insert(uid).second; }); + if (!isDuplicate) + continue; + seen = std::move(seenBefore); + animation_uids_each(*animation_edit(i), repair); } for (auto& entry : animations.entries) - if (auto group = std::get_if(&entry)) repair(group->uid); + if (auto group = std::get_if(&entry)) + repair(group->uid); for (auto& spritesheet : content.spritesheets) { - repair(spritesheet.uid); - for (auto& region : spritesheet.regions) - repair(region.uid); + repair(spritesheet.uid); + for (auto& region : spritesheet.regions) + repair(region.uid); } for (auto& shader : content.shaders) - repair(shader.uid); + repair(shader.uid); for (auto& layer : content.layers) - repair(layer.uid); + repair(layer.uid); for (auto& null : content.nulls) - repair(null.uid); + repair(null.uid); for (auto& event : content.events) - repair(event.uid); + repair(event.uid); for (auto& sound : content.sounds) - repair(sound.uid); + repair(sound.uid); for (auto& library : content.libraries) - repair(library.uid); - } + repair(library.uid); +} - // SVG spritesheets that layers show. - std::set spritesheets_vector_used_get(const Model& model) - { +// SVG spritesheets that layers show. +std::set spritesheets_vector_used_get(const Model& model) +{ std::set ids; for (auto& layer : model.content.layers) - if (auto spritesheet = item_get(model.content.spritesheets, layer.spritesheetId); - spritesheet && !layer.is_animation() && is_path_extension(spritesheet->path, SVG_EXTENSION)) - ids.insert(spritesheet->id); + if (auto spritesheet = item_get(model.content.spritesheets, layer.spritesheetId); + spritesheet && !layer.is_animation() && is_path_extension(spritesheet->path, SVG_EXTENSION)) + ids.insert(spritesheet->id); return ids; - } +} - int track_frames_count_get(const Track& track) { return (int)track.frames.size(); } +int track_frames_count_get(const Track& track) +{ + return (int)track.frames.size(); +} - int track_length_get(const Track& track) - { +int track_length_get(const Track& track) +{ int length = 0; for (auto& frame : track.frames) - length = track.type == ItemType::TRIGGER ? std::max(length, frame.atFrame) : length + frame.duration; + length = track.type == ItemType::TRIGGER ? std::max(length, frame.atFrame) : length + frame.duration; return length; - } +} - // The frames playback stays within: [start, end), from the markers (or the whole animation). - glm::ivec2 animation_play_range_get(const Animation& animation) - { +// The frames playback stays within: [start, end), from the markers (or the whole animation). +glm::ivec2 animation_play_range_get(const Animation& animation) +{ auto length = std::max(animation.frameNum, 1); auto start = animation.startMarker != -1 ? std::clamp(animation.startMarker, 0, length - 1) : 0; auto end = animation.endMarker != -1 ? std::clamp(animation.endMarker + 1, start + 1, length) : length; return {start, end}; - } +} - int animation_length_get(const Animation& animation) - { +int animation_length_get(const Animation& animation) +{ int length = 0; animation_tracks_each(animation, [&](const Track& track) { length = std::max(length, track_length_get(track)); }); return std::max(length, FRAME_DURATION_MIN); - } +} - Frame frame_clone(Frame frame) - { +Frame frame_clone(Frame frame) +{ frame.uid = uid_next(); return frame; - } +} - Track track_clone(Track track) - { +Track track_clone(Track track) +{ track.uid = uid_next(); for (auto& frame : track.frames) - frame.uid = uid_next(); + frame.uid = uid_next(); return track; - } +} - Animation animation_clone(Animation animation) - { +Animation animation_clone(Animation animation) +{ animation_uids_each(animation, [](std::uint64_t& uid) { uid = uid_next(); }); return animation; - } +} - static void track_locations_add(std::unordered_map& locations, const Track& track, - Reference reference) - { +static void track_locations_add(std::unordered_map& locations, const Track& track, + Reference reference) +{ constexpr ElementType TRACK_TYPES[] = {ElementType::UNKNOWN, ElementType::ROOT_ANIMATION, ElementType::LAYER_ANIMATION, ElementType::NULL_ANIMATION, ElementType::TRIGGERS}; locations[track.uid] = {reference, TRACK_TYPES[(int)track.type]}; for (auto& frame : track.frames) { - ++reference.frameIndex; - locations[frame.uid] = {reference, track.type == ItemType::TRIGGER ? ElementType::TRIGGER : ElementType::FRAME}; + ++reference.frameIndex; + locations[frame.uid] = {reference, track.type == ItemType::TRIGGER ? ElementType::TRIGGER : ElementType::FRAME}; } - } +} - UidIndex::UidIndex(const Model& model) - { +UidIndex::UidIndex(const Model& model) +{ for (auto [index, animation] : model.animations_get()) { - locations[animation->uid] = {{index}, ElementType::ANIMATION}; - track_locations_add(locations, animation->root, {index, ROOT}); - track_locations_add(locations, animation->triggers, {index, TRIGGER}); - for (auto type : {LAYER, NULL_}) - for (auto& entry : animation_entries_get(*animation, type)) - if (auto track = std::get_if(&entry)) - track_locations_add(locations, *track, {index, type, track->id}); - else - { - auto& group = std::get(entry); - locations[group.uid] = {{index, type, group.id}, ElementType::GROUP}; - track_locations_add(locations, group.root, {index, ROOT, -1, -1, type, group.id}); - for (auto& groupTrack : group.tracks) - track_locations_add(locations, groupTrack, {index, type, groupTrack.id, -1, type, group.id}); - } + locations[animation->uid] = {{index}, ElementType::ANIMATION}; + track_locations_add(locations, animation->root, {index, ROOT}); + track_locations_add(locations, animation->triggers, {index, TRIGGER}); + for (auto type : {LAYER, NULL_}) + for (auto& entry : animation_entries_get(*animation, type)) + if (auto track = std::get_if(&entry)) + track_locations_add(locations, *track, {index, type, track->id}); + else + { + auto& group = std::get(entry); + locations[group.uid] = {{index, type, group.id}, ElementType::GROUP}; + track_locations_add(locations, group.root, {index, ROOT, -1, -1, type, group.id}); + for (auto& groupTrack : group.tracks) + track_locations_add(locations, groupTrack, {index, type, groupTrack.id, -1, type, group.id}); + } } - } +} - bool UidIndex::contains(std::uint64_t uid) const { return uid && locations.contains(uid); } +bool UidIndex::contains(std::uint64_t uid) const +{ + return uid && locations.contains(uid); +} - std::optional UidIndex::reference_get(std::uint64_t uid) const - { +std::optional UidIndex::reference_get(std::uint64_t uid) const +{ auto it = locations.find(uid); return it == locations.end() ? std::nullopt : std::optional(it->second.reference); - } +} - ElementType UidIndex::type_get(std::uint64_t uid) const - { +ElementType UidIndex::type_get(std::uint64_t uid) const +{ auto it = locations.find(uid); return it == locations.end() ? ElementType::UNKNOWN : it->second.type; - } +} - // Equality by value; animations shared with another model compare by pointer first. - bool is_model_equal(const Model& left, const Model& right) - { +// Equality by value. Animations shared with another model compare by pointer first. +bool is_model_equal(const Model& left, const Model& right) +{ if (left.info != right.info || left.content != right.content || left.layout != right.layout || left.extras != right.extras || left.isValid != right.isValid || left.animations.defaultAnimation != right.animations.defaultAnimation || left.animations.extras != right.animations.extras || left.animations.entries.size() != right.animations.entries.size()) - return false; + return false; - auto is_animation_equal = [](const std::shared_ptr& a, const std::shared_ptr& b) - { return a == b || (a && b && *a == *b); }; + auto is_animation_equal = [](const std::shared_ptr& a, const std::shared_ptr& b) { + return a == b || (a && b && *a == *b); + }; for (std::size_t i = 0; i < left.animations.entries.size(); ++i) { - auto& a = left.animations.entries[i]; - auto& b = right.animations.entries[i]; - if (a.index() != b.index()) return false; - if (auto animation = std::get_if>(&a)) - { - if (!is_animation_equal(*animation, std::get>(b))) return false; - continue; - } - auto& groupA = std::get(a); - auto& groupB = std::get(b); - if (groupA.uid != groupB.uid || groupA.id != groupB.id || groupA.name != groupB.name || - groupA.isExpanded != groupB.isExpanded || groupA.isVisible != groupB.isVisible || - groupA.extras != groupB.extras || groupA.animations.size() != groupB.animations.size()) - return false; - for (std::size_t j = 0; j < groupA.animations.size(); ++j) - if (!is_animation_equal(groupA.animations[j], groupB.animations[j])) return false; + auto& a = left.animations.entries[i]; + auto& b = right.animations.entries[i]; + if (a.index() != b.index()) + return false; + if (auto animation = std::get_if>(&a)) + { + if (!is_animation_equal(*animation, std::get>(b))) + return false; + continue; + } + auto& groupA = std::get(a); + auto& groupB = std::get(b); + if (groupA.uid != groupB.uid || groupA.id != groupB.id || groupA.name != groupB.name || + groupA.isExpanded != groupB.isExpanded || groupA.isVisible != groupB.isVisible || + groupA.extras != groupB.extras || groupA.animations.size() != groupB.animations.size()) + return false; + for (std::size_t j = 0; j < groupA.animations.size(); ++j) + if (!is_animation_equal(groupA.animations[j], groupB.animations[j])) + return false; } return true; - } +} diff --git a/src/model/model.h b/src/model/model.h index 6de4700..685a478 100644 --- a/src/model/model.h +++ b/src/model/model.h @@ -14,31 +14,31 @@ #include "model/common.h" #include "uid.h" -// The typed document model. XML exists only in model/xml.cpp; everything else edits and reads these structs. - // An XML element the editor does not understand, kept verbatim so it survives a save. - struct XmlNode - { +// The typed document model. XML exists only in model/xml.cpp. Everything else edits and reads these structs. +// An XML element the editor does not understand, kept verbatim so it survives a save. +struct XmlNode +{ std::string tag; std::vector> attributes; std::string text; std::vector children; bool operator==(const XmlNode&) const = default; - }; +}; - // Unknown XML attached to a known node: attributes, text, and unknown children with the child index they had. - struct Extras - { +// Unknown XML attached to a known node: attributes, text, and unknown children with the child index they had. +struct Extras +{ std::vector> attributes; std::string text; std::vector> children; bool operator==(const Extras&) const = default; - }; +}; - // A keyframe; on a triggers track the same struct is a trigger (atFrame, eventIds, soundIds). - struct Frame - { +// A keyframe. On a triggers track the same struct is a trigger (atFrame, eventIds, soundIds). +struct Frame +{ std::uint64_t uid = uid_next(); glm::vec2 crop{}; glm::vec2 size{}; @@ -54,9 +54,9 @@ Interpolation interpolation = Interpolation::NONE; int regionId = -1; int shaderId = -1; - int depth = 0; // a layer frame draws this many layers above (or below) its place in the timeline; editor-only - float blur = 0; // Flash's BlurFilter at quality 1: one box blur this many canvas pixels wide; editor-only - // On an animation layer: the child animation (empty for the layer's own) and how it plays; editor-only. + int depth = 0; // a layer frame draws this many layers above (or below) its place in the timeline. Editor-only + float blur = 0; // Flash's BlurFilter at quality 1: one box blur this many canvas pixels wide. Editor-only + // On an animation layer: the child animation (empty for the layer's own) and how it plays. Editor-only. std::string childAnimation; ChildMode childMode = ChildMode::LOOP; int childStart = 0; @@ -68,10 +68,10 @@ Extras extras = {}; bool operator==(const Frame&) const = default; - }; +}; - struct Track - { +struct Track +{ std::uint64_t uid = uid_next(); ItemType type = ItemType::LAYER; int id = -1; @@ -80,10 +80,10 @@ Extras extras = {}; bool operator==(const Track&) const = default; - }; +}; - struct TrackGroup - { +struct TrackGroup +{ std::uint64_t uid = uid_next(); int id = -1; std::string name; @@ -94,17 +94,17 @@ Extras extras = {}; bool operator==(const TrackGroup&) const = default; - }; +}; - using TrackEntry = std::variant; +using TrackEntry = std::variant; - struct Animation - { +struct Animation +{ std::uint64_t uid = uid_next(); std::string name; int frameNum = 1; bool isLoop = true; - // Playback stays between these frames (inclusive) when set; -1 for none. Saved only in the editor's copy. + // Playback stays between these frames (inclusive) when set. -1 for none. Saved only in the editor's copy. int startMarker = -1; int endMarker = -1; Track root = {.type = ItemType::ROOT, .frames = {Frame{}}}; @@ -118,10 +118,10 @@ Extras nullsExtras = {}; bool operator==(const Animation&) const = default; - }; +}; - struct AnimationGroup - { +struct AnimationGroup +{ std::uint64_t uid = uid_next(); int id = -1; std::string name; @@ -131,12 +131,12 @@ Extras extras = {}; bool operator==(const AnimationGroup&) const = default; - }; +}; - using AnimationEntry = std::variant, AnimationGroup>; +using AnimationEntry = std::variant, AnimationGroup>; - struct Region - { +struct Region +{ std::uint64_t uid = uid_next(); int id = -1; std::string name; @@ -147,10 +147,10 @@ Extras extras = {}; bool operator==(const Region&) const = default; - }; +}; - struct Spritesheet - { +struct Spritesheet +{ std::uint64_t uid = uid_next(); int id = -1; std::filesystem::path path; @@ -158,20 +158,20 @@ Extras extras = {}; bool operator==(const Spritesheet&) const = default; - }; +}; - struct Component - { +struct Component +{ int index = -1; std::string binding; std::string value; Extras extras = {}; bool operator==(const Component&) const = default; - }; +}; - struct Uniform - { +struct Uniform +{ std::string name; std::string binding; std::string value; @@ -179,10 +179,10 @@ Extras extras = {}; bool operator==(const Uniform&) const = default; - }; +}; - struct Shader - { +struct Shader +{ std::uint64_t uid = uid_next(); int id = -1; std::string name; @@ -192,10 +192,10 @@ Extras extras = {}; bool operator==(const Shader&) const = default; - }; +}; - struct Layer - { +struct Layer +{ std::uint64_t uid = uid_next(); int id = -1; std::string name; @@ -206,23 +206,26 @@ std::string animation; Extras extras = {}; - bool is_animation() const { return !animation.empty(); } + bool is_animation() const + { + return !animation.empty(); + } bool operator==(const Layer&) const = default; - }; +}; - // Another .anm2 whose animations this one's layers can play. - struct Library - { +// Another .anm2 whose animations this one's layers can play. +struct Library +{ std::uint64_t uid = uid_next(); int id = -1; std::filesystem::path path; Extras extras = {}; bool operator==(const Library&) const = default; - }; +}; - struct Null - { +struct Null +{ std::uint64_t uid = uid_next(); int id = -1; std::string name; @@ -230,42 +233,43 @@ Extras extras = {}; bool operator==(const Null&) const = default; - }; +}; - struct Event - { +struct Event +{ std::uint64_t uid = uid_next(); int id = -1; std::string name; Extras extras = {}; bool operator==(const Event&) const = default; - }; +}; - struct Sound - { +struct Sound +{ std::uint64_t uid = uid_next(); int id = -1; std::filesystem::path path; Extras extras = {}; bool operator==(const Sound&) const = default; - }; +}; - struct Info - { +struct Info +{ std::string createdBy = "robot"; std::string createdOn; int fps = 30; int version = 0; - bool isIsaacIgnored = false; // last saved with Ignore and Save: nothing the game can't show worked around; editor-only + bool isIsaacIgnored = + false; // last saved with Ignore and Save: nothing the game can't show worked around. Editor-only Extras extras = {}; bool operator==(const Info&) const = default; - }; +}; - struct Content - { +struct Content +{ std::vector spritesheets; std::vector shaders; std::vector layers; @@ -279,79 +283,81 @@ std::vector> containerExtras; bool operator==(const Content&) const = default; - }; +}; - struct Animations - { +struct Animations +{ std::string defaultAnimation; std::vector entries; Extras extras = {}; bool operator==(const Animations&) const = default; - }; +}; - // Content item lookup by file id (layers, nulls, events, sounds, spritesheets, shaders, regions). - template auto item_get(Items& items, int id) -> decltype(&items.front()) - { +// Content item lookup by file id (layers, nulls, events, sounds, spritesheets, shaders, regions). +template auto item_get(Items& items, int id) -> decltype(&items.front()) +{ for (auto& item : items) - if (item.id == id) return &item; + if (item.id == id) + return &item; return nullptr; - } +} - template int item_next_id_get(const Items& items) - { +template int item_next_id_get(const Items& items) +{ int id = -1; for (auto& item : items) - id = std::max(id, item.id); + id = std::max(id, item.id); return id + 1; - } +} - // Tracks of one kind (layer or null) in order, including those inside groups; callback(track, group or nullptr). - template void tracks_each(Entries& entries, Callback&& callback) - { +// Tracks of one kind (layer or null) in order, including those inside groups. Callback(track, group or nullptr). +template void tracks_each(Entries& entries, Callback&& callback) +{ for (auto& entry : entries) - if (auto track = std::get_if(&entry)) - callback(*track, static_cast(entry))>(nullptr)); - else - { - auto& group = std::get(entry); - for (auto& groupTrack : group.tracks) - callback(groupTrack, &group); - } - } - - template void groups_each(Entries& entries, Callback&& callback) - { - for (auto& entry : entries) - if (auto group = std::get_if(&entry)) callback(*group); - } - - // Every track of an animation (root, group roots, layers, nulls, triggers). - template void animation_tracks_each(A& animation, Callback&& callback) - { - callback(animation.root); - for (auto* entries : {&animation.layers, &animation.nulls}) - for (auto& entry : *entries) if (auto track = std::get_if(&entry)) - callback(*track); + callback(*track, static_cast(entry))>(nullptr)); else { - auto& group = std::get(entry); - callback(group.root); - for (auto& groupTrack : group.tracks) - callback(groupTrack); + auto& group = std::get(entry); + for (auto& groupTrack : group.tracks) + callback(groupTrack, &group); } +} + +template void groups_each(Entries& entries, Callback&& callback) +{ + for (auto& entry : entries) + if (auto group = std::get_if(&entry)) + callback(*group); +} + +// Every track of an animation (root, group roots, layers, nulls, triggers). +template void animation_tracks_each(A& animation, Callback&& callback) +{ + callback(animation.root); + for (auto* entries : {&animation.layers, &animation.nulls}) + for (auto& entry : *entries) + if (auto track = std::get_if(&entry)) + callback(*track); + else + { + auto& group = std::get(entry); + callback(group.root); + for (auto& groupTrack : group.tracks) + callback(groupTrack); + } callback(animation.triggers); - } +} - template auto& animation_entries_get(A& animation, int itemType) - { +template auto& animation_entries_get(A& animation, int itemType) +{ return itemType == NULL_ ? animation.nulls : animation.layers; - } +} - class Model - { - public: +class Model +{ +public: Info info = {}; Content content = {}; Animations animations = {}; @@ -382,39 +388,39 @@ std::uint64_t uid_get(Reference, bool = false) const; Handle handle_get(Reference, bool = false) const; void uids_repair(); - }; +}; - // uid -> where that element is now (as a Reference) and what it is, built in one walk of the animations. - class UidIndex - { - public: +// uid -> where that element is now (as a Reference) and what it is, built in one walk of the animations. +class UidIndex +{ +public: struct Location { - Reference reference = {}; - ElementType type = {}; + Reference reference = {}; + ElementType type = {}; }; - private: +private: std::unordered_map locations; - public: +public: UidIndex() = default; explicit UidIndex(const Model&); bool contains(std::uint64_t) const; std::optional reference_get(std::uint64_t) const; ElementType type_get(std::uint64_t) const; - }; +}; - bool is_model_equal(const Model&, const Model&); - std::set spritesheets_vector_used_get(const Model&); - int track_frames_count_get(const Track&); - int track_length_get(const Track&); - int animation_length_get(const Animation&); - glm::ivec2 animation_play_range_get(const Animation&); - const Track* animation_track_get(const Animation&, int, int, int = NONE, int = -1); - Track* animation_track_get(Animation&, int, int, int = NONE, int = -1); - TrackGroup* animation_track_group_get(Animation&, int, int); - const TrackGroup* animation_track_group_get(const Animation&, int, int); - Animation animation_clone(Animation); - Frame frame_clone(Frame); - Track track_clone(Track); +bool is_model_equal(const Model&, const Model&); +std::set spritesheets_vector_used_get(const Model&); +int track_frames_count_get(const Track&); +int track_length_get(const Track&); +int animation_length_get(const Animation&); +glm::ivec2 animation_play_range_get(const Animation&); +const Track* animation_track_get(const Animation&, int, int, int = NONE, int = -1); +Track* animation_track_get(Animation&, int, int, int = NONE, int = -1); +TrackGroup* animation_track_group_get(Animation&, int, int); +const TrackGroup* animation_track_group_get(const Animation&, int, int); +Animation animation_clone(Animation); +Frame frame_clone(Frame); +Track track_clone(Track); diff --git a/src/model/xml.cpp b/src/model/xml.cpp index b52fc9c..81720b2 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -19,20 +19,21 @@ #include "path.h" #include "timestamp.h" - constexpr std::string_view ELEMENT_TAGS[] = { +constexpr std::string_view ELEMENT_TAGS[] = { #define X(symbol, tag) tag, - ANM2_ELEMENT_TYPES + ANM2_ELEMENT_TYPES #undef X - }; - constexpr std::string_view INTERPOLATION_VALUES[] = {"", "", "EaseIn", "EaseOut", "EaseInOut"}; - constexpr std::string_view ORIGIN_VALUES[] = {"", "TopLeft", "Center"}; - constexpr std::string_view CHILD_MODE_VALUES[] = {"Loop", "Once", "Hold"}; - constexpr std::string_view CHILD_START_RANDOM = "Random"; - constexpr const char* TINT_ATTRIBUTES[] = {"RedTint", "GreenTint", "BlueTint", "AlphaTint"}; - constexpr const char* OFFSET_ATTRIBUTES[] = {"RedOffset", "GreenOffset", "BlueOffset"}; - // Attributes the editor reads (or older builds wrote, like ExtendedVersion); any other attribute is kept verbatim as - // Extras. - // clang-format off +}; + +constexpr std::string_view INTERPOLATION_VALUES[] = {"", "", "EaseIn", "EaseOut", "EaseInOut"}; +constexpr std::string_view ORIGIN_VALUES[] = {"", "TopLeft", "Center"}; +constexpr std::string_view CHILD_MODE_VALUES[] = {"Loop", "Once", "Hold"}; +constexpr std::string_view CHILD_START_RANDOM = "Random"; +constexpr const char* TINT_ATTRIBUTES[] = {"RedTint", "GreenTint", "BlueTint", "AlphaTint"}; +constexpr const char* OFFSET_ATTRIBUTES[] = {"RedOffset", "GreenOffset", "BlueOffset"}; +// Attributes the editor reads (or older builds wrote, like ExtendedVersion). Any other attribute is kept verbatim as +// Extras. +// clang-format off constexpr std::string_view KNOWN_ATTRIBUTES[] = { "Name", "CreatedBy", "CreatedOn", "ExtendedVersion", "Binding", "Value", "DefaultAnimation", "Path", "Vertex", "Fragment", "Id", "LayerId", "NullId", "SpritesheetId", "Fps", "Version", "FrameNum", "Delay", "AtFrame", "EventId", "RegionId", @@ -42,201 +43,218 @@ "Interpolated", "Origin", "BakeInterpolation", "BakeDelay", "BakeCount", "OriginalDelay", "Library", "Animation", "IsaacIgnored", "ChildAnimation", "ChildMode", "ChildStart", "Restart", "Blur"}; - // clang-format on - constexpr std::pair BOOL_WORDS[] = {{"true", true}, {"True", true}, {"TRUE", true}, - {"false", false}, {"False", false}, {"FALSE", false}}; - constexpr std::string_view SOURCE_DOCUMENT_TAG = "SourceDocument"; - constexpr std::string_view FRAME_RESTORE_TAG = "FrameRestore"; - constexpr std::string_view LEGACY_OVERLAY_TAG = "Overlay"; - constexpr std::string_view LEGACY_GROUPS_TAG = "Groups"; - constexpr const char* CREATED_ON_FORMAT = "%m/%d/%Y %I:%M:%S %p"; - constexpr const char* SHADER_NAME_DEFAULT = "New Shader"; - constexpr std::size_t VALUE_BUFFER_SIZE = 64; - constexpr int FLOAT_DIGITS = 8; - constexpr int DOUBLE_DIGITS = 17; - constexpr double FLOAT_WHOLE_MAX = 1e8; - constexpr std::size_t FRAME_ATTRIBUTES_MAX = 27; - constexpr std::string_view INDENT = " "; - constexpr int TEXT_ENTITY_COUNT = 3; - constexpr std::pair ENTITIES[] = { - {'&', "&"}, {'<', "<"}, {'>', ">"}, {'"', """}, {'\'', "'"}}; - constexpr std::uint64_t HASH_OFFSET = 14695981039346656037ull; - constexpr std::uint64_t HASH_PRIME = 1099511628211ull; - constexpr Flags CLIPBOARD_FLAGS = SERIALIZE_EDITOR_DEFAULT; +// clang-format on +constexpr std::pair BOOL_WORDS[] = {{"true", true}, {"True", true}, {"TRUE", true}, + {"false", false}, {"False", false}, {"FALSE", false}}; +constexpr std::string_view SOURCE_DOCUMENT_TAG = "SourceDocument"; +constexpr std::string_view FRAME_RESTORE_TAG = "FrameRestore"; +constexpr std::string_view LEGACY_OVERLAY_TAG = "Overlay"; +constexpr std::string_view LEGACY_GROUPS_TAG = "Groups"; +constexpr const char* CREATED_ON_FORMAT = "%m/%d/%Y %I:%M:%S %p"; +constexpr const char* SHADER_NAME_DEFAULT = "New Shader"; +constexpr std::size_t VALUE_BUFFER_SIZE = 64; +constexpr int FLOAT_DIGITS = 8; +constexpr int DOUBLE_DIGITS = 17; +constexpr double FLOAT_WHOLE_MAX = 1e8; +constexpr std::size_t FRAME_ATTRIBUTES_MAX = 27; +constexpr std::string_view INDENT = " "; +constexpr int TEXT_ENTITY_COUNT = 3; +constexpr std::pair ENTITIES[] = { + {'&', "&"}, {'<', "<"}, {'>', ">"}, {'"', """}, {'\'', "'"}}; +constexpr std::uint64_t HASH_OFFSET = 14695981039346656037ull; +constexpr std::uint64_t HASH_PRIME = 1099511628211ull; +constexpr Flags CLIPBOARD_FLAGS = SERIALIZE_EDITOR_DEFAULT; - static const char* tag_get(ElementType type) { return ELEMENT_TAGS[(int)type].data(); } +static const char* tag_get(ElementType type) +{ + return ELEMENT_TAGS[(int)type].data(); +} - static ElementType type_get(pugi::xml_node element) - { +static ElementType type_get(pugi::xml_node element) +{ auto it = std::ranges::find(ELEMENT_TAGS, std::string_view(element.name())); return it == std::end(ELEMENT_TAGS) ? ElementType::UNKNOWN : (ElementType)(it - std::begin(ELEMENT_TAGS)); - } +} - static ElementType track_element_type_get(ItemType type) - { +static ElementType track_element_type_get(ItemType type) +{ switch (type) { - case ItemType::ROOT: - return ElementType::ROOT_ANIMATION; - case ItemType::NULL_: - return ElementType::NULL_ANIMATION; - case ItemType::TRIGGER: - return ElementType::TRIGGERS; - default: - return ElementType::LAYER_ANIMATION; + case ItemType::ROOT: + return ElementType::ROOT_ANIMATION; + case ItemType::NULL_: + return ElementType::NULL_ANIMATION; + case ItemType::TRIGGER: + return ElementType::TRIGGERS; + default: + return ElementType::LAYER_ANIMATION; } - } +} - // Reading: pugixml straight into the model. +// Reading: pugixml straight into the model. - // Numbers and booleans read as tinyxml2 (which older builds used) reads them: "%d" and "%f" on the leading text, - // and booleans as a number or true/false. - static const char* attribute_get(pugi::xml_node element, const char* name) - { +// Numbers and booleans read as tinyxml2 (which older builds used) reads them: "%d" and "%f" on the leading text, +// and booleans as a number or true/false. +static const char* attribute_get(pugi::xml_node element, const char* name) +{ auto attribute = element.attribute(name); return attribute ? attribute.value() : nullptr; - } +} - static bool is_int_read(const char* text, int& value) { return text && std::sscanf(text, "%d", &value) == 1; } +static bool is_int_read(const char* text, int& value) +{ + return text && std::sscanf(text, "%d", &value) == 1; +} - static int int_get(pugi::xml_node element, const char* name, int value = -1) - { +static int int_get(pugi::xml_node element, const char* name, int value = -1) +{ is_int_read(attribute_get(element, name), value); return value; - } +} - static float float_get(pugi::xml_node element, const char* name, float value = 0.0f) - { - if (auto text = attribute_get(element, name)) std::sscanf(text, "%f", &value); +static float float_get(pugi::xml_node element, const char* name, float value = 0.0f) +{ + if (auto text = attribute_get(element, name)) + std::sscanf(text, "%f", &value); return value; - } +} - static bool bool_get(pugi::xml_node element, const char* name, bool value) - { +static bool bool_get(pugi::xml_node element, const char* name, bool value) +{ auto text = attribute_get(element, name); - if (int number{}; is_int_read(text, number)) return number != 0; - if (!text) return value; + if (int number{}; is_int_read(text, number)) + return number != 0; + if (!text) + return value; for (auto [word, isTrue] : BOOL_WORDS) - if (word == text) return isTrue; + if (word == text) + return isTrue; return value; - } +} - static std::string string_get(pugi::xml_node element, const char* name, std::string value = {}) - { - if (auto attribute = attribute_get(element, name)) value = attribute; +static std::string string_get(pugi::xml_node element, const char* name, std::string value = {}) +{ + if (auto attribute = attribute_get(element, name)) + value = attribute; return value; - } +} - static std::filesystem::path path_get(pugi::xml_node element, const char* name) - { +static std::filesystem::path path_get(pugi::xml_node element, const char* name) +{ auto attribute = attribute_get(element, name); return attribute ? path_from_utf8(attribute) : std::filesystem::path{}; - } +} - static float color_get(pugi::xml_node element, const char* name, float value) - { - if (int color{}; is_int_read(attribute_get(element, name), color)) value = uint8_to_float(color); +static float color_get(pugi::xml_node element, const char* name, float value) +{ + if (int color{}; is_int_read(attribute_get(element, name), color)) + value = uint8_to_float(color); return value; - } +} - // An element's text: its first child, when that is text. - static const char* text_get(pugi::xml_node element) - { +// An element's text: its first child, when that is text. +static const char* text_get(pugi::xml_node element) +{ auto first = element.first_child(); return first.type() == pugi::node_pcdata || first.type() == pugi::node_cdata ? first.value() : nullptr; - } +} - static Interpolation interpolation_read(pugi::xml_node element, const char* name) - { +static Interpolation interpolation_read(pugi::xml_node element, const char* name) +{ auto value = attribute_get(element, name); - if (!value) return Interpolation::NONE; + if (!value) + return Interpolation::NONE; for (std::size_t i = 0; i < std::size(INTERPOLATION_VALUES); ++i) - if (!INTERPOLATION_VALUES[i].empty() && INTERPOLATION_VALUES[i] == value) return (Interpolation)i; + if (!INTERPOLATION_VALUES[i].empty() && INTERPOLATION_VALUES[i] == value) + return (Interpolation)i; return bool_get(element, name, false) ? Interpolation::LINEAR : Interpolation::NONE; - } +} - static pugi::xml_node element_next(pugi::xml_node node) - { +static pugi::xml_node element_next(pugi::xml_node node) +{ do - node = node.next_sibling(); + node = node.next_sibling(); while (node && node.type() != pugi::node_element); return node; - } +} - static pugi::xml_node element_first(pugi::xml_node parent) - { +static pugi::xml_node element_first(pugi::xml_node parent) +{ auto child = parent.first_child(); return !child || child.type() == pugi::node_element ? child : element_next(child); - } +} - // Shader elements are only read where they belong; one anywhere else is dropped. - static bool is_child_kept(pugi::xml_node parent, pugi::xml_node child) - { +// Shader elements are only read where they belong. One anywhere else is dropped. +static bool is_child_kept(pugi::xml_node parent, pugi::xml_node child) +{ std::string_view tag = child.name(); - if (tag == LEGACY_OVERLAY_TAG || tag == SOURCE_DOCUMENT_TAG) return false; + if (tag == LEGACY_OVERLAY_TAG || tag == SOURCE_DOCUMENT_TAG) + return false; auto parentType = parent.type() == pugi::node_element ? type_get(parent) : ElementType::UNKNOWN; switch (type_get(child)) { - case ElementType::SHADERS: - return parentType == ElementType::CONTENT; - case ElementType::SHADER: - return parentType == ElementType::SHADERS; - case ElementType::UNIFORM: - return parentType == ElementType::SHADER; - case ElementType::COMPONENT: - return parentType == ElementType::UNIFORM; - default: - return true; + case ElementType::SHADERS: + return parentType == ElementType::CONTENT; + case ElementType::SHADER: + return parentType == ElementType::SHADERS; + case ElementType::UNIFORM: + return parentType == ElementType::SHADER; + case ElementType::COMPONENT: + return parentType == ElementType::UNIFORM; + default: + return true; } - } +} - // Child elements with their position, skipping legacy Overlay, nested SourceDocument copies and misplaced shaders. - template static void children_each(pugi::xml_node parent, Callback&& callback) - { +// Child elements with their position, skipping legacy Overlay, nested SourceDocument copies and misplaced shaders. +template static void children_each(pugi::xml_node parent, Callback&& callback) +{ int position = 0; for (auto child : parent.children()) - if (child.type() == pugi::node_element && is_child_kept(parent, child)) - callback(child, type_get(child), position++); - } + if (child.type() == pugi::node_element && is_child_kept(parent, child)) + callback(child, type_get(child), position++); +} - // A repeated attribute keeps its first position and last value. - static void attribute_read(std::vector>& attributes, pugi::xml_attribute attribute) - { +// A repeated attribute keeps its first position and last value. +static void attribute_read(std::vector>& attributes, pugi::xml_attribute attribute) +{ auto existing = std::ranges::find(attributes, std::string_view(attribute.name()), [](const auto& pair) { return std::string_view(pair.first); }); if (existing != attributes.end()) - existing->second = attribute.value(); + existing->second = attribute.value(); else - attributes.emplace_back(attribute.name(), attribute.value()); - } + attributes.emplace_back(attribute.name(), attribute.value()); +} - static XmlNode node_read(pugi::xml_node element) - { +static XmlNode node_read(pugi::xml_node element) +{ XmlNode node = {.tag = element.name()}; for (auto attribute : element.attributes()) - attribute_read(node.attributes, attribute); - if (auto text = text_get(element)) node.text = text; + attribute_read(node.attributes, attribute); + if (auto text = text_get(element)) + node.text = text; children_each(element, [&](pugi::xml_node child, ElementType, int) { node.children.push_back(node_read(child)); }); return node; - } +} - static Extras extras_read(pugi::xml_node element) - { +static Extras extras_read(pugi::xml_node element) +{ Extras extras = {}; for (auto attribute : element.attributes()) - if (!std::ranges::contains(KNOWN_ATTRIBUTES, std::string_view(attribute.name()))) - attribute_read(extras.attributes, attribute); - if (auto text = text_get(element)) extras.text = text; + if (!std::ranges::contains(KNOWN_ATTRIBUTES, std::string_view(attribute.name()))) + attribute_read(extras.attributes, attribute); + if (auto text = text_get(element)) + extras.text = text; return extras; - } +} - static void extras_child_add(Extras& extras, pugi::xml_node child, int position) - { +static void extras_child_add(Extras& extras, pugi::xml_node child, int position) +{ extras.children.emplace_back(position, node_read(child)); - } +} - static Frame frame_read(pugi::xml_node element) - { +static Frame frame_read(pugi::xml_node element) +{ Frame frame = {}; frame.crop = {float_get(element, "XCrop"), float_get(element, "YCrop")}; frame.size = {float_get(element, "Width"), float_get(element, "Height")}; @@ -248,9 +266,9 @@ float_get(element, "SkewY", float_get(element, "ShearY"))}; frame.rotation = float_get(element, "Rotation"); for (int i = 0; i < (int)std::size(TINT_ATTRIBUTES); ++i) - frame.tint[i] = color_get(element, TINT_ATTRIBUTES[i], frame.tint[i]); + frame.tint[i] = color_get(element, TINT_ATTRIBUTES[i], frame.tint[i]); for (int i = 0; i < (int)std::size(OFFSET_ATTRIBUTES); ++i) - frame.colorOffset[i] = color_get(element, OFFSET_ATTRIBUTES[i], frame.colorOffset[i]); + frame.colorOffset[i] = color_get(element, OFFSET_ATTRIBUTES[i], frame.colorOffset[i]); frame.colorOffset.a = color_get(element, "AlphaOffset", frame.colorOffset.a); frame.duration = int_get(element, "Delay", frame.duration); frame.isVisible = bool_get(element, "Visible", frame.isVisible); @@ -262,63 +280,66 @@ frame.childAnimation = string_get(element, "ChildAnimation"); auto childMode = std::ranges::find(CHILD_MODE_VALUES, string_get(element, "ChildMode")); if (childMode != std::end(CHILD_MODE_VALUES)) - frame.childMode = (ChildMode)(childMode - std::begin(CHILD_MODE_VALUES)); + frame.childMode = (ChildMode)(childMode - std::begin(CHILD_MODE_VALUES)); frame.isChildStartRandom = string_get(element, "ChildStart") == CHILD_START_RANDOM; frame.childStart = int_get(element, "ChildStart", 0); frame.isChildRestart = bool_get(element, "Restart", false); frame.atFrame = int_get(element, "AtFrame"); frame.extras = extras_read(element); - if (type_get(element) != ElementType::TRIGGER) return frame; + if (type_get(element) != ElementType::TRIGGER) + return frame; - // A trigger's first event is its EventId and any others are children; its sounds are children + // A trigger's first event is its EventId and any others are children. Its sounds are children // (older files name one with a SoundId attribute instead). - auto ids_read = [&](std::vector& ids, const char* attribute, ElementType type) - { - children_each(element, - [&](pugi::xml_node child, ElementType childType, int) - { - if (childType == type) ids.push_back(int_get(child, "Id")); - }); - if (auto id = int_get(element, attribute); id != -1 && !std::ranges::contains(ids, id)) - ids.insert(ids.begin(), id); - std::erase(ids, -1); + auto ids_read = [&](std::vector& ids, const char* attribute, ElementType type) { + children_each(element, [&](pugi::xml_node child, ElementType childType, int) { + if (childType == type) + ids.push_back(int_get(child, "Id")); + }); + if (auto id = int_get(element, attribute); id != -1 && !std::ranges::contains(ids, id)) + ids.insert(ids.begin(), id); + std::erase(ids, -1); }; ids_read(frame.eventIds, "EventId", ElementType::EVENT_ELEMENT); ids_read(frame.soundIds, "SoundId", ElementType::SOUND_ELEMENT); return frame; - } +} - static Track track_read(pugi::xml_node element, ItemType type) - { +static Track track_read(pugi::xml_node element, ItemType type) +{ Track track = {.type = type, .isVisible = bool_get(element, "Visible", true), .extras = extras_read(element)}; - if (type == ItemType::LAYER) track.id = int_get(element, "LayerId"); - if (type == ItemType::NULL_) track.id = int_get(element, "NullId"); + if (type == ItemType::LAYER) + track.id = int_get(element, "LayerId"); + if (type == ItemType::NULL_) + track.id = int_get(element, "NullId"); auto frameType = type == ItemType::TRIGGER ? ElementType::TRIGGER : ElementType::FRAME; for (auto child = element_first(element); child;) { - auto childType = type_get(child); - // A frame written baked (BakeInterpolation/BakeDelay) is read back as the one interpolated frame it came from. - if (auto delay = int_get(child, "BakeDelay", 0); - childType == ElementType::FRAME && attribute_get(child, "BakeInterpolation") && delay >= FRAME_DURATION_MIN) - { - auto frame = frame_read(child); - frame.interpolation = interpolation_read(child, "BakeInterpolation"); - frame.duration = delay; - if (frameType == ElementType::FRAME) track.frames.push_back(std::move(frame)); - for (int i = 0; child && i < delay; ++i) - child = element_next(child); - continue; - } - if (childType == frameType) track.frames.push_back(frame_read(child)); - child = element_next(child); + auto childType = type_get(child); + // A frame written baked (BakeInterpolation/BakeDelay) is read back as the one interpolated frame it came from. + if (auto delay = int_get(child, "BakeDelay", 0); + childType == ElementType::FRAME && attribute_get(child, "BakeInterpolation") && delay >= FRAME_DURATION_MIN) + { + auto frame = frame_read(child); + frame.interpolation = interpolation_read(child, "BakeInterpolation"); + frame.duration = delay; + if (frameType == ElementType::FRAME) + track.frames.push_back(std::move(frame)); + for (int i = 0; child && i < delay; ++i) + child = element_next(child); + continue; + } + if (childType == frameType) + track.frames.push_back(frame_read(child)); + child = element_next(child); } return track; - } +} - // A container's children before groups are resolved: a child (with the group it names), a group (with any children - // nested in it), or unknown XML. - template struct ContainerItem - { +// A container's children before groups are resolved: a child (with the group it names), a group (with any children +// nested in it), or unknown XML. +template struct ContainerItem +{ using Group = GroupType; std::optional child; @@ -331,60 +352,70 @@ std::optional backupRoot; std::vector backupTracks; bool isBackup = false; - }; +}; - using TrackItem = ContainerItem; - using AnimationItem = ContainerItem, AnimationGroup>; +using TrackItem = ContainerItem; +using AnimationItem = ContainerItem, AnimationGroup>; - static auto& group_children_get(TrackGroup& group) { return group.tracks; } - static auto& group_children_get(AnimationGroup& group) { return group.animations; } +static auto& group_children_get(TrackGroup& group) +{ + return group.tracks; +} - // Groups become entries followed by their children: nested children move out after their group, and a child joins a - // group seen before it. Unknown XML becomes extras at its position. - template static std::vector entries_build(std::vector items, Extras& extras) - { +static auto& group_children_get(AnimationGroup& group) +{ + return group.animations; +} + +// Groups become entries followed by their children: nested children move out after their group, and a child joins a +// group seen before it. Unknown XML becomes extras at its position. +template static std::vector entries_build(std::vector items, Extras& extras) +{ int nextGroupId = 0; for (auto& item : items) - if (item.group) nextGroupId = std::max(nextGroupId, item.group->id + 1); + if (item.group) + nextGroupId = std::max(nextGroupId, item.group->id + 1); std::vector flat; for (auto& item : items) { - if (!item.group) - { + if (!item.group) + { + flat.push_back(std::move(item)); + continue; + } + if (item.group->id < 0) + item.group->id = nextGroupId++; + auto groupId = item.group->id; + auto children = std::move(item.children); flat.push_back(std::move(item)); - continue; - } - if (item.group->id < 0) item.group->id = nextGroupId++; - auto groupId = item.group->id; - auto children = std::move(item.children); - flat.push_back(std::move(item)); - for (auto& child : children) - flat.push_back({.child = std::move(child), .groupId = groupId}); + for (auto& child : children) + flat.push_back({.child = std::move(child), .groupId = groupId}); } std::vector entries; std::map groupEntries; for (int i = 0; i < (int)flat.size(); ++i) { - auto& item = flat[i]; - if (item.node) - extras.children.emplace_back(i, std::move(*item.node)); - else if (item.group) - { - groupEntries[item.group->id] = entries.size(); - entries.emplace_back(std::move(*item.group)); - } - else if (auto group = groupEntries.find(item.groupId); group != groupEntries.end()) - group_children_get(std::get(entries[group->second])).push_back(std::move(*item.child)); - else - entries.emplace_back(std::move(*item.child)); + auto& item = flat[i]; + if (item.node) + extras.children.emplace_back(i, std::move(*item.node)); + else if (item.group) + { + groupEntries[item.group->id] = entries.size(); + entries.emplace_back(std::move(*item.group)); + } + else if (auto group = groupEntries.find(item.groupId); group != groupEntries.end()) + group_children_get(std::get(entries[group->second])) + .push_back(std::move(*item.child)); + else + entries.emplace_back(std::move(*item.child)); } return entries; - } +} - static TrackItem track_group_item_read(pugi::xml_node element, ItemType type) - { +static TrackItem track_group_item_read(pugi::xml_node element, ItemType type) +{ TrackItem item{.group = TrackGroup{.id = int_get(element, "Id"), .name = string_get(element, "Name"), .isExpanded = bool_get(element, "IsExpanded", true), @@ -392,88 +423,85 @@ .extras = extras_read(element)}, .index = int_get(element, "Index")}; auto trackType = track_element_type_get(type); - children_each(element, - [&](pugi::xml_node child, ElementType childType, int) - { - if (childType == ElementType::ROOT_ANIMATION && !item.root) - item.root = track_read(child, ItemType::ROOT); - else if (childType == trackType) - item.children.push_back(track_read(child, type)); - else if (child.name() == FRAME_RESTORE_TAG && !item.isBackup) - { - item.isBackup = true; - children_each(child, - [&](pugi::xml_node backup, ElementType backupType, int) - { - if (backupType == ElementType::ROOT_ANIMATION && !item.backupRoot) - item.backupRoot = track_read(backup, ItemType::ROOT); - else if (backupType == trackType) - item.backupTracks.push_back(track_read(backup, type)); - }); - } - }); + children_each(element, [&](pugi::xml_node child, ElementType childType, int) { + if (childType == ElementType::ROOT_ANIMATION && !item.root) + item.root = track_read(child, ItemType::ROOT); + else if (childType == trackType) + item.children.push_back(track_read(child, type)); + else if (child.name() == FRAME_RESTORE_TAG && !item.isBackup) + { + item.isBackup = true; + children_each(child, [&](pugi::xml_node backup, ElementType backupType, int) { + if (backupType == ElementType::ROOT_ANIMATION && !item.backupRoot) + item.backupRoot = track_read(backup, ItemType::ROOT); + else if (backupType == trackType) + item.backupTracks.push_back(track_read(backup, type)); + }); + } + }); return item; - } +} - static std::vector track_items_read(pugi::xml_node container, ItemType type) - { +static std::vector track_items_read(pugi::xml_node container, ItemType type) +{ std::vector items; - children_each(container, - [&](pugi::xml_node child, ElementType childType, int) - { - if (childType == ElementType::GROUP) - items.push_back(track_group_item_read(child, type)); - else if (childType == track_element_type_get(type)) - items.push_back({.child = track_read(child, type), .groupId = int_get(child, "GroupId")}); - else - items.push_back({.node = node_read(child)}); - }); + children_each(container, [&](pugi::xml_node child, ElementType childType, int) { + if (childType == ElementType::GROUP) + items.push_back(track_group_item_read(child, type)); + else if (childType == track_element_type_get(type)) + items.push_back({.child = track_read(child, type), .groupId = int_get(child, "GroupId")}); + else + items.push_back({.node = node_read(child)}); + }); return items; - } +} - // Track groups as any version wrote them: legacy *AnimationGroups metadata is placed back at its Index, and a group - // whose tracks were written baked (FrameRestore) gets its original root and tracks back. - static std::vector track_entries_build(std::vector items, std::vector legacyGroups, - Extras& extras) - { +// Track groups as any version wrote them: legacy *AnimationGroups metadata is placed back at its Index, and a group +// whose tracks were written baked (FrameRestore) gets its original root and tracks back. +static std::vector track_entries_build(std::vector items, std::vector legacyGroups, + Extras& extras) +{ if (!legacyGroups.empty()) { - std::set legacyIds; - for (auto& item : legacyGroups) - if (item.group->id >= 0) legacyIds.insert(item.group->id); - std::erase_if(items, [&](const TrackItem& item) { return item.group && legacyIds.contains(item.group->id); }); - std::ranges::stable_sort(legacyGroups, - [](const TrackItem& left, const TrackItem& right) - { - if (left.index == -1 || right.index == -1) return left.index != -1; - return left.index < right.index; - }); - for (auto& legacy : legacyGroups) - { - auto first = std::ranges::find_if(items, [&](const TrackItem& item) - { return item.child && item.groupId == legacy.group->id; }); - auto position = legacy.index >= 0 ? std::min(legacy.index, (int)items.size()) : (int)(first - items.begin()); - items.insert(items.begin() + position, std::move(legacy)); - } + std::set legacyIds; + for (auto& item : legacyGroups) + if (item.group->id >= 0) + legacyIds.insert(item.group->id); + std::erase_if(items, [&](const TrackItem& item) { return item.group && legacyIds.contains(item.group->id); }); + std::ranges::stable_sort(legacyGroups, [](const TrackItem& left, const TrackItem& right) { + if (left.index == -1 || right.index == -1) + return left.index != -1; + return left.index < right.index; + }); + for (auto& legacy : legacyGroups) + { + auto first = std::ranges::find_if( + items, [&](const TrackItem& item) { return item.child && item.groupId == legacy.group->id; }); + auto position = + legacy.index >= 0 ? std::min(legacy.index, (int)items.size()) : (int)(first - items.begin()); + items.insert(items.begin() + position, std::move(legacy)); + } } std::set restoredIds; for (auto& item : items) - if (item.group && item.group->id >= 0 && item.isBackup && (item.backupRoot || !item.backupTracks.empty())) - { - if (item.backupRoot) item.root = item.backupRoot; - item.children = std::move(item.backupTracks); - restoredIds.insert(item.group->id); - } + if (item.group && item.group->id >= 0 && item.isBackup && (item.backupRoot || !item.backupTracks.empty())) + { + if (item.backupRoot) + item.root = item.backupRoot; + item.children = std::move(item.backupTracks); + restoredIds.insert(item.group->id); + } std::erase_if(items, [&](const TrackItem& item) { return item.child && restoredIds.contains(item.groupId); }); for (auto& item : items) - if (item.group) item.group->root = item.root.value_or(TrackGroup{}.root); + if (item.group) + item.group->root = item.root.value_or(TrackGroup{}.root); return entries_build(std::move(items), extras); - } +} - static Animation animation_read(pugi::xml_node element) - { +static Animation animation_read(pugi::xml_node element) +{ Animation animation{.name = string_get(element, "Name"), .frameNum = int_get(element, "FrameNum", 1), .isLoop = bool_get(element, "Loop", true), @@ -486,90 +514,83 @@ std::map> legacyGroups; std::set legacyRead; int skipped = 0; - children_each(element, - [&](pugi::xml_node child, ElementType type, int position) - { - if (type == ElementType::LAYER_ANIMATION_GROUPS || type == ElementType::NULL_ANIMATION_GROUPS) - { - auto isLayers = type == ElementType::LAYER_ANIMATION_GROUPS; - auto container = isLayers ? ElementType::LAYER_ANIMATIONS : ElementType::NULL_ANIMATIONS; - if (legacyRead.insert(type).second) - children_each(child, - [&](pugi::xml_node group, ElementType groupType, int) - { - if (groupType == ElementType::GROUP) - legacyGroups[container].push_back(track_group_item_read( - group, isLayers ? ItemType::LAYER : ItemType::NULL_)); - }); - ++skipped; - return; - } + children_each(element, [&](pugi::xml_node child, ElementType type, int position) { + if (type == ElementType::LAYER_ANIMATION_GROUPS || type == ElementType::NULL_ANIMATION_GROUPS) + { + auto isLayers = type == ElementType::LAYER_ANIMATION_GROUPS; + auto container = isLayers ? ElementType::LAYER_ANIMATIONS : ElementType::NULL_ANIMATIONS; + if (legacyRead.insert(type).second) + children_each(child, [&](pugi::xml_node group, ElementType groupType, int) { + if (groupType == ElementType::GROUP) + legacyGroups[container].push_back( + track_group_item_read(group, isLayers ? ItemType::LAYER : ItemType::NULL_)); + }); + ++skipped; + return; + } - auto isKnown = type == ElementType::ROOT_ANIMATION || type == ElementType::LAYER_ANIMATIONS || - type == ElementType::NULL_ANIMATIONS || type == ElementType::TRIGGERS; - if (!isKnown || std::ranges::contains(animation.layout, type)) - return extras_child_add(animation.extras, child, position - skipped); + auto isKnown = type == ElementType::ROOT_ANIMATION || type == ElementType::LAYER_ANIMATIONS || + type == ElementType::NULL_ANIMATIONS || type == ElementType::TRIGGERS; + if (!isKnown || std::ranges::contains(animation.layout, type)) + return extras_child_add(animation.extras, child, position - skipped); - animation.layout.push_back(type); - if (type == ElementType::ROOT_ANIMATION) animation.root = track_read(child, ItemType::ROOT); - if (type == ElementType::TRIGGERS) animation.triggers = track_read(child, ItemType::TRIGGER); - if (type == ElementType::LAYER_ANIMATIONS) - { - items[type] = track_items_read(child, ItemType::LAYER); - animation.layersExtras = extras_read(child); - } - if (type == ElementType::NULL_ANIMATIONS) - { - items[type] = track_items_read(child, ItemType::NULL_); - animation.nullsExtras = extras_read(child); - } - }); + animation.layout.push_back(type); + if (type == ElementType::ROOT_ANIMATION) + animation.root = track_read(child, ItemType::ROOT); + if (type == ElementType::TRIGGERS) + animation.triggers = track_read(child, ItemType::TRIGGER); + if (type == ElementType::LAYER_ANIMATIONS) + { + items[type] = track_items_read(child, ItemType::LAYER); + animation.layersExtras = extras_read(child); + } + if (type == ElementType::NULL_ANIMATIONS) + { + items[type] = track_items_read(child, ItemType::NULL_); + animation.nullsExtras = extras_read(child); + } + }); for (auto [type, entries, extras] : {std::tuple{ElementType::LAYER_ANIMATIONS, &animation.layers, &animation.layersExtras}, std::tuple{ElementType::NULL_ANIMATIONS, &animation.nulls, &animation.nullsExtras}}) { - if (!legacyGroups[type].empty() && !std::ranges::contains(animation.layout, type)) - animation.layout.push_back(type); - if (std::ranges::contains(animation.layout, type)) - *entries = track_entries_build(std::move(items[type]), std::move(legacyGroups[type]), *extras); + if (!legacyGroups[type].empty() && !std::ranges::contains(animation.layout, type)) + animation.layout.push_back(type); + if (std::ranges::contains(animation.layout, type)) + *entries = track_entries_build(std::move(items[type]), std::move(legacyGroups[type]), *extras); } return animation; - } +} - static std::vector animation_entries_read(pugi::xml_node parent, Extras& extras) - { +static std::vector animation_entries_read(pugi::xml_node parent, Extras& extras) +{ std::vector items; - children_each(parent, - [&](pugi::xml_node child, ElementType type, int) - { - if (type == ElementType::GROUP) - { - AnimationItem item{.group = AnimationGroup{.id = int_get(child, "Id"), - .name = string_get(child, "Name"), - .isExpanded = bool_get(child, "IsExpanded", true), - .isVisible = bool_get(child, "Visible", true), - .extras = extras_read(child)}}; - children_each(child, - [&](pugi::xml_node animation, ElementType animationType, int) - { - if (animationType == ElementType::ANIMATION) - item.children.push_back( - std::make_shared(animation_read(animation))); - }); - items.push_back(std::move(item)); - } - else if (type == ElementType::ANIMATION) - items.push_back({.child = std::make_shared(animation_read(child)), - .groupId = int_get(child, "GroupId")}); - else - items.push_back({.node = node_read(child)}); - }); + children_each(parent, [&](pugi::xml_node child, ElementType type, int) { + if (type == ElementType::GROUP) + { + AnimationItem item{.group = AnimationGroup{.id = int_get(child, "Id"), + .name = string_get(child, "Name"), + .isExpanded = bool_get(child, "IsExpanded", true), + .isVisible = bool_get(child, "Visible", true), + .extras = extras_read(child)}}; + children_each(child, [&](pugi::xml_node animation, ElementType animationType, int) { + if (animationType == ElementType::ANIMATION) + item.children.push_back(std::make_shared(animation_read(animation))); + }); + items.push_back(std::move(item)); + } + else if (type == ElementType::ANIMATION) + items.push_back({.child = std::make_shared(animation_read(child)), + .groupId = int_get(child, "GroupId")}); + else + items.push_back({.node = node_read(child)}); + }); return entries_build(std::move(items), extras); - } +} - static Region region_read(pugi::xml_node element) - { +static Region region_read(pugi::xml_node element) +{ Region region{.id = int_get(element, "Id"), .name = string_get(element, "Name"), .crop = {float_get(element, "XCrop"), float_get(element, "YCrop")}, @@ -577,172 +598,191 @@ .pivot = {float_get(element, "XPivot"), float_get(element, "YPivot")}, .extras = extras_read(element)}; if (auto origin = attribute_get(element, "Origin")) - for (std::size_t i = 0; i < std::size(ORIGIN_VALUES); ++i) - if (!ORIGIN_VALUES[i].empty() && ORIGIN_VALUES[i] == origin) region.origin = (Origin)i; - if (region.origin == Origin::TOP_LEFT) region.pivot = {}; - if (region.origin == Origin::CENTER) region.pivot = region.size * 0.5f; + for (std::size_t i = 0; i < std::size(ORIGIN_VALUES); ++i) + if (!ORIGIN_VALUES[i].empty() && ORIGIN_VALUES[i] == origin) + region.origin = (Origin)i; + if (region.origin == Origin::TOP_LEFT) + region.pivot = {}; + if (region.origin == Origin::CENTER) + region.pivot = region.size * 0.5f; return region; - } +} - static Spritesheet spritesheet_read(pugi::xml_node element) - { +static Spritesheet spritesheet_read(pugi::xml_node element) +{ Spritesheet spritesheet{ .id = int_get(element, "Id"), .path = path_get(element, "Path"), .extras = extras_read(element)}; - children_each(element, - [&](pugi::xml_node child, ElementType type, int position) - { - if (type == ElementType::REGION) - spritesheet.regions.push_back(region_read(child)); - else - extras_child_add(spritesheet.extras, child, position); - }); + children_each(element, [&](pugi::xml_node child, ElementType type, int position) { + if (type == ElementType::REGION) + spritesheet.regions.push_back(region_read(child)); + else + extras_child_add(spritesheet.extras, child, position); + }); return spritesheet; - } +} - static Shader shader_read(pugi::xml_node element) - { +static Shader shader_read(pugi::xml_node element) +{ Shader shader{.id = int_get(element, "Id"), .name = string_get(element, "Name"), .vertex = path_get(element, "Vertex"), .fragment = path_get(element, "Fragment"), .extras = extras_read(element)}; - children_each(element, - [&](pugi::xml_node child, ElementType type, int position) - { - if (type != ElementType::UNIFORM) return extras_child_add(shader.extras, child, position); - Uniform uniform{.name = string_get(child, "Name"), - .binding = string_get(child, "Binding"), - .value = string_get(child, "Value"), - .extras = extras_read(child)}; - children_each(child, - [&](pugi::xml_node component, ElementType componentType, int componentPosition) - { - if (componentType != ElementType::COMPONENT) - return extras_child_add(uniform.extras, component, componentPosition); - uniform.components.push_back({.index = int_get(component, "Index"), - .binding = string_get(component, "Binding"), - .value = string_get(component, "Value"), - .extras = extras_read(component)}); - }); - shader.uniforms.push_back(std::move(uniform)); - }); + children_each(element, [&](pugi::xml_node child, ElementType type, int position) { + if (type != ElementType::UNIFORM) + return extras_child_add(shader.extras, child, position); + Uniform uniform{.name = string_get(child, "Name"), + .binding = string_get(child, "Binding"), + .value = string_get(child, "Value"), + .extras = extras_read(child)}; + children_each(child, [&](pugi::xml_node component, ElementType componentType, int componentPosition) { + if (componentType != ElementType::COMPONENT) + return extras_child_add(uniform.extras, component, componentPosition); + uniform.components.push_back({.index = int_get(component, "Index"), + .binding = string_get(component, "Binding"), + .value = string_get(component, "Value"), + .extras = extras_read(component)}); + }); + shader.uniforms.push_back(std::move(uniform)); + }); return shader; - } +} - template static Item item_read(pugi::xml_node); - template <> Spritesheet item_read(pugi::xml_node element) { return spritesheet_read(element); } - template <> Region item_read(pugi::xml_node element) { return region_read(element); } - template <> Shader item_read(pugi::xml_node element) { return shader_read(element); } - template <> Layer item_read(pugi::xml_node element) - { +template static Item item_read(pugi::xml_node); +template <> Spritesheet item_read(pugi::xml_node element) +{ + return spritesheet_read(element); +} + +template <> Region item_read(pugi::xml_node element) +{ + return region_read(element); +} + +template <> Shader item_read(pugi::xml_node element) +{ + return shader_read(element); +} + +template <> Layer item_read(pugi::xml_node element) +{ return {.id = int_get(element, "Id"), .name = string_get(element, "Name"), .spritesheetId = int_get(element, "SpritesheetId", 0), .libraryId = int_get(element, "Library"), .animation = string_get(element, "Animation"), .extras = extras_read(element)}; - } - template <> Null item_read(pugi::xml_node element) - { +} + +template <> Null item_read(pugi::xml_node element) +{ return {.id = int_get(element, "Id"), .name = string_get(element, "Name"), .isShowRect = bool_get(element, "ShowRect", false), .extras = extras_read(element)}; - } - template <> Event item_read(pugi::xml_node element) - { +} + +template <> Event item_read(pugi::xml_node element) +{ return {.id = int_get(element, "Id"), .name = string_get(element, "Name"), .extras = extras_read(element)}; - } - template <> Sound item_read(pugi::xml_node element) - { - return {.id = int_get(element, "Id"), .path = path_get(element, "Path"), .extras = extras_read(element)}; - } - template <> Library item_read(pugi::xml_node element) - { - return {.id = int_get(element, "Id"), .path = path_get(element, "Path"), .extras = extras_read(element)}; - } +} - template constexpr ElementType ITEM_TYPE{}; - template <> constexpr ElementType ITEM_TYPE{ElementType::SPRITESHEET}; - template <> constexpr ElementType ITEM_TYPE{ElementType::REGION}; - template <> constexpr ElementType ITEM_TYPE{ElementType::SHADER}; - template <> constexpr ElementType ITEM_TYPE{ElementType::LAYER_ELEMENT}; - template <> constexpr ElementType ITEM_TYPE{ElementType::NULL_ELEMENT}; - template <> constexpr ElementType ITEM_TYPE{ElementType::EVENT_ELEMENT}; - template <> constexpr ElementType ITEM_TYPE{ElementType::SOUND_ELEMENT}; - template <> constexpr ElementType ITEM_TYPE{ElementType::LIBRARY}; +template <> Sound item_read(pugi::xml_node element) +{ + return {.id = int_get(element, "Id"), .path = path_get(element, "Path"), .extras = extras_read(element)}; +} - template static std::vector items_read(pugi::xml_node container, Content& content, ElementType type) - { +template <> Library item_read(pugi::xml_node element) +{ + return {.id = int_get(element, "Id"), .path = path_get(element, "Path"), .extras = extras_read(element)}; +} + +template constexpr ElementType ITEM_TYPE{}; +template <> constexpr ElementType ITEM_TYPE{ElementType::SPRITESHEET}; +template <> constexpr ElementType ITEM_TYPE{ElementType::REGION}; +template <> constexpr ElementType ITEM_TYPE{ElementType::SHADER}; +template <> constexpr ElementType ITEM_TYPE{ElementType::LAYER_ELEMENT}; +template <> constexpr ElementType ITEM_TYPE{ElementType::NULL_ELEMENT}; +template <> constexpr ElementType ITEM_TYPE{ElementType::EVENT_ELEMENT}; +template <> constexpr ElementType ITEM_TYPE{ElementType::SOUND_ELEMENT}; +template <> constexpr ElementType ITEM_TYPE{ElementType::LIBRARY}; + +template static std::vector items_read(pugi::xml_node container, Content& content, ElementType type) +{ std::vector items; auto extras = extras_read(container); - children_each(container, - [&](pugi::xml_node child, ElementType childType, int position) - { - if (childType == ITEM_TYPE) - items.push_back(item_read(child)); - else - extras_child_add(extras, child, position); - }); - if (extras != Extras{}) content.containerExtras.emplace_back(type, std::move(extras)); + children_each(container, [&](pugi::xml_node child, ElementType childType, int position) { + if (childType == ITEM_TYPE) + items.push_back(item_read(child)); + else + extras_child_add(extras, child, position); + }); + if (extras != Extras{}) + content.containerExtras.emplace_back(type, std::move(extras)); return items; - } +} - static Content content_read(pugi::xml_node element) - { +static Content content_read(pugi::xml_node element) +{ Content content = {.layout = {}, .extras = extras_read(element)}; - children_each(element, - [&](pugi::xml_node child, ElementType type, int position) - { - if (child.name() == LEGACY_GROUPS_TAG) return; - auto isKnown = type == ElementType::SPRITESHEETS || type == ElementType::SHADERS || - type == ElementType::LAYERS || type == ElementType::NULLS || - type == ElementType::EVENTS || type == ElementType::SOUNDS || - type == ElementType::LIBRARIES; - if (!isKnown || std::ranges::contains(content.layout, type)) - return extras_child_add(content.extras, child, position); - content.layout.push_back(type); - if (type == ElementType::SPRITESHEETS) - content.spritesheets = items_read(child, content, type); - if (type == ElementType::SHADERS) content.shaders = items_read(child, content, type); - if (type == ElementType::LAYERS) content.layers = items_read(child, content, type); - if (type == ElementType::NULLS) content.nulls = items_read(child, content, type); - if (type == ElementType::EVENTS) content.events = items_read(child, content, type); - if (type == ElementType::SOUNDS) content.sounds = items_read(child, content, type); - if (type == ElementType::LIBRARIES) content.libraries = items_read(child, content, type); - }); + children_each(element, [&](pugi::xml_node child, ElementType type, int position) { + if (child.name() == LEGACY_GROUPS_TAG) + return; + auto isKnown = type == ElementType::SPRITESHEETS || type == ElementType::SHADERS || + type == ElementType::LAYERS || type == ElementType::NULLS || type == ElementType::EVENTS || + type == ElementType::SOUNDS || type == ElementType::LIBRARIES; + if (!isKnown || std::ranges::contains(content.layout, type)) + return extras_child_add(content.extras, child, position); + content.layout.push_back(type); + if (type == ElementType::SPRITESHEETS) + content.spritesheets = items_read(child, content, type); + if (type == ElementType::SHADERS) + content.shaders = items_read(child, content, type); + if (type == ElementType::LAYERS) + content.layers = items_read(child, content, type); + if (type == ElementType::NULLS) + content.nulls = items_read(child, content, type); + if (type == ElementType::EVENTS) + content.events = items_read(child, content, type); + if (type == ElementType::SOUNDS) + content.sounds = items_read(child, content, type); + if (type == ElementType::LIBRARIES) + content.libraries = items_read(child, content, type); + }); return content; - } +} - // Gives every item a unique, non-negative id; the first holder of a duplicated id keeps it. - template static void ids_repair(Items& items) - { +// Gives every item a unique, non-negative id. The first holder of a duplicated id keeps it. +template static void ids_repair(Items& items) +{ std::set usedIds; for (auto& item : items) - if (item.id >= 0) usedIds.insert(item.id); + if (item.id >= 0) + usedIds.insert(item.id); std::set keptIds; int nextId = 0; for (auto& item : items) { - if (item.id >= 0 && keptIds.insert(item.id).second) continue; - while (usedIds.contains(nextId)) - ++nextId; - item.id = nextId; - usedIds.insert(nextId); - keptIds.insert(nextId); + if (item.id >= 0 && keptIds.insert(item.id).second) + continue; + while (usedIds.contains(nextId)) + ++nextId; + item.id = nextId; + usedIds.insert(nextId); + keptIds.insert(nextId); } - } +} - static bool is_region_matched(const Region& region, const Frame& frame) - { +static bool is_region_matched(const Region& region, const Frame& frame) +{ return glm::ivec2(region.crop) == glm::ivec2(frame.crop) && glm::ivec2(region.size) == glm::ivec2(frame.size) && glm::ivec2(region.pivot) == glm::ivec2(frame.pivot); - } +} - // Loaded documents get unique content ids, frames lose dangling shader ids, and layer frames point at the region - // matching their rectangle and take that region's rectangle. - void model_repair(Model& model) - { +// Loaded documents get unique content ids, frames lose dangling shader ids, and layer frames point at the region +// matching their rectangle and take that region's rectangle. +void model_repair(Model& model) +{ auto& content = model.content; ids_repair(content.spritesheets); ids_repair(content.shaders); @@ -752,87 +792,86 @@ ids_repair(content.sounds); ids_repair(content.libraries); for (auto& spritesheet : content.spritesheets) - ids_repair(spritesheet.regions); + ids_repair(spritesheet.regions); for (auto& shader : content.shaders) - if (shader.name.empty()) shader.name = SHADER_NAME_DEFAULT; + if (shader.name.empty()) + shader.name = SHADER_NAME_DEFAULT; for (int i = 0; i < model.animations_count_get(); ++i) { - auto& animation = *model.animation_edit(i); - animation_tracks_each(animation, - [&](Track& track) - { - if (track.type == ItemType::TRIGGER) return; - for (auto& frame : track.frames) - if (frame.shaderId != -1 && !item_get(content.shaders, frame.shaderId)) - frame.shaderId = -1; - }); - tracks_each(animation.layers, - [&](Track& track, auto*) - { - auto layer = item_get(content.layers, track.id); - auto spritesheet = layer ? item_get(content.spritesheets, layer->spritesheetId) : nullptr; - if (!spritesheet) return; - for (auto& frame : track.frames) - { - auto region = frame.regionId == -1 ? nullptr : item_get(spritesheet->regions, frame.regionId); - auto match = std::ranges::find_if(spritesheet->regions, [&](const Region& candidate) - { return is_region_matched(candidate, frame); }); - if ((!region || !is_region_matched(*region, frame)) && match != spritesheet->regions.end()) - frame.regionId = match->id; - if (frame.regionId == -1) continue; - region = item_get(spritesheet->regions, frame.regionId); - if (!region) - { - frame.regionId = -1; - continue; - } - frame.crop = region->crop; - frame.size = region->size; - frame.pivot = region->pivot; - } - }); + auto& animation = *model.animation_edit(i); + animation_tracks_each(animation, [&](Track& track) { + if (track.type == ItemType::TRIGGER) + return; + for (auto& frame : track.frames) + if (frame.shaderId != -1 && !item_get(content.shaders, frame.shaderId)) + frame.shaderId = -1; + }); + tracks_each(animation.layers, [&](Track& track, auto*) { + auto layer = item_get(content.layers, track.id); + auto spritesheet = layer ? item_get(content.spritesheets, layer->spritesheetId) : nullptr; + if (!spritesheet) + return; + for (auto& frame : track.frames) + { + auto region = frame.regionId == -1 ? nullptr : item_get(spritesheet->regions, frame.regionId); + auto match = std::ranges::find_if( + spritesheet->regions, [&](const Region& candidate) { return is_region_matched(candidate, frame); }); + if ((!region || !is_region_matched(*region, frame)) && match != spritesheet->regions.end()) + frame.regionId = match->id; + if (frame.regionId == -1) + continue; + region = item_get(spritesheet->regions, frame.regionId); + if (!region) + { + frame.regionId = -1; + continue; + } + frame.crop = region->crop; + frame.size = region->size; + frame.pivot = region->pivot; + } + }); } - } +} - static Model model_read(pugi::xml_node element) - { +static Model model_read(pugi::xml_node element) +{ Model model = {.layout = {}, .extras = extras_read(element)}; - children_each(element, - [&](pugi::xml_node child, ElementType type, int position) - { - auto isKnown = - type == ElementType::INFO || type == ElementType::CONTENT || type == ElementType::ANIMATIONS; - if (!isKnown || std::ranges::contains(model.layout, type)) - return extras_child_add(model.extras, child, position); - model.layout.push_back(type); - if (type == ElementType::INFO) - { - model.info = {.createdBy = string_get(child, "CreatedBy", Info{}.createdBy), - .createdOn = string_get(child, "CreatedOn"), - .fps = int_get(child, "Fps", Info{}.fps), - .version = int_get(child, "Version", 0), - .isIsaacIgnored = bool_get(child, "IsaacIgnored", false), - .extras = extras_read(child)}; - children_each(child, [&](pugi::xml_node infoChild, ElementType, int infoPosition) - { extras_child_add(model.info.extras, infoChild, infoPosition); }); - } - if (type == ElementType::CONTENT) model.content = content_read(child); - if (type == ElementType::ANIMATIONS) - { - model.animations.defaultAnimation = string_get(child, "DefaultAnimation"); - model.animations.extras = extras_read(child); - model.animations.entries = animation_entries_read(child, model.animations.extras); - } - }); + children_each(element, [&](pugi::xml_node child, ElementType type, int position) { + auto isKnown = type == ElementType::INFO || type == ElementType::CONTENT || type == ElementType::ANIMATIONS; + if (!isKnown || std::ranges::contains(model.layout, type)) + return extras_child_add(model.extras, child, position); + model.layout.push_back(type); + if (type == ElementType::INFO) + { + model.info = {.createdBy = string_get(child, "CreatedBy", Info{}.createdBy), + .createdOn = string_get(child, "CreatedOn"), + .fps = int_get(child, "Fps", Info{}.fps), + .version = int_get(child, "Version", 0), + .isIsaacIgnored = bool_get(child, "IsaacIgnored", false), + .extras = extras_read(child)}; + children_each(child, [&](pugi::xml_node infoChild, ElementType, int infoPosition) { + extras_child_add(model.info.extras, infoChild, infoPosition); + }); + } + if (type == ElementType::CONTENT) + model.content = content_read(child); + if (type == ElementType::ANIMATIONS) + { + model.animations.defaultAnimation = string_get(child, "DefaultAnimation"); + model.animations.extras = extras_read(child); + model.animations.entries = animation_entries_read(child, model.animations.extras); + } + }); model_repair(model); return model; - } +} - // Writing: the model goes straight to a Sink in the shape a set of flags asks for, as text, a hash or an XmlNode tree. +// Writing: the model goes straight to a Sink in the shape a set of flags asks for, as text, a hash or an XmlNode tree. - struct Writer - { +struct Writer +{ Flags flags = {}; const Model* model = nullptr; std::map shaderIds; @@ -842,49 +881,53 @@ // With a model, a whole document is written: shader, layer and region ids are renumbered by position. Writer(Flags flags, const Model* model = nullptr) : flags(flags), model(model) { - if (!model) return; - auto& content = model->content; - for (int i = 0; i < (int)content.shaders.size(); ++i) - shaderIds[content.shaders[i].id] = i; - for (int i = 0; i < (int)content.layers.size(); ++i) - layerIds[content.layers[i].id] = i; - std::set spritesheetIds; - for (auto& spritesheet : content.spritesheets) - if (spritesheetIds.insert(spritesheet.id).second && !spritesheet.regions.empty()) - for (int i = 0; i < (int)spritesheet.regions.size(); ++i) - regionIds[spritesheet.id][spritesheet.regions[i].id] = i; + if (!model) + return; + auto& content = model->content; + for (int i = 0; i < (int)content.shaders.size(); ++i) + shaderIds[content.shaders[i].id] = i; + for (int i = 0; i < (int)content.layers.size(); ++i) + layerIds[content.layers[i].id] = i; + std::set spritesheetIds; + for (auto& spritesheet : content.spritesheets) + if (spritesheetIds.insert(spritesheet.id).second && !spritesheet.regions.empty()) + for (int i = 0; i < (int)spritesheet.regions.size(); ++i) + regionIds[spritesheet.id][spritesheet.regions[i].id] = i; } - bool is(Flag flag) const { return has_flag(flags, flag); } - }; + bool is(Flag flag) const + { + return has_flag(flags, flag); + } +}; - static int id_map_get(const std::map& ids, int id) - { +static int id_map_get(const std::map& ids, int id) +{ auto it = ids.find(id); return it == ids.end() ? -1 : it->second; - } +} - static bool is_float_whole(double value) - { +static bool is_float_whole(double value) +{ return std::abs(value) < FLOAT_WHOLE_MAX && value == std::trunc(value) && !(value == 0 && std::signbit(value)); - } +} - // Where written XML goes. TEXT prints as tinyxml2's XMLPrinter did (4-space indents, entities escaped, - // text keeping its element's children inline); HASH folds the same elements into an FNV hash; TREE builds an XmlNode. - struct Sink - { +// Where written XML goes. TEXT prints as tinyxml2's XMLPrinter did (4-space indents, entities escaped, +// text keeping its element's children inline). HASH folds the same elements into an FNV hash. TREE builds an XmlNode. +struct Sink +{ enum Mode { - TEXT, - HASH, - TREE + TEXT, + HASH, + TREE }; struct Open { - std::string_view tag; - bool isEmpty = true; - bool isTextDone = false; + std::string_view tag; + bool isEmpty = true; + bool isTextDone = false; }; Mode mode = TEXT; @@ -897,181 +940,195 @@ void hash_add(char marker, std::string_view value) { - hash = (hash ^ (unsigned char)marker) * HASH_PRIME; - for (unsigned char character : value) - hash = (hash ^ character) * HASH_PRIME; - hash *= HASH_PRIME; + hash = (hash ^ (unsigned char)marker) * HASH_PRIME; + for (unsigned char character : value) + hash = (hash ^ character) * HASH_PRIME; + hash *= HASH_PRIME; } - // Attributes escape all five entities; text only the first three. + // Attributes escape all five entities. Text only the first three. void escape(std::string_view value, bool isAttribute) { - for (auto character : value) - { - auto entity = std::ranges::find(ENTITIES, character, &std::pair::first); - if (entity != std::end(ENTITIES) && (isAttribute || entity - ENTITIES < TEXT_ENTITY_COUNT)) - text += entity->second; - else - text += character; - } + for (auto character : value) + { + auto entity = std::ranges::find(ENTITIES, character, &std::pair::first); + if (entity != std::end(ENTITIES) && (isAttribute || entity - ENTITIES < TEXT_ENTITY_COUNT)) + text += entity->second; + else + text += character; + } } void indent(std::size_t depth) { - for (std::size_t i = 0; i < depth; ++i) - text += INDENT; + for (std::size_t i = 0; i < depth; ++i) + text += INDENT; } // The open element gets content: its start tag is finished, and its (empty) text is hashed. void content_begin() { - if (stack.empty()) return; - auto& parent = stack.back(); - if (mode == TEXT && parent.isEmpty) text += '>'; - if (mode == HASH && !parent.isTextDone) hash_add('T', {}); - parent.isEmpty = false; - parent.isTextDone = true; + if (stack.empty()) + return; + auto& parent = stack.back(); + if (mode == TEXT && parent.isEmpty) + text += '>'; + if (mode == HASH && !parent.isTextDone) + hash_add('T', {}); + parent.isEmpty = false; + parent.isTextDone = true; } void open(std::string_view tag) { - content_begin(); - if (mode == TEXT) - { - if (!text.empty() && textDepth < 0) text += '\n'; - if (text.empty() || textDepth < 0) indent(stack.size()); - text += '<'; - text += tag; - } - if (mode == HASH) hash_add('E', tag); - if (mode == TREE) - { - auto& node = nodes.empty() ? root : nodes.back()->children.emplace_back(); - node.tag = tag; - nodes.push_back(&node); - } - stack.push_back({tag}); + content_begin(); + if (mode == TEXT) + { + if (!text.empty() && textDepth < 0) + text += '\n'; + if (text.empty() || textDepth < 0) + indent(stack.size()); + text += '<'; + text += tag; + } + if (mode == HASH) + hash_add('E', tag); + if (mode == TREE) + { + auto& node = nodes.empty() ? root : nodes.back()->children.emplace_back(); + node.tag = tag; + nodes.push_back(&node); + } + stack.push_back({tag}); } // Numbers never need escaping. void attribute_text(std::string_view name, std::string_view value, bool isEscaped = true) { - if (mode == TEXT) - { - text += ' '; - text += name; - text += "=\""; - if (isEscaped) - escape(value, true); - else - text += value; - text += '"'; - } - if (mode == HASH) - { - hash_add('A', name); - hash_add('V', value); - } - if (mode == TREE) nodes.back()->attributes.emplace_back(name, value); + if (mode == TEXT) + { + text += ' '; + text += name; + text += "=\""; + if (isEscaped) + escape(value, true); + else + text += value; + text += '"'; + } + if (mode == HASH) + { + hash_add('A', name); + hash_add('V', value); + } + if (mode == TREE) + nodes.back()->attributes.emplace_back(name, value); } - // Numbers print as tinyxml2's XMLUtil::ToStr did ("%d", "%.8g", "true"/"false"), without printf; whole numbers + // Numbers print as tinyxml2's XMLUtil::ToStr did ("%d", "%.8g", "true"/"false"), without printf. Whole numbers // (most values) print as integers, which "%.8g" also does below 1e8 (but keeps "-0"). template void attribute(std::string_view name, const T& value) { - if constexpr (std::is_convertible_v) - attribute_text(name, value); - else - { - char buffer[VALUE_BUFFER_SIZE]{}; - auto end = buffer; - if constexpr (std::is_same_v) - end = std::ranges::copy(std::string_view(value ? "true" : "false"), buffer).out; - else if constexpr (std::is_floating_point_v) - end = is_float_whole(value) - ? std::to_chars(buffer, buffer + sizeof(buffer), (long long)value).ptr - : std::to_chars(buffer, buffer + sizeof(buffer), value, std::chars_format::general, - std::is_same_v ? FLOAT_DIGITS : DOUBLE_DIGITS) - .ptr; + if constexpr (std::is_convertible_v) + attribute_text(name, value); else - end = std::to_chars(buffer, buffer + sizeof(buffer), (long long)value).ptr; - attribute_text(name, std::string_view(buffer, end), false); - } + { + char buffer[VALUE_BUFFER_SIZE]{}; + auto end = buffer; + if constexpr (std::is_same_v) + end = std::ranges::copy(std::string_view(value ? "true" : "false"), buffer).out; + else if constexpr (std::is_floating_point_v) + end = is_float_whole(value) + ? std::to_chars(buffer, buffer + sizeof(buffer), (long long)value).ptr + : std::to_chars(buffer, buffer + sizeof(buffer), value, std::chars_format::general, + std::is_same_v ? FLOAT_DIGITS : DOUBLE_DIGITS) + .ptr; + else + end = std::to_chars(buffer, buffer + sizeof(buffer), (long long)value).ptr; + attribute_text(name, std::string_view(buffer, end), false); + } } // An element's text, after its attributes and before its children. void text_add(std::string_view value) { - auto& open = stack.back(); - if (mode == HASH) hash_add('T', value); - if (mode == TREE) nodes.back()->text = value; - if (mode == TEXT && !value.empty()) - { - textDepth = (int)stack.size() - 1; - text += '>'; - open.isEmpty = false; - escape(value, false); - } - open.isTextDone = true; + auto& open = stack.back(); + if (mode == HASH) + hash_add('T', value); + if (mode == TREE) + nodes.back()->text = value; + if (mode == TEXT && !value.empty()) + { + textDepth = (int)stack.size() - 1; + text += '>'; + open.isEmpty = false; + escape(value, false); + } + open.isTextDone = true; } void close() { - auto open = stack.back(); - stack.pop_back(); - if (mode == HASH) - { - if (!open.isTextDone) hash_add('T', {}); - hash_add(']', {}); - } - if (mode == TREE) nodes.pop_back(); - if (mode != TEXT) return; - if (open.isEmpty) - text += "/>"; - else - { - if (textDepth < 0) + auto open = stack.back(); + stack.pop_back(); + if (mode == HASH) { - text += '\n'; - indent(stack.size()); + if (!open.isTextDone) + hash_add('T', {}); + hash_add(']', {}); } - text += "'; - } - if (textDepth == (int)stack.size()) textDepth = -1; - if (stack.empty()) text += '\n'; + if (mode == TREE) + nodes.pop_back(); + if (mode != TEXT) + return; + if (open.isEmpty) + text += "/>"; + else + { + if (textDepth < 0) + { + text += '\n'; + indent(stack.size()); + } + text += "'; + } + if (textDepth == (int)stack.size()) + textDepth = -1; + if (stack.empty()) + text += '\n'; } void node(const XmlNode& node) { - open(node.tag); - for (auto& [name, value] : node.attributes) - attribute_text(name, value); - text_add(node.text); - for (auto& child : node.children) - this->node(child); - close(); + open(node.tag); + for (auto& [name, value] : node.attributes) + attribute_text(name, value); + text_add(node.text); + for (auto& child : node.children) + this->node(child); + close(); } - }; +}; - // Unknown XML goes back where it was read: attributes after the known ones, then text, and (through Children) - // children at their recorded positions among the known ones. - static void extras_attributes_write(Sink& sink, const Extras& extras) - { +// Unknown XML goes back where it was read: attributes after the known ones, then text, and (through Children) +// children at their recorded positions among the known ones. +static void extras_attributes_write(Sink& sink, const Extras& extras) +{ for (auto& [name, value] : extras.attributes) - sink.attribute_text(name, value); - } + sink.attribute_text(name, value); +} - static void extras_write(Sink& sink, const Extras& extras) - { +static void extras_write(Sink& sink, const Extras& extras) +{ extras_attributes_write(sink, extras); sink.text_add(extras.text); - } +} - // Interleaves an element's unknown children with its known ones: add() comes before each known child. - struct Children - { +// Interleaves an element's unknown children with its known ones: add() comes before each known child. +struct Children +{ Sink& sink; const Extras& extras; std::size_t next = 0; @@ -1079,123 +1136,134 @@ void add() { - while (next < extras.children.size() && extras.children[next].first <= position) - { - sink.node(extras.children[next++].second); + while (next < extras.children.size() && extras.children[next].first <= position) + { + sink.node(extras.children[next++].second); + ++position; + } ++position; - } - ++position; } void flush() { - while (next < extras.children.size()) - sink.node(extras.children[next++].second); + while (next < extras.children.size()) + sink.node(extras.children[next++].second); } void close() { - flush(); - sink.close(); + flush(); + sink.close(); } - }; +}; - static void element_close(Sink& sink, const Extras& extras) { Children{sink, extras}.close(); } +static void element_close(Sink& sink, const Extras& extras) +{ + Children{sink, extras}.close(); +} - static void path_add(Sink& sink, const char* name, const std::filesystem::path& value) - { - if (!value.empty()) sink.attribute(name, path_to_utf8(value)); - } +static void path_add(Sink& sink, const char* name, const std::filesystem::path& value) +{ + if (!value.empty()) + sink.attribute(name, path_to_utf8(value)); +} - static void interpolation_add(Sink& sink, const char* name, Interpolation interpolation) - { +static void interpolation_add(Sink& sink, const char* name, Interpolation interpolation) +{ if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR) - sink.attribute(name, interpolation == Interpolation::LINEAR); + sink.attribute(name, interpolation == Interpolation::LINEAR); else - sink.attribute(name, INTERPOLATION_VALUES[(int)interpolation]); - } + sink.attribute(name, INTERPOLATION_VALUES[(int)interpolation]); +} - static bool is_group_id_written(const Writer& writer) - { +static bool is_group_id_written(const Writer& writer) +{ return writer.is(SERIALIZE_GROUPS) && !writer.is(SERIALIZE_NESTED_GROUPS); - } +} - static bool is_special_interpolation(Interpolation interpolation) - { +static bool is_special_interpolation(Interpolation interpolation) +{ return interpolation != Interpolation::NONE && interpolation != Interpolation::LINEAR; - } +} - // A whole document's frames use renumbered shader and region ids; a layer frame on a region takes its rectangle. - static Frame frame_normalize(const Writer& writer, Frame frame, const Track* layerTrack) - { - if (!writer.model) return frame; - if (frame.shaderId != -1) frame.shaderId = id_map_get(writer.shaderIds, frame.shaderId); - if (!layerTrack || frame.regionId == -1) return frame; +// A whole document's frames use renumbered shader and region ids. A layer frame on a region takes its rectangle. +static Frame frame_normalize(const Writer& writer, Frame frame, const Track* layerTrack) +{ + if (!writer.model) + return frame; + if (frame.shaderId != -1) + frame.shaderId = id_map_get(writer.shaderIds, frame.shaderId); + if (!layerTrack || frame.regionId == -1) + return frame; auto& content = writer.model->content; auto layer = item_get(content.layers, layerTrack->id); auto spritesheet = layer ? item_get(content.spritesheets, layer->spritesheetId) : nullptr; - if (!spritesheet) return frame; + if (!spritesheet) + return frame; auto regionIds = writer.regionIds.find(spritesheet->id); frame.regionId = regionIds == writer.regionIds.end() ? -1 : id_map_get(regionIds->second, frame.regionId); - if (frame.regionId == -1) return frame; + if (frame.regionId == -1) + return frame; auto& region = spritesheet->regions[frame.regionId]; frame.crop = region.crop; frame.size = region.size; frame.pivot = region.pivot; return frame; - } +} - // A frame baked into single steps for the game records, on its first step, how to read them back as one. - struct FrameBake - { +// A frame baked into single steps for the game records, on its first step, how to read them back as one. +struct FrameBake +{ Interpolation interpolation = {}; int delay = 0; - }; +}; - static void frame_write(Sink& sink, const Writer& writer, const Frame& frame, ItemType type, FrameBake bake = {}) - { +static void frame_write(Sink& sink, const Writer& writer, const Frame& frame, ItemType type, FrameBake bake = {}) +{ if (type == ItemType::TRIGGER) { - sink.open(tag_get(ElementType::TRIGGER)); - if (!frame.eventIds.empty()) sink.attribute("EventId", frame.eventIds.front()); - sink.attribute("AtFrame", frame.atFrame); - extras_write(sink, frame.extras); - Children children = {sink, frame.extras}; - if (writer.is(SERIALIZE_EXTENSIONS)) - for (auto eventId : frame.eventIds | std::views::drop(1)) - { - children.add(); - sink.open(tag_get(ElementType::EVENT_ELEMENT)); - sink.attribute("Id", eventId); - sink.close(); - } - if (writer.is(SERIALIZE_SOUNDS)) - for (auto soundId : frame.soundIds) - if (soundId != -1) - { - children.add(); - sink.open(tag_get(ElementType::SOUND_ELEMENT)); - sink.attribute("Id", soundId); - sink.close(); - } - return children.close(); + sink.open(tag_get(ElementType::TRIGGER)); + if (!frame.eventIds.empty()) + sink.attribute("EventId", frame.eventIds.front()); + sink.attribute("AtFrame", frame.atFrame); + extras_write(sink, frame.extras); + Children children = {sink, frame.extras}; + if (writer.is(SERIALIZE_EXTENSIONS)) + for (auto eventId : frame.eventIds | std::views::drop(1)) + { + children.add(); + sink.open(tag_get(ElementType::EVENT_ELEMENT)); + sink.attribute("Id", eventId); + sink.close(); + } + if (writer.is(SERIALIZE_SOUNDS)) + for (auto soundId : frame.soundIds) + if (soundId != -1) + { + children.add(); + sink.open(tag_get(ElementType::SOUND_ELEMENT)); + sink.attribute("Id", soundId); + sink.close(); + } + return children.close(); } sink.open(tag_get(ElementType::FRAME)); if (type == ItemType::LAYER) { - auto isRegion = writer.is(SERIALIZE_REGIONS) && frame.regionId != -1; - if (isRegion) sink.attribute("RegionId", frame.regionId); - if (writer.is(SERIALIZE_REDUNDANT_FRAME_REGION_VALUES) || !isRegion) - { - sink.attribute("XPivot", frame.pivot.x); - sink.attribute("YPivot", frame.pivot.y); - sink.attribute("XCrop", frame.crop.x); - sink.attribute("YCrop", frame.crop.y); - sink.attribute("Width", frame.size.x); - sink.attribute("Height", frame.size.y); - } + auto isRegion = writer.is(SERIALIZE_REGIONS) && frame.regionId != -1; + if (isRegion) + sink.attribute("RegionId", frame.regionId); + if (writer.is(SERIALIZE_REDUNDANT_FRAME_REGION_VALUES) || !isRegion) + { + sink.attribute("XPivot", frame.pivot.x); + sink.attribute("YPivot", frame.pivot.y); + sink.attribute("XCrop", frame.crop.x); + sink.attribute("YCrop", frame.crop.y); + sink.attribute("Width", frame.size.x); + sink.attribute("Height", frame.size.y); + } } sink.attribute("XPosition", frame.position.x); sink.attribute("YPosition", frame.position.y); @@ -1205,55 +1273,63 @@ sink.attribute("YScale", frame.scale.y); if (writer.is(SERIALIZE_EXTENSIONS)) { - sink.attribute("SkewX", frame.skew.x); - sink.attribute("SkewY", frame.skew.y); + sink.attribute("SkewX", frame.skew.x); + sink.attribute("SkewY", frame.skew.y); } auto isPurged = writer.is(SERIALIZE_PURGE_DEFAULT_COLORS); for (int i = 0; i < (int)std::size(TINT_ATTRIBUTES); ++i) - if (auto tint = float_to_uint8(frame.tint[i]); !isPurged || tint != float_to_uint8(1.0f)) - sink.attribute(TINT_ATTRIBUTES[i], tint); + if (auto tint = float_to_uint8(frame.tint[i]); !isPurged || tint != float_to_uint8(1.0f)) + sink.attribute(TINT_ATTRIBUTES[i], tint); for (int i = 0; i < (int)std::size(OFFSET_ATTRIBUTES); ++i) - if (auto offset = float_to_uint8(frame.colorOffset[i]); !isPurged || offset != 0) - sink.attribute(OFFSET_ATTRIBUTES[i], offset); + if (auto offset = float_to_uint8(frame.colorOffset[i]); !isPurged || offset != 0) + sink.attribute(OFFSET_ATTRIBUTES[i], offset); if (writer.is(SERIALIZE_EXTENSIONS) && float_to_uint8(frame.colorOffset.a) != 0) - sink.attribute("AlphaOffset", float_to_uint8(frame.colorOffset.a)); + sink.attribute("AlphaOffset", float_to_uint8(frame.colorOffset.a)); sink.attribute("Rotation", frame.rotation); interpolation_add(sink, "Interpolated", frame.interpolation); - if (writer.is(SERIALIZE_EXTENSIONS) && frame.shaderId != -1) sink.attribute("ShaderId", frame.shaderId); + if (writer.is(SERIALIZE_EXTENSIONS) && frame.shaderId != -1) + sink.attribute("ShaderId", frame.shaderId); if (writer.is(SERIALIZE_EXTENSIONS) && type == ItemType::LAYER) { - if (frame.depth != 0) sink.attribute("Depth", frame.depth); - if (frame.blur != 0.0f) sink.attribute("Blur", frame.blur); - if (!frame.childAnimation.empty()) sink.attribute("ChildAnimation", frame.childAnimation); - if (frame.childMode != ChildMode::LOOP) sink.attribute("ChildMode", CHILD_MODE_VALUES[(int)frame.childMode]); - if (frame.isChildStartRandom) - sink.attribute("ChildStart", CHILD_START_RANDOM); - else if (frame.childStart != 0) - sink.attribute("ChildStart", frame.childStart); - if (frame.isChildRestart) sink.attribute("Restart", frame.isChildRestart); + if (frame.depth != 0) + sink.attribute("Depth", frame.depth); + if (frame.blur != 0.0f) + sink.attribute("Blur", frame.blur); + if (!frame.childAnimation.empty()) + sink.attribute("ChildAnimation", frame.childAnimation); + if (frame.childMode != ChildMode::LOOP) + sink.attribute("ChildMode", CHILD_MODE_VALUES[(int)frame.childMode]); + if (frame.isChildStartRandom) + sink.attribute("ChildStart", CHILD_START_RANDOM); + else if (frame.childStart != 0) + sink.attribute("ChildStart", frame.childStart); + if (frame.isChildRestart) + sink.attribute("Restart", frame.isChildRestart); } extras_attributes_write(sink, frame.extras); if (bake.delay > 0) { - sink.attribute("BakeInterpolation", INTERPOLATION_VALUES[(int)bake.interpolation]); - sink.attribute("BakeDelay", bake.delay); + sink.attribute("BakeInterpolation", INTERPOLATION_VALUES[(int)bake.interpolation]); + sink.attribute("BakeDelay", bake.delay); } sink.text_add(frame.extras.text); element_close(sink, frame.extras); - } +} - // A backup (FrameRestore) track keeps its frames' region ids as they are. - static void track_write(Sink& sink, const Writer& writer, const Track& track, int groupId = -1, bool isBackup = false) - { +// A backup (FrameRestore) track keeps its frames' region ids as they are. +static void track_write(Sink& sink, const Writer& writer, const Track& track, int groupId = -1, bool isBackup = false) +{ sink.open(tag_get(track_element_type_get(track.type))); if (track.type == ItemType::LAYER || track.type == ItemType::NULL_) { - auto id = track.id; - if (track.type == ItemType::LAYER && writer.model) - if (auto it = writer.layerIds.find(id); it != writer.layerIds.end()) id = it->second; - sink.attribute(track.type == ItemType::LAYER ? "LayerId" : "NullId", id); - sink.attribute("Visible", track.isVisible); - if (groupId != -1 && is_group_id_written(writer)) sink.attribute("GroupId", groupId); + auto id = track.id; + if (track.type == ItemType::LAYER && writer.model) + if (auto it = writer.layerIds.find(id); it != writer.layerIds.end()) + id = it->second; + sink.attribute(track.type == ItemType::LAYER ? "LayerId" : "NullId", id); + sink.attribute("Visible", track.isVisible); + if (groupId != -1 && is_group_id_written(writer)) + sink.attribute("GroupId", groupId); } extras_write(sink, track.extras); @@ -1261,231 +1337,234 @@ auto layerTrack = track.type == ItemType::LAYER && !isBackup ? &track : nullptr; for (int i = 0; i < (int)track.frames.size(); ++i) { - auto frame = frame_normalize(writer, track.frames[i], layerTrack); - if (!writer.is(SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES) || track.type == ItemType::TRIGGER || - !is_special_interpolation(frame.interpolation)) - { - children.add(); - frame_write(sink, writer, frame, track.type); - continue; - } - // Written for the game as single-step frames; the first records how to read them back as one. - auto baked = frame_bake_split(frame, i + 1 < (int)track.frames.size() ? track.frames[i + 1] : frame, - FRAME_DURATION_MIN, false, false); - for (int bakeIndex = 0; bakeIndex < (int)baked.size(); ++bakeIndex) - { - children.add(); - frame_write(sink, writer, baked[bakeIndex], track.type, - bakeIndex == 0 ? FrameBake{frame.interpolation, (int)baked.size()} : FrameBake{}); - } + auto frame = frame_normalize(writer, track.frames[i], layerTrack); + if (!writer.is(SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES) || track.type == ItemType::TRIGGER || + !is_special_interpolation(frame.interpolation)) + { + children.add(); + frame_write(sink, writer, frame, track.type); + continue; + } + // Written for the game as single-step frames. The first records how to read them back as one. + auto baked = frame_bake_split(frame, i + 1 < (int)track.frames.size() ? track.frames[i + 1] : frame, + FRAME_DURATION_MIN, false, false); + for (int bakeIndex = 0; bakeIndex < (int)baked.size(); ++bakeIndex) + { + children.add(); + frame_write(sink, writer, baked[bakeIndex], track.type, + bakeIndex == 0 ? FrameBake{frame.interpolation, (int)baked.size()} : FrameBake{}); + } } children.close(); - } +} - // A group; `index` records its position when groups are written apart from their container, and `members` writes - // the children nested into it. - template - void group_write(Sink& sink, const Writer& writer, const Group& group, std::optional index = {}, - const std::function& members = {}) - { +// A group. `index` records its position when groups are written apart from their container, and `members` writes +// the children nested into it. +template +void group_write(Sink& sink, const Writer& writer, const Group& group, std::optional index = {}, + const std::function& members = {}) +{ sink.open(tag_get(ElementType::GROUP)); - if (!writer.is(SERIALIZE_NESTED_GROUPS)) sink.attribute("Id", group.id); + if (!writer.is(SERIALIZE_NESTED_GROUPS)) + sink.attribute("Id", group.id); sink.attribute("Name", group.name); sink.attribute("IsExpanded", group.isExpanded); sink.attribute("Visible", group.isVisible); - if (index) sink.attribute("Index", *index); + if (index) + sink.attribute("Index", *index); extras_write(sink, group.extras); Children children = {sink, group.extras}; if constexpr (requires { group.root; }) { - children.add(); - track_write(sink, writer, group.root); + children.add(); + track_write(sink, writer, group.root); } children.flush(); - if (members) members(); + if (members) + members(); sink.close(); - } +} - struct ContainerChild - { +struct ContainerChild +{ std::function, const std::function&)> write{}; int groupId = -1; std::optional ownGroupId; - }; +}; - template static ContainerChild group_child_make(Sink& sink, const Writer& writer, const Group& group) - { - return {.write = [&](std::optional index, const std::function& members) - { group_write(sink, writer, group, index, members); }, +template static ContainerChild group_child_make(Sink& sink, const Writer& writer, const Group& group) +{ + return {.write = [&](std::optional index, + const std::function& members) { group_write(sink, writer, group, index, members); }, .ownGroupId = group.id}; - } +} - // Children are laid out flat (a group, then its children) and reshaped for the flags: nested into their groups, or, - // in a track container, moved to a *AnimationGroups sibling (`groupsType`) that records each group's position. - static void container_write(Sink& sink, const Writer& writer, std::vector flat, const Extras& extras, - ElementType groupsType = ElementType::UNKNOWN) - { +// Children are laid out flat (a group, then its children) and reshaped for the flags: nested into their groups, or, +// in a track container, moved to a *AnimationGroups sibling (`groupsType`) that records each group's position. +static void container_write(Sink& sink, const Writer& writer, std::vector flat, const Extras& extras, + ElementType groupsType = ElementType::UNKNOWN) +{ extras_write(sink, extras); for (auto& [index, node] : extras.children) - flat.insert(flat.begin() + std::min(index, (int)flat.size()), - ContainerChild{.write = [&sink, &node](std::optional, const std::function&) - { sink.node(node); }}); + flat.insert(flat.begin() + std::min(index, (int)flat.size()), + ContainerChild{.write = [&sink, &node](std::optional, const std::function&) { + sink.node(node); + }}); auto isGroups = writer.is(SERIALIZE_GROUPS); std::map> grouped; if (isGroups && writer.is(SERIALIZE_NESTED_GROUPS)) { - std::set groupIds; - for (auto& child : flat) - if (child.ownGroupId && *child.ownGroupId >= 0) groupIds.insert(*child.ownGroupId); - for (auto& child : flat) - if (!child.ownGroupId && groupIds.contains(child.groupId)) grouped[child.groupId].push_back(child); - std::erase_if(flat, - [&](const ContainerChild& child) { return !child.ownGroupId && groupIds.contains(child.groupId); }); + std::set groupIds; + for (auto& child : flat) + if (child.ownGroupId && *child.ownGroupId >= 0) + groupIds.insert(*child.ownGroupId); + for (auto& child : flat) + if (!child.ownGroupId && groupIds.contains(child.groupId)) + grouped[child.groupId].push_back(child); + std::erase_if( + flat, [&](const ContainerChild& child) { return !child.ownGroupId && groupIds.contains(child.groupId); }); } auto isExtracted = groupsType != ElementType::UNKNOWN && isGroups && !writer.is(SERIALIZE_NESTED_GROUPS); std::vector extracted; for (int i = 0; i < (int)flat.size(); ++i) { - auto& child = flat[i]; - if (child.ownGroupId && !isGroups) continue; - if (child.ownGroupId && isExtracted) - { - extracted.push_back(i); - continue; - } - auto members = child.ownGroupId ? grouped.find(*child.ownGroupId) : grouped.end(); - child.write({}, - [&]() - { - if (members != grouped.end()) - for (auto& member : members->second) - member.write({}, {}); - }); + auto& child = flat[i]; + if (child.ownGroupId && !isGroups) + continue; + if (child.ownGroupId && isExtracted) + { + extracted.push_back(i); + continue; + } + auto members = child.ownGroupId ? grouped.find(*child.ownGroupId) : grouped.end(); + child.write({}, [&]() { + if (members != grouped.end()) + for (auto& member : members->second) + member.write({}, {}); + }); } sink.close(); - if (extracted.empty()) return; + if (extracted.empty()) + return; sink.open(tag_get(groupsType)); for (auto i : extracted) - flat[i].write(i, {}); + flat[i].write(i, {}); sink.close(); - } +} - static void track_entries_write(Sink& sink, const Writer& writer, const std::vector& entries, ElementType type, - const Extras& extras) - { +static void track_entries_write(Sink& sink, const Writer& writer, const std::vector& entries, + ElementType type, const Extras& extras) +{ std::vector flat; - auto track_child_make = [&](const Track& track, int groupId) - { - return ContainerChild{.write = [&, groupId](std::optional, const std::function&) - { track_write(sink, writer, track, groupId); }, - .groupId = groupId}; + auto track_child_make = [&](const Track& track, int groupId) { + return ContainerChild{ + .write = [&, groupId](std::optional, + const std::function&) { track_write(sink, writer, track, groupId); }, + .groupId = groupId}; }; for (auto& entry : entries) - if (auto track = std::get_if(&entry)) - flat.push_back(track_child_make(*track, -1)); - else - { - auto& group = std::get(entry); - flat.push_back(group_child_make(sink, writer, group)); - for (auto& groupTrack : group.tracks) - flat.push_back(track_child_make(groupTrack, group.id)); - } + if (auto track = std::get_if(&entry)) + flat.push_back(track_child_make(*track, -1)); + else + { + auto& group = std::get(entry); + flat.push_back(group_child_make(sink, writer, group)); + for (auto& groupTrack : group.tracks) + flat.push_back(track_child_make(groupTrack, group.id)); + } sink.open(tag_get(type)); container_write(sink, writer, std::move(flat), extras, type == ElementType::LAYER_ANIMATIONS ? ElementType::LAYER_ANIMATION_GROUPS : ElementType::NULL_ANIMATION_GROUPS); - } +} - static bool is_frame_transform_default(const Frame& frame) - { +static bool is_frame_transform_default(const Frame& frame) +{ Frame base = {}; return frame.position == base.position && frame.scale == base.scale && frame.rotation == base.rotation && frame.skew == base.skew && frame.tint == base.tint && frame.colorOffset == base.colorOffset; - } +} - IsaacIssues isaac_issues_get(const Model& model) - { +IsaacIssues isaac_issues_get(const Model& model) +{ IsaacIssues issues = {}; issues.animationLayers = (int)std::ranges::count_if(model.content.layers, &Layer::is_animation); issues.vectorSpritesheets = (int)spritesheets_vector_used_get(model).size(); for (auto [index, animation] : model.animations_get()) { - for (const auto* entries : {&animation->layers, &animation->nulls}) - groups_each(*entries, [&](const TrackGroup& group) - { issues.groupTransforms += !std::ranges::all_of(group.root.frames, is_frame_transform_default); }); - animation_tracks_each( - *animation, - [&](const Track& track) - { + for (const auto* entries : {&animation->layers, &animation->nulls}) + groups_each(*entries, [&](const TrackGroup& group) { + issues.groupTransforms += !std::ranges::all_of(group.root.frames, is_frame_transform_default); + }); + animation_tracks_each(*animation, [&](const Track& track) { for (auto& frame : track.frames) { - issues.easedFrames += track.type != ItemType::TRIGGER && is_special_interpolation(frame.interpolation); - issues.skewFrames += frame.skew != glm::vec2(); - issues.shaderFrames += frame.shaderId != -1; - issues.depthFrames += track.type == ItemType::LAYER && frame.depth != 0; - issues.alphaOffsetFrames += float_to_uint8(frame.colorOffset.a) != 0; - issues.blurFrames += track.type == ItemType::LAYER && frame.blur != 0.0f; - issues.extraEvents += track.type == ItemType::TRIGGER ? std::max((int)frame.eventIds.size() - 1, 0) : 0; - issues.triggerSounds += track.type == ItemType::TRIGGER && - std::ranges::any_of(frame.soundIds, [](int id) { return id != -1; }); + issues.easedFrames += track.type != ItemType::TRIGGER && is_special_interpolation(frame.interpolation); + issues.skewFrames += frame.skew != glm::vec2(); + issues.shaderFrames += frame.shaderId != -1; + issues.depthFrames += track.type == ItemType::LAYER && frame.depth != 0; + issues.alphaOffsetFrames += float_to_uint8(frame.colorOffset.a) != 0; + issues.blurFrames += track.type == ItemType::LAYER && frame.blur != 0.0f; + issues.extraEvents += track.type == ItemType::TRIGGER ? std::max((int)frame.eventIds.size() - 1, 0) : 0; + issues.triggerSounds += track.type == ItemType::TRIGGER && + std::ranges::any_of(frame.soundIds, [](int id) { return id != -1; }); } - }); + }); } return issues; - } +} - // The game's copy: group roots baked into their tracks (originals kept in a FrameRestore node the editor reads - // back), and interpolation flattened into single-step frames. - static Animation animation_bake(const Writer& writer, Animation animation) - { +// The game's copy: group roots baked into their tracks (originals kept in a FrameRestore node the editor reads +// back), and interpolation flattened into single-step frames. +static Animation animation_bake(const Writer& writer, Animation animation) +{ if (writer.is(SERIALIZE_BAKE_GROUP_FRAMES)) - for (auto* entries : {&animation.layers, &animation.nulls}) - groups_each(*entries, - [&](TrackGroup& group) - { - if (std::ranges::all_of(group.root.frames, is_frame_transform_default)) return; - Sink backup = {.mode = Sink::TREE}; - backup.open(FRAME_RESTORE_TAG); - track_write(backup, writer, group.root); - for (auto& track : group.tracks) - { - track_write(backup, writer, track, group.id, true); - track_group_root_bake(track, group.root, animation.frameNum); - } - backup.close(); - group.root = TrackGroup{}.root; - // Kept in order of position, where it reads back the same as appended at position 1. - auto& children = group.extras.children; - children.insert(std::ranges::lower_bound(children, 1, {}, &std::pair::first), - {1, std::move(backup.root)}); - }); + for (auto* entries : {&animation.layers, &animation.nulls}) + groups_each(*entries, [&](TrackGroup& group) { + if (std::ranges::all_of(group.root.frames, is_frame_transform_default)) + return; + Sink backup = {.mode = Sink::TREE}; + backup.open(FRAME_RESTORE_TAG); + track_write(backup, writer, group.root); + for (auto& track : group.tracks) + { + track_write(backup, writer, track, group.id, true); + track_group_root_bake(track, group.root, animation.frameNum); + } + backup.close(); + group.root = TrackGroup{}.root; + // Kept in order of position, where it reads back the same as appended at position 1. + auto& children = group.extras.children; + children.insert(std::ranges::lower_bound(children, 1, {}, &std::pair::first), + {1, std::move(backup.root)}); + }); if (writer.is(SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES)) - animation_tracks_each(animation, - [](Track& track) - { - if (track.type == ItemType::TRIGGER) return; - for (int index = (int)track.frames.size() - 1; index >= 0; --index) - if (track.frames[index].interpolation != Interpolation::NONE) - frame_bake(track, index, FRAME_DURATION_MIN, false, false); - }); + animation_tracks_each(animation, [](Track& track) { + if (track.type == ItemType::TRIGGER) + return; + for (int index = (int)track.frames.size() - 1; index >= 0; --index) + if (track.frames[index].interpolation != Interpolation::NONE) + frame_bake(track, index, FRAME_DURATION_MIN, false, false); + }); return animation; - } +} - // Known children in their recorded order; a part with content that was never in the file is appended. - static std::vector layout_get(std::vector layout, - std::initializer_list> parts) - { +// Known children in their recorded order. A part with content that was never in the file is appended. +static std::vector layout_get(std::vector layout, + std::initializer_list> parts) +{ for (auto [type, isContent] : parts) - if (isContent && !std::ranges::contains(layout, type)) layout.push_back(type); + if (isContent && !std::ranges::contains(layout, type)) + layout.push_back(type); return layout; - } +} - static void animation_write(Sink& sink, const Writer& writer, const Animation& source, int groupId = -1) - { +static void animation_write(Sink& sink, const Writer& writer, const Animation& source, int groupId = -1) +{ auto isBaked = writer.model && (writer.is(SERIALIZE_BAKE_GROUP_FRAMES) || writer.is(SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES)); auto baked = isBaked ? std::optional(animation_bake(writer, source)) : std::nullopt; @@ -1496,9 +1575,12 @@ sink.attribute("FrameNum", animation.frameNum); sink.attribute("Loop", animation.isLoop); if (writer.is(SERIALIZE_EXTENSIONS)) - for (auto [name, marker] : {std::pair{"StartMarker", animation.startMarker}, {"EndMarker", animation.endMarker}}) - if (marker != -1) sink.attribute(name, marker); - if (groupId != -1 && is_group_id_written(writer)) sink.attribute("GroupId", groupId); + for (auto [name, marker] : + {std::pair{"StartMarker", animation.startMarker}, {"EndMarker", animation.endMarker}}) + if (marker != -1) + sink.attribute(name, marker); + if (groupId != -1 && is_group_id_written(writer)) + sink.attribute("GroupId", groupId); extras_write(sink, animation.extras); Children children = {sink, animation.extras}; @@ -1507,43 +1589,45 @@ {ElementType::NULL_ANIMATIONS, !animation.nulls.empty()}, {ElementType::TRIGGERS, !animation.triggers.frames.empty()}})) { - children.add(); - if (type == ElementType::ROOT_ANIMATION) track_write(sink, writer, animation.root); - if (type == ElementType::TRIGGERS) track_write(sink, writer, animation.triggers); - if (type == ElementType::LAYER_ANIMATIONS) - track_entries_write(sink, writer, animation.layers, type, animation.layersExtras); - if (type == ElementType::NULL_ANIMATIONS) - track_entries_write(sink, writer, animation.nulls, type, animation.nullsExtras); + children.add(); + if (type == ElementType::ROOT_ANIMATION) + track_write(sink, writer, animation.root); + if (type == ElementType::TRIGGERS) + track_write(sink, writer, animation.triggers); + if (type == ElementType::LAYER_ANIMATIONS) + track_entries_write(sink, writer, animation.layers, type, animation.layersExtras); + if (type == ElementType::NULL_ANIMATIONS) + track_entries_write(sink, writer, animation.nulls, type, animation.nullsExtras); } children.close(); - } +} - static void animations_write(Sink& sink, const Writer& writer, const Animations& animations) - { +static void animations_write(Sink& sink, const Writer& writer, const Animations& animations) +{ std::vector flat; - auto animation_child_make = [&](const Animation& animation, int groupId) - { - return ContainerChild{.write = [&, groupId](std::optional, const std::function&) - { animation_write(sink, writer, animation, groupId); }, - .groupId = groupId}; + auto animation_child_make = [&](const Animation& animation, int groupId) { + return ContainerChild{ + .write = [&, groupId](std::optional, + const std::function&) { animation_write(sink, writer, animation, groupId); }, + .groupId = groupId}; }; for (auto& entry : animations.entries) - if (auto animation = std::get_if>(&entry)) - flat.push_back(animation_child_make(**animation, -1)); - else - { - auto& group = std::get(entry); - flat.push_back(group_child_make(sink, writer, group)); - for (auto& groupAnimation : group.animations) - flat.push_back(animation_child_make(*groupAnimation, group.id)); - } + if (auto animation = std::get_if>(&entry)) + flat.push_back(animation_child_make(**animation, -1)); + else + { + auto& group = std::get(entry); + flat.push_back(group_child_make(sink, writer, group)); + for (auto& groupAnimation : group.animations) + flat.push_back(animation_child_make(*groupAnimation, group.id)); + } sink.open(tag_get(ElementType::ANIMATIONS)); sink.attribute("DefaultAnimation", animations.defaultAnimation); container_write(sink, writer, std::move(flat), animations.extras); - } +} - static void item_write(Sink& sink, const Writer&, const Region& region, int id) - { +static void item_write(Sink& sink, const Writer&, const Region& region, int id) +{ sink.open(tag_get(ElementType::REGION)); sink.attribute("Id", id); sink.attribute("Name", region.name); @@ -1552,40 +1636,42 @@ sink.attribute("Width", region.size.x); sink.attribute("Height", region.size.y); if (region.origin != Origin::CUSTOM) - sink.attribute("Origin", ORIGIN_VALUES[(int)region.origin]); + sink.attribute("Origin", ORIGIN_VALUES[(int)region.origin]); else { - sink.attribute("XPivot", region.pivot.x); - sink.attribute("YPivot", region.pivot.y); + sink.attribute("XPivot", region.pivot.x); + sink.attribute("YPivot", region.pivot.y); } extras_write(sink, region.extras); element_close(sink, region.extras); - } +} - static void item_write(Sink& sink, const Writer& writer, const Spritesheet& spritesheet, int id) - { +static void item_write(Sink& sink, const Writer& writer, const Spritesheet& spritesheet, int id) +{ sink.open(tag_get(ElementType::SPRITESHEET)); sink.attribute("Id", id); path_add(sink, "Path", spritesheet.path); extras_write(sink, spritesheet.extras); Children children = {sink, spritesheet.extras}; if (writer.is(SERIALIZE_REGIONS)) - for (int i = 0; i < (int)spritesheet.regions.size(); ++i) - { - children.add(); - item_write(sink, writer, spritesheet.regions[i], writer.model ? i : spritesheet.regions[i].id); - } + for (int i = 0; i < (int)spritesheet.regions.size(); ++i) + { + children.add(); + item_write(sink, writer, spritesheet.regions[i], writer.model ? i : spritesheet.regions[i].id); + } children.close(); - } +} - static void binding_value_add(Sink& sink, const std::string& binding, const std::string& value) - { - if (!binding.empty()) sink.attribute("Binding", binding); - if (!value.empty()) sink.attribute("Value", value); - } +static void binding_value_add(Sink& sink, const std::string& binding, const std::string& value) +{ + if (!binding.empty()) + sink.attribute("Binding", binding); + if (!value.empty()) + sink.attribute("Value", value); +} - static void item_write(Sink& sink, const Writer&, const Shader& shader, int id) - { +static void item_write(Sink& sink, const Writer&, const Shader& shader, int id) +{ sink.open(tag_get(ElementType::SHADER)); sink.attribute("Id", id); sink.attribute("Name", shader.name); @@ -1595,112 +1681,116 @@ Children children = {sink, shader.extras}; for (auto& uniform : shader.uniforms) { - children.add(); - sink.open(tag_get(ElementType::UNIFORM)); - sink.attribute("Name", uniform.name); - binding_value_add(sink, uniform.binding, uniform.value); - extras_write(sink, uniform.extras); - Children components = {sink, uniform.extras}; - for (auto& component : uniform.components) - { - components.add(); - sink.open(tag_get(ElementType::COMPONENT)); - sink.attribute("Index", component.index); - binding_value_add(sink, component.binding, component.value); - extras_write(sink, component.extras); - element_close(sink, component.extras); - } - components.close(); + children.add(); + sink.open(tag_get(ElementType::UNIFORM)); + sink.attribute("Name", uniform.name); + binding_value_add(sink, uniform.binding, uniform.value); + extras_write(sink, uniform.extras); + Children components = {sink, uniform.extras}; + for (auto& component : uniform.components) + { + components.add(); + sink.open(tag_get(ElementType::COMPONENT)); + sink.attribute("Index", component.index); + binding_value_add(sink, component.binding, component.value); + extras_write(sink, component.extras); + element_close(sink, component.extras); + } + components.close(); } children.close(); - } +} - static void item_write(Sink& sink, const Writer& writer, const Layer& layer, int id) - { +static void item_write(Sink& sink, const Writer& writer, const Layer& layer, int id) +{ sink.open(tag_get(ElementType::LAYER_ELEMENT)); sink.attribute("Id", id); sink.attribute("Name", layer.name); sink.attribute("SpritesheetId", layer.spritesheetId); if (writer.is(SERIALIZE_EXTENSIONS) && layer.is_animation()) { - if (layer.libraryId != -1) sink.attribute("Library", layer.libraryId); - sink.attribute("Animation", layer.animation); + if (layer.libraryId != -1) + sink.attribute("Library", layer.libraryId); + sink.attribute("Animation", layer.animation); } extras_write(sink, layer.extras); element_close(sink, layer.extras); - } +} - static void item_write(Sink& sink, const Writer&, const Null& null, int id) - { +static void item_write(Sink& sink, const Writer&, const Null& null, int id) +{ sink.open(tag_get(ElementType::NULL_ELEMENT)); sink.attribute("Id", id); sink.attribute("Name", null.name); - if (null.isShowRect) sink.attribute("ShowRect", null.isShowRect); + if (null.isShowRect) + sink.attribute("ShowRect", null.isShowRect); extras_write(sink, null.extras); element_close(sink, null.extras); - } +} - static void item_write(Sink& sink, const Writer&, const Event& event, int id) - { +static void item_write(Sink& sink, const Writer&, const Event& event, int id) +{ sink.open(tag_get(ElementType::EVENT_ELEMENT)); sink.attribute("Id", id); sink.attribute("Name", event.name); extras_write(sink, event.extras); element_close(sink, event.extras); - } +} - // Sounds and libraries are a path. - template static void item_path_write(Sink& sink, const Item& item, ElementType type, int id) - { +// Sounds and libraries are a path. +template static void item_path_write(Sink& sink, const Item& item, ElementType type, int id) +{ sink.open(tag_get(type)); sink.attribute("Id", id); path_add(sink, "Path", item.path); extras_write(sink, item.extras); element_close(sink, item.extras); - } +} - static void item_write(Sink& sink, const Writer&, const Sound& sound, int id) - { +static void item_write(Sink& sink, const Writer&, const Sound& sound, int id) +{ item_path_write(sink, sound, ElementType::SOUND_ELEMENT, id); - } +} - static void item_write(Sink& sink, const Writer&, const Library& library, int id) - { +static void item_write(Sink& sink, const Writer&, const Library& library, int id) +{ item_path_write(sink, library, ElementType::LIBRARY, id); - } +} - // A content container's unknown XML (a file may repeat a container; its parts are merged in order). - static Extras container_extras_get(const Content& content, ElementType type) - { +// A content container's unknown XML (a file may repeat a container. Its parts are merged in order). +static Extras container_extras_get(const Content& content, ElementType type) +{ Extras merged = {}; for (auto& [extrasType, extras] : content.containerExtras) { - if (extrasType != type) continue; - merged.attributes.insert(merged.attributes.end(), extras.attributes.begin(), extras.attributes.end()); - if (!extras.text.empty()) merged.text = extras.text; - merged.children.insert(merged.children.end(), extras.children.begin(), extras.children.end()); + if (extrasType != type) + continue; + merged.attributes.insert(merged.attributes.end(), extras.attributes.begin(), extras.attributes.end()); + if (!extras.text.empty()) + merged.text = extras.text; + merged.children.insert(merged.children.end(), extras.children.begin(), extras.children.end()); } return merged; - } +} - template - void items_write(Sink& sink, const Writer& writer, const std::vector& items, ElementType type, - const Extras& extras) - { +template +void items_write(Sink& sink, const Writer& writer, const std::vector& items, ElementType type, + const Extras& extras) +{ sink.open(tag_get(type)); extras_write(sink, extras); Children children = {sink, extras}; auto isRenumbered = writer.model && (type == ElementType::LAYERS || type == ElementType::SHADERS); for (int i = 0; i < (int)items.size(); ++i) { - children.add(); - item_write(sink, writer, items[i], isRenumbered ? i : items[i].id); + children.add(); + item_write(sink, writer, items[i], isRenumbered ? i : items[i].id); } children.close(); - } +} - static void content_write(Sink& sink, const Writer& writer, const Content& content) - { +static void content_write(Sink& sink, const Writer& writer, const Content& content) +{ sink.open(tag_get(ElementType::CONTENT)); extras_write(sink, content.extras); Children children = {sink, content.extras}; @@ -1712,31 +1802,35 @@ {ElementType::SOUNDS, !content.sounds.empty()}, {ElementType::LIBRARIES, !content.libraries.empty()}})) { - children.add(); - auto extras = container_extras_get(content, type); - // Optional containers are left out when the flags drop them or they are empty (their place still counts for - // where unknown children go). - if (type == ElementType::SHADERS && writer.is(SERIALIZE_EXTENSIONS) && - (!content.shaders.empty() || !extras.children.empty())) - items_write(sink, writer, content.shaders, type, extras); - if (type == ElementType::SOUNDS && writer.is(SERIALIZE_SOUNDS) && - (!content.sounds.empty() || !extras.children.empty())) - items_write(sink, writer, content.sounds, type, extras); - if (type == ElementType::LIBRARIES && writer.is(SERIALIZE_EXTENSIONS) && - (!content.libraries.empty() || !extras.children.empty())) - items_write(sink, writer, content.libraries, type, extras); - if (type == ElementType::SPRITESHEETS) items_write(sink, writer, content.spritesheets, type, extras); - if (type == ElementType::LAYERS) items_write(sink, writer, content.layers, type, extras); - if (type == ElementType::NULLS) items_write(sink, writer, content.nulls, type, extras); - if (type == ElementType::EVENTS) items_write(sink, writer, content.events, type, extras); + children.add(); + auto extras = container_extras_get(content, type); + // Optional containers are left out when the flags drop them or they are empty (their place still counts for + // where unknown children go). + if (type == ElementType::SHADERS && writer.is(SERIALIZE_EXTENSIONS) && + (!content.shaders.empty() || !extras.children.empty())) + items_write(sink, writer, content.shaders, type, extras); + if (type == ElementType::SOUNDS && writer.is(SERIALIZE_SOUNDS) && + (!content.sounds.empty() || !extras.children.empty())) + items_write(sink, writer, content.sounds, type, extras); + if (type == ElementType::LIBRARIES && writer.is(SERIALIZE_EXTENSIONS) && + (!content.libraries.empty() || !extras.children.empty())) + items_write(sink, writer, content.libraries, type, extras); + if (type == ElementType::SPRITESHEETS) + items_write(sink, writer, content.spritesheets, type, extras); + if (type == ElementType::LAYERS) + items_write(sink, writer, content.layers, type, extras); + if (type == ElementType::NULLS) + items_write(sink, writer, content.nulls, type, extras); + if (type == ElementType::EVENTS) + items_write(sink, writer, content.events, type, extras); } children.close(); - } +} - // A whole document; `inner` writes anything after its children (the SourceDocument copy) and `tag` renames it. - static void model_write(Sink& sink, const Model& model, Flags flags, const std::function& inner = {}, - std::string_view tag = {}) - { +// A whole document. `inner` writes anything after its children (the SourceDocument copy) and `tag` renames it. +static void model_write(Sink& sink, const Model& model, Flags flags, const std::function& inner = {}, + std::string_view tag = {}) +{ Writer writer(flags, &model); sink.open(tag.empty() ? tag_get(ElementType::ANIMATED_ACTOR) : tag); extras_write(sink, model.extras); @@ -1747,199 +1841,220 @@ {ElementType::CONTENT, true}, {ElementType::ANIMATIONS, !model.animations.entries.empty()}})) { - children.add(); - if (type == ElementType::CONTENT) content_write(sink, writer, model.content); - if (type == ElementType::ANIMATIONS) animations_write(sink, writer, model.animations); - if (type != ElementType::INFO) continue; - sink.open(tag_get(ElementType::INFO)); - sink.attribute("CreatedBy", model.info.createdBy); - sink.attribute("CreatedOn", model.info.createdOn); - sink.attribute("Fps", model.info.fps); - sink.attribute("Version", model.info.version); - if (isIgnored) sink.attribute("IsaacIgnored", true); - extras_write(sink, model.info.extras); - element_close(sink, model.info.extras); + children.add(); + if (type == ElementType::CONTENT) + content_write(sink, writer, model.content); + if (type == ElementType::ANIMATIONS) + animations_write(sink, writer, model.animations); + if (type != ElementType::INFO) + continue; + sink.open(tag_get(ElementType::INFO)); + sink.attribute("CreatedBy", model.info.createdBy); + sink.attribute("CreatedOn", model.info.createdOn); + sink.attribute("Fps", model.info.fps); + sink.attribute("Version", model.info.version); + if (isIgnored) + sink.attribute("IsaacIgnored", true); + extras_write(sink, model.info.extras); + element_close(sink, model.info.extras); } children.flush(); - if (inner) inner(); + if (inner) + inner(); sink.close(); - } +} - // A save is the game's document with the editor's own copy embedded as SourceDocument; neither writes tints of 255 - // or color offsets of 0, which readers assume. - static void document_write(Sink& sink, const Model& model, Options options) - { - model_write( - sink, options.gameModel ? *options.gameModel : model, SERIALIZE_ISAAC_DEFAULT | SERIALIZE_PURGE_DEFAULT_COLORS, - [&]() - { - model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT | SERIALIZE_PURGE_DEFAULT_COLORS, {}, SOURCE_DOCUMENT_TAG); - }); - } +// A save is the game's document with the editor's own copy embedded as SourceDocument. Neither writes tints of 255 +// or color offsets of 0, which readers assume. +static void document_write(Sink& sink, const Model& model, Options options) +{ + model_write(sink, options.gameModel ? *options.gameModel : model, + SERIALIZE_ISAAC_DEFAULT | SERIALIZE_PURGE_DEFAULT_COLORS, [&]() { + model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT | SERIALIZE_PURGE_DEFAULT_COLORS, {}, + SOURCE_DOCUMENT_TAG); + }); +} - // The text of whatever `write` sends to a sink. - template static std::string text_get(Write&& write) - { +// The text of whatever `write` sends to a sink. +template static std::string text_get(Write&& write) +{ Sink sink = {}; write(sink); return std::move(sink.text); - } +} - static bool model_invalid_set(Model& model) - { +static bool model_invalid_set(Model& model) +{ model = model_make(); model.isValid = false; return false; - } +} - // A parse error says where it is: "Error parsing element name (line 12)". - static bool document_parse(pugi::xml_document& document, std::string_view text, std::string* errorString) - { +// A parse error says where it is: "Error parsing element name (line 12)". +static bool document_parse(pugi::xml_document& document, std::string_view text, std::string* errorString) +{ auto result = document.load_buffer(text.data(), text.size()); - if (result) return true; + if (result) + return true; if (errorString) - *errorString = std::format("{} (line {})", result.description(), - std::ranges::count(text.substr(0, result.offset), '\n') + 1); + *errorString = std::format("{} (line {})", result.description(), + std::ranges::count(text.substr(0, result.offset), '\n') + 1); return false; - } +} - static bool document_load(Model& model, std::string_view text, std::string* errorString) - { +static bool document_load(Model& model, std::string_view text, std::string* errorString) +{ pugi::xml_document document; - if (!document_parse(document, text, errorString)) return model_invalid_set(model); + if (!document_parse(document, text, errorString)) + return model_invalid_set(model); auto root = document.document_element(); if (!root) { - if (errorString) *errorString = "No root element."; - return model_invalid_set(model); + if (errorString) + *errorString = "No root element."; + return model_invalid_set(model); } auto source = root.name() == SOURCE_DOCUMENT_TAG ? root : root.child(SOURCE_DOCUMENT_TAG.data()); // A document without one (as the old extended format saved) is read as the editor's own. model = model_read(source ? source : root); return true; - } +} - Model model_make() - { +Model model_make() +{ Model model = {}; model.info.createdOn = timestamp_get(CREATED_ON_FORMAT); return model; - } +} - bool model_load(Model& model, const std::filesystem::path& path, std::string* errorString) - { +bool model_load(Model& model, const std::filesystem::path& path, std::string* errorString) +{ std::string text; - if (file_text_load(path, &text)) return model_load_string(model, text, errorString); - if (errorString) *errorString = "File not found."; + if (file_text_load(path, &text)) + return model_load_string(model, text, errorString); + if (errorString) + *errorString = "File not found."; return model_invalid_set(model); - } +} - bool model_load_string(Model& model, std::string_view text, std::string* errorString) - { - if (is_json(text)) return model_from_json(model, text, errorString) || model_invalid_set(model); +bool model_load_string(Model& model, std::string_view text, std::string* errorString) +{ + if (is_json(text)) + return model_from_json(model, text, errorString) || model_invalid_set(model); return document_load(model, text, errorString); - } +} - bool model_save(const Model& model, const std::filesystem::path& path, std::string* errorString, Options options) - { +bool model_save(const Model& model, const std::filesystem::path& path, std::string* errorString, Options options) +{ auto text = model_to_string(model, options); File file(path, "wb"); if (!file) { - if (errorString) *errorString = "File permissions."; - return false; + if (errorString) + *errorString = "File permissions."; + return false; } - if (std::fwrite(text.data(), 1, text.size(), file.get()) == text.size()) return true; - if (errorString) *errorString = "Could not write the file."; + if (std::fwrite(text.data(), 1, text.size(), file.get()) == text.size()) + return true; + if (errorString) + *errorString = "Could not write the file."; return false; - } +} - std::string model_to_string(const Model& model, Options options) - { - if (options.isJson) return model_to_json(model); +std::string model_to_string(const Model& model, Options options) +{ + if (options.isJson) + return model_to_json(model); return text_get([&](Sink& sink) { document_write(sink, model, options); }); - } +} - std::string model_serialize(const Model& model, Flags flags) - { +std::string model_serialize(const Model& model, Flags flags) +{ return text_get([&](Sink& sink) { model_write(sink, model, flags); }); - } +} - // The hash of what the editor would save, so it changes exactly when a save would. - std::uint64_t model_hash(const Model& model) - { +// The hash of what the editor would save, so it changes exactly when a save would. +std::uint64_t model_hash(const Model& model) +{ Sink sink = {.mode = Sink::HASH}; model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT); return sink.hash; - } +} - std::string frame_to_string(const Frame& frame, ItemType type) - { +std::string frame_to_string(const Frame& frame, ItemType type) +{ return text_get([&](Sink& sink) { frame_write(sink, Writer(CLIPBOARD_FLAGS), frame, type); }); - } +} - std::string animation_to_string(const Animation& animation, int groupId) - { +std::string animation_to_string(const Animation& animation, int groupId) +{ return text_get([&](Sink& sink) { animation_write(sink, Writer(CLIPBOARD_FLAGS), animation, groupId); }); - } +} - std::string animation_group_to_string(const AnimationGroup& group) - { +std::string animation_group_to_string(const AnimationGroup& group) +{ return text_get([&](Sink& sink) { group_write(sink, Writer(CLIPBOARD_FLAGS), group); }); - } +} - std::vector frames_from_string(const std::string& text, ItemType type, std::string* errorString) - { +std::vector frames_from_string(const std::string& text, ItemType type, std::string* errorString) +{ pugi::xml_document document; - if (!document_parse(document, text, errorString)) return {}; + if (!document_parse(document, text, errorString)) + return {}; auto tag = tag_get(type == ItemType::TRIGGER ? ElementType::TRIGGER : ElementType::FRAME); std::vector frames; for (auto element : document.children(tag)) - frames.push_back(frame_read(element)); - if (frames.empty() && errorString) *errorString = std::format("No valid {}(s).", tag); + frames.push_back(frame_read(element)); + if (frames.empty() && errorString) + *errorString = std::format("No valid {}(s).", tag); return frames; - } +} - std::vector animations_from_string(const std::string& text, std::string* errorString) - { +std::vector animations_from_string(const std::string& text, std::string* errorString) +{ pugi::xml_document document; - if (!document_parse(document, text, errorString)) return {}; + if (!document_parse(document, text, errorString)) + return {}; Extras extras = {}; auto entries = animation_entries_read(document, extras); - if (entries.empty() && errorString) *errorString = "No valid animation(s)."; + if (entries.empty() && errorString) + *errorString = "No valid animation(s)."; return entries; - } +} - template static std::string item_to_string(const Item& item) - { +template static std::string item_to_string(const Item& item) +{ return text_get([&](Sink& sink) { item_write(sink, Writer(CLIPBOARD_FLAGS), item, item.id); }); - } +} - template static std::vector items_from_string(const std::string& text, std::string* errorString) - { +template static std::vector items_from_string(const std::string& text, std::string* errorString) +{ pugi::xml_document document; - if (!document_parse(document, text, errorString)) return {}; + if (!document_parse(document, text, errorString)) + return {}; auto tag = tag_get(ITEM_TYPE); std::vector items; for (auto element : document.children(tag)) { - auto item = item_read(element); - if constexpr (requires { item.path; }) item.path = path_backslash_handle(item.path); - items.push_back(std::move(item)); + auto item = item_read(element); + if constexpr (requires { item.path; }) + item.path = path_backslash_handle(item.path); + items.push_back(std::move(item)); } - if (items.empty() && errorString) *errorString = std::format("No valid {}(s).", tag); + if (items.empty() && errorString) + *errorString = std::format("No valid {}(s).", tag); return items; - } +} #define X(Item) \ - template std::string item_to_string(const Item&); \ - template std::vector items_from_string(const std::string&, std::string*); - X(Spritesheet) - X(Region) - X(Shader) - X(Layer) - X(Null) - X(Event) - X(Sound) - X(Library) + template std::string item_to_string(const Item&); \ + template std::vector items_from_string(const std::string&, std::string*); +X(Spritesheet) +X(Region) +X(Shader) +X(Layer) +X(Null) +X(Event) +X(Sound) +X(Library) #undef X diff --git a/src/model/xml.h b/src/model/xml.h index 82dd9d8..53a4be7 100644 --- a/src/model/xml.h +++ b/src/model/xml.h @@ -6,9 +6,9 @@ #include "model/model.h" // The only place the model meets XML: reading and writing documents (with the SourceDocument copy) and clipboard text. - // What the game's copy of a save can't keep as it is: how many of each. - struct IsaacIssues - { +// What the game's copy of a save can't keep as it is: how many of each. +struct IsaacIssues +{ int easedFrames = 0; int groupTransforms = 0; int skewFrames = 0; @@ -22,23 +22,23 @@ int vectorSpritesheets = 0; bool operator==(const IsaacIssues&) const = default; - }; +}; - Model model_make(); - IsaacIssues isaac_issues_get(const Model&); - void model_repair(Model&); - bool model_load(Model&, const std::filesystem::path&, std::string* = nullptr); - bool model_load_string(Model&, std::string_view, std::string* = nullptr); - bool model_save(const Model&, const std::filesystem::path&, std::string* = nullptr, Options = {}); - std::string model_to_string(const Model&, Options = {}); - std::string model_serialize(const Model&, Flags); - std::uint64_t model_hash(const Model&); +Model model_make(); +IsaacIssues isaac_issues_get(const Model&); +void model_repair(Model&); +bool model_load(Model&, const std::filesystem::path&, std::string* = nullptr); +bool model_load_string(Model&, std::string_view, std::string* = nullptr); +bool model_save(const Model&, const std::filesystem::path&, std::string* = nullptr, Options = {}); +std::string model_to_string(const Model&, Options = {}); +std::string model_serialize(const Model&, Flags); +std::uint64_t model_hash(const Model&); - std::string frame_to_string(const Frame&, ItemType); - std::string animation_to_string(const Animation&, int = -1); - std::string animation_group_to_string(const AnimationGroup&); - std::vector frames_from_string(const std::string&, ItemType, std::string* = nullptr); - std::vector animations_from_string(const std::string&, std::string* = nullptr); +std::string frame_to_string(const Frame&, ItemType); +std::string animation_to_string(const Animation&, int = -1); +std::string animation_group_to_string(const AnimationGroup&); +std::vector frames_from_string(const std::string&, ItemType, std::string* = nullptr); +std::vector animations_from_string(const std::string&, std::string* = nullptr); - template std::string item_to_string(const Item&); - template std::vector items_from_string(const std::string&, std::string* = nullptr); +template std::string item_to_string(const Item&); +template std::vector items_from_string(const std::string&, std::string* = nullptr); diff --git a/src/pack.cpp b/src/pack.cpp index f69c130..c36ddf3 100644 --- a/src/pack.cpp +++ b/src/pack.cpp @@ -5,107 +5,112 @@ #include #include - constexpr int WIDTH_CANDIDATES_MAX = 512; +constexpr int WIDTH_CANDIDATES_MAX = 512; - struct Rect - { +struct Rect +{ int x = 0; int y = 0; int w = 0; int h = 0; - }; +}; - static bool is_rect_intersecting(const Rect& a, const Rect& b) - { +static 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); - } +} - static bool is_rect_contained(const Rect& a, const Rect& b) - { +static 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; - } +} - static void free_rects_split(std::vector& freeRects, const Rect& used) - { +static void free_rects_split(std::vector& freeRects, const Rect& used) +{ std::vector 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)}); + 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); - } +} - static void free_rects_prune(std::vector& freeRects) - { +static void free_rects_prune(std::vector& 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])) + if (freeRects[i].w <= 0 || freeRects[i].h <= 0) { - freeRects.erase(freeRects.begin() + i--); - break; + freeRects.erase(freeRects.begin() + i--); + continue; } - else - ++j; - } + 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; } - } +} - static bool rect_insert(std::vector& freeRects, glm::ivec2 size, Rect& result) - { +static bool rect_insert(std::vector& freeRects, glm::ivec2 size, Rect& result) +{ int bestShort = std::numeric_limits::max(); int bestLong = std::numeric_limits::max(); bool isFound = false; 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 (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; + if (!isFound) + return false; free_rects_split(freeRects, result); free_rects_prune(freeRects); return true; - } +} - bool rects_pack(const std::vector& sizes, glm::ivec2& packedSize, std::vector& positions) - { - if (sizes.empty()) return false; +bool rects_pack(const std::vector& sizes, glm::ivec2& packedSize, std::vector& positions) +{ + if (sizes.empty()) + return false; glm::ivec2 maxSize{}; glm::ivec2 sumSize{}; std::int64_t totalArea = 0; for (auto& size : sizes) { - maxSize = glm::max(maxSize, size); - sumSize += size; - totalArea += (std::int64_t)size.x * size.y; + maxSize = glm::max(maxSize, size); + sumSize += size; + totalArea += (std::int64_t)size.x * size.y; } - if (maxSize.x <= 0 || maxSize.y <= 0) return false; + if (maxSize.x <= 0 || maxSize.y <= 0) + return false; int bestSquareDelta = std::numeric_limits::max(); int bestArea = std::numeric_limits::max(); @@ -114,34 +119,37 @@ for (int width = maxSize.x; width <= endWidth; width += step) { - std::vector candidate(sizes.size()); - glm::ivec2 used{}; - bool isValid = false; - for (int height = std::max(maxSize.y, (int)std::ceil((double)totalArea / width)); height <= sumSize.y && !isValid; - ++height) - { - std::vector freeRects{{0, 0, width, height}}; - used = {}; - isValid = true; - for (int i = 0; i < (int)sizes.size() && isValid; ++i) + std::vector candidate(sizes.size()); + glm::ivec2 used{}; + bool isValid = false; + for (int height = std::max(maxSize.y, (int)std::ceil((double)totalArea / width)); + height <= sumSize.y && !isValid; ++height) { - 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)); + std::vector 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; + 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; + 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::max(); - } +} diff --git a/src/pack.h b/src/pack.h index 7e7a212..4783b0c 100644 --- a/src/pack.h +++ b/src/pack.h @@ -4,4 +4,4 @@ #include - bool rects_pack(const std::vector&, glm::ivec2&, std::vector&); +bool rects_pack(const std::vector&, glm::ivec2&, std::vector&); diff --git a/src/path.cpp b/src/path.cpp index 2a8153f..aa8f705 100644 --- a/src/path.cpp +++ b/src/path.cpp @@ -6,161 +6,183 @@ #include #include - template static CharT to_lower_char(CharT character) - { +template static CharT to_lower_char(CharT character) +{ if constexpr (std::is_same_v) - return static_cast(std::towlower(static_cast(character))); + return static_cast(std::towlower(static_cast(character))); else - return static_cast(std::tolower(static_cast(character))); - } + return static_cast(std::tolower(static_cast(character))); +} - std::filesystem::path path_to_lower(const std::filesystem::path& path) - { +std::filesystem::path path_to_lower(const std::filesystem::path& path) +{ auto native = path.native(); for (auto& character : native) - character = to_lower_char(character); + character = to_lower_char(character); return std::filesystem::path(native); - } +} - std::filesystem::path path_backslash_replace(const std::filesystem::path& path) - { +std::filesystem::path path_backslash_replace(const std::filesystem::path& path) +{ auto native = path.native(); constexpr auto backslash = static_cast('\\'); constexpr auto slash = static_cast('/'); for (auto& character : native) - if (character == backslash) character = slash; + if (character == backslash) + character = slash; return std::filesystem::path(native); - } +} - std::string path_to_utf8(const std::filesystem::path& path) - { +std::string path_to_utf8(const std::filesystem::path& path) +{ auto u8 = path.u8string(); return std::string(u8.begin(), u8.end()); - } +} - std::filesystem::path path_from_utf8(const std::string& utf8) - { +std::filesystem::path path_from_utf8(const std::string& utf8) +{ return std::filesystem::path(std::u8string(utf8.begin(), utf8.end())); - } +} - bool is_path_exist(const std::filesystem::path& path) - { - if (path.empty()) return false; +bool is_path_exist(const std::filesystem::path& path) +{ + if (path.empty()) + return false; std::error_code errorCode; return std::filesystem::exists(path, errorCode) && ((void)std::filesystem::status(path, errorCode), !errorCode); - } +} - bool is_path_extension(const std::filesystem::path& path, const std::string& extension) - { - if (path.empty()) return false; +bool is_path_extension(const std::filesystem::path& path, const std::string& extension) +{ + if (path.empty()) + return false; auto extensionUtf8 = path_to_utf8(std::filesystem::path(path).extension()); std::transform(extensionUtf8.begin(), extensionUtf8.end(), extensionUtf8.begin(), ::tolower); return extensionUtf8 == ("." + extension); - } +} - bool is_path_executable(const std::filesystem::path& path) - { - if (path.empty()) return false; +bool is_path_executable(const std::filesystem::path& path) +{ + if (path.empty()) + return false; std::error_code ec; auto status = std::filesystem::status(path, ec); - if (ec) return false; - if (!std::filesystem::exists(status)) return false; - if (!std::filesystem::is_regular_file(status)) return false; + if (ec) + return false; + if (!std::filesystem::exists(status)) + return false; + if (!std::filesystem::is_regular_file(status)) + return false; #ifdef WIN32 auto extension = path_to_lower(path.extension()); - if (extension != ".exe" && extension != ".bat" && extension != ".cmd") return false; + if (extension != ".exe" && extension != ".bat" && extension != ".cmd") + return false; #else auto permissions = status.permissions(); auto executableMask = std::filesystem::perms::owner_exec | std::filesystem::perms::group_exec | std::filesystem::perms::others_exec; - if ((permissions & executableMask) == std::filesystem::perms::none) return false; + if ((permissions & executableMask) == std::filesystem::perms::none) + return false; #endif return true; - } +} - bool path_ensure_directory(const std::filesystem::path& path) - { - if (path.empty()) return false; +bool path_ensure_directory(const std::filesystem::path& path) +{ + if (path.empty()) + return false; std::error_code ec; - if (std::filesystem::create_directories(path, ec)) return true; + if (std::filesystem::create_directories(path, ec)) + return true; return is_path_exist(path.parent_path()); - } +} - std::filesystem::path path_make_relative(const std::filesystem::path& path) - { - if (path.empty()) return path; - if (!path.is_absolute()) return path; +std::filesystem::path path_make_relative(const std::filesystem::path& path) +{ + if (path.empty()) + return path; + if (!path.is_absolute()) + return path; std::error_code ec; auto relative = std::filesystem::relative(path, ec); - if (!ec) return relative; + if (!ec) + return relative; return path; - } +} - std::filesystem::path path_make_relative(const std::filesystem::path& path, const std::filesystem::path& base) - { - if (path.empty()) return path; - if (base.empty() || !path.is_absolute()) return path; +std::filesystem::path path_make_relative(const std::filesystem::path& path, const std::filesystem::path& base) +{ + if (path.empty()) + return path; + if (base.empty() || !path.is_absolute()) + return path; std::error_code ec; auto relative = std::filesystem::relative(path, base, ec); - if (!ec) return relative; + if (!ec) + return relative; return path; - } +} - std::filesystem::path path_backslash_handle(const std::filesystem::path& path) - { +std::filesystem::path path_backslash_handle(const std::filesystem::path& path) +{ auto newPath = path; - if (is_path_exist(newPath)) return newPath; + if (is_path_exist(newPath)) + return newPath; newPath = path_backslash_replace(newPath); return newPath; - } +} - std::filesystem::path path_case_insensitive_find(const std::filesystem::path& path) - { +std::filesystem::path path_case_insensitive_find(const std::filesystem::path& path) +{ auto handledPath = path_backslash_handle(path); - if (is_path_exist(handledPath)) return handledPath; + if (is_path_exist(handledPath)) + return handledPath; auto resolvedPath = handledPath.root_path(); for (auto& part : handledPath.relative_path()) { - auto candidate = resolvedPath / part; - if (is_path_exist(candidate)) - { - resolvedPath = candidate; - continue; - } + auto candidate = resolvedPath / part; + if (is_path_exist(candidate)) + { + resolvedPath = candidate; + continue; + } - auto parent = resolvedPath.empty() ? std::filesystem::path(".") : resolvedPath; - std::error_code ec; - bool isFound = false; - if (std::filesystem::is_directory(parent, ec)) - { - auto partLower = path_to_lower(part); - std::filesystem::directory_iterator it(parent, ec); - std::filesystem::directory_iterator end = {}; - for (; !ec && it != end; it.increment(ec)) - if (path_to_lower(it->path().filename()) == partLower) - { - resolvedPath /= it->path().filename(); - isFound = true; - break; - } - } + auto parent = resolvedPath.empty() ? std::filesystem::path(".") : resolvedPath; + std::error_code ec; + bool isFound = false; + if (std::filesystem::is_directory(parent, ec)) + { + auto partLower = path_to_lower(part); + std::filesystem::directory_iterator it(parent, ec); + std::filesystem::directory_iterator end = {}; + for (; !ec && it != end; it.increment(ec)) + if (path_to_lower(it->path().filename()) == partLower) + { + resolvedPath /= it->path().filename(); + isFound = true; + break; + } + } - if (!isFound) resolvedPath = candidate; + if (!isFound) + resolvedPath = candidate; } - if (is_path_exist(resolvedPath)) return resolvedPath; + if (is_path_exist(resolvedPath)) + return resolvedPath; auto lowerPath = path_to_lower(handledPath); - if (is_path_exist(lowerPath)) return lowerPath; + if (is_path_exist(lowerPath)) + return lowerPath; return handledPath; - } +} diff --git a/src/path.h b/src/path.h index 6923d97..9d1f231 100644 --- a/src/path.h +++ b/src/path.h @@ -3,18 +3,18 @@ #include #include - std::filesystem::path path_to_lower(const std::filesystem::path&); - std::filesystem::path path_backslash_replace(const std::filesystem::path&); - std::string path_to_utf8(const std::filesystem::path&); - std::filesystem::path path_from_utf8(const std::string&); - std::filesystem::path path_make_relative(const std::filesystem::path&); - std::filesystem::path path_make_relative(const std::filesystem::path&, const std::filesystem::path&); +std::filesystem::path path_to_lower(const std::filesystem::path&); +std::filesystem::path path_backslash_replace(const std::filesystem::path&); +std::string path_to_utf8(const std::filesystem::path&); +std::filesystem::path path_from_utf8(const std::string&); +std::filesystem::path path_make_relative(const std::filesystem::path&); +std::filesystem::path path_make_relative(const std::filesystem::path&, const std::filesystem::path&); - bool is_path_exist(const std::filesystem::path&); - bool is_path_executable(const std::filesystem::path&); - bool is_path_extension(const std::filesystem::path&, const std::string&); +bool is_path_exist(const std::filesystem::path&); +bool is_path_executable(const std::filesystem::path&); +bool is_path_extension(const std::filesystem::path&, const std::string&); - bool path_ensure_directory(const std::filesystem::path&); +bool path_ensure_directory(const std::filesystem::path&); - std::filesystem::path path_backslash_handle(const std::filesystem::path&); - std::filesystem::path path_case_insensitive_find(const std::filesystem::path&); +std::filesystem::path path_backslash_handle(const std::filesystem::path&); +std::filesystem::path path_case_insensitive_find(const std::filesystem::path&); diff --git a/src/playback.cpp b/src/playback.cpp index 062b37b..5de2e1d 100644 --- a/src/playback.cpp +++ b/src/playback.cpp @@ -4,53 +4,64 @@ #include - void Playback::toggle() - { - if (isFinished) time = 0.0f; +void Playback::toggle() +{ + if (isFinished) + time = 0.0f; isFinished = false; isPlaying = !isPlaying; timing_reset(); - } +} - void Playback::timing_reset() { tickAccumulator = 0.0f; } +void Playback::timing_reset() +{ + tickAccumulator = 0.0f; +} - void Playback::clamp(int length) { time = glm::clamp(time, 0.0f, (float)length - 1.0f); } +void Playback::clamp(int length) +{ + time = glm::clamp(time, 0.0f, (float)length - 1.0f); +} - // Plays the frames [start, end); a playhead outside them starts at start. - void Playback::tick(int fps, int start, int end, bool isLoop, float deltaSeconds) - { - if (isLoop) isFinished = false; - if (isFinished || !isPlaying || fps <= 0 || end <= start) return; - if (deltaSeconds <= 0.0f) return; +// Plays the frames [start, end). A playhead outside them starts at start. +void Playback::tick(int fps, int start, int end, bool isLoop, float deltaSeconds) +{ + if (isLoop) + isFinished = false; + if (isFinished || !isPlaying || fps <= 0 || end <= start) + return; + if (deltaSeconds <= 0.0f) + return; - if (!std::isfinite(time) || time < (float)start || time >= (float)end) time = (float)start; + if (!std::isfinite(time) || time < (float)start || time >= (float)end) + time = (float)start; time += deltaSeconds * (float)fps; if (isLoop) { - time = (float)start + std::fmod(time - (float)start, (float)(end - start)); - return; + time = (float)start + std::fmod(time - (float)start, (float)(end - start)); + return; } if (time >= (float)end) { - time = (float)end - 1.0f; - isPlaying = false; - isFinished = true; - timing_reset(); + time = (float)end - 1.0f; + isPlaying = false; + isFinished = true; + timing_reset(); } - } +} - void Playback::decrement(int length) - { +void Playback::decrement(int length) +{ --time; clamp(length); timing_reset(); - } +} - void Playback::increment(int length) - { +void Playback::increment(int length) +{ ++time; clamp(length); timing_reset(); - } +} diff --git a/src/playback.h b/src/playback.h index 30e9c15..fb3b374 100644 --- a/src/playback.h +++ b/src/playback.h @@ -1,8 +1,8 @@ #pragma once - class Playback - { - public: +class Playback +{ +public: float time = 0; bool isPlaying = false; bool isFinished = false; @@ -14,6 +14,6 @@ void decrement(int); void increment(int); - private: +private: float tickAccumulator = 0; - }; +}; diff --git a/src/render.cpp b/src/render.cpp index d852efd..d519988 100644 --- a/src/render.cpp +++ b/src/render.cpp @@ -28,11 +28,12 @@ #include "texture.h" #include "ui/toast.h" - bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesystem::path& path, - const std::vector& framePaths, AudioStream& audioStream, - RenderType type, int fps) - { - if (framePaths.empty() || ffmpegPath.empty() || path.empty()) return false; +bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesystem::path& path, + const std::vector& framePaths, AudioStream& audioStream, RenderType type, + int fps) +{ + if (framePaths.empty() || ffmpegPath.empty() || path.empty()) + return false; fps = std::max(fps, 1); auto pathString = path_to_utf8(path); @@ -51,62 +52,61 @@ std::string audioOutputArguments = "-an"; std::string command; auto temporaryDirectory = framePaths.front().parent_path(); - if (temporaryDirectory.empty()) temporaryDirectory = std::filesystem::temp_directory_path(); + if (temporaryDirectory.empty()) + temporaryDirectory = std::filesystem::temp_directory_path(); - auto audio_remove = [&]() - { - if (!audioPath.empty()) - { - std::error_code ec; - std::filesystem::remove(audioPath, ec); - } + auto audio_remove = [&]() { + if (!audioPath.empty()) + { + std::error_code ec; + std::filesystem::remove(audioPath, ec); + } }; - if (type != RENDER_GIF && !audioStream.stream.empty() && audioStream.spec.freq > 0 && - audioStream.spec.channels > 0) + if (type != RENDER_GIF && !audioStream.stream.empty() && audioStream.spec.freq > 0 && audioStream.spec.channels > 0) { - auto tempFilenameUtf8 = - std::format("anm2ed_audio_{}_{}.f32", std::hash{}(pathString), SDL_GetTicks()); - audioPath = temporaryDirectory / path_from_utf8(tempFilenameUtf8); + auto tempFilenameUtf8 = + std::format("anm2ed_audio_{}_{}.f32", std::hash{}(pathString), SDL_GetTicks()); + audioPath = temporaryDirectory / path_from_utf8(tempFilenameUtf8); - auto data = (const char*)audioStream.stream.data(); - auto byteCount = audioStream.stream.size() * sizeof(float); - if (file_text_save(audioPath, std::string_view(data, byteCount), "wb")) - { - auto sampleRate = std::max(audioStream.spec.freq, 1); - auto channels = std::max(audioStream.spec.channels, 1); - auto audioDurationFilter = std::string{}; - auto frameCount = (double)std::max((int)framePaths.size(), 1); - auto expectedDurationSeconds = frameCount / (double)fps; - if (expectedDurationSeconds > 0.0) - audioDurationFilter += std::format("apad,atrim=duration={:.9f}", expectedDurationSeconds); - - audioInputArguments = - std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", sampleRate, channels, path_to_utf8(audioPath)); - - switch (type) + auto data = (const char*)audioStream.stream.data(); + auto byteCount = audioStream.stream.size() * sizeof(float); + if (file_text_save(audioPath, std::string_view(data, byteCount), "wb")) { - case RENDER_WEBM: - audioOutputArguments = "-c:a libopus -b:a 160k -shortest"; - break; - case RENDER_OGV: - audioOutputArguments = "-c:a libvorbis -q:a 4 -shortest"; - break; - case RENDER_MP4: - audioOutputArguments = "-c:a aac -b:a 192k -shortest"; - break; - default: - break; - } + auto sampleRate = std::max(audioStream.spec.freq, 1); + auto channels = std::max(audioStream.spec.channels, 1); + auto audioDurationFilter = std::string{}; + auto frameCount = (double)std::max((int)framePaths.size(), 1); + auto expectedDurationSeconds = frameCount / (double)fps; + if (expectedDurationSeconds > 0.0) + audioDurationFilter += std::format("apad,atrim=duration={:.9f}", expectedDurationSeconds); - if (!audioDurationFilter.empty()) - audioOutputArguments = std::format("-af \"{}\" {}", audioDurationFilter, audioOutputArguments); - } - else - { - logger.warning("Failed to open temporary audio file; exporting video without audio."); - audio_remove(); - } + audioInputArguments = + std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", sampleRate, channels, path_to_utf8(audioPath)); + + switch (type) + { + case RENDER_WEBM: + audioOutputArguments = "-c:a libopus -b:a 160k -shortest"; + break; + case RENDER_OGV: + audioOutputArguments = "-c:a libvorbis -q:a 4 -shortest"; + break; + case RENDER_MP4: + audioOutputArguments = "-c:a aac -b:a 192k -shortest"; + break; + default: + break; + } + + if (!audioDurationFilter.empty()) + audioOutputArguments = std::format("-af \"{}\" {}", audioDurationFilter, audioOutputArguments); + } + else + { + logger.warning("Failed to open temporary audio file; exporting video without audio."); + audio_remove(); + } } auto framePattern = temporaryDirectory / path_from_utf8("frame_%06d.png"); @@ -114,37 +114,42 @@ command = std::format("\"{0}\" -y -framerate {1} -start_number 0 -i \"{2}\"", ffmpegPathString, fps, framePatternString); - if (!audioInputArguments.empty()) command += " " + audioInputArguments; + if (!audioInputArguments.empty()) + command += " " + audioInputArguments; command += std::format(" -fps_mode cfr -r {}", fps); switch (type) { - case RENDER_GIF: - command += " -lavfi \"split[s0][s1];[s0]palettegen=stats_mode=full:reserve_transparent=1[p];" - "[s1][p]paletteuse=dither=floyd_steinberg:alpha_threshold=128\"" - " -loop 0"; - command += std::format(" \"{}\"", pathString); - break; - case RENDER_WEBM: - command += " -c:v libvpx-vp9 -crf 30 -b:v 0 -pix_fmt yuva420p -row-mt 1 -threads 0 -speed 2 -auto-alt-ref 0"; - if (!audioOutputArguments.empty()) command += " " + audioOutputArguments; - command += std::format(" \"{}\"", pathString); - break; - case RENDER_OGV: - command += " -vf \"format=yuv420p,scale=trunc(iw/2)*2:trunc(ih/2)*2\" -c:v libtheora -q:v 7"; - if (!audioOutputArguments.empty()) command += " " + audioOutputArguments; - command += std::format(" \"{}\"", pathString); - break; - case RENDER_MP4: - command += " -vf \"format=yuv420p,scale=trunc(iw/2)*2:trunc(ih/2)*2\" -c:v libx265 -crf 20 -preset slow" - " -tag:v hvc1 -movflags +faststart"; - if (!audioOutputArguments.empty()) command += " " + audioOutputArguments; - command += std::format(" \"{}\"", pathString); - break; - default: - { - return false; - } + case RENDER_GIF: + command += " -lavfi \"split[s0][s1];[s0]palettegen=stats_mode=full:reserve_transparent=1[p];" + "[s1][p]paletteuse=dither=floyd_steinberg:alpha_threshold=128\"" + " -loop 0"; + command += std::format(" \"{}\"", pathString); + break; + case RENDER_WEBM: + command += + " -c:v libvpx-vp9 -crf 30 -b:v 0 -pix_fmt yuva420p -row-mt 1 -threads 0 -speed 2 -auto-alt-ref 0"; + if (!audioOutputArguments.empty()) + command += " " + audioOutputArguments; + command += std::format(" \"{}\"", pathString); + break; + case RENDER_OGV: + command += " -vf \"format=yuv420p,scale=trunc(iw/2)*2:trunc(ih/2)*2\" -c:v libtheora -q:v 7"; + if (!audioOutputArguments.empty()) + command += " " + audioOutputArguments; + command += std::format(" \"{}\"", pathString); + break; + case RENDER_MP4: + command += " -vf \"format=yuv420p,scale=trunc(iw/2)*2:trunc(ih/2)*2\" -c:v libx265 -crf 20 -preset slow" + " -tag:v hvc1 -movflags +faststart"; + if (!audioOutputArguments.empty()) + command += " " + audioOutputArguments; + command += std::format(" \"{}\"", pathString); + break; + default: + { + return false; + } } #if _WIN32 @@ -161,99 +166,107 @@ if (!process.get()) { - audio_remove(); - return false; + audio_remove(); + return false; } auto ffmpegExitCode = process.close(); if (ffmpegExitCode != 0) { - logger.error(std::format("FFmpeg exited with code {} while exporting {}", ffmpegExitCode, pathString)); - audio_remove(); - return false; + logger.error(std::format("FFmpeg exited with code {} while exporting {}", ffmpegExitCode, pathString)); + audio_remove(); + return false; } audio_remove(); return true; - } +} - constexpr int TEMP_DIRECTORY_ATTEMPTS = 1000; - constexpr glm::vec4 BOUNDS_DEFAULT = {-32.0f, -32.0f, 64.0f, 64.0f}; - constexpr int ALPHA_OPAQUE = 255; - constexpr float CHANNEL_MAX = 255.0f; +constexpr int TEMP_DIRECTORY_ATTEMPTS = 1000; +constexpr glm::vec4 BOUNDS_DEFAULT = {-32.0f, -32.0f, 64.0f, 64.0f}; +constexpr int ALPHA_OPAQUE = 255; +constexpr float CHANNEL_MAX = 255.0f; - static std::filesystem::path frame_filename_get(const std::filesystem::path& format, int index, RenderType type) - { +static std::filesystem::path frame_filename_get(const std::filesystem::path& format, int index, RenderType type) +{ auto fallback = path_from_utf8(std::format("frame_{:06}.png", index)); - if (type != RENDER_PNGS) return fallback; + if (type != RENDER_PNGS) + return fallback; try { - auto filename = path_from_utf8(std::vformat(path_to_utf8(format), std::make_format_args(index))).filename(); - if (filename.empty()) return fallback; - if (filename.extension().empty()) filename.replace_extension(RENDER_EXTENSIONS[RENDER_SPRITESHEET]); - return filename; + auto filename = path_from_utf8(std::vformat(path_to_utf8(format), std::make_format_args(index))).filename(); + if (filename.empty()) + return fallback; + if (filename.extension().empty()) + filename.replace_extension(RENDER_EXTENSIONS[RENDER_SPRITESHEET]); + return filename; } catch (...) { - return fallback; + return fallback; } - } +} - // PNG sequences go straight to their folder; other outputs collect frames in a temporary folder beside the output. - static std::filesystem::path frames_directory_create(const RecorderOptions& options) - { +// PNG sequences go straight to their folder. Other outputs collect frames in a temporary folder beside the output. +static std::filesystem::path frames_directory_create(const RecorderOptions& options) +{ std::error_code ec; if (options.type == RENDER_PNGS) { - std::filesystem::create_directories(options.path, ec); - return options.path; + std::filesystem::create_directories(options.path, ec); + return options.path; } auto directory = options.path.parent_path(); - if (directory.empty()) directory = std::filesystem::current_path(); + if (directory.empty()) + directory = std::filesystem::current_path(); std::filesystem::create_directories(directory, ec); auto timestamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); for (int suffix = 0; suffix < TEMP_DIRECTORY_ATTEMPTS; ++suffix) { - auto temporary = directory / path_from_utf8(std::format(".anm2ed_render_tmp_{}_{}", timestamp, suffix)); - if (std::filesystem::create_directories(temporary, ec)) return temporary; + auto temporary = directory / path_from_utf8(std::format(".anm2ed_render_tmp_{}_{}", timestamp, suffix)); + if (std::filesystem::create_directories(temporary, ec)) + return temporary; } return {}; - } +} - // Rendered pixels are premultiplied; outputs on a transparent background want straight alpha. - void pixels_unpremultiply(std::vector& pixels) - { +// Rendered pixels are premultiplied. Outputs on a transparent background want straight alpha. +void pixels_unpremultiply(std::vector& pixels) +{ for (std::size_t index = 0; index + 3 < pixels.size(); index += IMAGE_CHANNELS) { - auto alpha = pixels[index + 3]; - if (alpha == ALPHA_OPAQUE) continue; - for (int channel = 0; channel < 3; ++channel) - pixels[index + channel] = - alpha == 0 - ? 0 - : (uint8_t)glm::clamp(std::round(pixels[index + channel] * CHANNEL_MAX / alpha), 0.0f, CHANNEL_MAX); + auto alpha = pixels[index + 3]; + if (alpha == ALPHA_OPAQUE) + continue; + for (int channel = 0; channel < 3; ++channel) + pixels[index + channel] = + alpha == 0 + ? 0 + : (uint8_t)glm::clamp(std::round(pixels[index + channel] * CHANNEL_MAX / alpha), 0.0f, CHANNEL_MAX); } - } +} - static void sounds_detach(const Document& document, MIX_Mixer* mixer) - { +static void sounds_detach(const Document& document, MIX_Mixer* mixer) +{ for (auto sound : document.sounds_get()) - audio_track_detach(*sound, mixer); - } + audio_track_detach(*sound, mixer); +} - // Mixes each frame's trigger sounds into one stream at the render frame rate. - static bool audio_stream_generate(AudioStream& audioStream, const Document& document, - const std::vector>& frameSounds, int fps) - { +// Mixes each frame's trigger sounds into one stream at the render frame rate. +static bool audio_stream_generate(AudioStream& audioStream, const Document& document, + const std::vector>& frameSounds, int fps) +{ audioStream.stream.clear(); - if (frameSounds.empty() || fps <= 0) return true; + if (frameSounds.empty() || fps <= 0) + return true; SDL_AudioSpec mixSpec = audioStream.spec; mixSpec.format = SDL_AUDIO_F32; auto mixer = MIX_CreateMixer(&mixSpec); - if (!mixer) return false; + if (!mixer) + return false; auto channels = std::max(mixSpec.channels, 1); auto framesPerStep = (double)std::max(mixSpec.freq, 1) / (double)fps; @@ -262,58 +275,68 @@ auto isGenerated = true; for (auto& sounds : frameSounds) { - for (auto sound : sounds) - audio_play(*sound, false, mixer); - accumulator += framesPerStep; - auto sampleFrames = std::max((int)std::floor(accumulator), 1); - accumulator -= (double)sampleFrames; - buffer.resize((std::size_t)sampleFrames * (std::size_t)channels); - if (!(isGenerated = MIX_Generate(mixer, buffer.data(), (int)(buffer.size() * sizeof(float))))) break; - audioStream.stream.insert(audioStream.stream.end(), buffer.begin(), buffer.end()); + for (auto sound : sounds) + audio_play(*sound, false, mixer); + accumulator += framesPerStep; + auto sampleFrames = std::max((int)std::floor(accumulator), 1); + accumulator -= (double)sampleFrames; + buffer.resize((std::size_t)sampleFrames * (std::size_t)channels); + if (!(isGenerated = MIX_Generate(mixer, buffer.data(), (int)(buffer.size() * sizeof(float))))) + break; + audioStream.stream.insert(audioStream.stream.end(), buffer.begin(), buffer.end()); } sounds_detach(document, mixer); MIX_DestroyMixer(mixer); - if (!isGenerated) audioStream.stream.clear(); + if (!isGenerated) + audioStream.stream.clear(); return isGenerated; - } +} - HeadlessGL::HeadlessGL() - { - if (!SDL_Init(SDL_INIT_VIDEO)) return; +HeadlessGL::HeadlessGL() +{ + if (!SDL_Init(SDL_INIT_VIDEO)) + return; SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); window = SDL_CreateWindow("anm2ed", 1, 1, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN); - if (window) context = SDL_GL_CreateContext(window); + if (window) + context = SDL_GL_CreateContext(window); if (!context || !gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) { - if (context) SDL_GL_DestroyContext(context); - context = nullptr; - return; + if (context) + SDL_GL_DestroyContext(context); + context = nullptr; + return; } glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); - } +} - HeadlessGL::~HeadlessGL() - { - if (context) SDL_GL_DestroyContext(context); - if (window) SDL_DestroyWindow(window); +HeadlessGL::~HeadlessGL() +{ + if (context) + SDL_GL_DestroyContext(context); + if (window) + SDL_DestroyWindow(window); SDL_Quit(); - } +} - bool HeadlessGL::is_valid() const { return context != nullptr; } +bool HeadlessGL::is_valid() const +{ + return context != nullptr; +} - glm::vec4 animation_bounds_get(const Document& document, const Animation& animation, bool isRootTransform) - { +glm::vec4 animation_bounds_get(const Document& document, const Animation& animation, bool isRootTransform) +{ auto bounds = animation_rect(document.model, animation, isRootTransform, document.library_resolver_get()); return bounds != glm::vec4(-1.0f) ? bounds : BOUNDS_DEFAULT; - } +} - std::vector animation_frame_render(Canvas& canvas, ShaderProgram& shader, Document& document, - const Animation& animation, float time, glm::vec4 bounds, - float scale, glm::vec4 background, bool isRootTransform) - { +std::vector animation_frame_render(Canvas& canvas, ShaderProgram& shader, Document& document, + const Animation& animation, float time, glm::vec4 bounds, float scale, + glm::vec4 background, bool isRootTransform) +{ canvas.size_set(glm::vec2(glm::max(glm::ivec2(glm::ceil(glm::vec2(bounds.z, bounds.w) * scale)), glm::ivec2(1)))); float zoom = 0; glm::vec2 pan{}; @@ -330,10 +353,10 @@ auto pixels = canvas.pixels_get(); canvas.unbind(); return pixels; - } +} - bool Recorder::start(const RecorderOptions& recorderOptions) - { +bool Recorder::start(const RecorderOptions& recorderOptions) +{ options = recorderOptions; index = 0; count = frame_count_get(options.start, options.end, options.animationFps, options.fps); @@ -342,121 +365,136 @@ soundTime = -1; directory = frames_directory_create(options); return !directory.empty(); - } +} - bool Recorder::is_done() const { return index >= count; } +bool Recorder::is_done() const +{ + return index >= count; +} - float Recorder::time_get() const { return frame_time_get(options.start, index, options.animationFps, options.fps); } +float Recorder::time_get() const +{ + return frame_time_get(options.start, index, options.animationFps, options.fps); +} - // A trigger sound is taken once per animation frame, however many render frames it spans. - bool Recorder::is_sound_frame() const { return (int)std::floor(time_get()) != soundTime; } +// A trigger sound is taken once per animation frame, however many render frames it spans. +bool Recorder::is_sound_frame() const +{ + return (int)std::floor(time_get()) != soundTime; +} - bool Recorder::frame_capture(std::vector pixels, glm::ivec2 size, - std::vector frameSounds) - { +bool Recorder::frame_capture(std::vector pixels, glm::ivec2 size, std::vector frameSounds) +{ soundTime = (int)std::floor(time_get()); sounds.push_back(std::move(frameSounds)); - if (options.isIsolated || options.isBounded) pixels_unpremultiply(pixels); + if (options.isIsolated || options.isBounded) + pixels_unpremultiply(pixels); auto framePath = directory / frame_filename_get(options.format, index, options.type); - if (!Image::write_pixels_png(framePath, size, pixels.data())) return false; + if (!Image::write_pixels_png(framePath, size, pixels.data())) + return false; frames.push_back(framePath); ++index; return true; - } +} - void Recorder::finish(const Document& document, AudioStream& audioStream) - { +void Recorder::finish(const Document& document, AudioStream& audioStream) +{ auto pathString = path_to_utf8(options.path); if (options.type == RENDER_PNGS) - toast_log(frames.empty() ? Level::ERROR : Level::INFO, - frames.empty() ? TOAST_EXPORT_RENDERED_FRAMES_FAILED : TOAST_EXPORT_RENDERED_FRAMES, pathString); + toast_log(frames.empty() ? Level::ERROR : Level::INFO, + frames.empty() ? TOAST_EXPORT_RENDERED_FRAMES_FAILED : TOAST_EXPORT_RENDERED_FRAMES, pathString); else if (options.type == RENDER_SPRITESHEET) { - auto layout = spritesheet_layout_get(options.rows, options.columns, (int)frames.size()); - auto first = frames.empty() ? Image{} : Image(frames.front()); - if (frames.empty()) - toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES); - else if (!first.is_valid()) - toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY); - else - { - Image sheet = {}; - sheet.size = first.size * glm::ivec2(layout.columns, layout.rows); - sheet.pixels.resize((std::size_t)sheet.size.x * sheet.size.y * IMAGE_CHANNELS); - for (int i = 0; i < (int)frames.size() && i < layout.rows * layout.columns; ++i) - if (auto frame = Image(frames[i]); frame.size == first.size) - sheet.paste(frame, first.size * glm::ivec2(i % layout.columns, i / layout.columns)); - auto isSaved = sheet.write_png(options.path); - toast_log(isSaved ? Level::INFO : Level::ERROR, - isSaved ? TOAST_EXPORT_SPRITESHEET : TOAST_EXPORT_SPRITESHEET_FAILED, pathString); - } + auto layout = spritesheet_layout_get(options.rows, options.columns, (int)frames.size()); + auto first = frames.empty() ? Image{} : Image(frames.front()); + if (frames.empty()) + toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES); + else if (!first.is_valid()) + toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY); + else + { + Image sheet = {}; + sheet.size = first.size * glm::ivec2(layout.columns, layout.rows); + sheet.pixels.resize((std::size_t)sheet.size.x * sheet.size.y * IMAGE_CHANNELS); + for (int i = 0; i < (int)frames.size() && i < layout.rows * layout.columns; ++i) + if (auto frame = Image(frames[i]); frame.size == first.size) + sheet.paste(frame, first.size * glm::ivec2(i % layout.columns, i / layout.columns)); + auto isSaved = sheet.write_png(options.path); + toast_log(isSaved ? Level::INFO : Level::ERROR, + isSaved ? TOAST_EXPORT_SPRITESHEET : TOAST_EXPORT_SPRITESHEET_FAILED, pathString); + } } else { - audioStream.stream.clear(); - if (options.isSound && options.type != RENDER_GIF && !audio_stream_generate(audioStream, document, sounds, options.fps)) - { - toasts.push(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED)); - logger.error("Failed to generate deterministic render audio stream; exporting without audio."); - } - auto isRendered = - animation_render(options.ffmpegPath, options.path, frames, audioStream, options.type, options.fps); - toast_log(isRendered ? Level::INFO : Level::ERROR, - isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); + audioStream.stream.clear(); + if (options.isSound && options.type != RENDER_GIF && + !audio_stream_generate(audioStream, document, sounds, options.fps)) + { + toasts.push(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED)); + logger.error("Failed to generate deterministic render audio stream; exporting without audio."); + } + auto isRendered = + animation_render(options.ffmpegPath, options.path, frames, audioStream, options.type, options.fps); + toast_log(isRendered ? Level::INFO : Level::ERROR, + isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); } cancel(); - } +} - // Stops; the temporary frame folder is removed (a PNG sequence's own folder is kept). - void Recorder::cancel() - { +// Stops. The temporary frame folder is removed (a PNG sequence's own folder is kept). +void Recorder::cancel() +{ std::error_code ec; - if (options.type != RENDER_PNGS && !directory.empty()) std::filesystem::remove_all(directory, ec); + if (options.type != RENDER_PNGS && !directory.empty()) + std::filesystem::remove_all(directory, ec); directory.clear(); frames.clear(); sounds.clear(); index = count = 0; - } +} - bool animation_record(const RecorderOptions& recorderOptions, Canvas& canvas, ShaderProgram& shader, Document& document, - const Animation& animation, glm::vec4 bounds, float scale, glm::vec4 background, - bool isRootTransform) - { +bool animation_record(const RecorderOptions& recorderOptions, Canvas& canvas, ShaderProgram& shader, Document& document, + const Animation& animation, glm::vec4 bounds, float scale, glm::vec4 background, + bool isRootTransform) +{ auto options = recorderOptions; options.isIsolated = options.isBounded = true; Recorder recorder = {}; - if (!recorder.start(options)) return false; + if (!recorder.start(options)) + return false; while (!recorder.is_done()) { - auto pixels = animation_frame_render(canvas, shader, document, animation, recorder.time_get(), bounds, scale, - background, isRootTransform); - if (recorder.frame_capture(std::move(pixels), glm::ivec2(canvas.size))) continue; - recorder.cancel(); - return false; + auto pixels = animation_frame_render(canvas, shader, document, animation, recorder.time_get(), bounds, scale, + background, isRootTransform); + if (recorder.frame_capture(std::move(pixels), glm::ivec2(canvas.size))) + continue; + recorder.cancel(); + return false; } AudioStream audioStream(nullptr); recorder.finish(document, audioStream); return is_path_exist(options.path); - } +} - constexpr float BAKE_MARGIN = 1.0f; - constexpr int BAKED_SIZE_MAX = 4096; +constexpr float BAKE_MARGIN = 1.0f; +constexpr int BAKED_SIZE_MAX = 4096; - // A layer draw alone at canvas pixels, cut to what it can cover (its blur's reach too): its image (straight alpha) and - // the canvas position of the image's top-left. Its tint and color offset go into the pixels only when `isColored`. - static std::optional> draw_bake(Canvas& canvas, ShaderProgram& shader, Document& document, - const Draw& draw, bool isColored) - { +// A layer draw alone at canvas pixels, cut to what it can cover (its blur's reach too): its image (straight alpha) and +// the canvas position of the image's top-left. Its tint and color offset go into the pixels only when `isColored`. +static std::optional> draw_bake(Canvas& canvas, ShaderProgram& shader, Document& document, + const Draw& draw, bool isColored) +{ auto image = document.draw_image_get(draw, draw_scale_get(draw)); - if (!image || !image->is_valid() || draw.frame.size == glm::vec2()) return {}; + if (!image || !image->is_valid() || draw.frame.size == glm::vec2()) + return {}; auto quad = draw.parent * draw_quad_model_get(draw); glm::vec2 low{std::numeric_limits::max()}; glm::vec2 high{std::numeric_limits::lowest()}; for (auto corner : {glm::vec2(0.0f), glm::vec2(1.0f, 0.0f), glm::vec2(0.0f, 1.0f), glm::vec2(1.0f)}) { - auto point = glm::vec2(quad * glm::vec4(corner, 0.0f, 1.0f)); - low = glm::min(low, point); - high = glm::max(high, point); + auto point = glm::vec2(quad * glm::vec4(corner, 0.0f, 1.0f)); + low = glm::min(low, point); + high = glm::max(high, point); } auto reach = draw.frame.blur + BAKE_MARGIN; low = glm::floor(low - reach); @@ -478,33 +516,39 @@ canvas.unbind(); pixels_unpremultiply(pixels); return std::pair{Image(pixels.data(), size), low}; - } +} - // The game's copy with the layer frames it can't draw baked into images: skewed, blurred or shaded ones, and every - // layer frame under a skewed root or group root, which then goes into the images (the root becomes plain). A layer has one spritesheet in the game, so baked frames stand on a copy of their layer - // ("name (baked)") right after it, one frame per step, while the layer hides them. The images (each once) are packed - // into one spritesheet written to `path`, beside the document; when it can't be, `result` keeps its frames. - void frames_bake(Document& document, Model& result, const std::filesystem::path& path) - { +// The game's copy with the layer frames it can't draw baked into images: skewed, blurred or shaded ones, and every +// layer frame under a skewed root or group root, which then goes into the images (the root becomes plain). A layer has +// one spritesheet in the game, so baked frames stand on a copy of their layer +// ("name (baked)") right after it, one frame per step, while the layer hides them. The images (each once) are packed +// into one spritesheet written to `path`, beside the document. When it can't be, `result` keeps its frames. +void frames_bake(Document& document, Model& result, const std::filesystem::path& path) +{ auto game = result; - auto is_baked = [](const Frame& frame) - { return frame.skew != glm::vec2() || frame.blur > 0.0f || frame.shaderId != -1; }; - auto is_skewed = [](const Track& root) - { return std::ranges::any_of(root.frames, [](const Frame& frame) { return frame.skew != glm::vec2(); }); }; + auto is_baked = [](const Frame& frame) { + return frame.skew != glm::vec2() || frame.blur > 0.0f || frame.shaderId != -1; + }; + auto is_skewed = [](const Track& root) { + return std::ranges::any_of(root.frames, [](const Frame& frame) { return frame.skew != glm::vec2(); }); + }; std::vector indices; for (int i = 0; i < game.animations_count_get(); ++i) { - auto& animation = *game.animation_get(i); - auto isNeeded = is_skewed(animation.root); - tracks_each( - animation.layers, [&](const Track& track, const TrackGroup* group) - { isNeeded |= (group && is_skewed(group->root)) || std::ranges::any_of(track.frames, is_baked); }); - if (isNeeded) indices.push_back(i); + auto& animation = *game.animation_get(i); + auto isNeeded = is_skewed(animation.root); + tracks_each(animation.layers, [&](const Track& track, const TrackGroup* group) { + isNeeded |= (group && is_skewed(group->root)) || std::ranges::any_of(track.frames, is_baked); + }); + if (isNeeded) + indices.push_back(i); } auto pathUtf8 = path_to_utf8(path); - if (indices.empty()) return; - if (!SDL_GL_GetCurrentContext()) return toast_log(Level::WARNING, TOAST_BAKE_NO_OPENGL, pathUtf8); + if (indices.empty()) + return; + if (!SDL_GL_GetCurrentContext()) + return toast_log(Level::WARNING, TOAST_BAKE_NO_OPENGL, pathUtf8); auto& textureInfo = SHADERS[SHADER_TEXTURE]; ShaderProgram shader(textureInfo.vertex, textureInfo.fragment); @@ -514,187 +558,192 @@ std::vector images; std::map> imageHashes; - auto image_index_get = [&](Image image) - { - auto hash = - std::hash{}(std::string_view((const char*)image.pixels.data(), image.pixels.size())); - for (auto index : imageHashes[hash]) - if (images[index].size == image.size && images[index].pixels == image.pixels) return index; - imageHashes[hash].push_back((int)images.size()); - images.push_back(std::move(image)); - return (int)images.size() - 1; + auto image_index_get = [&](Image image) { + auto hash = + std::hash{}(std::string_view((const char*)image.pixels.data(), image.pixels.size())); + for (auto index : imageHashes[hash]) + if (images[index].size == image.size && images[index].pixels == image.pixels) + return index; + imageHashes[hash].push_back((int)images.size()); + images.push_back(std::move(image)); + return (int)images.size() - 1; }; std::map bakedLayerIds; - auto baked_layer_id_get = [&](int layerId) - { - auto [it, isNew] = bakedLayerIds.try_emplace(layerId); - if (!isNew) return it->second; - auto layer = item_get(content.layers, layerId); - it->second = item_next_id_get(content.layers); - content.layers.push_back({.id = it->second, - .name = (layer ? layer->name : std::string{}) + " (baked)", - .spritesheetId = spritesheetId}); - return it->second; + auto baked_layer_id_get = [&](int layerId) { + auto [it, isNew] = bakedLayerIds.try_emplace(layerId); + if (!isNew) + return it->second; + auto layer = item_get(content.layers, layerId); + it->second = item_next_id_get(content.layers); + content.layers.push_back({.id = it->second, + .name = (layer ? layer->name : std::string{}) + " (baked)", + .spritesheetId = spritesheetId}); + return it->second; }; // Steps alike join into one frame. - auto step_add = [](Track& track, Frame frame) - { - frame.duration = FRAME_DURATION_MIN; - frame.interpolation = Interpolation::NONE; - if (!track.frames.empty()) - { - auto last = track.frames.back(); - last.uid = frame.uid; - last.duration = frame.duration; - if (last == frame) return (void)++track.frames.back().duration; - } - track.frames.push_back(frame); + auto step_add = [](Track& track, Frame frame) { + frame.duration = FRAME_DURATION_MIN; + frame.interpolation = Interpolation::NONE; + if (!track.frames.empty()) + { + auto last = track.frames.back(); + last.uid = frame.uid; + last.duration = frame.duration; + if (last == frame) + return (void)++track.frames.back().duration; + } + track.frames.push_back(frame); }; for (auto index : indices) { - auto& animation = *game.animation_edit(index); - auto isRootFolded = is_skewed(animation.root); - // A layer track's baked copy, the track left with the rest; nothing when no frame of it bakes. - auto track_bake = [&](Track& track, const Track* groupRoot) -> std::optional - { - auto isForced = isRootFolded || groupRoot; - auto layer = item_get(content.layers, track.id); - if (!layer || (!isForced && std::ranges::none_of(track.frames, is_baked))) return {}; - Track plain = track; - plain.frames.clear(); - Track baked = {.type = ItemType::LAYER, .id = -1, .isVisible = track.isVisible}; - auto isBaked = false; - auto length = std::max(track_length_get(track), animation.frameNum); - for (int time = 0; time < length; ++time) - { - auto frame = frame_generate(track, (float)time); - std::optional> bakedImage{}; - Draw draw{.type = DrawType::LAYER, - .id = track.id, - .time = (float)time, - .frame = frame, - .source = &document.model, - .spritesheetId = layer->spritesheetId}; - if (frame.isVisible && (isForced || is_baked(frame))) - { - for (auto* root : - std::initializer_list{isRootFolded ? &animation.root : nullptr, groupRoot}) - if (root) - { - auto rootFrame = frame_generate(*root, (float)time); - draw.parent *= frame_parent_model_get(rootFrame); - draw.frame.tint *= rootFrame.tint; - draw.frame.colorOffset += rootFrame.colorOffset; - } - bakedImage = draw_bake(canvas, shader, document, draw, draw.frame.shaderId != -1); - } - if (!bakedImage) - { - step_add(plain, frame); - step_add(baked, Frame{.isVisible = false}); + auto& animation = *game.animation_edit(index); + auto isRootFolded = is_skewed(animation.root); + // A layer track's baked copy, the track left with the rest. Nothing when no frame of it bakes. + auto track_bake = [&](Track& track, const Track* groupRoot) -> std::optional { + auto isForced = isRootFolded || groupRoot; + auto layer = item_get(content.layers, track.id); + if (!layer || (!isForced && std::ranges::none_of(track.frames, is_baked))) + return {}; + Track plain = track; + plain.frames.clear(); + Track baked = {.type = ItemType::LAYER, .id = -1, .isVisible = track.isVisible}; + auto isBaked = false; + auto length = std::max(track_length_get(track), animation.frameNum); + for (int time = 0; time < length; ++time) + { + auto frame = frame_generate(track, (float)time); + std::optional> bakedImage{}; + Draw draw{.type = DrawType::LAYER, + .id = track.id, + .time = (float)time, + .frame = frame, + .source = &document.model, + .spritesheetId = layer->spritesheetId}; + if (frame.isVisible && (isForced || is_baked(frame))) + { + for (auto* root : + std::initializer_list{isRootFolded ? &animation.root : nullptr, groupRoot}) + if (root) + { + auto rootFrame = frame_generate(*root, (float)time); + draw.parent *= frame_parent_model_get(rootFrame); + draw.frame.tint *= rootFrame.tint; + draw.frame.colorOffset += rootFrame.colorOffset; + } + bakedImage = draw_bake(canvas, shader, document, draw, draw.frame.shaderId != -1); + } + if (!bakedImage) + { + step_add(plain, frame); + step_add(baked, Frame{.isVisible = false}); + continue; + } + // The image stands where it was drawn, its region found once the images are packed (kept in regionId). + auto step = draw.frame; + if (step.shaderId != -1) + { + step.tint = glm::vec4(1.0f); + step.colorOffset = {}; + } + step.crop = {}; + step.size = glm::vec2(bakedImage->first.size); + step.pivot = {}; + step.position = bakedImage->second; + step.scale = Frame{}.scale; + step.skew = {}; + step.rotation = 0.0f; + step.blur = 0.0f; + step.shaderId = -1; + step.regionId = image_index_get(std::move(bakedImage->first)); + step_add(baked, step); + step_add(plain, Frame{.isVisible = false}); + isBaked = true; + } + if (!isBaked) + return {}; + baked.id = baked_layer_id_get(track.id); + track = std::move(plain); + return baked; + }; + + std::vector entries; + for (auto& entry : animation.layers) + if (auto track = std::get_if(&entry)) + { + auto baked = track_bake(*track, nullptr); + entries.emplace_back(std::move(*track)); + if (baked) + entries.emplace_back(std::move(*baked)); + } + else + { + auto group = std::get(entry); + auto isGroupFolded = is_skewed(group.root); + std::vector tracks; + for (auto& groupTrack : group.tracks) + { + auto baked = track_bake(groupTrack, isGroupFolded ? &group.root : nullptr); + tracks.push_back(std::move(groupTrack)); + if (baked) + tracks.push_back(std::move(*baked)); + } + group.tracks = std::move(tracks); + if (isGroupFolded) + group.root = TrackGroup{}.root; + entries.emplace_back(std::move(group)); + } + animation.layers = std::move(entries); + + // A folded root's transform goes into the nulls too (their group roots first), and the root becomes plain. + if (!isRootFolded) continue; - } - // The image stands where it was drawn, its region found once the images are packed (kept in regionId). - auto step = draw.frame; - if (step.shaderId != -1) - { - step.tint = glm::vec4(1.0f); - step.colorOffset = {}; - } - step.crop = {}; - step.size = glm::vec2(bakedImage->first.size); - step.pivot = {}; - step.position = bakedImage->second; - step.scale = Frame{}.scale; - step.skew = {}; - step.rotation = 0.0f; - step.blur = 0.0f; - step.shaderId = -1; - step.regionId = image_index_get(std::move(bakedImage->first)); - step_add(baked, step); - step_add(plain, Frame{.isVisible = false}); - isBaked = true; - } - if (!isBaked) return {}; - baked.id = baked_layer_id_get(track.id); - track = std::move(plain); - return baked; - }; - - std::vector entries; - for (auto& entry : animation.layers) - if (auto track = std::get_if(&entry)) - { - auto baked = track_bake(*track, nullptr); - entries.emplace_back(std::move(*track)); - if (baked) entries.emplace_back(std::move(*baked)); - } - else - { - auto group = std::get(entry); - auto isGroupFolded = is_skewed(group.root); - std::vector tracks; - for (auto& groupTrack : group.tracks) - { - auto baked = track_bake(groupTrack, isGroupFolded ? &group.root : nullptr); - tracks.push_back(std::move(groupTrack)); - if (baked) tracks.push_back(std::move(*baked)); - } - group.tracks = std::move(tracks); - if (isGroupFolded) group.root = TrackGroup{}.root; - entries.emplace_back(std::move(group)); - } - animation.layers = std::move(entries); - - // A folded root's transform goes into the nulls too (their group roots first), and the root becomes plain. - if (!isRootFolded) continue; - for (auto& entry : animation.nulls) - if (auto track = std::get_if(&entry)) - track_group_root_bake(*track, animation.root, animation.frameNum); - else - { - auto& group = std::get(entry); - for (auto& groupTrack : group.tracks) - { - track_group_root_bake(groupTrack, group.root, animation.frameNum); - track_group_root_bake(groupTrack, animation.root, animation.frameNum); - } - group.root = TrackGroup{}.root; - } - animation.root = Animation{}.root; + for (auto& entry : animation.nulls) + if (auto track = std::get_if(&entry)) + track_group_root_bake(*track, animation.root, animation.frameNum); + else + { + auto& group = std::get(entry); + for (auto& groupTrack : group.tracks) + { + track_group_root_bake(groupTrack, group.root, animation.frameNum); + track_group_root_bake(groupTrack, animation.root, animation.frameNum); + } + group.root = TrackGroup{}.root; + } + animation.root = Animation{}.root; } - if (images.empty()) return; + if (images.empty()) + return; std::vector sizes{}; for (auto& image : images) - sizes.push_back(image.size); + sizes.push_back(image.size); glm::ivec2 packedSize{}; std::vector positions{}; rects_pack(sizes, packedSize, positions); std::vector parts; for (int i = 0; i < (int)images.size(); ++i) - parts.push_back({.image = &images[i], .size = images[i].size, .destination = positions[i]}); + parts.push_back({.image = &images[i], .size = images[i].size, .destination = positions[i]}); if (!Image::compose(parts, packedSize, false).write_png(path)) - return toast_log(Level::ERROR, TOAST_BAKE_WRITE_FAILED, pathUtf8); + return toast_log(Level::ERROR, TOAST_BAKE_WRITE_FAILED, pathUtf8); if (packedSize.x > BAKED_SIZE_MAX || packedSize.y > BAKED_SIZE_MAX) - toast_log(Level::WARNING, TOAST_BAKE_LARGE, pathUtf8, packedSize.x, packedSize.y, BAKED_SIZE_MAX); + toast_log(Level::WARNING, TOAST_BAKE_LARGE, pathUtf8, packedSize.x, packedSize.y, BAKED_SIZE_MAX); content.spritesheets.push_back({.id = spritesheetId, .path = path.filename()}); std::set bakedIds; for (auto [layerId, bakedId] : bakedLayerIds) - bakedIds.insert(bakedId); + bakedIds.insert(bakedId); for (auto index : indices) - tracks_each(game.animation_edit(index)->layers, - [&](Track& track, auto*) - { - if (!bakedIds.contains(track.id)) return; - for (auto& frame : track.frames) - if (frame.regionId != -1) - { - frame.crop = glm::vec2(positions[frame.regionId]); - frame.regionId = -1; - } - }); + tracks_each(game.animation_edit(index)->layers, [&](Track& track, auto*) { + if (!bakedIds.contains(track.id)) + return; + for (auto& frame : track.frames) + if (frame.regionId != -1) + { + frame.crop = glm::vec2(positions[frame.regionId]); + frame.regionId = -1; + } + }); result = std::move(game); - } +} diff --git a/src/render.h b/src/render.h index a838ed1..76ad196 100644 --- a/src/render.h +++ b/src/render.h @@ -12,132 +12,135 @@ struct SDL_Window; struct SDL_GLContextState; - class Canvas; - class Document; +class Canvas; +class Document; - struct Animation; - class Model; +struct Animation; +class Model; - class ShaderProgram; +class ShaderProgram; #define RENDER_LIST \ - X(RENDER_PNGS, "PNGs", "") \ - X(RENDER_SPRITESHEET, "Spritesheet (PNG)", ".png") \ - X(RENDER_GIF, "GIF", ".gif") \ - X(RENDER_WEBM, "WebM", ".webm") \ - X(RENDER_OGV, "OGV", ".ogv") \ - X(RENDER_MP4, "MP4", ".mp4") + X(RENDER_PNGS, "PNGs", "") \ + X(RENDER_SPRITESHEET, "Spritesheet (PNG)", ".png") \ + X(RENDER_GIF, "GIF", ".gif") \ + X(RENDER_WEBM, "WebM", ".webm") \ + X(RENDER_OGV, "OGV", ".ogv") \ + X(RENDER_MP4, "MP4", ".mp4") - enum RenderType - { +enum RenderType +{ #define X(symbol, string, extension) symbol, RENDER_LIST #undef X RENDER_COUNT - }; +}; - enum FpsMode - { +enum FpsMode +{ FPS_ANIMATION, FPS_PLAYBACK_RATE, FPS_COUNT - }; +}; - constexpr const char* RENDER_STRINGS[] = { +constexpr const char* RENDER_STRINGS[] = { #define X(symbol, string, extension) string, - RENDER_LIST + RENDER_LIST #undef X - }; +}; - constexpr const char* RENDER_EXTENSIONS[] = { +constexpr const char* RENDER_EXTENSIONS[] = { #define X(symbol, string, extension) extension, - RENDER_LIST + RENDER_LIST #undef X - }; +}; - struct SpritesheetLayout - { +struct SpritesheetLayout +{ int rows = 0; int columns = 0; - }; +}; - inline int frame_count_get(int start, int end) { return std::max(end - start + 1, 1); } +inline int frame_count_get(int start, int end) +{ + return std::max(end - start + 1, 1); +} - inline int frame_count_get(int start, int end, int animationFps, int renderFps) - { +inline int frame_count_get(int start, int end, int animationFps, int renderFps) +{ animationFps = std::max(animationFps, 1); renderFps = std::max(renderFps, 1); auto duration = (double)frame_count_get(start, end) / (double)animationFps; return std::max((int)std::ceil(duration * (double)renderFps), 1); - } +} - inline float frame_time_get(int start, int frameIndex, int animationFps, int renderFps) - { +inline float frame_time_get(int start, int frameIndex, int animationFps, int renderFps) +{ animationFps = std::max(animationFps, 1); renderFps = std::max(renderFps, 1); return (float)start + ((float)frameIndex * ((float)animationFps / (float)renderFps)); - } +} - inline int fps_get(int mode, int animationFps, int playbackRate) - { +inline int fps_get(int mode, int animationFps, int playbackRate) +{ switch (mode) { - case FPS_PLAYBACK_RATE: - return std::max(playbackRate, 1); - case FPS_ANIMATION: - default: - return std::max(animationFps, 1); + case FPS_PLAYBACK_RATE: + return std::max(playbackRate, 1); + case FPS_ANIMATION: + default: + return std::max(animationFps, 1); } - } +} - inline SpritesheetLayout spritesheet_layout_get(int rows, int columns, int frameCount) - { +inline SpritesheetLayout spritesheet_layout_get(int rows, int columns, int frameCount) +{ frameCount = std::max(frameCount, 1); rows = std::max(rows, 0); columns = std::max(columns, 0); if (rows == 0 && columns == 0) { - columns = std::max((int)std::ceil(std::sqrt((float)frameCount)), 1); - rows = (frameCount + columns - 1) / columns; + columns = std::max((int)std::ceil(std::sqrt((float)frameCount)), 1); + rows = (frameCount + columns - 1) / columns; } else if (rows == 0) - rows = (frameCount + columns - 1) / columns; + rows = (frameCount + columns - 1) / columns; else if (columns == 0) - columns = (frameCount + rows - 1) / rows; + columns = (frameCount + rows - 1) / rows; else if (rows * columns < frameCount) { - if (rows <= columns) - columns = (frameCount + rows - 1) / rows; - else - rows = (frameCount + columns - 1) / columns; + if (rows <= columns) + columns = (frameCount + rows - 1) / rows; + else + rows = (frameCount + columns - 1) / columns; } return {rows, columns}; - } +} - // An OpenGL context with no visible window, for drawing animations outside the editor (the CLI, render tests). - class HeadlessGL - { +// An OpenGL context with no visible window, for drawing animations outside the editor (the CLI, render tests). +class HeadlessGL +{ SDL_Window* window = nullptr; SDL_GLContextState* context = nullptr; - public: +public: HeadlessGL(); ~HeadlessGL(); bool is_valid() const; - }; +}; - // The area an animation covers over all its frames (or a default one when it draws nothing). - glm::vec4 animation_bounds_get(const Document&, const Animation&, bool); - // One frame drawn over `bounds` at `scale`, as premultiplied RGBA rows from the top. - std::vector animation_frame_render(Canvas&, ShaderProgram&, Document&, const Animation&, float, - glm::vec4, float, glm::vec4, bool); - void pixels_unpremultiply(std::vector&); - void frames_bake(Document&, Model&, const std::filesystem::path&); +// The area an animation covers over all its frames (or a default one when it draws nothing). +glm::vec4 animation_bounds_get(const Document&, const Animation&, bool); +// One frame drawn over `bounds` at `scale`, as premultiplied RGBA rows from the top. +std::vector animation_frame_render(Canvas&, ShaderProgram&, Document&, const Animation&, float, glm::vec4, + float, glm::vec4, bool); +void pixels_unpremultiply(std::vector&); +void frames_bake(Document&, Model&, const std::filesystem::path&); - struct RecorderOptions - { +struct RecorderOptions +{ RenderType type = {}; std::filesystem::path path; std::filesystem::path format; @@ -151,13 +154,13 @@ struct SDL_GLContextState; bool isSound = false; bool isIsolated = false; bool isBounded = false; - }; +}; - // A render in progress: which animation times to capture, the frames captured so far (written to disk) and the - // trigger sounds of each, and assembling the output when done. - class Recorder - { - public: +// A render in progress: which animation times to capture, the frames captured so far (written to disk) and the +// trigger sounds of each, and assembling the output when done. +class Recorder +{ +public: RecorderOptions options = {}; int index = 0; int count = 0; @@ -170,18 +173,18 @@ struct SDL_GLContextState; void finish(const Document&, AudioStream&); void cancel(); - private: +private: std::filesystem::path directory; std::vector frames; std::vector> sounds; int soundTime = -1; - }; +}; - // Records a whole animation with these options (bounded and isolated), each frame drawn as animation_frame_render - // draws it; false when a frame or the output can't be written. - bool animation_record(const RecorderOptions&, Canvas&, ShaderProgram&, Document&, const Animation&, - glm::vec4, float, glm::vec4, bool); +// Records a whole animation with these options (bounded and isolated), each frame drawn as animation_frame_render +// draws it. False when a frame or the output can't be written. +bool animation_record(const RecorderOptions&, Canvas&, ShaderProgram&, Document&, const Animation&, glm::vec4, float, + glm::vec4, bool); - std::filesystem::path ffmpeg_log_path(); - bool animation_render(const std::filesystem::path&, const std::filesystem::path&, - const std::vector&, AudioStream&, RenderType, int); +std::filesystem::path ffmpeg_log_path(); +bool animation_render(const std::filesystem::path&, const std::filesystem::path&, + const std::vector&, AudioStream&, RenderType, int); diff --git a/src/resources.cpp b/src/resources.cpp index 77cffb7..d4e48e3 100644 --- a/src/resources.cpp +++ b/src/resources.cpp @@ -16,44 +16,52 @@ static constexpr int CHINESE_FALLBACK_NUMBER = 2; static constexpr int KOREAN_FALLBACK_NUMBER = 1; #endif - Resources::Resources() - { +Resources::Resources() +{ auto isKoreanFallback = std::filesystem::exists(KOREAN_FALLBACK); auto isChineseFallback = std::filesystem::exists(CHINESE_FALLBACK); - if (!isKoreanFallback) logger.error(std::format("Failed to load Korean fallback font: {}", KOREAN_FALLBACK)); - if (!isChineseFallback) logger.error(std::format("Failed to load Chinese fallback font: {}", CHINESE_FALLBACK)); + if (!isKoreanFallback) + logger.error(std::format("Failed to load Korean fallback font: {}", KOREAN_FALLBACK)); + if (!isChineseFallback) + logger.error(std::format("Failed to load Chinese fallback font: {}", CHINESE_FALLBACK)); for (auto [i, fontInfo] : std::views::enumerate(FONTS)) { - fonts[i] = Font((void*)fontInfo->data, fontInfo->size, FONT_SIZE); - if (isKoreanFallback) - fonts[i].append(KOREAN_FALLBACK, FONT_SIZE, KOREAN_FALLBACK_NUMBER); - else - fonts[i].append((void*)FONT_KOREAN_TTF.data, FONT_KOREAN_TTF.size, FONT_SIZE); - if (isChineseFallback) - fonts[i].append(CHINESE_FALLBACK, FONT_SIZE, CHINESE_FALLBACK_NUMBER); - else - fonts[i].append((void*)FONT_CHINESE_TTF.data, FONT_CHINESE_TTF.size, FONT_SIZE); + fonts[i] = Font((void*)fontInfo->data, fontInfo->size, FONT_SIZE); + if (isKoreanFallback) + fonts[i].append(KOREAN_FALLBACK, FONT_SIZE, KOREAN_FALLBACK_NUMBER); + else + fonts[i].append((void*)FONT_KOREAN_TTF.data, FONT_KOREAN_TTF.size, FONT_SIZE); + if (isChineseFallback) + fonts[i].append(CHINESE_FALLBACK, FONT_SIZE, CHINESE_FALLBACK_NUMBER); + else + fonts[i].append((void*)FONT_CHINESE_TTF.data, FONT_CHINESE_TTF.size, FONT_SIZE); } for (auto [i, iconInfo] : std::views::enumerate(ICONS)) - icons[i] = texture_svg_load((const char*)iconInfo.svg->data, iconInfo.svg->size, iconInfo.size); + icons[i] = texture_svg_load((const char*)iconInfo.svg->data, iconInfo.svg->size, iconInfo.size); for (auto [i, shaderInfo] : std::views::enumerate(SHADERS)) - shaders[i] = ShaderProgram(shaderInfo.vertex, shaderInfo.fragment); - }; + shaders[i] = ShaderProgram(shaderInfo.vertex, shaderInfo.fragment); +}; - GLuint Resources::icon_id_get(int icon) { return texture_id_get(icons[icon]); } +GLuint Resources::icon_id_get(int icon) +{ + return texture_id_get(icons[icon]); +} - AudioData& Resources::music_track() - { +AudioData& Resources::music_track() +{ if (!isMusicLoaded) { - music = AudioData(MUSIC_ABOUT_OPUS.data, MUSIC_ABOUT_OPUS.size); - isMusicLoaded = true; + music = AudioData(MUSIC_ABOUT_OPUS.data, MUSIC_ABOUT_OPUS.size); + isMusicLoaded = true; } return music; - } +} - AudioData* Resources::music_track_if_loaded() { return isMusicLoaded ? &music : nullptr; } +AudioData* Resources::music_track_if_loaded() +{ + return isMusicLoaded ? &music : nullptr; +} diff --git a/src/resources.h b/src/resources.h index e37d58f..bbdde61 100644 --- a/src/resources.h +++ b/src/resources.h @@ -8,9 +8,9 @@ #include "shader.h" #include "texture.h" - class Resources - { - public: +class Resources +{ +public: Font fonts[FONT_COUNT]{}; Image icons[ICON_COUNT]{}; ShaderProgram shaders[SHADER_COUNT]{}; @@ -21,6 +21,6 @@ AudioData& music_track(); AudioData* music_track_if_loaded(); - private: +private: bool isMusicLoaded = false; - }; +}; diff --git a/src/sdl.cpp b/src/sdl.cpp index 741881b..15510fa 100644 --- a/src/sdl.cpp +++ b/src/sdl.cpp @@ -5,11 +5,12 @@ #include "path.h" - std::filesystem::path preferences_directory_get() - { +std::filesystem::path preferences_directory_get() +{ auto sdlPath = SDL_GetPrefPath(nullptr, "anm2ed"); - if (!sdlPath) return {}; + if (!sdlPath) + return {}; auto filePath = path_from_utf8(sdlPath); SDL_free(sdlPath); return filePath; - } +} diff --git a/src/sdl.h b/src/sdl.h index e7d87d6..682df5a 100644 --- a/src/sdl.h +++ b/src/sdl.h @@ -2,4 +2,4 @@ #include - std::filesystem::path preferences_directory_get(); +std::filesystem::path preferences_directory_get(); diff --git a/src/selection.cpp b/src/selection.cpp index 0dd560c..8094c82 100644 --- a/src/selection.cpp +++ b/src/selection.cpp @@ -1,133 +1,148 @@ #include "selection.h" - std::set selection_references_get(const Selection& selection, const UidIndex& index, - SelectionKind kind) - { +std::set selection_references_get(const Selection& selection, const UidIndex& index, SelectionKind kind) +{ std::set references; if (auto uids = selection.uids.find(kind); uids != selection.uids.end()) - for (auto uid : uids->second) - if (auto reference = index.reference_get(uid)) references.insert(*reference); + for (auto uid : uids->second) + if (auto reference = index.reference_get(uid)) + references.insert(*reference); return references; - } +} - static std::uint64_t handle_uid_get(Handle handle) - { +static std::uint64_t handle_uid_get(Handle handle) +{ return handle.frame ? handle.frame : handle.item ? handle.item : handle.animation; - } +} - void selection_references_set(Selection& selection, const Model& model, SelectionKind kind, - const std::set& references) - { +void selection_references_set(Selection& selection, const Model& model, SelectionKind kind, + const std::set& references) +{ auto& uids = selection.uids[kind]; uids.clear(); for (auto reference : references) - if (auto uid = handle_uid_get(model.handle_get(reference, kind == SelectionKind::GROUPS))) uids.insert(uid); - } + if (auto uid = handle_uid_get(model.handle_get(reference, kind == SelectionKind::GROUPS))) + uids.insert(uid); +} - // The most specific part of the focus that still exists. - Reference selection_focus_get(const Selection& selection, const UidIndex& index) - { +// The most specific part of the focus that still exists. +Reference selection_focus_get(const Selection& selection, const UidIndex& index) +{ for (auto uid : {selection.focus.frame, selection.focus.item, selection.focus.animation}) - if (auto reference = index.reference_get(uid)) return *reference; + if (auto reference = index.reference_get(uid)) + return *reference; return {}; - } +} - void selection_focus_set(Selection& selection, const Model& model, Reference reference) - { +void selection_focus_set(Selection& selection, const Model& model, Reference reference) +{ selection.focus = model.handle_get(reference); - } +} - // (id, uid) of every content item a kind selects from. - static std::vector> content_keys_get(const Selection& selection, const Model& model, - SelectionKind kind) - { +// (id, uid) of every content item a kind selects from. +static std::vector> content_keys_get(const Selection& selection, const Model& model, + SelectionKind kind) +{ std::vector> keys; - auto add = [&](const auto& items) - { - for (auto& item : items) - keys.emplace_back(item.id, item.uid); + auto add = [&](const auto& items) { + for (auto& item : items) + keys.emplace_back(item.id, item.uid); }; auto& content = model.content; - if (kind == SelectionKind::SPRITESHEETS) add(content.spritesheets); - if (kind == SelectionKind::SHADERS) add(content.shaders); - if (kind == SelectionKind::LAYERS) add(content.layers); - if (kind == SelectionKind::NULLS) add(content.nulls); - if (kind == SelectionKind::EVENTS) add(content.events); - if (kind == SelectionKind::SOUNDS) add(content.sounds); - if (kind == SelectionKind::LIBRARIES) add(content.libraries); + if (kind == SelectionKind::SPRITESHEETS) + add(content.spritesheets); + if (kind == SelectionKind::SHADERS) + add(content.shaders); + if (kind == SelectionKind::LAYERS) + add(content.layers); + if (kind == SelectionKind::NULLS) + add(content.nulls); + if (kind == SelectionKind::EVENTS) + add(content.events); + if (kind == SelectionKind::SOUNDS) + add(content.sounds); + if (kind == SelectionKind::LIBRARIES) + add(content.libraries); if (kind == SelectionKind::REGIONS) - if (auto spritesheet = item_get(content.spritesheets, - selection_focus_id_get(selection, model, SelectionKind::SPRITESHEETS))) - add(spritesheet->regions); + if (auto spritesheet = + item_get(content.spritesheets, selection_focus_id_get(selection, model, SelectionKind::SPRITESHEETS))) + add(spritesheet->regions); return keys; - } +} - std::set selection_ids_get(const Selection& selection, const Model& model, SelectionKind kind) - { +std::set selection_ids_get(const Selection& selection, const Model& model, SelectionKind kind) +{ std::set ids; auto uids = selection.uids.find(kind); - if (uids == selection.uids.end()) return ids; + if (uids == selection.uids.end()) + return ids; for (auto [id, uid] : content_keys_get(selection, model, kind)) - if (uids->second.contains(uid)) ids.insert(id); + if (uids->second.contains(uid)) + ids.insert(id); return ids; - } +} - void selection_ids_set(Selection& selection, const Model& model, SelectionKind kind, const std::set& ids) - { +void selection_ids_set(Selection& selection, const Model& model, SelectionKind kind, const std::set& ids) +{ auto& uids = selection.uids[kind]; uids.clear(); for (auto [id, uid] : content_keys_get(selection, model, kind)) - if (ids.contains(id)) uids.insert(uid); - } + if (ids.contains(id)) + uids.insert(uid); +} - int selection_focus_id_get(const Selection& selection, const Model& model, SelectionKind kind) - { +int selection_focus_id_get(const Selection& selection, const Model& model, SelectionKind kind) +{ auto focus = selection.focuses.find(kind); - if (focus == selection.focuses.end()) return -1; + if (focus == selection.focuses.end()) + return -1; for (auto [id, uid] : content_keys_get(selection, model, kind)) - if (uid == focus->second) return id; + if (uid == focus->second) + return id; return -1; - } +} - void selection_focus_id_set(Selection& selection, const Model& model, SelectionKind kind, int id) - { +void selection_focus_id_set(Selection& selection, const Model& model, SelectionKind kind, int id) +{ selection.focuses.erase(kind); for (auto [itemId, uid] : content_keys_get(selection, model, kind)) - if (itemId == id) - { - selection.focuses[kind] = uid; - return; - } - } + if (itemId == id) + { + selection.focuses[kind] = uid; + return; + } +} - // After an edit: drops uids that no longer exist, and moves a focus whose element was removed to its nearest - // survivor (a frame at the same index of its track, the animation's root track, or the nearest animation). - void selection_follow(Selection& selection, const Model& model, const UidIndex& index, Reference before) - { +// After an edit: drops uids that no longer exist, and moves a focus whose element was removed to its nearest +// survivor (a frame at the same index of its track, the animation's root track, or the nearest animation). +void selection_follow(Selection& selection, const Model& model, const UidIndex& index, Reference before) +{ for (auto& [kind, uids] : selection.uids) - if (kind < SelectionKind::SPRITESHEETS) - std::erase_if(uids, [&](std::uint64_t uid) { return !index.contains(uid); }); + if (kind < SelectionKind::SPRITESHEETS) + std::erase_if(uids, [&](std::uint64_t uid) { return !index.contains(uid); }); auto [animationUid, itemUid, frameUid] = selection.focus; - auto is_removed = [&](std::uint64_t uid) { return uid && !index.contains(uid); }; + auto is_removed = [&](std::uint64_t uid) { + return uid && !index.contains(uid); + }; auto reference = selection_focus_get(selection, index); if (is_removed(animationUid) || !animationUid) { - auto count = model.animations_count_get(); - reference = - count > 0 && animationUid ? Reference{std::clamp(before.animationIndex, 0, count - 1), ROOT} : Reference{}; + auto count = model.animations_count_get(); + reference = + count > 0 && animationUid ? Reference{std::clamp(before.animationIndex, 0, count - 1), ROOT} : Reference{}; } else if (is_removed(itemUid)) - reference = {reference.animationIndex, ROOT}; + reference = {reference.animationIndex, ROOT}; else if (is_removed(frameUid)) { - auto track = model.track_get(reference); - auto count = track ? (int)track->frames.size() : 0; - reference.frameIndex = count > 0 ? std::clamp(before.frameIndex, 0, count - 1) : -1; + auto track = model.track_get(reference); + auto count = track ? (int)track->frames.size() : 0; + reference.frameIndex = count > 0 ? std::clamp(before.frameIndex, 0, count - 1) : -1; } else - return; + return; selection_focus_set(selection, model, reference); - } +} diff --git a/src/selection.h b/src/selection.h index 7a74a3a..f8e8c3d 100644 --- a/src/selection.h +++ b/src/selection.h @@ -5,8 +5,8 @@ #include "model/model.h" - enum class SelectionKind - { +enum class SelectionKind +{ ANIMATIONS, ANIMATION_GROUPS, TRACKS, @@ -20,27 +20,27 @@ EVENTS, SOUNDS, LIBRARIES - }; +}; - // What is selected, by element uid, plus the focused animation/track/frame. uids follow elements through edits, - // so nothing here is repaired by index; the UI reads it as References through a UidIndex. - struct Selection - { +// What is selected, by element uid, plus the focused animation/track/frame. uids follow elements through edits, +// so nothing here is repaired by index. The UI reads it as References through a UidIndex. +struct Selection +{ std::map> uids; Handle focus = {}; std::map focuses; bool operator==(const Selection&) const = default; - }; +}; - std::set selection_references_get(const Selection&, const UidIndex&, SelectionKind); - void selection_references_set(Selection&, const Model&, SelectionKind, const std::set&); - Reference selection_focus_get(const Selection&, const UidIndex&); - void selection_focus_set(Selection&, const Model&, Reference); - // Content items (spritesheets, regions of the focused spritesheet, shaders, layers, ...) are selected by uid and - // read back as ids. - std::set selection_ids_get(const Selection&, const Model&, SelectionKind); - void selection_ids_set(Selection&, const Model&, SelectionKind, const std::set&); - int selection_focus_id_get(const Selection&, const Model&, SelectionKind); - void selection_focus_id_set(Selection&, const Model&, SelectionKind, int); - void selection_follow(Selection&, const Model&, const UidIndex&, Reference); +std::set selection_references_get(const Selection&, const UidIndex&, SelectionKind); +void selection_references_set(Selection&, const Model&, SelectionKind, const std::set&); +Reference selection_focus_get(const Selection&, const UidIndex&); +void selection_focus_set(Selection&, const Model&, Reference); +// Content items (spritesheets, regions of the focused spritesheet, shaders, layers, ...) are selected by uid and +// read back as ids. +std::set selection_ids_get(const Selection&, const Model&, SelectionKind); +void selection_ids_set(Selection&, const Model&, SelectionKind, const std::set&); +int selection_focus_id_get(const Selection&, const Model&, SelectionKind); +void selection_focus_id_set(Selection&, const Model&, SelectionKind, int); +void selection_follow(Selection&, const Model&, const UidIndex&, Reference); diff --git a/src/settings.cpp b/src/settings.cpp index c576b4f..dae72d5 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -11,26 +11,28 @@ using namespace glm; - constexpr std::string_view SETTINGS_SHEAR = "Shear"; +constexpr std::string_view SETTINGS_SHEAR = "Shear"; - constexpr const char* COMPONENT_SUFFIXES_XY[] = {"X", "Y"}; - constexpr const char* COMPONENT_SUFFIXES_WH[] = {"W", "H"}; - constexpr const char* COMPONENT_SUFFIXES_RGBA[] = {"R", "G", "B", "A"}; +constexpr const char* COMPONENT_SUFFIXES_XY[] = {"X", "Y"}; +constexpr const char* COMPONENT_SUFFIXES_WH[] = {"W", "H"}; +constexpr const char* COMPONENT_SUFFIXES_RGBA[] = {"R", "G", "B", "A"}; - template - concept GlmVector = requires(T value) { +template +concept GlmVector = requires(T value) { T::length(); value[0]; - }; +}; - static const char* const* component_suffixes_get(std::string_view type) - { - if (type.ends_with("_WH")) return COMPONENT_SUFFIXES_WH; - if (type.starts_with("VEC3") || type.starts_with("VEC4")) return COMPONENT_SUFFIXES_RGBA; +static const char* const* component_suffixes_get(std::string_view type) +{ + if (type.ends_with("_WH")) + return COMPONENT_SUFFIXES_WH; + if (type.starts_with("VEC3") || type.starts_with("VEC4")) + return COMPONENT_SUFFIXES_RGBA; return COMPONENT_SUFFIXES_XY; - } +} - constexpr auto IMGUI_DEFAULT = R"( +constexpr auto IMGUI_DEFAULT = R"( [Window][##DockSpace] Pos=0,54 Size=1918,1007 @@ -181,114 +183,118 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 )"; - Settings::Settings(const std::filesystem::path& path) - { +Settings::Settings(const std::filesystem::path& path) +{ auto pathUtf8 = path_to_utf8(path); if (is_path_exist(path)) - logger.info(std::format("Using settings from: {}", pathUtf8)); + logger.info(std::format("Using settings from: {}", pathUtf8)); else { - logger.warning("Settings file does not exist; using default"); - save(path, IMGUI_DEFAULT); - isDefault = true; + logger.warning("Settings file does not exist; using default"); + save(path, IMGUI_DEFAULT); + isDefault = true; } std::string fileData; if (!file_text_load(path, &fileData, "rb")) { - logger.error(std::format("Failed to open settings file: {}", pathUtf8)); - return; + logger.error(std::format("Failed to open settings file: {}", pathUtf8)); + return; } std::istringstream file(fileData); std::string line; - auto stream_assign = [](auto& dest, std::istringstream& ss) { ss >> dest; }; - - auto value_set = [&](auto& dest, std::istringstream& ss) - { - using T = std::decay_t; - - if constexpr (std::is_same_v) - { - std::string val; - stream_assign(val, ss); - dest = (val == "true" || val == "1"); - } - else if constexpr (std::is_same_v) - { - std::getline(ss, dest); - } - else if constexpr (std::is_same_v) - { - std::string value; - std::getline(ss, value); - dest = path_from_utf8(value); - } - else - { - stream_assign(dest, ss); - } + auto stream_assign = [](auto& dest, std::istringstream& ss) { + ss >> dest; }; - auto entry_load = - [&](const std::string& key, std::istringstream& ss, const std::string& name, auto& value, std::string_view type) - { - using T = std::decay_t; - if constexpr (GlmVector) - { - auto suffixes = component_suffixes_get(type); - for (int i = 0; i < T::length(); ++i) - if (key == name + suffixes[i]) - { - stream_assign(value[i], ss); - return true; - } - } - else if (key == name) - { - value_set(value, ss); - return true; - } + auto value_set = [&](auto& dest, std::istringstream& ss) { + using T = std::decay_t; - return false; + if constexpr (std::is_same_v) + { + std::string val; + stream_assign(val, ss); + dest = (val == "true" || val == "1"); + } + else if constexpr (std::is_same_v) + { + std::getline(ss, dest); + } + else if constexpr (std::is_same_v) + { + std::string value; + std::getline(ss, value); + dest = path_from_utf8(value); + } + else + { + stream_assign(dest, ss); + } + }; + + auto entry_load = [&](const std::string& key, std::istringstream& ss, const std::string& name, auto& value, + std::string_view type) { + using T = std::decay_t; + if constexpr (GlmVector) + { + auto suffixes = component_suffixes_get(type); + for (int i = 0; i < T::length(); ++i) + if (key == name + suffixes[i]) + { + stream_assign(value[i], ss); + return true; + } + } + else if (key == name) + { + value_set(value, ss); + return true; + } + + return false; }; while (std::getline(file, line)) { - if (line == "[Settings]" || line.empty()) continue; - if (line == "# Dear ImGui") break; + if (line == "[Settings]" || line.empty()) + continue; + if (line == "# Dear ImGui") + break; - auto eq = line.find('='); - if (eq == std::string::npos) continue; + auto eq = line.find('='); + if (eq == std::string::npos) + continue; - auto key = line.substr(0, eq); - // Skew settings were once named for shear. - if (auto legacy = key.find(SETTINGS_SHEAR); legacy != std::string::npos) - key.replace(legacy, SETTINGS_SHEAR.size(), "Skew"); - std::istringstream ss(line.substr(eq + 1)); + auto key = line.substr(0, eq); + // Skew settings were once named for shear. + if (auto legacy = key.find(SETTINGS_SHEAR); legacy != std::string::npos) + key.replace(legacy, SETTINGS_SHEAR.size(), "Skew"); + std::istringstream ss(line.substr(eq + 1)); #define X(symbol, name, string, type, ...) \ - if (entry_load(key, ss, #name, name, #type)) continue; - SETTINGS_MEMBERS SETTINGS_SHORTCUTS SETTINGS_WINDOWS + if (entry_load(key, ss, #name, name, #type)) \ + continue; + SETTINGS_MEMBERS SETTINGS_SHORTCUTS SETTINGS_WINDOWS #undef X } - // Scales were once saved as multipliers; a value below the minimum percent is one, and is converted. + // Scales were once saved as multipliers. A value below the minimum percent is one, and is converted. for (auto [scale, min, max] : {std::tuple{&uiScale, UI_SCALE_MIN, UI_SCALE_MAX}, std::tuple{&renderScale, RENDER_SCALE_MIN, RENDER_SCALE_MAX}}) - *scale = std::clamp(*scale < min ? unit_to_percent(*scale) : *scale, min, max); - } + *scale = std::clamp(*scale < min ? unit_to_percent(*scale) : *scale, min, max); +} - std::string Settings::imgui_data_load(const std::filesystem::path& path) - { +std::string Settings::imgui_data_load(const std::filesystem::path& path) +{ auto pathUtf8 = path_to_utf8(path); std::string fileData; if (!file_text_load(path, &fileData, "rb")) { - logger.error( - std::format("Failed to open settings file for Dear ImGui data: {}; using Dear ImGui defaults", pathUtf8)); - return {}; + logger.error( + std::format("Failed to open settings file for Dear ImGui data: {}; using Dear ImGui defaults", pathUtf8)); + return {}; } std::istringstream file(fileData); @@ -299,64 +305,65 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 while (std::getline(file, line)) { - if (!isImGuiSection) - { - if (line == "# Dear ImGui") isImGuiSection = true; - continue; - } + if (!isImGuiSection) + { + if (line == "# Dear ImGui") + isImGuiSection = true; + continue; + } - if (isContent) dataStream << "\n"; - dataStream << line; - isContent = true; + if (isContent) + dataStream << "\n"; + dataStream << line; + isContent = true; } if (!isImGuiSection) { - logger.warning( - std::format("Dear ImGui section missing from settings file: {}; using Dear ImGui defaults", pathUtf8)); - return {}; + logger.warning( + std::format("Dear ImGui section missing from settings file: {}; using Dear ImGui defaults", pathUtf8)); + return {}; } if (!isContent) { - logger.warning(std::format("Dear ImGui section empty in settings file: {}; using Dear ImGui defaults", pathUtf8)); - return {}; + logger.warning( + std::format("Dear ImGui section empty in settings file: {}; using Dear ImGui defaults", pathUtf8)); + return {}; } return dataStream.str(); - } +} - void Settings::save(const std::filesystem::path& path, const std::string& imguiData) - { +void Settings::save(const std::filesystem::path& path, const std::string& imguiData) +{ auto pathUtf8 = path_to_utf8(path); logger.info(std::format("Saving settings to: {}", pathUtf8)); std::ostringstream file; file << "[Settings]\n"; - auto value_save = [&](const std::string& key, const auto& value) - { - using T = std::decay_t; + auto value_save = [&](const std::string& key, const auto& value) { + using T = std::decay_t; - if constexpr (std::is_same_v) - file << key << "=" << (value ? "true" : "false") << "\n"; - else if constexpr (std::is_same_v) - file << key << "=" << path_to_utf8(value) << "\n"; - else - file << key << "=" << value << "\n"; + if constexpr (std::is_same_v) + file << key << "=" << (value ? "true" : "false") << "\n"; + else if constexpr (std::is_same_v) + file << key << "=" << path_to_utf8(value) << "\n"; + else + file << key << "=" << value << "\n"; }; - auto entry_save = [&](const std::string& name, const auto& value, const std::string_view type) - { - using T = std::decay_t; + auto entry_save = [&](const std::string& name, const auto& value, const std::string_view type) { + using T = std::decay_t; - if constexpr (GlmVector) - { - auto suffixes = component_suffixes_get(type); - for (int i = 0; i < T::length(); ++i) - value_save(name + suffixes[i], value[i]); - } - else - value_save(name, value); + if constexpr (GlmVector) + { + auto suffixes = component_suffixes_get(type); + for (int i = 0; i < T::length(); ++i) + value_save(name + suffixes[i], value[i]); + } + else + value_save(name, value); }; #define X(symbol, name, string, type, ...) entry_save(#name, name, #type); @@ -369,13 +376,13 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 if (file.fail()) { - logger.error(std::format("Failed while writing settings file: {}", pathUtf8)); - return; + logger.error(std::format("Failed while writing settings file: {}", pathUtf8)); + return; } if (!file_text_save(path, file.str(), "wb")) { - logger.error(std::format("Failed to save settings file: {}", pathUtf8)); - return; + logger.error(std::format("Failed to save settings file: {}", pathUtf8)); + return; } logger.info(std::format("Saved settings to: {}", pathUtf8)); - } +} diff --git a/src/settings.h b/src/settings.h index a25640e..06ccfd3 100644 --- a/src/settings.h +++ b/src/settings.h @@ -12,311 +12,311 @@ #include "ui/theme.h" #ifdef _WIN32 - constexpr auto FFMPEG_PATH_DEFAULT = "C:\\ffmpeg\\bin\\ffmpeg.exe"; +constexpr auto FFMPEG_PATH_DEFAULT = "C:\\ffmpeg\\bin\\ffmpeg.exe"; #else - constexpr auto FFMPEG_PATH_DEFAULT = "/usr/bin/ffmpeg"; +constexpr auto FFMPEG_PATH_DEFAULT = "/usr/bin/ffmpeg"; #endif #ifdef _WIN32 - constexpr auto OUTPUT_PATH_DEFAULT = ".\\output.gif"; +constexpr auto OUTPUT_PATH_DEFAULT = ".\\output.gif"; #else - constexpr auto OUTPUT_PATH_DEFAULT = "./output.gif"; +constexpr auto OUTPUT_PATH_DEFAULT = "./output.gif"; #endif - constexpr auto AUTO_RELOAD_INTERVAL = 3.0f; // seconds between checks of spritesheet and library files - // Scales are percents. - constexpr auto UI_SCALE_MIN = 50.0f; - constexpr auto UI_SCALE_MAX = 200.0f; - constexpr auto UI_SCALE_STEP = 25.0f; - constexpr auto RENDER_SCALE_MIN = 25.0f; - constexpr auto RENDER_SCALE_MAX = 1000.0f; - constexpr auto RENDER_SCALE_STEP = 25.0f; +constexpr auto AUTO_RELOAD_INTERVAL = 3.0f; // seconds between checks of spritesheet and library files +// Scales are percents. +constexpr auto UI_SCALE_MIN = 50.0f; +constexpr auto UI_SCALE_MAX = 200.0f; +constexpr auto UI_SCALE_STEP = 25.0f; +constexpr auto RENDER_SCALE_MIN = 25.0f; +constexpr auto RENDER_SCALE_MAX = 1000.0f; +constexpr auto RENDER_SCALE_STEP = 25.0f; #define SETTINGS_TYPES \ - X(INT, int) \ - X(BOOL, bool) \ - X(FLOAT, float) \ - X(STRING, std::string) \ - X(PATH, std::filesystem::path) \ - X(IVEC2, glm::ivec2) \ - X(IVEC2_WH, glm::ivec2) \ - X(VEC2, glm::vec2) \ - X(VEC2_WH, glm::vec2) \ - X(VEC3, glm::vec3) \ - X(VEC4, glm::vec4) + X(INT, int) \ + X(BOOL, bool) \ + X(FLOAT, float) \ + X(STRING, std::string) \ + X(PATH, std::filesystem::path) \ + X(IVEC2, glm::ivec2) \ + X(IVEC2_WH, glm::ivec2) \ + X(VEC2, glm::vec2) \ + X(VEC2_WH, glm::vec2) \ + X(VEC3, glm::vec3) \ + X(VEC4, glm::vec4) #define X(name, type) using TYPE_##name = type; - SETTINGS_TYPES +SETTINGS_TYPES #undef X #define SETTINGS_MEMBERS \ - /* Symbol / Name / String / Type / Default */ \ - X(WINDOW_SIZE, windowSize, STRING_UNDEFINED, IVEC2_WH, {1200, 720}) \ - X(WINDOW_POSITION, windowPosition, STRING_UNDEFINED, IVEC2, glm::ivec2()) \ - X(IS_VSYNC, isVsync, STRING_UNDEFINED, BOOL, true) \ - X(IS_DETACHABLE_WINDOWS, isDetachableWindows, STRING_UNDEFINED, BOOL, true) \ - X(UI_SCALE, uiScale, STRING_UNDEFINED, FLOAT, 100.0f) \ - X(THEME, theme, STRING_UNDEFINED, INT, THEME_DARK) \ - X(LANGUAGE, language, STRING_UNDEFINED, INT, ENGLISH) \ + /* Symbol / Name / String / Type / Default */ \ + X(WINDOW_SIZE, windowSize, STRING_UNDEFINED, IVEC2_WH, {1200, 720}) \ + X(WINDOW_POSITION, windowPosition, STRING_UNDEFINED, IVEC2, glm::ivec2()) \ + X(IS_VSYNC, isVsync, STRING_UNDEFINED, BOOL, true) \ + X(IS_DETACHABLE_WINDOWS, isDetachableWindows, STRING_UNDEFINED, BOOL, true) \ + X(UI_SCALE, uiScale, STRING_UNDEFINED, FLOAT, 100.0f) \ + X(THEME, theme, STRING_UNDEFINED, INT, THEME_DARK) \ + X(LANGUAGE, language, STRING_UNDEFINED, INT, ENGLISH) \ \ - X(FILE_IS_AUTOSAVE, fileIsAutosave, STRING_UNDEFINED, BOOL, true) \ - X(FILE_IS_WARN_OVERWRITE, fileIsWarnOverwrite, STRING_UNDEFINED, BOOL, true) \ - X(FILE_IS_WARN_ISAAC, fileIsWarnIsaac, STRING_UNDEFINED, BOOL, true) \ - X(FILE_IS_AUTO_RELOAD_RESOURCES, fileIsAutoReloadResources, STRING_UNDEFINED, BOOL, true) \ - X(FILE_IS_JSON, fileIsJson, STRING_UNDEFINED, BOOL, false) \ - X(FILE_SNAPSHOT_STACK_SIZE, fileSnapshotStackSize, STRING_UNDEFINED, INT, 50) \ + X(FILE_IS_AUTOSAVE, fileIsAutosave, STRING_UNDEFINED, BOOL, true) \ + X(FILE_IS_WARN_OVERWRITE, fileIsWarnOverwrite, STRING_UNDEFINED, BOOL, true) \ + X(FILE_IS_WARN_ISAAC, fileIsWarnIsaac, STRING_UNDEFINED, BOOL, true) \ + X(FILE_IS_AUTO_RELOAD_RESOURCES, fileIsAutoReloadResources, STRING_UNDEFINED, BOOL, true) \ + X(FILE_IS_JSON, fileIsJson, STRING_UNDEFINED, BOOL, false) \ + X(FILE_SNAPSHOT_STACK_SIZE, fileSnapshotStackSize, STRING_UNDEFINED, INT, 50) \ \ - X(KEYBOARD_REPEAT_DELAY, keyboardRepeatDelay, STRING_UNDEFINED, FLOAT, 0.300f) \ - X(KEYBOARD_REPEAT_RATE, keyboardRepeatRate, STRING_UNDEFINED, FLOAT, 0.050f) \ + X(KEYBOARD_REPEAT_DELAY, keyboardRepeatDelay, STRING_UNDEFINED, FLOAT, 0.300f) \ + X(KEYBOARD_REPEAT_RATE, keyboardRepeatRate, STRING_UNDEFINED, FLOAT, 0.050f) \ \ - X(INPUT_IS_MOVE_TOOL_SNAP_TO_MOUSE, inputIsMoveToolSnapToMouse, STRING_UNDEFINED, BOOL, false) \ + X(INPUT_IS_MOVE_TOOL_SNAP_TO_MOUSE, inputIsMoveToolSnapToMouse, STRING_UNDEFINED, BOOL, false) \ \ - X(PLAYBACK_IS_LOOP, playbackIsLoop, STRING_UNDEFINED, BOOL, true) \ - X(PLAYBACK_IS_CLAMP, playbackIsClamp, STRING_UNDEFINED, BOOL, true) \ - X(PLAYBACK_TICK_RATE, playbackTickRate, STRING_UNDEFINED, INT, 30) \ + X(PLAYBACK_IS_LOOP, playbackIsLoop, STRING_UNDEFINED, BOOL, true) \ + X(PLAYBACK_IS_CLAMP, playbackIsClamp, STRING_UNDEFINED, BOOL, true) \ + X(PLAYBACK_TICK_RATE, playbackTickRate, STRING_UNDEFINED, INT, 30) \ \ - X(CHANGE_IS_CROP_X, changeIsCropX, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_CROP_Y, changeIsCropY, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_SIZE_X, changeIsSizeX, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_SIZE_Y, changeIsSizeY, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_POSITION_X, changeIsPositionX, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_POSITION_Y, changeIsPositionY, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_PIVOT_X, changeIsPivotX, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_PIVOT_Y, changeIsPivotY, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_SCALE_X, changeIsScaleX, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_SCALE_Y, changeIsScaleY, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_SKEW_X, changeIsSkewX, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_SKEW_Y, changeIsSkewY, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_ROTATION, changeIsRotation, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_DURATION, changeIsDuration, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_DEPTH, changeIsDepth, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_BLUR, changeIsBlur, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_CHILD_ANIMATION, changeIsChildAnimation, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_CHILD_MODE, changeIsChildMode, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_CHILD_START, changeIsChildStart, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_CHILD_START_RANDOM_SET, changeIsChildStartRandomSet, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_CHILD_RESTART_SET, changeIsChildRestartSet, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_TINT_R, changeIsTintR, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_TINT_G, changeIsTintG, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_TINT_B, changeIsTintB, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_TINT_A, changeIsTintA, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_COLOR_OFFSET_R, changeIsColorOffsetR, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_COLOR_OFFSET_G, changeIsColorOffsetG, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_COLOR_OFFSET_B, changeIsColorOffsetB, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_COLOR_OFFSET_A, changeIsColorOffsetA, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_VISIBLE_SET, changeIsVisibleSet, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_INTERPOLATION_SET, changeIsInterpolationSet, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_FLIP_X_SET, changeIsFlipXSet, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_FLIP_Y_SET, changeIsFlipYSet, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_REGION, changeIsRegion, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_SHADER, changeIsShader, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_CROP, changeCrop, STRING_UNDEFINED, VEC2, {}) \ - X(CHANGE_SIZE, changeSize, STRING_UNDEFINED, VEC2, {}) \ - X(CHANGE_POSITION, changePosition, STRING_UNDEFINED, VEC2, {}) \ - X(CHANGE_PIVOT, changePivot, STRING_UNDEFINED, VEC2, {}) \ - X(CHANGE_SCALE, changeScale, STRING_UNDEFINED, VEC2, {}) \ - X(CHANGE_SKEW, changeSkew, STRING_UNDEFINED, VEC2, {}) \ - X(CHANGE_ROTATION, changeRotation, STRING_UNDEFINED, FLOAT, 0.0f) \ - X(CHANGE_DURATION, changeDuration, STRING_UNDEFINED, INT, 0) \ - X(CHANGE_DEPTH, changeDepth, STRING_UNDEFINED, INT, 0) \ - X(CHANGE_BLUR, changeBlur, STRING_UNDEFINED, FLOAT, 0.0f) \ - X(CHANGE_CHILD_ANIMATION, changeChildAnimation, STRING_UNDEFINED, STRING, "") \ - X(CHANGE_CHILD_MODE, changeChildMode, STRING_UNDEFINED, INT, 0) \ - X(CHANGE_CHILD_START, changeChildStart, STRING_UNDEFINED, INT, 0) \ - X(CHANGE_IS_CHILD_START_RANDOM, changeIsChildStartRandom, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_CHILD_RESTART, changeIsChildRestart, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_TINT, changeTint, STRING_UNDEFINED, VEC4, {}) \ - X(CHANGE_COLOR_OFFSET, changeColorOffset, STRING_UNDEFINED, VEC4, {}) \ - X(CHANGE_REGION_ID, changeRegionId, STRING_UNDEFINED, INT, -1) \ - X(CHANGE_IS_VISIBLE, changeIsVisible, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_INTERPOLATION, changeInterpolation, STRING_UNDEFINED, INT, 0) \ - X(CHANGE_IS_FLIP_X, changeIsFlipX, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_IS_FLIP_Y, changeIsFlipY, STRING_UNDEFINED, BOOL, false) \ - X(CHANGE_DESTINATION, changeDestination, STRING_UNDEFINED, INT, 0) \ - X(CHANGE_IS_ROOT, changeIsRoot, STRING_UNDEFINED, BOOL, true) \ - X(CHANGE_IS_LAYERS, changeIsLayers, STRING_UNDEFINED, BOOL, true) \ - X(CHANGE_IS_NULLS, changeIsNulls, STRING_UNDEFINED, BOOL, true) \ + X(CHANGE_IS_CROP_X, changeIsCropX, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CROP_Y, changeIsCropY, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SIZE_X, changeIsSizeX, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SIZE_Y, changeIsSizeY, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_POSITION_X, changeIsPositionX, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_POSITION_Y, changeIsPositionY, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_PIVOT_X, changeIsPivotX, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_PIVOT_Y, changeIsPivotY, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SCALE_X, changeIsScaleX, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SCALE_Y, changeIsScaleY, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SKEW_X, changeIsSkewX, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SKEW_Y, changeIsSkewY, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_ROTATION, changeIsRotation, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_DURATION, changeIsDuration, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_DEPTH, changeIsDepth, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_BLUR, changeIsBlur, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_ANIMATION, changeIsChildAnimation, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_MODE, changeIsChildMode, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_START, changeIsChildStart, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_START_RANDOM_SET, changeIsChildStartRandomSet, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_RESTART_SET, changeIsChildRestartSet, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_TINT_R, changeIsTintR, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_TINT_G, changeIsTintG, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_TINT_B, changeIsTintB, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_TINT_A, changeIsTintA, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_COLOR_OFFSET_R, changeIsColorOffsetR, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_COLOR_OFFSET_G, changeIsColorOffsetG, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_COLOR_OFFSET_B, changeIsColorOffsetB, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_COLOR_OFFSET_A, changeIsColorOffsetA, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_VISIBLE_SET, changeIsVisibleSet, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_INTERPOLATION_SET, changeIsInterpolationSet, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_FLIP_X_SET, changeIsFlipXSet, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_FLIP_Y_SET, changeIsFlipYSet, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_REGION, changeIsRegion, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SHADER, changeIsShader, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_CROP, changeCrop, STRING_UNDEFINED, VEC2, {}) \ + X(CHANGE_SIZE, changeSize, STRING_UNDEFINED, VEC2, {}) \ + X(CHANGE_POSITION, changePosition, STRING_UNDEFINED, VEC2, {}) \ + X(CHANGE_PIVOT, changePivot, STRING_UNDEFINED, VEC2, {}) \ + X(CHANGE_SCALE, changeScale, STRING_UNDEFINED, VEC2, {}) \ + X(CHANGE_SKEW, changeSkew, STRING_UNDEFINED, VEC2, {}) \ + X(CHANGE_ROTATION, changeRotation, STRING_UNDEFINED, FLOAT, 0.0f) \ + X(CHANGE_DURATION, changeDuration, STRING_UNDEFINED, INT, 0) \ + X(CHANGE_DEPTH, changeDepth, STRING_UNDEFINED, INT, 0) \ + X(CHANGE_BLUR, changeBlur, STRING_UNDEFINED, FLOAT, 0.0f) \ + X(CHANGE_CHILD_ANIMATION, changeChildAnimation, STRING_UNDEFINED, STRING, "") \ + X(CHANGE_CHILD_MODE, changeChildMode, STRING_UNDEFINED, INT, 0) \ + X(CHANGE_CHILD_START, changeChildStart, STRING_UNDEFINED, INT, 0) \ + X(CHANGE_IS_CHILD_START_RANDOM, changeIsChildStartRandom, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_RESTART, changeIsChildRestart, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_TINT, changeTint, STRING_UNDEFINED, VEC4, {}) \ + X(CHANGE_COLOR_OFFSET, changeColorOffset, STRING_UNDEFINED, VEC4, {}) \ + X(CHANGE_REGION_ID, changeRegionId, STRING_UNDEFINED, INT, -1) \ + X(CHANGE_IS_VISIBLE, changeIsVisible, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_INTERPOLATION, changeInterpolation, STRING_UNDEFINED, INT, 0) \ + X(CHANGE_IS_FLIP_X, changeIsFlipX, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_FLIP_Y, changeIsFlipY, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_DESTINATION, changeDestination, STRING_UNDEFINED, INT, 0) \ + X(CHANGE_IS_ROOT, changeIsRoot, STRING_UNDEFINED, BOOL, true) \ + X(CHANGE_IS_LAYERS, changeIsLayers, STRING_UNDEFINED, BOOL, true) \ + X(CHANGE_IS_NULLS, changeIsNulls, STRING_UNDEFINED, BOOL, true) \ \ - X(SCALE_VALUE, scaleValue, STRING_UNDEFINED, FLOAT, 1.0f) \ + X(SCALE_VALUE, scaleValue, STRING_UNDEFINED, FLOAT, 1.0f) \ \ - X(PREVIEW_IS_AXES, previewIsAxes, STRING_UNDEFINED, BOOL, true) \ - X(PREVIEW_IS_GRID, previewIsGrid, STRING_UNDEFINED, BOOL, true) \ - X(PREVIEW_IS_ROOT_TRANSFORM, previewIsRootTransform, STRING_UNDEFINED, BOOL, true) \ - X(PREVIEW_IS_PIVOTS, previewIsPivots, STRING_UNDEFINED, BOOL, false) \ - X(PREVIEW_IS_BORDER, previewIsBorder, STRING_UNDEFINED, BOOL, false) \ - X(PREVIEW_IS_ALT_ICONS, previewIsAltIcons, STRING_UNDEFINED, BOOL, false) \ - X(PREVIEW_IS_TRANSPARENT, animationPreviewTransparent, STRING_UNDEFINED, BOOL, false) \ - X(PREVIEW_OVERLAY_TRANSPARENCY, previewOverlayTransparency, STRING_UNDEFINED, FLOAT, 100.0f) \ - X(PREVIEW_OVERLAY_DRAW_ORDER, previewOverlayDrawOrder, STRING_UNDEFINED, INT, OVERLAY_OVER) \ - X(PREVIEW_START_ZOOM, previewStartZoom, STRING_UNDEFINED, FLOAT, 200.0f) \ - X(PREVIEW_GRID_SIZE, previewGridSize, STRING_UNDEFINED, IVEC2, {32, 32}) \ - X(PREVIEW_GRID_OFFSET, previewGridOffset, STRING_UNDEFINED, IVEC2, {}) \ - X(PREVIEW_GRID_COLOR, previewGridColor, STRING_UNDEFINED, VEC4, {1.0f, 1.0f, 1.0f, 0.125f}) \ - X(PREVIEW_AXES_COLOR, previewAxesColor, STRING_UNDEFINED, VEC4, {1.0f, 1.0f, 1.0f, 0.125f}) \ - X(PREVIEW_BACKGROUND_COLOR, previewBackgroundColor, STRING_UNDEFINED, VEC3, {0.113f, 0.184f, 0.286f}) \ + X(PREVIEW_IS_AXES, previewIsAxes, STRING_UNDEFINED, BOOL, true) \ + X(PREVIEW_IS_GRID, previewIsGrid, STRING_UNDEFINED, BOOL, true) \ + X(PREVIEW_IS_ROOT_TRANSFORM, previewIsRootTransform, STRING_UNDEFINED, BOOL, true) \ + X(PREVIEW_IS_PIVOTS, previewIsPivots, STRING_UNDEFINED, BOOL, false) \ + X(PREVIEW_IS_BORDER, previewIsBorder, STRING_UNDEFINED, BOOL, false) \ + X(PREVIEW_IS_ALT_ICONS, previewIsAltIcons, STRING_UNDEFINED, BOOL, false) \ + X(PREVIEW_IS_TRANSPARENT, animationPreviewTransparent, STRING_UNDEFINED, BOOL, false) \ + X(PREVIEW_OVERLAY_TRANSPARENCY, previewOverlayTransparency, STRING_UNDEFINED, FLOAT, 100.0f) \ + X(PREVIEW_OVERLAY_DRAW_ORDER, previewOverlayDrawOrder, STRING_UNDEFINED, INT, OVERLAY_OVER) \ + X(PREVIEW_START_ZOOM, previewStartZoom, STRING_UNDEFINED, FLOAT, 200.0f) \ + X(PREVIEW_GRID_SIZE, previewGridSize, STRING_UNDEFINED, IVEC2, {32, 32}) \ + X(PREVIEW_GRID_OFFSET, previewGridOffset, STRING_UNDEFINED, IVEC2, {}) \ + X(PREVIEW_GRID_COLOR, previewGridColor, STRING_UNDEFINED, VEC4, {1.0f, 1.0f, 1.0f, 0.125f}) \ + X(PREVIEW_AXES_COLOR, previewAxesColor, STRING_UNDEFINED, VEC4, {1.0f, 1.0f, 1.0f, 0.125f}) \ + X(PREVIEW_BACKGROUND_COLOR, previewBackgroundColor, STRING_UNDEFINED, VEC3, {0.113f, 0.184f, 0.286f}) \ \ - X(PROPERTIES_IS_ROUND, propertiesIsRound, STRING_UNDEFINED, BOOL, false) \ + X(PROPERTIES_IS_ROUND, propertiesIsRound, STRING_UNDEFINED, BOOL, false) \ \ - X(GENERATE_START_POSITION, generateStartPosition, STRING_UNDEFINED, IVEC2, {}) \ - X(GENERATE_SIZE, generateSize, STRING_UNDEFINED, IVEC2, {64, 64}) \ - X(GENERATE_PIVOT, generatePivot, STRING_UNDEFINED, VEC2, {32, 32}) \ - X(GENERATE_ROWS, generateRows, STRING_UNDEFINED, INT, 4) \ - X(GENERATE_COLUMNS, generateColumns, STRING_UNDEFINED, INT, 4) \ - X(GENERATE_COUNT, generateCount, STRING_UNDEFINED, INT, 16) \ - X(GENERATE_DURATION, generateDuration, STRING_UNDEFINED, INT, 1) \ - X(GENERATE_IS_MAKE_REGIONS, generateIsMakeRegions, STRING_UNDEFINED, BOOL, false) \ - X(GENERATE_REGION_NAME_FORMAT, generateRegionNameFormat, STRING_UNDEFINED, STRING, "Frame {}") \ - X(GENERATE_ZOOM, generateZoom, STRING_UNDEFINED, FLOAT, 100.0f) \ + X(GENERATE_START_POSITION, generateStartPosition, STRING_UNDEFINED, IVEC2, {}) \ + X(GENERATE_SIZE, generateSize, STRING_UNDEFINED, IVEC2, {64, 64}) \ + X(GENERATE_PIVOT, generatePivot, STRING_UNDEFINED, VEC2, {32, 32}) \ + X(GENERATE_ROWS, generateRows, STRING_UNDEFINED, INT, 4) \ + X(GENERATE_COLUMNS, generateColumns, STRING_UNDEFINED, INT, 4) \ + X(GENERATE_COUNT, generateCount, STRING_UNDEFINED, INT, 16) \ + X(GENERATE_DURATION, generateDuration, STRING_UNDEFINED, INT, 1) \ + X(GENERATE_IS_MAKE_REGIONS, generateIsMakeRegions, STRING_UNDEFINED, BOOL, false) \ + X(GENERATE_REGION_NAME_FORMAT, generateRegionNameFormat, STRING_UNDEFINED, STRING, "Frame {}") \ + X(GENERATE_ZOOM, generateZoom, STRING_UNDEFINED, FLOAT, 100.0f) \ \ - X(EDITOR_IS_GRID, editorIsGrid, STRING_UNDEFINED, BOOL, true) \ - X(EDITOR_IS_GRID_SNAP, editorIsGridSnap, STRING_UNDEFINED, BOOL, true) \ - X(EDITOR_IS_BORDER, editorIsBorder, STRING_UNDEFINED, BOOL, true) \ - X(EDITOR_IS_TRANSPARENT, editorIsTransparent, STRING_UNDEFINED, BOOL, true) \ - X(EDITOR_START_ZOOM, editorStartZoom, STRING_UNDEFINED, FLOAT, 200.0f) \ - X(EDITOR_SIZE, editorSize, STRING_UNDEFINED, IVEC2_WH, {1200, 600}) \ - X(EDITOR_GRID_SIZE, editorGridSize, STRING_UNDEFINED, IVEC2, {32, 32}) \ - X(EDITOR_GRID_OFFSET, editorGridOffset, STRING_UNDEFINED, IVEC2, {32, 32}) \ - X(EDITOR_GRID_COLOR, editorGridColor, STRING_UNDEFINED, VEC4, {1.0, 1.0, 1.0, 0.125}) \ - X(EDITOR_BACKGROUND_COLOR, editorBackgroundColor, STRING_UNDEFINED, VEC3, {0.113, 0.184, 0.286}) \ + X(EDITOR_IS_GRID, editorIsGrid, STRING_UNDEFINED, BOOL, true) \ + X(EDITOR_IS_GRID_SNAP, editorIsGridSnap, STRING_UNDEFINED, BOOL, true) \ + X(EDITOR_IS_BORDER, editorIsBorder, STRING_UNDEFINED, BOOL, true) \ + X(EDITOR_IS_TRANSPARENT, editorIsTransparent, STRING_UNDEFINED, BOOL, true) \ + X(EDITOR_START_ZOOM, editorStartZoom, STRING_UNDEFINED, FLOAT, 200.0f) \ + X(EDITOR_SIZE, editorSize, STRING_UNDEFINED, IVEC2_WH, {1200, 600}) \ + X(EDITOR_GRID_SIZE, editorGridSize, STRING_UNDEFINED, IVEC2, {32, 32}) \ + X(EDITOR_GRID_OFFSET, editorGridOffset, STRING_UNDEFINED, IVEC2, {32, 32}) \ + X(EDITOR_GRID_COLOR, editorGridColor, STRING_UNDEFINED, VEC4, {1.0, 1.0, 1.0, 0.125}) \ + X(EDITOR_BACKGROUND_COLOR, editorBackgroundColor, STRING_UNDEFINED, VEC3, {0.113, 0.184, 0.286}) \ \ - X(MERGE_TYPE, mergeType, STRING_UNDEFINED, INT, 0) \ - X(MERGE_IS_DELETE_ANIMATIONS_AFTER, mergeIsDeleteAnimationsAfter, STRING_UNDEFINED, BOOL, false) \ - X(MERGE_SPRITESHEETS_ORIGIN, mergeSpritesheetsOrigin, STRING_UNDEFINED, INT, APPEND_RIGHT) \ - X(MERGE_SPRITESHEETS_IS_MAKE_REGIONS, mergeSpritesheetsIsMakeRegions, STRING_UNDEFINED, BOOL, true) \ - X(MERGE_SPRITESHEETS_IS_MAKE_PRIMARY_REGION, mergeSpritesheetsIsMakePrimaryRegion, STRING_UNDEFINED, BOOL, true) \ - X(MERGE_SPRITESHEETS_REGION_ORIGIN, mergeSpritesheetsRegionOrigin, STRING_UNDEFINED, INT, 0) \ - X(PACK_PADDING, packPadding, STRING_UNDEFINED, INT, 1) \ - X(EXPORT_REGION_PATH, exportRegionPath, STRING_UNDEFINED, PATH, "./region.png") \ - X(EXPORT_REGION_IS_MAKE_SPRITESHEET, isExportRegionMakeSpritesheet, STRING_UNDEFINED, BOOL, true) \ - X(EXPORT_REGION_IS_REMOVE_CURRENT, isExportRegionRemoveCurrent, STRING_UNDEFINED, BOOL, true) \ + X(MERGE_TYPE, mergeType, STRING_UNDEFINED, INT, 0) \ + X(MERGE_IS_DELETE_ANIMATIONS_AFTER, mergeIsDeleteAnimationsAfter, STRING_UNDEFINED, BOOL, false) \ + X(MERGE_SPRITESHEETS_ORIGIN, mergeSpritesheetsOrigin, STRING_UNDEFINED, INT, APPEND_RIGHT) \ + X(MERGE_SPRITESHEETS_IS_MAKE_REGIONS, mergeSpritesheetsIsMakeRegions, STRING_UNDEFINED, BOOL, true) \ + X(MERGE_SPRITESHEETS_IS_MAKE_PRIMARY_REGION, mergeSpritesheetsIsMakePrimaryRegion, STRING_UNDEFINED, BOOL, true) \ + X(MERGE_SPRITESHEETS_REGION_ORIGIN, mergeSpritesheetsRegionOrigin, STRING_UNDEFINED, INT, 0) \ + X(PACK_PADDING, packPadding, STRING_UNDEFINED, INT, 1) \ + X(EXPORT_REGION_PATH, exportRegionPath, STRING_UNDEFINED, PATH, "./region.png") \ + X(EXPORT_REGION_IS_MAKE_SPRITESHEET, isExportRegionMakeSpritesheet, STRING_UNDEFINED, BOOL, true) \ + X(EXPORT_REGION_IS_REMOVE_CURRENT, isExportRegionRemoveCurrent, STRING_UNDEFINED, BOOL, true) \ \ - X(BAKE_INTERVAL, bakeInterval, STRING_UNDEFINED, INT, 1) \ - X(BAKE_IS_ROUND_SCALE, bakeIsRoundScale, STRING_UNDEFINED, BOOL, true) \ - X(BAKE_IS_ROUND_ROTATION, bakeIsRoundRotation, STRING_UNDEFINED, BOOL, true) \ - X(BAKE_IS_MATCH_ROOT_INTERPOLATION, bakeIsMatchRootInterpolation, STRING_UNDEFINED, BOOL, false) \ - X(BAKE_IS_USE_ROOT_PIVOT, bakeIsUseRootPivot, STRING_UNDEFINED, BOOL, true) \ + X(BAKE_INTERVAL, bakeInterval, STRING_UNDEFINED, INT, 1) \ + X(BAKE_IS_ROUND_SCALE, bakeIsRoundScale, STRING_UNDEFINED, BOOL, true) \ + X(BAKE_IS_ROUND_ROTATION, bakeIsRoundRotation, STRING_UNDEFINED, BOOL, true) \ + X(BAKE_IS_MATCH_ROOT_INTERPOLATION, bakeIsMatchRootInterpolation, STRING_UNDEFINED, BOOL, false) \ + X(BAKE_IS_USE_ROOT_PIVOT, bakeIsUseRootPivot, STRING_UNDEFINED, BOOL, true) \ \ - X(TIMELINE_ADD_ITEM_TYPE, timelineAddItemType, STRING_UNDEFINED, INT, LAYER) \ - X(TIMELINE_ADD_ITEM_DESTINATION, timelineAddItemDestination, STRING_UNDEFINED, INT, DESTINATION_ALL) \ - X(TIMELINE_ADD_ITEM_SOURCE, timelineAddItemSource, STRING_UNDEFINED, INT, SOURCE_NEW) \ - X(TIMELINE_IS_SHOW_UNUSED, timelineIsShowUnused, STRING_UNDEFINED, BOOL, true) \ - X(TIMELINE_IS_ONLY_SHOW_LAYERS, timelineIsOnlyShowLayers, STRING_UNDEFINED, BOOL, false) \ - X(TIMELINE_IS_SOUND, timelineIsSound, STRING_UNDEFINED, BOOL, true) \ + X(TIMELINE_ADD_ITEM_TYPE, timelineAddItemType, STRING_UNDEFINED, INT, LAYER) \ + X(TIMELINE_ADD_ITEM_DESTINATION, timelineAddItemDestination, STRING_UNDEFINED, INT, DESTINATION_ALL) \ + X(TIMELINE_ADD_ITEM_SOURCE, timelineAddItemSource, STRING_UNDEFINED, INT, SOURCE_NEW) \ + X(TIMELINE_IS_SHOW_UNUSED, timelineIsShowUnused, STRING_UNDEFINED, BOOL, true) \ + X(TIMELINE_IS_ONLY_SHOW_LAYERS, timelineIsOnlyShowLayers, STRING_UNDEFINED, BOOL, false) \ + X(TIMELINE_IS_SOUND, timelineIsSound, STRING_UNDEFINED, BOOL, true) \ \ - X(ONIONSKIN_IS_ENABLED, onionskinIsEnabled, STRING_UNDEFINED, BOOL, false) \ - X(ONIONSKIN_BEFORE_COUNT, onionskinBeforeCount, STRING_UNDEFINED, INT, 0) \ - X(ONIONSKIN_AFTER_COUNT, onionskinAfterCount, STRING_UNDEFINED, INT, 0) \ - X(ONIONSKIN_BEFORE_COLOR, onionskinBeforeColor, STRING_UNDEFINED, VEC3, COLOR_RED) \ - X(ONIONSKIN_AFTER_COLOR, onionskinAfterColor, STRING_UNDEFINED, VEC3, COLOR_BLUE) \ - X(ONIONSKIN_MODE, onionskinMode, STRING_UNDEFINED, INT, (int)OnionskinMode::TIME) \ - X(ONIONSKIN_IS_PIVOT_PATH, onionskinIsPivotPath, STRING_UNDEFINED, BOOL, false) \ - X(ONIONSKIN_IS_ONLY_SELECTED, onionskinIsOnlySelected, STRING_UNDEFINED, BOOL, false) \ + X(ONIONSKIN_IS_ENABLED, onionskinIsEnabled, STRING_UNDEFINED, BOOL, false) \ + X(ONIONSKIN_BEFORE_COUNT, onionskinBeforeCount, STRING_UNDEFINED, INT, 0) \ + X(ONIONSKIN_AFTER_COUNT, onionskinAfterCount, STRING_UNDEFINED, INT, 0) \ + X(ONIONSKIN_BEFORE_COLOR, onionskinBeforeColor, STRING_UNDEFINED, VEC3, COLOR_RED) \ + X(ONIONSKIN_AFTER_COLOR, onionskinAfterColor, STRING_UNDEFINED, VEC3, COLOR_BLUE) \ + X(ONIONSKIN_MODE, onionskinMode, STRING_UNDEFINED, INT, (int)OnionskinMode::TIME) \ + X(ONIONSKIN_IS_PIVOT_PATH, onionskinIsPivotPath, STRING_UNDEFINED, BOOL, false) \ + X(ONIONSKIN_IS_ONLY_SELECTED, onionskinIsOnlySelected, STRING_UNDEFINED, BOOL, false) \ \ - X(TOOL, tool, STRING_UNDEFINED, INT, 0) \ - X(TOOL_COLOR, toolColor, STRING_UNDEFINED, VEC4, {1.0, 1.0, 1.0, 1.0}) \ + X(TOOL, tool, STRING_UNDEFINED, INT, 0) \ + X(TOOL_COLOR, toolColor, STRING_UNDEFINED, VEC4, {1.0, 1.0, 1.0, 1.0}) \ \ - X(RENDER_TYPE, renderType, STRING_UNDEFINED, INT, RENDER_GIF) \ - X(RENDER_PATH, renderPath, STRING_UNDEFINED, PATH, OUTPUT_PATH_DEFAULT) \ - X(RENDER_ROWS, renderRows, STRING_UNDEFINED, INT, 0) \ - X(RENDER_COLUMNS, renderColumns, STRING_UNDEFINED, INT, 0) \ - X(RENDER_FORMAT, renderFormat, STRING_UNDEFINED, PATH, "{}.png") \ - X(RENDER_IS_USE_ANIMATION_BOUNDS, renderIsUseAnimationBounds, STRING_UNDEFINED, BOOL, true) \ - X(RENDER_IS_USE_ISOLATED_ANIMATION, renderIsUseIsolatedAnimation, STRING_UNDEFINED, BOOL, false) \ - X(RENDER_SCALE, renderScale, STRING_UNDEFINED, FLOAT, 100.0f) \ - X(RENDER_FPS_MODE, renderFpsMode, STRING_UNDEFINED, INT, FPS_ANIMATION) \ - X(RENDER_FFMPEG_PATH, renderFFmpegPath, STRING_UNDEFINED, PATH, FFMPEG_PATH_DEFAULT) + X(RENDER_TYPE, renderType, STRING_UNDEFINED, INT, RENDER_GIF) \ + X(RENDER_PATH, renderPath, STRING_UNDEFINED, PATH, OUTPUT_PATH_DEFAULT) \ + X(RENDER_ROWS, renderRows, STRING_UNDEFINED, INT, 0) \ + X(RENDER_COLUMNS, renderColumns, STRING_UNDEFINED, INT, 0) \ + X(RENDER_FORMAT, renderFormat, STRING_UNDEFINED, PATH, "{}.png") \ + X(RENDER_IS_USE_ANIMATION_BOUNDS, renderIsUseAnimationBounds, STRING_UNDEFINED, BOOL, true) \ + X(RENDER_IS_USE_ISOLATED_ANIMATION, renderIsUseIsolatedAnimation, STRING_UNDEFINED, BOOL, false) \ + X(RENDER_SCALE, renderScale, STRING_UNDEFINED, FLOAT, 100.0f) \ + X(RENDER_FPS_MODE, renderFpsMode, STRING_UNDEFINED, INT, FPS_ANIMATION) \ + X(RENDER_FFMPEG_PATH, renderFFmpegPath, STRING_UNDEFINED, PATH, FFMPEG_PATH_DEFAULT) #define SETTINGS_SHORTCUTS \ - /* Symbol / Name / String / Type / Default */ \ - /* File */ \ - X(SHORTCUT_NEW, shortcutNew, SHORTCUT_STRING_NEW, STRING, "Ctrl+N") \ - X(SHORTCUT_OPEN, shortcutOpen, SHORTCUT_STRING_OPEN, STRING, "Ctrl+O") \ - X(SHORTCUT_CLOSE, shortcutClose, SHORTCUT_STRING_CLOSE, STRING, "Ctrl+W") \ - X(SHORTCUT_SAVE, shortcutSave, SHORTCUT_STRING_SAVE, STRING, "Ctrl+S") \ - X(SHORTCUT_SAVE_AS, shortcutSaveAs, SHORTCUT_STRING_SAVE_AS, STRING, "Ctrl+Shift+S") \ - X(SHORTCUT_EXIT, shortcutExit, SHORTCUT_STRING_EXIT, STRING, "Alt+F4") \ - /* Edit */ \ - X(SHORTCUT_UNDO, shortcutUndo, SHORTCUT_STRING_UNDO, STRING, "Ctrl+Z") \ - X(SHORTCUT_REDO, shortcutRedo, SHORTCUT_STRING_REDO, STRING, "Ctrl+Y") \ - X(SHORTCUT_CUT, shortcutCut, SHORTCUT_STRING_CUT, STRING, "Ctrl+X") \ - X(SHORTCUT_COPY, shortcutCopy, SHORTCUT_STRING_COPY, STRING, "Ctrl+C") \ - X(SHORTCUT_PASTE, shortcutPaste, SHORTCUT_STRING_PASTE, STRING, "Ctrl+V") \ - X(SHORTCUT_DUPLICATE, shortcutDuplicate, SHORTCUT_STRING_DUPLICATE, STRING, "Ctrl+J") \ - X(SHORTCUT_ADD, shortcutAdd, SHORTCUT_STRING_ADD, STRING, "Insert") \ - X(SHORTCUT_REMOVE, shortcutRemove, SHORTCUT_STRING_REMOVE, STRING, "Delete") \ - X(SHORTCUT_RENAME, shortcutRename, SHORTCUT_STRING_RENAME, STRING, "F2") \ - X(SHORTCUT_DEFAULT, shortcutDefault, SHORTCUT_STRING_DEFAULT, STRING, "Home") \ - X(SHORTCUT_MERGE, shortcutMerge, SHORTCUT_STRING_MERGE, STRING, "Ctrl+E") \ - X(SHORTCUT_GROUP, shortcutGroup, SHORTCUT_STRING_GROUP, STRING, "Ctrl+G") \ - X(SHORTCUT_CONFIRM, shortcutConfirm, SHORTCUT_STRING_CONFIRM, STRING, "Enter") \ - X(SHORTCUT_CANCEL, shortcutCancel, SHORTCUT_STRING_CANCEL, STRING, "Escape") \ - /* Tools */ \ - X(SHORTCUT_PAN, shortcutPan, SHORTCUT_STRING_PAN, STRING, "P") \ - X(SHORTCUT_MOVE, shortcutMove, SHORTCUT_STRING_MOVE, STRING, "V") \ - X(SHORTCUT_ROTATE, shortcutRotate, SHORTCUT_STRING_ROTATE, STRING, "R") \ - X(SHORTCUT_SCALE, shortcutScale, SHORTCUT_STRING_SCALE, STRING, "S") \ - X(SHORTCUT_SKEW, shortcutSkew, SHORTCUT_STRING_SKEW, STRING, "H") \ - X(SHORTCUT_CROP, shortcutCrop, SHORTCUT_STRING_CROP, STRING, "C") \ - X(SHORTCUT_DRAW, shortcutDraw, SHORTCUT_STRING_DRAW, STRING, "B") \ - X(SHORTCUT_ERASE, shortcutErase, SHORTCUT_STRING_ERASE, STRING, "E") \ - X(SHORTCUT_COLOR_PICKER, shortcutColorPicker, SHORTCUT_STRING_COLOR_PICKER, STRING, "I") \ - X(SHORTCUT_COLOR, shortcutColor, SHORTCUT_STRING_COLOR, STRING, "X") \ - /* View */ \ - X(SHORTCUT_CENTER_VIEW, shortcutCenterView, SHORTCUT_STRING_CENTER_VIEW, STRING, "Home") \ - X(SHORTCUT_FIT, shortcutFit, SHORTCUT_STRING_FIT, STRING, "F") \ - X(SHORTCUT_ZOOM_IN, shortcutZoomIn, SHORTCUT_STRING_ZOOM_IN, STRING, "Ctrl+Equal") \ - X(SHORTCUT_ZOOM_OUT, shortcutZoomOut, SHORTCUT_STRING_ZOOM_OUT, STRING, "Ctrl+Minus") \ - /* Timeline / Playback */ \ - X(SHORTCUT_BAKE, shortcutBake, SHORTCUT_STRING_BAKE, STRING, "Ctrl+B") \ - X(SHORTCUT_SPLIT, shortcutSplit, SHORTCUT_STRING_SPLIT, STRING, "Ctrl+P") \ - X(SHORTCUT_PLAY_PAUSE, shortcutPlayPause, SHORTCUT_STRING_PLAY_PAUSE, STRING, "Space") \ - X(SHORTCUT_MOVE_PLAYHEAD_BACK, shortcutMovePlayheadBack, SHORTCUT_STRING_PLAYHEAD_BACK, STRING, "Comma") \ - X(SHORTCUT_MOVE_PLAYHEAD_FORWARD, shortcutMovePlayheadForward, SHORTCUT_STRING_PLAYHEAD_FORWARD, STRING, "Period") \ - X(SHORTCUT_SHORTEN_FRAME, shortcutShortenFrame, SHORTCUT_STRING_SHORTEN_FRAME, STRING, "F4") \ - X(SHORTCUT_EXTEND_FRAME, shortcutExtendFrame, SHORTCUT_STRING_EXTEND_FRAME, STRING, "F5") \ - X(SHORTCUT_INSERT_FRAME, shortcutInsertFrame, SHORTCUT_STRING_INSERT_FRAME, STRING, "F6") \ - X(SHORTCUT_PREVIOUS_FRAME, shortcutPreviousFrame, SHORTCUT_STRING_PREVIOUS_FRAME, STRING, "F7") \ - X(SHORTCUT_NEXT_FRAME, shortcutNextFrame, SHORTCUT_STRING_NEXT_FRAME, STRING, "F8") \ - /* Item */ \ - X(SHORTCUT_START_MARKER, shortcutStartMarker, SHORTCUT_STRING_START_MARKER, STRING, "Shift+Comma") \ - X(SHORTCUT_END_MARKER, shortcutEndMarker, SHORTCUT_STRING_END_MARKER, STRING, "Shift+Period") \ - X(SHORTCUT_PREVIOUS_ITEM, shortcutPreviousItem, SHORTCUT_STRING_PREVIOUS_ITEM, STRING, "Shift+F7") \ - X(SHORTCUT_NEXT_ITEM, shortcutNextItem, SHORTCUT_STRING_NEXT_ITEM, STRING, "Shift+F8") \ - /* Animation */ \ - X(SHORTCUT_PREVIOUS_ANIMATION, shortcutPreviousAnimation, SHORTCUT_STRING_PREVIOUS_ANIMATION, STRING, "F9") \ - X(SHORTCUT_NEXT_ANIMATION, shortcutNextAnimation, SHORTCUT_STRING_NEXT_ANIMATION, STRING, "F10") \ - /* Toggles */ \ - X(SHORTCUT_ONIONSKIN, shortcutOnionskin, SHORTCUT_STRING_ONIONSKIN, STRING, "O") + /* Symbol / Name / String / Type / Default */ \ + /* File */ \ + X(SHORTCUT_NEW, shortcutNew, SHORTCUT_STRING_NEW, STRING, "Ctrl+N") \ + X(SHORTCUT_OPEN, shortcutOpen, SHORTCUT_STRING_OPEN, STRING, "Ctrl+O") \ + X(SHORTCUT_CLOSE, shortcutClose, SHORTCUT_STRING_CLOSE, STRING, "Ctrl+W") \ + X(SHORTCUT_SAVE, shortcutSave, SHORTCUT_STRING_SAVE, STRING, "Ctrl+S") \ + X(SHORTCUT_SAVE_AS, shortcutSaveAs, SHORTCUT_STRING_SAVE_AS, STRING, "Ctrl+Shift+S") \ + X(SHORTCUT_EXIT, shortcutExit, SHORTCUT_STRING_EXIT, STRING, "Alt+F4") \ + /* Edit */ \ + X(SHORTCUT_UNDO, shortcutUndo, SHORTCUT_STRING_UNDO, STRING, "Ctrl+Z") \ + X(SHORTCUT_REDO, shortcutRedo, SHORTCUT_STRING_REDO, STRING, "Ctrl+Y") \ + X(SHORTCUT_CUT, shortcutCut, SHORTCUT_STRING_CUT, STRING, "Ctrl+X") \ + X(SHORTCUT_COPY, shortcutCopy, SHORTCUT_STRING_COPY, STRING, "Ctrl+C") \ + X(SHORTCUT_PASTE, shortcutPaste, SHORTCUT_STRING_PASTE, STRING, "Ctrl+V") \ + X(SHORTCUT_DUPLICATE, shortcutDuplicate, SHORTCUT_STRING_DUPLICATE, STRING, "Ctrl+J") \ + X(SHORTCUT_ADD, shortcutAdd, SHORTCUT_STRING_ADD, STRING, "Insert") \ + X(SHORTCUT_REMOVE, shortcutRemove, SHORTCUT_STRING_REMOVE, STRING, "Delete") \ + X(SHORTCUT_RENAME, shortcutRename, SHORTCUT_STRING_RENAME, STRING, "F2") \ + X(SHORTCUT_DEFAULT, shortcutDefault, SHORTCUT_STRING_DEFAULT, STRING, "Home") \ + X(SHORTCUT_MERGE, shortcutMerge, SHORTCUT_STRING_MERGE, STRING, "Ctrl+E") \ + X(SHORTCUT_GROUP, shortcutGroup, SHORTCUT_STRING_GROUP, STRING, "Ctrl+G") \ + X(SHORTCUT_CONFIRM, shortcutConfirm, SHORTCUT_STRING_CONFIRM, STRING, "Enter") \ + X(SHORTCUT_CANCEL, shortcutCancel, SHORTCUT_STRING_CANCEL, STRING, "Escape") \ + /* Tools */ \ + X(SHORTCUT_PAN, shortcutPan, SHORTCUT_STRING_PAN, STRING, "P") \ + X(SHORTCUT_MOVE, shortcutMove, SHORTCUT_STRING_MOVE, STRING, "V") \ + X(SHORTCUT_ROTATE, shortcutRotate, SHORTCUT_STRING_ROTATE, STRING, "R") \ + X(SHORTCUT_SCALE, shortcutScale, SHORTCUT_STRING_SCALE, STRING, "S") \ + X(SHORTCUT_SKEW, shortcutSkew, SHORTCUT_STRING_SKEW, STRING, "H") \ + X(SHORTCUT_CROP, shortcutCrop, SHORTCUT_STRING_CROP, STRING, "C") \ + X(SHORTCUT_DRAW, shortcutDraw, SHORTCUT_STRING_DRAW, STRING, "B") \ + X(SHORTCUT_ERASE, shortcutErase, SHORTCUT_STRING_ERASE, STRING, "E") \ + X(SHORTCUT_COLOR_PICKER, shortcutColorPicker, SHORTCUT_STRING_COLOR_PICKER, STRING, "I") \ + X(SHORTCUT_COLOR, shortcutColor, SHORTCUT_STRING_COLOR, STRING, "X") \ + /* View */ \ + X(SHORTCUT_CENTER_VIEW, shortcutCenterView, SHORTCUT_STRING_CENTER_VIEW, STRING, "Home") \ + X(SHORTCUT_FIT, shortcutFit, SHORTCUT_STRING_FIT, STRING, "F") \ + X(SHORTCUT_ZOOM_IN, shortcutZoomIn, SHORTCUT_STRING_ZOOM_IN, STRING, "Ctrl+Equal") \ + X(SHORTCUT_ZOOM_OUT, shortcutZoomOut, SHORTCUT_STRING_ZOOM_OUT, STRING, "Ctrl+Minus") \ + /* Timeline / Playback */ \ + X(SHORTCUT_BAKE, shortcutBake, SHORTCUT_STRING_BAKE, STRING, "Ctrl+B") \ + X(SHORTCUT_SPLIT, shortcutSplit, SHORTCUT_STRING_SPLIT, STRING, "Ctrl+P") \ + X(SHORTCUT_PLAY_PAUSE, shortcutPlayPause, SHORTCUT_STRING_PLAY_PAUSE, STRING, "Space") \ + X(SHORTCUT_MOVE_PLAYHEAD_BACK, shortcutMovePlayheadBack, SHORTCUT_STRING_PLAYHEAD_BACK, STRING, "Comma") \ + X(SHORTCUT_MOVE_PLAYHEAD_FORWARD, shortcutMovePlayheadForward, SHORTCUT_STRING_PLAYHEAD_FORWARD, STRING, "Period") \ + X(SHORTCUT_SHORTEN_FRAME, shortcutShortenFrame, SHORTCUT_STRING_SHORTEN_FRAME, STRING, "F4") \ + X(SHORTCUT_EXTEND_FRAME, shortcutExtendFrame, SHORTCUT_STRING_EXTEND_FRAME, STRING, "F5") \ + X(SHORTCUT_INSERT_FRAME, shortcutInsertFrame, SHORTCUT_STRING_INSERT_FRAME, STRING, "F6") \ + X(SHORTCUT_PREVIOUS_FRAME, shortcutPreviousFrame, SHORTCUT_STRING_PREVIOUS_FRAME, STRING, "F7") \ + X(SHORTCUT_NEXT_FRAME, shortcutNextFrame, SHORTCUT_STRING_NEXT_FRAME, STRING, "F8") \ + /* Item */ \ + X(SHORTCUT_START_MARKER, shortcutStartMarker, SHORTCUT_STRING_START_MARKER, STRING, "Shift+Comma") \ + X(SHORTCUT_END_MARKER, shortcutEndMarker, SHORTCUT_STRING_END_MARKER, STRING, "Shift+Period") \ + X(SHORTCUT_PREVIOUS_ITEM, shortcutPreviousItem, SHORTCUT_STRING_PREVIOUS_ITEM, STRING, "Shift+F7") \ + X(SHORTCUT_NEXT_ITEM, shortcutNextItem, SHORTCUT_STRING_NEXT_ITEM, STRING, "Shift+F8") \ + /* Animation */ \ + X(SHORTCUT_PREVIOUS_ANIMATION, shortcutPreviousAnimation, SHORTCUT_STRING_PREVIOUS_ANIMATION, STRING, "F9") \ + X(SHORTCUT_NEXT_ANIMATION, shortcutNextAnimation, SHORTCUT_STRING_NEXT_ANIMATION, STRING, "F10") \ + /* Toggles */ \ + X(SHORTCUT_ONIONSKIN, shortcutOnionskin, SHORTCUT_STRING_ONIONSKIN, STRING, "O") #define SETTINGS_WINDOWS \ - /* Symbol / Name / String / Type / Default */ \ - X(WINDOW_ANIMATIONS, windowIsAnimations, LABEL_ANIMATIONS_WINDOW, BOOL, true) \ - X(WINDOW_ANIMATION_PREVIEW, windowIsAnimationPreview, LABEL_ANIMATION_PREVIEW_WINDOW, BOOL, true) \ - X(WINDOW_REGIONS, windowIsRegions, LABEL_REGIONS_WINDOW, BOOL, true) \ - X(WINDOW_EVENTS, windowIsEvents, LABEL_EVENTS_WINDOW, BOOL, true) \ - X(WINDOW_FRAME_PROPERTIES, windowIsFrameProperties, LABEL_FRAME_PROPERTIES_WINDOW, BOOL, true) \ - X(WINDOW_LAYERS, windowIsLayers, LABEL_LAYERS_WINDOW, BOOL, true) \ - X(WINDOW_LIBRARIES, windowIsLibraries, LABEL_LIBRARIES_WINDOW, BOOL, true) \ - X(WINDOW_NULLS, windowIsNulls, LABEL_NULLS_WINDOW, BOOL, true) \ - X(WINDOW_ONIONSKIN, windowIsOnionskin, LABEL_ONIONSKIN_WINDOW, BOOL, true) \ - X(WINDOW_PREVIEW, windowIsSpritesheets, LABEL_SPRITESHEETS_WINDOW, BOOL, true) \ - X(WINDOW_SHADERS, windowIsShaders, LABEL_SHADERS_WINDOW, BOOL, true) \ - X(WINDOW_SOUNDS, windowIsSounds, LABEL_SOUNDS_WINDOW, BOOL, true) \ - X(WINDOW_SPRITESHEET_EDITOR, windowIsSpritesheetEditor, LABEL_SPRITESHEET_EDITOR_WINDOW, BOOL, true) \ - X(WINDOW_TIMELINE, windowIsTimeline, LABEL_TIMELINE_WINDOW, BOOL, true) \ - X(WINDOW_TOOLS, windowIsTools, LABEL_TOOLS_WINDOW, BOOL, true) + /* Symbol / Name / String / Type / Default */ \ + X(WINDOW_ANIMATIONS, windowIsAnimations, LABEL_ANIMATIONS_WINDOW, BOOL, true) \ + X(WINDOW_ANIMATION_PREVIEW, windowIsAnimationPreview, LABEL_ANIMATION_PREVIEW_WINDOW, BOOL, true) \ + X(WINDOW_REGIONS, windowIsRegions, LABEL_REGIONS_WINDOW, BOOL, true) \ + X(WINDOW_EVENTS, windowIsEvents, LABEL_EVENTS_WINDOW, BOOL, true) \ + X(WINDOW_FRAME_PROPERTIES, windowIsFrameProperties, LABEL_FRAME_PROPERTIES_WINDOW, BOOL, true) \ + X(WINDOW_LAYERS, windowIsLayers, LABEL_LAYERS_WINDOW, BOOL, true) \ + X(WINDOW_LIBRARIES, windowIsLibraries, LABEL_LIBRARIES_WINDOW, BOOL, true) \ + X(WINDOW_NULLS, windowIsNulls, LABEL_NULLS_WINDOW, BOOL, true) \ + X(WINDOW_ONIONSKIN, windowIsOnionskin, LABEL_ONIONSKIN_WINDOW, BOOL, true) \ + X(WINDOW_PREVIEW, windowIsSpritesheets, LABEL_SPRITESHEETS_WINDOW, BOOL, true) \ + X(WINDOW_SHADERS, windowIsShaders, LABEL_SHADERS_WINDOW, BOOL, true) \ + X(WINDOW_SOUNDS, windowIsSounds, LABEL_SOUNDS_WINDOW, BOOL, true) \ + X(WINDOW_SPRITESHEET_EDITOR, windowIsSpritesheetEditor, LABEL_SPRITESHEET_EDITOR_WINDOW, BOOL, true) \ + X(WINDOW_TIMELINE, windowIsTimeline, LABEL_TIMELINE_WINDOW, BOOL, true) \ + X(WINDOW_TOOLS, windowIsTools, LABEL_TOOLS_WINDOW, BOOL, true) - enum ShortcutType - { +enum ShortcutType +{ #define X(symbol, name, string, type, ...) symbol, SETTINGS_SHORTCUTS #undef X SHORTCUT_COUNT - }; +}; - class Settings - { - public: +class Settings +{ +public: #define X(symbol, name, string, type, ...) TYPE_##type name = __VA_ARGS__; SETTINGS_MEMBERS SETTINGS_SHORTCUTS SETTINGS_WINDOWS #undef X @@ -328,38 +328,38 @@ Settings(const std::filesystem::path&); void save(const std::filesystem::path&, const std::string&); static std::string imgui_data_load(const std::filesystem::path&); - }; +}; - constexpr StringType SHORTCUT_STRING_TYPES[] = { +constexpr StringType SHORTCUT_STRING_TYPES[] = { #define X(symbol, name, stringType, type, ...) stringType, - SETTINGS_SHORTCUTS + SETTINGS_SHORTCUTS #undef X - }; +}; - using ShortcutMember = std::string Settings::*; - constexpr ShortcutMember SHORTCUT_MEMBERS[] = { +using ShortcutMember = std::string Settings::*; +constexpr ShortcutMember SHORTCUT_MEMBERS[] = { #define X(symbol, name, string, type, ...) &Settings::name, - SETTINGS_SHORTCUTS + SETTINGS_SHORTCUTS #undef X - }; +}; - enum WindowType - { +enum WindowType +{ #define X(symbol, name, string, type, ...) symbol, SETTINGS_WINDOWS #undef X WINDOW_COUNT - }; +}; - constexpr StringType WINDOW_STRING_TYPES[] = { +constexpr StringType WINDOW_STRING_TYPES[] = { #define X(symbol, name, stringType, type, ...) stringType, - SETTINGS_WINDOWS + SETTINGS_WINDOWS #undef X - }; +}; - using WindowMember = bool Settings::*; - static constexpr WindowMember WINDOW_MEMBERS[] = { +using WindowMember = bool Settings::*; +static constexpr WindowMember WINDOW_MEMBERS[] = { #define X(symbol, name, string, type, ...) &Settings::name, - SETTINGS_WINDOWS + SETTINGS_WINDOWS #undef X - }; +}; diff --git a/src/shader.cpp b/src/shader.cpp index 8f93c44..8e10238 100644 --- a/src/shader.cpp +++ b/src/shader.cpp @@ -10,147 +10,162 @@ #include "model/model.h" #define SHADER_GLES_WORD_REPLACEMENTS \ - X("texture2D", "texture") \ - X("gl_FragColor", "fragColor") + X("texture2D", "texture") \ + X("gl_FragColor", "fragColor") - struct UniformAlias - { +struct UniformAlias +{ UniformBinding binding = {}; const char* name = nullptr; - }; +}; #define RESOURCE_SHADER_UNIFORM_ALIASES \ - X(UNIFORM_BINDING_MAIN_TEXTURE, UNIFORM_TEXTURE) \ - X(UNIFORM_BINDING_MAIN_TEXTURE, "Texture0") \ - X(UNIFORM_BINDING_MAIN_TEXTURE, "texture0") \ - X(UNIFORM_BINDING_MAIN_TEXTURE, "Texture") \ - X(UNIFORM_BINDING_MAIN_TEXTURE, "Sampler0") \ - X(UNIFORM_BINDING_MAIN_TEXTURE, "ColorMap") \ - X(UNIFORM_BINDING_TRANSFORM, UNIFORM_TRANSFORM) \ - X(UNIFORM_BINDING_TRANSFORM, "Transform") \ - X(UNIFORM_BINDING_TRANSFORM, "MVP") \ - X(UNIFORM_BINDING_TRANSFORM, "Matrix") \ - X(UNIFORM_BINDING_FRAME_TINT, UNIFORM_TINT) \ - X(UNIFORM_BINDING_FRAME_TINT, "Tint") \ - X(UNIFORM_BINDING_FRAME_TINT, "Color") \ - X(UNIFORM_BINDING_FRAME_TINT, "Color0") \ - X(UNIFORM_BINDING_COLOR_OFFSET, UNIFORM_COLOR_OFFSET) \ - X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset") \ - X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset0") \ - X(UNIFORM_BINDING_TEXTURE_SIZE, "u_texture_size") \ - X(UNIFORM_BINDING_TEXTURE_SIZE, "TextureSize") \ - X(UNIFORM_BINDING_TEXTURE_SIZE, "TexSize") + X(UNIFORM_BINDING_MAIN_TEXTURE, UNIFORM_TEXTURE) \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "Texture0") \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "texture0") \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "Texture") \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "Sampler0") \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "ColorMap") \ + X(UNIFORM_BINDING_TRANSFORM, UNIFORM_TRANSFORM) \ + X(UNIFORM_BINDING_TRANSFORM, "Transform") \ + X(UNIFORM_BINDING_TRANSFORM, "MVP") \ + X(UNIFORM_BINDING_TRANSFORM, "Matrix") \ + X(UNIFORM_BINDING_FRAME_TINT, UNIFORM_TINT) \ + X(UNIFORM_BINDING_FRAME_TINT, "Tint") \ + X(UNIFORM_BINDING_FRAME_TINT, "Color") \ + X(UNIFORM_BINDING_FRAME_TINT, "Color0") \ + X(UNIFORM_BINDING_COLOR_OFFSET, UNIFORM_COLOR_OFFSET) \ + X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset") \ + X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset0") \ + X(UNIFORM_BINDING_TEXTURE_SIZE, "u_texture_size") \ + X(UNIFORM_BINDING_TEXTURE_SIZE, "TextureSize") \ + X(UNIFORM_BINDING_TEXTURE_SIZE, "TexSize") - constexpr UniformAlias UNIFORM_ALIASES[] = { +constexpr UniformAlias UNIFORM_ALIASES[] = { #define X(binding, name) {binding, name}, - RESOURCE_SHADER_UNIFORM_ALIASES + RESOURCE_SHADER_UNIFORM_ALIASES #undef X - }; +}; - static bool is_shader_identifier(char character) { return std::isalnum((unsigned char)character) || character == '_'; } +static bool is_shader_identifier(char character) +{ + return std::isalnum((unsigned char)character) || character == '_'; +} - static std::string shader_text_replace(std::string string, std::string_view from, std::string_view to) - { - if (from.empty()) return string; +static std::string shader_text_replace(std::string string, std::string_view from, std::string_view to) +{ + if (from.empty()) + return string; std::size_t position = 0; while ((position = string.find(from, position)) != std::string::npos) { - string.replace(position, from.size(), to.data(), to.size()); - position += to.size(); - } - return string; - } - - static std::string shader_word_replace(std::string string, std::string_view from, std::string_view to) - { - if (from.empty()) return string; - - std::size_t position = 0; - while ((position = string.find(from, position)) != std::string::npos) - { - auto after = position + from.size(); - auto isBeforeIdentifier = position > 0 && is_shader_identifier(string[position - 1]); - auto isAfterIdentifier = after < string.size() && is_shader_identifier(string[after]); - if (!isBeforeIdentifier && !isAfterIdentifier) - { string.replace(position, from.size(), to.data(), to.size()); position += to.size(); - continue; - } - position = after; } return string; - } +} - static std::string shader_space_collapse(std::string_view string) - { +static std::string shader_word_replace(std::string string, std::string_view from, std::string_view to) +{ + if (from.empty()) + return string; + + std::size_t position = 0; + while ((position = string.find(from, position)) != std::string::npos) + { + auto after = position + from.size(); + auto isBeforeIdentifier = position > 0 && is_shader_identifier(string[position - 1]); + auto isAfterIdentifier = after < string.size() && is_shader_identifier(string[after]); + if (!isBeforeIdentifier && !isAfterIdentifier) + { + string.replace(position, from.size(), to.data(), to.size()); + position += to.size(); + continue; + } + position = after; + } + return string; +} + +static std::string shader_space_collapse(std::string_view string) +{ std::string out; bool isSpace = false; for (auto character : string) { - if (std::isspace((unsigned char)character)) - { - if (!out.empty() && !isSpace) out.push_back(' '); - isSpace = true; - continue; - } - out.push_back(character); - isSpace = false; + if (std::isspace((unsigned char)character)) + { + if (!out.empty() && !isSpace) + out.push_back(' '); + isSpace = true; + continue; + } + out.push_back(character); + isSpace = false; } - if (!out.empty() && out.back() == ' ') out.pop_back(); + if (!out.empty() && out.back() == ' ') + out.pop_back(); return out; - } +} - static std::string shader_trim_get(std::string_view line) - { +static std::string shader_trim_get(std::string_view line) +{ std::size_t begin = 0; while (begin < line.size() && std::isspace((unsigned char)line[begin])) - ++begin; + ++begin; auto end = line.size(); while (end > begin && std::isspace((unsigned char)line[end - 1])) - --end; + --end; return std::string(line.substr(begin, end - begin)); - } +} - static bool is_shader_word_present(std::string_view string, std::string_view word) - { +static bool is_shader_word_present(std::string_view string, std::string_view word) +{ std::size_t position = 0; while ((position = string.find(word, position)) != std::string_view::npos) { - auto after = position + word.size(); - auto isBeforeIdentifier = position > 0 && is_shader_identifier(string[position - 1]); - auto isAfterIdentifier = after < string.size() && is_shader_identifier(string[after]); - if (!isBeforeIdentifier && !isAfterIdentifier) return true; - position = after; + auto after = position + word.size(); + auto isBeforeIdentifier = position > 0 && is_shader_identifier(string[position - 1]); + auto isAfterIdentifier = after < string.size() && is_shader_identifier(string[after]); + if (!isBeforeIdentifier && !isAfterIdentifier) + return true; + position = after; } return false; - } +} - static bool is_shader_line_skipped(std::string_view line) - { +static bool is_shader_line_skipped(std::string_view line) +{ auto normalized = shader_space_collapse(shader_trim_get(line)); - if (normalized.starts_with("#version")) return true; - if (normalized.starts_with("precision ")) return true; - if (normalized == "#define lowp" || normalized == "# define lowp") return true; - if (normalized == "#define mediump" || normalized == "# define mediump") return true; - if (normalized == "#define highp" || normalized == "# define highp") return true; - if (normalized == "#define texture texture2D" || normalized == "# define texture texture2D") return true; - if (normalized == "#define fragColor gl_FragColor" || normalized == "# define fragColor gl_FragColor") return true; + if (normalized.starts_with("#version")) + return true; + if (normalized.starts_with("precision ")) + return true; + if (normalized == "#define lowp" || normalized == "# define lowp") + return true; + if (normalized == "#define mediump" || normalized == "# define mediump") + return true; + if (normalized == "#define highp" || normalized == "# define highp") + return true; + if (normalized == "#define texture texture2D" || normalized == "# define texture texture2D") + return true; + if (normalized == "#define fragColor gl_FragColor" || normalized == "# define fragColor gl_FragColor") + return true; return false; - } +} - static std::string shader_precision_erase(std::string line) - { +static std::string shader_precision_erase(std::string line) +{ line = shader_word_replace(std::move(line), "lowp", ""); line = shader_word_replace(std::move(line), "mediump", ""); line = shader_word_replace(std::move(line), "highp", ""); return line; - } +} - static std::string shader_line_convert(std::string line, ShaderStage stage) - { +static std::string shader_line_convert(std::string line, ShaderStage stage) +{ line = shader_precision_erase(std::move(line)); line = shader_word_replace(std::move(line), "attribute", "in"); line = shader_word_replace(std::move(line), "varying", stage == SHADER_STAGE_VERTEX ? "out" : "in"); @@ -158,204 +173,226 @@ SHADER_GLES_WORD_REPLACEMENTS #undef X return line; - } +} - static std::string shader_fragment_declarations_get(std::string_view body) - { - if (!is_shader_word_present(body, "fragColor")) return {}; - if (body.find("out vec4 fragColor") != std::string_view::npos) return {}; +static std::string shader_fragment_declarations_get(std::string_view body) +{ + if (!is_shader_word_present(body, "fragColor")) + return {}; + if (body.find("out vec4 fragColor") != std::string_view::npos) + return {}; return "out vec4 fragColor;\n"; - } +} - static std::string uniform_name_clean_get(std::string name) - { - if (name.ends_with("[0]")) name.erase(name.size() - 3); +static std::string uniform_name_clean_get(std::string name) +{ + if (name.ends_with("[0]")) + name.erase(name.size() - 3); return name; - } +} - static std::string uniform_float_string_get(float value) { return std::format("{:.6g}", value); } +static std::string uniform_float_string_get(float value) +{ + return std::format("{:.6g}", value); +} - UniformBinding uniform_binding_auto_get(std::string_view name, UniformValueType type) - { +UniformBinding uniform_binding_auto_get(std::string_view name, UniformValueType type) +{ for (auto& alias : UNIFORM_ALIASES) - if (name == alias.name && is_uniform_binding_valid(alias.binding, type)) return alias.binding; - if (type == UNIFORM_VALUE_SAMPLER2D) return UNIFORM_BINDING_MAIN_TEXTURE; - if (is_uniform_value_editable(type)) return UNIFORM_BINDING_MANUAL; + if (name == alias.name && is_uniform_binding_valid(alias.binding, type)) + return alias.binding; + if (type == UNIFORM_VALUE_SAMPLER2D) + return UNIFORM_BINDING_MAIN_TEXTURE; + if (is_uniform_value_editable(type)) + return UNIFORM_BINDING_MANUAL; return UNIFORM_BINDING_IGNORE; - } +} - UniformBinding uniform_binding_get(std::string_view value) - { +UniformBinding uniform_binding_get(std::string_view value) +{ for (auto& info : UNIFORM_BINDING_INFOS) - if (value == info.value) return info.binding; + if (value == info.value) + return info.binding; return UNIFORM_BINDING_IGNORE; - } +} - std::string_view uniform_binding_value_get(UniformBinding binding) - { +std::string_view uniform_binding_value_get(UniformBinding binding) +{ for (auto& info : UNIFORM_BINDING_INFOS) - if (binding == info.binding) return info.value; + if (binding == info.binding) + return info.value; return UNIFORM_BINDING_INFOS[0].value; - } +} - std::string_view uniform_binding_label_get(UniformBinding binding) - { +std::string_view uniform_binding_label_get(UniformBinding binding) +{ for (auto& info : UNIFORM_BINDING_INFOS) - if (binding == info.binding) return info.label; + if (binding == info.binding) + return info.label; return UNIFORM_BINDING_INFOS[0].label; - } +} - UniformValueType uniform_value_type_get(GLenum type) - { +UniformValueType uniform_value_type_get(GLenum type) +{ switch (type) { - case GL_FLOAT: - return UNIFORM_VALUE_FLOAT; - case GL_INT: - case GL_BOOL: - return UNIFORM_VALUE_INT; - case GL_FLOAT_VEC2: - return UNIFORM_VALUE_VEC2; - case GL_FLOAT_VEC3: - return UNIFORM_VALUE_VEC3; - case GL_FLOAT_VEC4: - return UNIFORM_VALUE_VEC4; - case GL_FLOAT_MAT4: - return UNIFORM_VALUE_MAT4; - case GL_SAMPLER_2D: - return UNIFORM_VALUE_SAMPLER2D; - default: - return UNIFORM_VALUE_UNKNOWN; + case GL_FLOAT: + return UNIFORM_VALUE_FLOAT; + case GL_INT: + case GL_BOOL: + return UNIFORM_VALUE_INT; + case GL_FLOAT_VEC2: + return UNIFORM_VALUE_VEC2; + case GL_FLOAT_VEC3: + return UNIFORM_VALUE_VEC3; + case GL_FLOAT_VEC4: + return UNIFORM_VALUE_VEC4; + case GL_FLOAT_MAT4: + return UNIFORM_VALUE_MAT4; + case GL_SAMPLER_2D: + return UNIFORM_VALUE_SAMPLER2D; + default: + return UNIFORM_VALUE_UNKNOWN; } - } +} - std::string_view uniform_value_type_label_get(UniformValueType type) - { +std::string_view uniform_value_type_label_get(UniformValueType type) +{ return UNIFORM_VALUE_TYPE_INFOS[type < UNIFORM_VALUE_COUNT ? type : UNIFORM_VALUE_UNKNOWN].label; - } +} - bool is_uniform_value_editable(UniformValueType type) - { +bool is_uniform_value_editable(UniformValueType type) +{ return type == UNIFORM_VALUE_FLOAT || type == UNIFORM_VALUE_INT || type == UNIFORM_VALUE_VEC2 || type == UNIFORM_VALUE_VEC3 || type == UNIFORM_VALUE_VEC4 || type == UNIFORM_VALUE_SAMPLER2D; - } +} - bool is_uniform_value_vector(UniformValueType type) { return UNIFORM_VALUE_TYPE_INFOS[type].componentCount > 0; } +bool is_uniform_value_vector(UniformValueType type) +{ + return UNIFORM_VALUE_TYPE_INFOS[type].componentCount > 0; +} - static bool is_component_binding_valid(UniformBinding binding) - { +static bool is_component_binding_valid(UniformBinding binding) +{ return binding == UNIFORM_BINDING_MANUAL || binding == UNIFORM_BINDING_PLAYBACK_TIME; - } +} - void uniform_configs_apply(const Shader& shader, std::vector& uniforms) - { +void uniform_configs_apply(const Shader& shader, std::vector& uniforms) +{ for (auto& uniform : uniforms) { - auto config = std::ranges::find(shader.uniforms, uniform.name, &Uniform::name); - if (config == shader.uniforms.end()) continue; + auto config = std::ranges::find(shader.uniforms, uniform.name, &Uniform::name); + if (config == shader.uniforms.end()) + 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 = std::ranges::find(config->components, index, &Component::index); - if (component == config->components.end()) 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; - } + 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 = std::ranges::find(config->components, index, &Component::index); + if (component == config->components.end()) + 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; + } } - } +} - // Drops saved uniform settings the compiled shader no longer has or cannot use. - bool uniform_configs_trim(Shader& shader, const std::vector& uniforms) - { - bool isChanged = std::erase_if(shader.uniforms, - [&](const Uniform& config) - { - return std::ranges::none_of(uniforms, [&](const ShaderUniform& uniform) - { return uniform.name == config.name; }); - }) > 0; +// Drops saved uniform settings the compiled shader no longer has or cannot use. +bool uniform_configs_trim(Shader& shader, const std::vector& uniforms) +{ + bool isChanged = std::erase_if(shader.uniforms, [&](const Uniform& config) { + return std::ranges::none_of( + uniforms, [&](const ShaderUniform& uniform) { return uniform.name == config.name; }); + }) > 0; for (auto& config : shader.uniforms) { - auto& uniform = *std::ranges::find(uniforms, config.name, &ShaderUniform::name); - if (!config.binding.empty() && !is_uniform_binding_valid(uniform_binding_get(config.binding), uniform.valueType)) - { - config.binding.clear(); - isChanged = true; - } + auto& uniform = *std::ranges::find(uniforms, config.name, &ShaderUniform::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.components, [&](const Component& component) - { return !isComponents || component.index < 0 || component.index >= componentCount; }) > 0; + auto componentCount = UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount; + auto isComponents = uniform_binding_get(config.binding) == UNIFORM_BINDING_COMPONENTS; + isChanged |= std::erase_if(config.components, [&](const Component& component) { + return !isComponents || component.index < 0 || component.index >= componentCount; + }) > 0; - for (auto& component : config.components) - { - if (component.binding.empty() || is_component_binding_valid(uniform_binding_get(component.binding))) continue; - component.binding.clear(); - isChanged = true; - } + for (auto& component : config.components) + { + if (component.binding.empty() || is_component_binding_valid(uniform_binding_get(component.binding))) + continue; + component.binding.clear(); + isChanged = true; + } } return isChanged; - } +} - void uniform_config_save(Shader& shader, const ShaderUniform& uniform) - { +void uniform_config_save(Shader& shader, const ShaderUniform& uniform) +{ auto config = std::ranges::find(shader.uniforms, uniform.name, &Uniform::name); - if (config == shader.uniforms.end()) config = shader.uniforms.insert(shader.uniforms.end(), {.name = uniform.name}); + if (config == shader.uniforms.end()) + config = shader.uniforms.insert(shader.uniforms.end(), {.name = uniform.name}); config->binding = std::string(uniform_binding_value_get(uniform.binding)); config->value = uniform_value_string_get(uniform); config->components.clear(); - if (uniform.binding != UNIFORM_BINDING_COMPONENTS) return; + if (uniform.binding != UNIFORM_BINDING_COMPONENTS) + return; for (int index = 0; index < (int)uniform.components.size(); ++index) - config->components.push_back( - {.index = index, - .binding = std::string(uniform_binding_value_get(uniform.components[index].binding)), - .value = std::format("{:.6g}", uniform.components[index].value)}); - } + config->components.push_back( + {.index = index, + .binding = std::string(uniform_binding_value_get(uniform.components[index].binding)), + .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) +{ switch (binding) { - case UNIFORM_BINDING_IGNORE: - return true; - case UNIFORM_BINDING_MANUAL: - return is_uniform_value_editable(type); - case UNIFORM_BINDING_MAIN_TEXTURE: - return type == UNIFORM_VALUE_SAMPLER2D; - case UNIFORM_BINDING_TRANSFORM: - return type == UNIFORM_VALUE_MAT4; - case UNIFORM_BINDING_FRAME_TINT: - case UNIFORM_BINDING_COLOR_OFFSET: - case UNIFORM_BINDING_TEXTURE_SIZE: - case UNIFORM_BINDING_PLAYBACK_TIME: - return type == UNIFORM_VALUE_FLOAT || is_uniform_value_vector(type); - case UNIFORM_BINDING_COMPONENTS: - return is_uniform_value_vector(type); - default: - return false; + case UNIFORM_BINDING_IGNORE: + return true; + case UNIFORM_BINDING_MANUAL: + return is_uniform_value_editable(type); + case UNIFORM_BINDING_MAIN_TEXTURE: + return type == UNIFORM_VALUE_SAMPLER2D; + case UNIFORM_BINDING_TRANSFORM: + return type == UNIFORM_VALUE_MAT4; + case UNIFORM_BINDING_FRAME_TINT: + case UNIFORM_BINDING_COLOR_OFFSET: + case UNIFORM_BINDING_TEXTURE_SIZE: + case UNIFORM_BINDING_PLAYBACK_TIME: + return type == UNIFORM_VALUE_FLOAT || is_uniform_value_vector(type); + case UNIFORM_BINDING_COMPONENTS: + return is_uniform_value_vector(type); + default: + return false; } - } +} - void uniform_value_parse(ShaderUniform& uniform, std::string_view value) - { - if (value.empty()) return; +void uniform_value_parse(ShaderUniform& uniform, std::string_view value) +{ + if (value.empty()) + return; std::stringstream stream{std::string(value)}; if (uniform.valueType == UNIFORM_VALUE_INT || uniform.valueType == UNIFORM_VALUE_SAMPLER2D) { - stream >> uniform.intValue; - return; + stream >> uniform.intValue; + return; } stream >> uniform.value.x >> uniform.value.y >> uniform.value.z >> uniform.value.w; @@ -363,72 +400,73 @@ uniform.components[1].value = uniform.value.y; uniform.components[2].value = uniform.value.z; uniform.components[3].value = uniform.value.w; - } +} - std::string uniform_value_string_get(const ShaderUniform& uniform) - { +std::string uniform_value_string_get(const ShaderUniform& uniform) +{ switch (uniform.valueType) { - case UNIFORM_VALUE_FLOAT: - return uniform_float_string_get(uniform.value.x); - case UNIFORM_VALUE_INT: - case UNIFORM_VALUE_SAMPLER2D: - return std::format("{}", uniform.intValue); - case UNIFORM_VALUE_VEC2: - return std::format("{} {}", uniform_float_string_get(uniform.value.x), - uniform_float_string_get(uniform.value.y)); - case UNIFORM_VALUE_VEC3: - return std::format("{} {} {}", uniform_float_string_get(uniform.value.x), - uniform_float_string_get(uniform.value.y), uniform_float_string_get(uniform.value.z)); - case UNIFORM_VALUE_VEC4: - 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.w)); - default: - return {}; + case UNIFORM_VALUE_FLOAT: + return uniform_float_string_get(uniform.value.x); + case UNIFORM_VALUE_INT: + case UNIFORM_VALUE_SAMPLER2D: + return std::format("{}", uniform.intValue); + case UNIFORM_VALUE_VEC2: + return std::format("{} {}", uniform_float_string_get(uniform.value.x), + uniform_float_string_get(uniform.value.y)); + case UNIFORM_VALUE_VEC3: + return std::format("{} {} {}", uniform_float_string_get(uniform.value.x), + uniform_float_string_get(uniform.value.y), uniform_float_string_get(uniform.value.z)); + case UNIFORM_VALUE_VEC4: + 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.w)); + default: + return {}; } - } +} - static std::vector uniforms_get(GLuint id) - { +static std::vector uniforms_get(GLuint id) +{ GLint count = 0; GLint maxLength = 0; glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &count); glGetProgramiv(id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxLength); std::vector uniforms; - if (count <= 0 || maxLength <= 0) return uniforms; + if (count <= 0 || maxLength <= 0) + return uniforms; std::string name((std::size_t)maxLength, '\0'); for (GLint index = 0; index < count; ++index) { - GLsizei length = 0; - GLint size = 0; - GLenum type = 0; - glGetActiveUniform(id, (GLuint)index, maxLength, &length, &size, &type, name.data()); + GLsizei length = 0; + GLint size = 0; + GLenum type = 0; + glGetActiveUniform(id, (GLuint)index, maxLength, &length, &size, &type, name.data()); - auto uniformName = uniform_name_clean_get(std::string(name.data(), (std::size_t)length)); - auto valueType = uniform_value_type_get(type); + auto uniformName = uniform_name_clean_get(std::string(name.data(), (std::size_t)length)); + auto valueType = uniform_value_type_get(type); - ShaderUniform uniform = {}; - uniform.name = uniformName; - uniform.location = glGetUniformLocation(id, uniformName.c_str()); - uniform.glType = type; - uniform.size = size; - uniform.valueType = valueType; - uniform.binding = uniform_binding_auto_get(uniformName, valueType); - uniform.components[0].value = uniform.value.x; - uniform.components[1].value = uniform.value.y; - uniform.components[2].value = uniform.value.z; - uniform.components[3].value = uniform.value.w; - uniforms.push_back(std::move(uniform)); + ShaderUniform uniform = {}; + uniform.name = uniformName; + uniform.location = glGetUniformLocation(id, uniformName.c_str()); + uniform.glType = type; + uniform.size = size; + uniform.valueType = valueType; + uniform.binding = uniform_binding_auto_get(uniformName, valueType); + uniform.components[0].value = uniform.value.x; + uniform.components[1].value = uniform.value.y; + uniform.components[2].value = uniform.value.z; + uniform.components[3].value = uniform.value.w; + uniforms.push_back(std::move(uniform)); } return uniforms; - } +} - std::string gles_convert(std::string_view source, ShaderStage stage) - { +std::string gles_convert(std::string_view source, ShaderStage stage) +{ auto normalized = shader_text_replace(std::string(source), "\r\n", "\n"); normalized = shader_text_replace(std::move(normalized), "\r", "\n"); @@ -436,45 +474,53 @@ std::size_t position = 0; while (position <= normalized.size()) { - auto end = normalized.find('\n', position); - auto isEnd = end == std::string::npos; - auto line = normalized.substr(position, isEnd ? std::string::npos : end - position); - if (!is_shader_line_skipped(line)) body += shader_line_convert(std::move(line), stage) + "\n"; - if (isEnd) break; - position = end + 1; + auto end = normalized.find('\n', position); + auto isEnd = end == std::string::npos; + auto line = normalized.substr(position, isEnd ? std::string::npos : end - position); + if (!is_shader_line_skipped(line)) + body += shader_line_convert(std::move(line), stage) + "\n"; + if (isEnd) + break; + position = end + 1; } auto declarations = stage == SHADER_STAGE_FRAGMENT ? shader_fragment_declarations_get(body) : std::string{}; return "#version 330 core\n" + declarations + body; - } +} - std::string gles_fragment_convert(std::string_view source) { return gles_convert(source, SHADER_STAGE_FRAGMENT); } +std::string gles_fragment_convert(std::string_view source) +{ + return gles_convert(source, SHADER_STAGE_FRAGMENT); +} - std::string gles_vertex_convert(std::string_view source) { return gles_convert(source, SHADER_STAGE_VERTEX); } +std::string gles_vertex_convert(std::string_view source) +{ + return gles_convert(source, SHADER_STAGE_VERTEX); +} - ShaderCompileResult shader_compile(const char* vertex, const char* fragment) - { +ShaderCompileResult shader_compile(const char* vertex, const char* fragment) +{ ShaderCompileResult result = {}; result.id = glCreateProgram(); - auto compile = [&](const GLuint& id, const char* text, const char* label) - { - int isCompile = 0; - glShaderSource(id, 1, &text, nullptr); - glCompileShader(id); - glGetShaderiv(id, GL_COMPILE_STATUS, &isCompile); + auto compile = [&](const GLuint& id, const char* text, const char* label) { + int isCompile = 0; + glShaderSource(id, 1, &text, nullptr); + glCompileShader(id); + glGetShaderiv(id, GL_COMPILE_STATUS, &isCompile); - if (!isCompile) - { - GLint length = 0; - glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); - if (length <= 0) length = 1; - std::string compileLog((std::size_t)length, '\0'); - glGetShaderInfoLog(id, length, nullptr, compileLog.data()); - result.output += std::format("{} shader compile log:\n{}\n", label, compileLog.c_str()); - return false; - } - return true; + if (!isCompile) + { + GLint length = 0; + glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); + if (length <= 0) + length = 1; + std::string compileLog((std::size_t)length, '\0'); + glGetShaderInfoLog(id, length, nullptr, compileLog.data()); + result.output += std::format("{} shader compile log:\n{}\n", label, compileLog.c_str()); + return false; + } + return true; }; auto vertexHandle = glCreateShader(GL_VERTEX_SHADER); @@ -485,28 +531,29 @@ result.isCompiled = isVertexCompiled && isFragmentCompiled; if (result.isCompiled) { - glAttachShader(result.id, vertexHandle); - glAttachShader(result.id, fragmentHandle); + glAttachShader(result.id, vertexHandle); + glAttachShader(result.id, fragmentHandle); - for (auto& alias : ATTRIBUTE_ALIASES) - glBindAttribLocation(result.id, alias.index, alias.name); + for (auto& alias : ATTRIBUTE_ALIASES) + glBindAttribLocation(result.id, alias.index, alias.name); - glLinkProgram(result.id); + glLinkProgram(result.id); - auto isLinked = GL_FALSE; - glGetProgramiv(result.id, GL_LINK_STATUS, &isLinked); - result.isLinked = isLinked == GL_TRUE; - if (!result.isLinked) - { - GLint length = 0; - glGetProgramiv(result.id, GL_INFO_LOG_LENGTH, &length); - if (length <= 0) length = 1; - std::string linkLog((std::size_t)length, '\0'); - glGetProgramInfoLog(result.id, length, nullptr, linkLog.data()); - result.output += std::format("Shader link log:\n{}\n", linkLog.c_str()); - } - else - result.uniforms = uniforms_get(result.id); + auto isLinked = GL_FALSE; + glGetProgramiv(result.id, GL_LINK_STATUS, &isLinked); + result.isLinked = isLinked == GL_TRUE; + if (!result.isLinked) + { + GLint length = 0; + glGetProgramiv(result.id, GL_INFO_LOG_LENGTH, &length); + if (length <= 0) + length = 1; + std::string linkLog((std::size_t)length, '\0'); + glGetProgramInfoLog(result.id, length, nullptr, linkLog.data()); + result.output += std::format("Shader link log:\n{}\n", linkLog.c_str()); + } + else + result.uniforms = uniforms_get(result.id); } glDeleteShader(vertexHandle); @@ -514,40 +561,49 @@ if (!result.isLinked) { - glDeleteProgram(result.id); - result.id = 0; + glDeleteProgram(result.id); + result.id = 0; } return result; - } +} - ShaderProgram::ShaderProgram() = default; +ShaderProgram::ShaderProgram() = default; - ShaderProgram::ShaderProgram(const char* vertex, const char* fragment) - { +ShaderProgram::ShaderProgram(const char* vertex, const char* fragment) +{ auto result = shader_compile(vertex, fragment); id = result.id; uniforms = std::move(result.uniforms); - if (!result.output.empty()) logger.error(result.output); - } + if (!result.output.empty()) + logger.error(result.output); +} - ShaderProgram::ShaderProgram(ShaderProgram&& other) noexcept { *this = std::move(other); } +ShaderProgram::ShaderProgram(ShaderProgram&& other) noexcept +{ + *this = std::move(other); +} - ShaderProgram& ShaderProgram::operator=(ShaderProgram&& other) noexcept - { +ShaderProgram& ShaderProgram::operator=(ShaderProgram&& other) noexcept +{ if (this != &other) { - if (is_valid()) glDeleteProgram(id); - id = other.id; - uniforms = std::move(other.uniforms); - other.id = 0; + if (is_valid()) + glDeleteProgram(id); + id = other.id; + uniforms = std::move(other.uniforms); + other.id = 0; } return *this; - } +} - ShaderProgram::~ShaderProgram() - { - if (is_valid()) glDeleteProgram(id); - } +ShaderProgram::~ShaderProgram() +{ + if (is_valid()) + glDeleteProgram(id); +} - bool ShaderProgram::is_valid() const { return id != 0; } +bool ShaderProgram::is_valid() const +{ + return id != 0; +} diff --git a/src/shader.h b/src/shader.h index a8f9cc4..8352393 100644 --- a/src/shader.h +++ b/src/shader.h @@ -8,15 +8,15 @@ #include #include - struct Shader; +struct Shader; - struct ShaderInfo - { +struct ShaderInfo +{ const char* vertex; const char* fragment; - }; +}; - inline constexpr auto VERTEX = R"( +inline constexpr auto VERTEX = R"( #version 330 core layout (location = 0) in vec2 i_position; layout (location = 1) in vec2 i_uv; @@ -29,7 +29,7 @@ } )"; - inline constexpr auto TEXTURE_COMPATIBILITY_VERTEX = R"( +inline constexpr auto TEXTURE_COMPATIBILITY_VERTEX = R"( #version 330 core layout (location = 0) in vec2 i_position; layout (location = 1) in vec2 i_uv; @@ -47,7 +47,7 @@ } )"; - inline constexpr auto AXIS_VERTEX = R"( +inline constexpr auto AXIS_VERTEX = R"( #version 330 core layout (location = 0) in vec2 i_position; // full screen line segment: -1..1 uniform vec2 u_origin_ndc; // world origin in NDC @@ -63,7 +63,7 @@ } )"; - inline constexpr auto FRAGMENT = R"( +inline constexpr auto FRAGMENT = R"( #version 330 core out vec4 o_fragColor; uniform vec4 u_color; @@ -73,9 +73,9 @@ } )"; - // u_blur > 0: Flash's low-quality BlurFilter, a box of 2 * u_blur + 1 texels averaged (premultiplied) over the - // u_region crop, clear outside it; a wide box steps over texels so a fragment reads at most BLUR_SAMPLES per axis. - inline constexpr auto TEXTURE_FRAGMENT = R"( +// u_blur > 0: Flash's low-quality BlurFilter, a box of 2 * u_blur + 1 texels averaged (premultiplied) over the +// u_region crop, clear outside it. A wide box steps over texels so a fragment reads at most BLUR_SAMPLES per axis. +inline constexpr auto TEXTURE_FRAGMENT = R"( #version 330 core in vec2 i_uv_out; uniform sampler2D u_texture; @@ -118,7 +118,7 @@ } )"; - inline constexpr auto GRID_VERTEX = R"( +inline constexpr auto GRID_VERTEX = R"( #version 330 core layout (location = 0) in vec2 i_position; layout (location = 1) in vec2 i_uv; @@ -132,7 +132,7 @@ } )"; - inline constexpr auto GRID_FRAGMENT = R"( +inline constexpr auto GRID_FRAGMENT = R"( #version 330 core in vec2 i_uv_out; @@ -165,7 +165,7 @@ } )"; - inline constexpr auto DASHED_VERTEX = R"( +inline constexpr auto DASHED_VERTEX = R"( #version 330 core layout (location = 0) in vec2 i_position; @@ -180,7 +180,7 @@ } )"; - inline constexpr auto DASHED_FRAGMENT = R"( +inline constexpr auto DASHED_FRAGMENT = R"( #version 330 core in vec2 v_local; @@ -238,124 +238,124 @@ } )"; - constexpr auto UNIFORM_AXIS = "u_axis"; - constexpr auto UNIFORM_COLOR = "u_color"; - constexpr auto UNIFORM_TRANSFORM = "u_transform"; - constexpr auto UNIFORM_TINT = "u_tint"; - constexpr auto UNIFORM_COLOR_OFFSET = "u_color_offset"; - constexpr auto UNIFORM_OFFSET = "u_offset"; - constexpr auto UNIFORM_ORIGIN_NDC = "u_origin_ndc"; - constexpr auto UNIFORM_SIZE = "u_size"; - constexpr auto UNIFORM_MODEL = "u_model"; - constexpr auto UNIFORM_RECT_SIZE = "u_rect_size"; - constexpr auto UNIFORM_TEXTURE = "u_texture"; - constexpr auto UNIFORM_AXIS_X = "u_axis_x"; - constexpr auto UNIFORM_AXIS_Y = "u_axis_y"; - constexpr auto UNIFORM_DASH_LENGTH = "u_dash_length"; - constexpr auto UNIFORM_DASH_GAP = "u_dash_gap"; - constexpr auto UNIFORM_DASH_OFFSET = "u_dash_offset"; - constexpr auto UNIFORM_BLUR = "u_blur"; - constexpr auto UNIFORM_REGION = "u_region"; - constexpr auto UNIFORM_TEXEL = "u_texel"; +constexpr auto UNIFORM_AXIS = "u_axis"; +constexpr auto UNIFORM_COLOR = "u_color"; +constexpr auto UNIFORM_TRANSFORM = "u_transform"; +constexpr auto UNIFORM_TINT = "u_tint"; +constexpr auto UNIFORM_COLOR_OFFSET = "u_color_offset"; +constexpr auto UNIFORM_OFFSET = "u_offset"; +constexpr auto UNIFORM_ORIGIN_NDC = "u_origin_ndc"; +constexpr auto UNIFORM_SIZE = "u_size"; +constexpr auto UNIFORM_MODEL = "u_model"; +constexpr auto UNIFORM_RECT_SIZE = "u_rect_size"; +constexpr auto UNIFORM_TEXTURE = "u_texture"; +constexpr auto UNIFORM_AXIS_X = "u_axis_x"; +constexpr auto UNIFORM_AXIS_Y = "u_axis_y"; +constexpr auto UNIFORM_DASH_LENGTH = "u_dash_length"; +constexpr auto UNIFORM_DASH_GAP = "u_dash_gap"; +constexpr auto UNIFORM_DASH_OFFSET = "u_dash_offset"; +constexpr auto UNIFORM_BLUR = "u_blur"; +constexpr auto UNIFORM_REGION = "u_region"; +constexpr auto UNIFORM_TEXEL = "u_texel"; #define RESOURCE_SHADER_ATTRIBUTE_ALIASES \ - X(0, "i_position") \ - X(0, "a_position") \ - X(0, "Position") \ - X(0, "Position0") \ - X(1, "i_uv") \ - X(1, "a_uv") \ - X(1, "TexCoord") \ - X(1, "TexCoord0") \ - X(1, "TextureCoord") \ - X(1, "UV") \ - X(1, "UV0") \ - X(2, "i_color") \ - X(2, "a_color") \ - X(2, "Color") \ - X(2, "Color0") + X(0, "i_position") \ + X(0, "a_position") \ + X(0, "Position") \ + X(0, "Position0") \ + X(1, "i_uv") \ + X(1, "a_uv") \ + X(1, "TexCoord") \ + X(1, "TexCoord0") \ + X(1, "TextureCoord") \ + X(1, "UV") \ + X(1, "UV0") \ + X(2, "i_color") \ + X(2, "a_color") \ + X(2, "Color") \ + X(2, "Color0") - struct AttributeAlias - { +struct AttributeAlias +{ GLuint index = 0; const char* name = nullptr; - }; +}; - inline constexpr AttributeAlias ATTRIBUTE_ALIASES[] = { +inline constexpr AttributeAlias ATTRIBUTE_ALIASES[] = { #define X(index, name) {index, name}, - RESOURCE_SHADER_ATTRIBUTE_ALIASES + RESOURCE_SHADER_ATTRIBUTE_ALIASES #undef X - }; +}; #define RESOURCE_SHADER_UNIFORM_BINDINGS \ - X(IGNORE, "Ignore", "Ignore") \ - X(MAIN_TEXTURE, "MainTexture", "Main Texture") \ - X(TRANSFORM, "Transform", "Transform") \ - X(FRAME_TINT, "FrameTint", "Frame Tint") \ - X(COLOR_OFFSET, "ColorOffset", "Color Offset") \ - X(TEXTURE_SIZE, "TextureSize", "Texture Size") \ - X(PLAYBACK_TIME, "PlaybackTime", "Playback Time") \ - X(COMPONENTS, "Components", "Per Component") \ - X(MANUAL, "Manual", "Manual") + X(IGNORE, "Ignore", "Ignore") \ + X(MAIN_TEXTURE, "MainTexture", "Main Texture") \ + X(TRANSFORM, "Transform", "Transform") \ + X(FRAME_TINT, "FrameTint", "Frame Tint") \ + X(COLOR_OFFSET, "ColorOffset", "Color Offset") \ + X(TEXTURE_SIZE, "TextureSize", "Texture Size") \ + X(PLAYBACK_TIME, "PlaybackTime", "Playback Time") \ + X(COMPONENTS, "Components", "Per Component") \ + X(MANUAL, "Manual", "Manual") - enum UniformBinding - { +enum UniformBinding +{ #define X(symbol, value, label) UNIFORM_BINDING_##symbol, RESOURCE_SHADER_UNIFORM_BINDINGS #undef X UNIFORM_BINDING_COUNT - }; +}; - struct UniformBindingInfo - { +struct UniformBindingInfo +{ UniformBinding binding = {}; const char* value = nullptr; const char* label = nullptr; - }; +}; - inline constexpr UniformBindingInfo UNIFORM_BINDING_INFOS[] = { +inline constexpr UniformBindingInfo UNIFORM_BINDING_INFOS[] = { #define X(symbol, value, label) {UNIFORM_BINDING_##symbol, value, label}, - RESOURCE_SHADER_UNIFORM_BINDINGS + RESOURCE_SHADER_UNIFORM_BINDINGS #undef X - }; +}; #define RESOURCE_SHADER_UNIFORM_VALUE_TYPES \ - X(UNKNOWN, "Unknown", 0) \ - X(FLOAT, "Float", 0) \ - X(INT, "Int", 0) \ - X(VEC2, "Vec2", 2) \ - X(VEC3, "Vec3", 3) \ - X(VEC4, "Vec4", 4) \ - X(MAT4, "Mat4", 0) \ - X(SAMPLER2D, "Sampler2D", 0) + X(UNKNOWN, "Unknown", 0) \ + X(FLOAT, "Float", 0) \ + X(INT, "Int", 0) \ + X(VEC2, "Vec2", 2) \ + X(VEC3, "Vec3", 3) \ + X(VEC4, "Vec4", 4) \ + X(MAT4, "Mat4", 0) \ + X(SAMPLER2D, "Sampler2D", 0) - enum UniformValueType - { +enum UniformValueType +{ #define X(symbol, label, componentCount) UNIFORM_VALUE_##symbol, RESOURCE_SHADER_UNIFORM_VALUE_TYPES #undef X UNIFORM_VALUE_COUNT - }; +}; - struct UniformValueTypeInfo - { +struct UniformValueTypeInfo +{ UniformValueType type = {}; const char* label = nullptr; int componentCount = 0; - }; +}; - inline constexpr UniformValueTypeInfo UNIFORM_VALUE_TYPE_INFOS[] = { +inline constexpr UniformValueTypeInfo UNIFORM_VALUE_TYPE_INFOS[] = { #define X(symbol, label, componentCount) {UNIFORM_VALUE_##symbol, label, componentCount}, - RESOURCE_SHADER_UNIFORM_VALUE_TYPES + RESOURCE_SHADER_UNIFORM_VALUE_TYPES #undef X - }; +}; - struct ShaderUniform - { +struct ShaderUniform +{ struct Component { - UniformBinding binding = UNIFORM_BINDING_MANUAL; - float value = 0; + UniformBinding binding = UNIFORM_BINDING_MANUAL; + float value = 0; }; std::string name; @@ -367,62 +367,62 @@ glm::vec4 value{}; int intValue = 0; std::array components = {}; - }; +}; - enum ShaderStage - { +enum ShaderStage +{ SHADER_STAGE_VERTEX, SHADER_STAGE_FRAGMENT - }; +}; - enum ShaderType - { +enum ShaderType +{ SHADER_LINE, SHADER_DASHED, SHADER_TEXTURE, SHADER_AXIS, SHADER_GRID, SHADER_COUNT - }; +}; - const ShaderInfo SHADERS[SHADER_COUNT] = {{VERTEX, FRAGMENT}, - {DASHED_VERTEX, DASHED_FRAGMENT}, - {VERTEX, TEXTURE_FRAGMENT}, - {AXIS_VERTEX, FRAGMENT}, - {GRID_VERTEX, GRID_FRAGMENT}}; +const ShaderInfo SHADERS[SHADER_COUNT] = {{VERTEX, FRAGMENT}, + {DASHED_VERTEX, DASHED_FRAGMENT}, + {VERTEX, TEXTURE_FRAGMENT}, + {AXIS_VERTEX, FRAGMENT}, + {GRID_VERTEX, GRID_FRAGMENT}}; - UniformBinding uniform_binding_auto_get(std::string_view, UniformValueType); - void uniform_configs_apply(const Shader&, std::vector&); - bool uniform_configs_trim(Shader&, const std::vector&); - void uniform_config_save(Shader&, const ShaderUniform&); - UniformBinding uniform_binding_get(std::string_view); - std::string_view uniform_binding_value_get(UniformBinding); - std::string_view uniform_binding_label_get(UniformBinding); - UniformValueType uniform_value_type_get(GLenum); - std::string_view uniform_value_type_label_get(UniformValueType); - bool is_uniform_value_editable(UniformValueType); - bool is_uniform_value_vector(UniformValueType); - bool is_uniform_binding_valid(UniformBinding, UniformValueType); - void uniform_value_parse(ShaderUniform&, std::string_view); - std::string uniform_value_string_get(const ShaderUniform&); - std::string gles_convert(std::string_view, ShaderStage); - std::string gles_fragment_convert(std::string_view); - std::string gles_vertex_convert(std::string_view); +UniformBinding uniform_binding_auto_get(std::string_view, UniformValueType); +void uniform_configs_apply(const Shader&, std::vector&); +bool uniform_configs_trim(Shader&, const std::vector&); +void uniform_config_save(Shader&, const ShaderUniform&); +UniformBinding uniform_binding_get(std::string_view); +std::string_view uniform_binding_value_get(UniformBinding); +std::string_view uniform_binding_label_get(UniformBinding); +UniformValueType uniform_value_type_get(GLenum); +std::string_view uniform_value_type_label_get(UniformValueType); +bool is_uniform_value_editable(UniformValueType); +bool is_uniform_value_vector(UniformValueType); +bool is_uniform_binding_valid(UniformBinding, UniformValueType); +void uniform_value_parse(ShaderUniform&, std::string_view); +std::string uniform_value_string_get(const ShaderUniform&); +std::string gles_convert(std::string_view, ShaderStage); +std::string gles_fragment_convert(std::string_view); +std::string gles_vertex_convert(std::string_view); - struct ShaderCompileResult - { +struct ShaderCompileResult +{ GLuint id = 0; std::string output; std::vector uniforms; bool isCompiled = false; bool isLinked = false; - }; +}; - ShaderCompileResult shader_compile(const char*, const char*); +ShaderCompileResult shader_compile(const char*, const char*); - class ShaderProgram - { - public: +class ShaderProgram +{ +public: GLuint id = 0; std::vector uniforms; @@ -432,4 +432,4 @@ ShaderProgram& operator=(ShaderProgram&&) noexcept; ~ShaderProgram(); bool is_valid() const; - }; +}; diff --git a/src/snapshots.cpp b/src/snapshots.cpp index 89e22b8..0c6722f 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -2,132 +2,157 @@ #include - template static bool is_value_equal(const T& left, const T& right) { return left == right; } +template static bool is_value_equal(const T& left, const T& right) +{ + return left == right; +} - static bool is_value_equal(const Model& left, const Model& right) - { +static bool is_value_equal(const Model& left, const Model& right) +{ return is_model_equal(left, right); - } +} - static bool is_value_equal(const Playback& left, const Playback& right) - { +static bool is_value_equal(const Playback& left, const Playback& right) +{ return left.time == right.time && left.isPlaying == right.isPlaying && left.isFinished == right.isFinished; - } +} - static bool is_step_empty(const SnapshotStep& step) - { +static bool is_step_empty(const SnapshotStep& step) +{ #define X(type, name) \ - if (!is_value_equal(step.before.name, step.after.name)) return false; + if (!is_value_equal(step.before.name, step.after.name)) \ + return false; SNAPSHOT_STEP_STATE_FIELDS #undef X return true; - } +} - static void step_apply(Snapshot& current, const SnapshotStep& step, bool isUndo) - { +static void step_apply(Snapshot& current, const SnapshotStep& step, bool isUndo) +{ auto& target = isUndo ? step.before : step.after; #define X(type, name) \ - if (!is_value_equal(step.before.name, step.after.name)) current.name = target.name; + if (!is_value_equal(step.before.name, step.after.name)) \ + current.name = target.name; SNAPSHOT_STEP_STATE_FIELDS #undef X current.message = step.after.message; - } +} - static Reference focus_get(const Snapshot& snapshot) - { +static Reference focus_get(const Snapshot& snapshot) +{ return selection_focus_get(snapshot.selection, UidIndex(snapshot.model)); - } +} - static void selection_follow(Snapshot& snapshot, Reference before) - { +static void selection_follow(Snapshot& snapshot, Reference before) +{ snapshot.model.uids_repair(); selection_follow(snapshot.selection, snapshot.model, UidIndex(snapshot.model), before); - } +} - int SnapshotStack::maxSize = SNAPSHOT_MAX; +int SnapshotStack::maxSize = SNAPSHOT_MAX; - bool SnapshotStack::is_empty() { return stack.empty(); } - std::size_t SnapshotStack::size() const { return stack.size(); } +bool SnapshotStack::is_empty() +{ + return stack.empty(); +} - void SnapshotStack::push(SnapshotStep step) - { +std::size_t SnapshotStack::size() const +{ + return stack.size(); +} + +void SnapshotStack::push(SnapshotStep step) +{ stack.push_back(std::move(step)); trim_to_limit(); - } +} - std::optional SnapshotStack::pop() - { - if (stack.empty()) return std::nullopt; +std::optional SnapshotStack::pop() +{ + if (stack.empty()) + return std::nullopt; auto step = std::move(stack.back()); stack.pop_back(); return step; - } +} - void SnapshotStack::clear() { stack.clear(); } +void SnapshotStack::clear() +{ + stack.clear(); +} - void SnapshotStack::trim_to_limit() - { +void SnapshotStack::trim_to_limit() +{ while ((int)stack.size() > maxSize) - stack.pop_front(); - } + stack.pop_front(); +} - void SnapshotStack::max_size_set(int value) { maxSize = std::max(value, 0); } +void SnapshotStack::max_size_set(int value) +{ + maxSize = std::max(value, 0); +} - // Starts an undoable edit: remembers the state before it (cheap; animations are shared). - void Snapshots::push(const std::string& message) - { - if (pending || pendingFocus) commit(); +// Starts an undoable edit: remembers the state before it (cheap. Animations are shared). +void Snapshots::push(const std::string& message) +{ + if (pending || pendingFocus) + commit(); pendingFocus = focus_get(current); current.message = message; pending = current; - } +} - void Snapshots::commit() - { - if (pendingFocus) selection_follow(current, *std::exchange(pendingFocus, std::nullopt)); - if (!pending) return; +void Snapshots::commit() +{ + if (pendingFocus) + selection_follow(current, *std::exchange(pendingFocus, std::nullopt)); + if (!pending) + return; SnapshotStep step = {std::move(*std::exchange(pending, std::nullopt)), current}; - if (is_step_empty(step)) return; + if (is_step_empty(step)) + return; undoStack.push(std::move(step)); redoStack.clear(); - } +} - bool Snapshots::undo() - { +bool Snapshots::undo() +{ pending.reset(); pendingFocus.reset(); auto step = undoStack.pop(); - if (!step) return false; + if (!step) + return false; auto focus = focus_get(current); step_apply(current, *step, true); selection_follow(current, focus); redoStack.push(std::move(*step)); return true; - } +} - bool Snapshots::redo() - { +bool Snapshots::redo() +{ pending.reset(); pendingFocus.reset(); auto step = redoStack.pop(); - if (!step) return false; + if (!step) + return false; auto focus = focus_get(current); step_apply(current, *step, false); selection_follow(current, focus); undoStack.push(std::move(*step)); return true; - } +} - void Snapshots::reset() - { +void Snapshots::reset() +{ undoStack.clear(); redoStack.clear(); pending.reset(); pendingFocus.reset(); - } +} - void Snapshots::apply_limit() - { +void Snapshots::apply_limit() +{ undoStack.trim_to_limit(); redoStack.trim_to_limit(); - } +} diff --git a/src/snapshots.h b/src/snapshots.h index 14e2c29..e02c885 100644 --- a/src/snapshots.h +++ b/src/snapshots.h @@ -9,38 +9,38 @@ #include "playback.h" #include "selection.h" - constexpr auto SNAPSHOT_ACTION = "Action"; - constexpr auto SNAPSHOT_MAX = 20; +constexpr auto SNAPSHOT_ACTION = "Action"; +constexpr auto SNAPSHOT_MAX = 20; - using AssetKeys = std::map; +using AssetKeys = std::map; #define SNAPSHOT_STEP_STATE_FIELDS \ - X(Model, model) \ - X(Playback, playback) \ - X(Selection, selection) \ - X(float, frameTime) \ - X(AssetKeys, textures) \ - X(AssetKeys, sounds) + X(Model, model) \ + X(Playback, playback) \ + X(Selection, selection) \ + X(float, frameTime) \ + X(AssetKeys, textures) \ + X(AssetKeys, sounds) - // Everything undo restores. The model's animations are shared between snapshots and copied only when edited. - struct Snapshot - { +// Everything undo restores. The model's animations are shared between snapshots and copied only when edited. +struct Snapshot +{ #define X(type, name) type name{}; SNAPSHOT_STEP_STATE_FIELDS #undef X std::string message = SNAPSHOT_ACTION; - }; +}; - // One undoable edit: the state before and after it; undo/redo restore only the fields the edit changed. - struct SnapshotStep - { +// One undoable edit: the state before and after it. Undo/redo restore only the fields the edit changed. +struct SnapshotStep +{ Snapshot before = {}; Snapshot after = {}; - }; +}; - class SnapshotStack - { - public: +class SnapshotStack +{ +public: bool is_empty(); std::size_t size() const; void push(SnapshotStep); @@ -50,14 +50,14 @@ static void max_size_set(int); - private: +private: static int maxSize; std::deque stack; - }; +}; - class Snapshots - { - public: +class Snapshots +{ +public: SnapshotStack undoStack = {}; SnapshotStack redoStack = {}; Snapshot current = {}; @@ -70,4 +70,4 @@ bool redo(); void reset(); void apply_limit(); - }; +}; diff --git a/src/socket.cpp b/src/socket.cpp index b285212..72b5bed 100644 --- a/src/socket.cpp +++ b/src/socket.cpp @@ -4,55 +4,62 @@ #include #ifdef _WIN32 - struct WSAInitializer - { +struct WSAInitializer +{ WSAInitializer() { - WSADATA data = {}; - WSAStartup(MAKEWORD(2, 2), &data); + WSADATA data = {}; + WSAStartup(MAKEWORD(2, 2), &data); } - ~WSAInitializer() { WSACleanup(); } - }; + ~WSAInitializer() + { + WSACleanup(); + } +}; - WSAInitializer initializer = {}; +WSAInitializer initializer = {}; #endif - static int socket_last_error() - { +static int socket_last_error() +{ #ifdef _WIN32 return WSAGetLastError(); #else return errno; #endif - } +} - Socket::Socket() : handle(SOCKET_INVALID), role(CLIENT), lastError(0) {} +Socket::Socket() : handle(SOCKET_INVALID), role(CLIENT), lastError(0) +{} - Socket::Socket(Socket&& other) noexcept : handle(other.handle), role(other.role), lastError(other.lastError) - { +Socket::Socket(Socket&& other) noexcept : handle(other.handle), role(other.role), lastError(other.lastError) +{ other.handle = SOCKET_INVALID; other.lastError = 0; - } +} - Socket& Socket::operator=(Socket&& other) noexcept - { +Socket& Socket::operator=(Socket&& other) noexcept +{ if (this != &other) { - close(); - handle = other.handle; - role = other.role; - other.handle = SOCKET_INVALID; - lastError = other.lastError; - other.lastError = 0; + close(); + handle = other.handle; + role = other.role; + other.handle = SOCKET_INVALID; + lastError = other.lastError; + other.lastError = 0; } return *this; - } +} - Socket::~Socket() { close(); } +Socket::~Socket() +{ + close(); +} - bool Socket::open(SocketRole newRole) - { +bool Socket::open(SocketRole newRole) +{ close(); role = newRole; @@ -60,41 +67,42 @@ if (!is_valid()) { - lastError = socket_last_error(); - return false; + lastError = socket_last_error(); + return false; } if (role == SERVER) { #ifdef _WIN32 - BOOL opt = TRUE; - if (::setsockopt(handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast(&opt), sizeof(opt)) != 0) - { - lastError = socket_last_error(); - close(); - return false; - } + BOOL opt = TRUE; + if (::setsockopt(handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast(&opt), sizeof(opt)) != + 0) + { + lastError = socket_last_error(); + close(); + return false; + } #else - int opt = 1; - if (::setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&opt), sizeof(opt)) != 0) - { - lastError = socket_last_error(); - close(); - return false; - } + int opt = 1; + if (::setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&opt), sizeof(opt)) != 0) + { + lastError = socket_last_error(); + close(); + return false; + } #endif } lastError = 0; return true; - } +} - bool Socket::bind(const SocketAddress& address) - { +bool Socket::bind(const SocketAddress& address) +{ if (!is_valid()) { - lastError = EINVAL; - return false; + lastError = EINVAL; + return false; } sockaddr_in addr = {}; @@ -102,53 +110,51 @@ addr.sin_port = htons(address.port); if (address.host.empty()) - addr.sin_addr.s_addr = htonl(INADDR_ANY); - else + addr.sin_addr.s_addr = htonl(INADDR_ANY); + else if (::inet_pton(AF_INET, address.host.c_str(), &addr.sin_addr) <= 0) { - if (::inet_pton(AF_INET, address.host.c_str(), &addr.sin_addr) <= 0) - { lastError = socket_last_error(); return false; - } } if (::bind(handle, reinterpret_cast(&addr), sizeof(addr)) == 0) { - lastError = 0; - return true; + lastError = 0; + return true; } lastError = socket_last_error(); return false; - } +} - bool Socket::listen() - { +bool Socket::listen() +{ if (!is_valid()) { - lastError = EINVAL; - return false; + lastError = EINVAL; + return false; } if (::listen(handle, SOMAXCONN) == 0) { - lastError = 0; - return true; + lastError = 0; + return true; } lastError = socket_last_error(); return false; - } +} - Socket Socket::accept() - { +Socket Socket::accept() +{ Socket client = {}; - if (!is_valid()) return client; + if (!is_valid()) + return client; auto accepted = ::accept(handle, nullptr, nullptr); if (accepted == SOCKET_INVALID) { - lastError = socket_last_error(); - return client; + lastError = socket_last_error(); + return client; } client.close(); @@ -156,14 +162,14 @@ client.role = CLIENT; lastError = 0; return client; - } +} - bool Socket::connect(const SocketAddress& address) - { +bool Socket::connect(const SocketAddress& address) +{ if (!is_valid()) { - lastError = EINVAL; - return false; + lastError = EINVAL; + return false; } sockaddr_in addr = {}; @@ -172,26 +178,26 @@ if (::inet_pton(AF_INET, address.host.c_str(), &addr.sin_addr) <= 0) { - lastError = socket_last_error(); - return false; + lastError = socket_last_error(); + return false; } if (::connect(handle, reinterpret_cast(&addr), sizeof(addr)) == 0) { - lastError = 0; - return true; + lastError = 0; + return true; } lastError = socket_last_error(); return false; - } +} - bool Socket::send(const void* data, size_t size) - { +bool Socket::send(const void* data, size_t size) +{ if (!is_valid() || !data || size == 0) { - lastError = EINVAL; - return false; + lastError = EINVAL; + return false; } auto bytes = reinterpret_cast(data); @@ -199,30 +205,30 @@ while (totalSent < size) { - auto chunkSize = static_cast(std::min(size - totalSent, static_cast(INT_MAX))); + auto chunkSize = static_cast(std::min(size - totalSent, static_cast(INT_MAX))); #ifdef MSG_NOSIGNAL - auto sent = ::send(handle, bytes + totalSent, chunkSize, MSG_NOSIGNAL); + auto sent = ::send(handle, bytes + totalSent, chunkSize, MSG_NOSIGNAL); #else - auto sent = ::send(handle, bytes + totalSent, chunkSize, 0); + auto sent = ::send(handle, bytes + totalSent, chunkSize, 0); #endif - if (sent <= 0) - { - lastError = socket_last_error(); - return false; - } - totalSent += static_cast(sent); + if (sent <= 0) + { + lastError = socket_last_error(); + return false; + } + totalSent += static_cast(sent); } lastError = 0; return true; - } +} - bool Socket::receive(void* buffer, size_t size) - { +bool Socket::receive(void* buffer, size_t size) +{ if (!is_valid() || !buffer || size == 0) { - lastError = EINVAL; - return false; + lastError = EINVAL; + return false; } auto* bytes = reinterpret_cast(buffer); @@ -230,23 +236,24 @@ while (totalReceived < size) { - auto chunkSize = static_cast(std::min(size - totalReceived, static_cast(INT_MAX))); - auto received = ::recv(handle, bytes + totalReceived, chunkSize, 0); - if (received <= 0) - { - lastError = socket_last_error(); - return false; - } - totalReceived += static_cast(received); + auto chunkSize = static_cast(std::min(size - totalReceived, static_cast(INT_MAX))); + auto received = ::recv(handle, bytes + totalReceived, chunkSize, 0); + if (received <= 0) + { + lastError = socket_last_error(); + return false; + } + totalReceived += static_cast(received); } lastError = 0; return true; - } +} - void Socket::close() - { - if (!is_valid()) return; +void Socket::close() +{ + if (!is_valid()) + return; #ifdef _WIN32 ::closesocket(handle); @@ -255,8 +262,14 @@ #endif handle = SOCKET_INVALID; lastError = 0; - } +} - bool Socket::is_valid() const { return handle != SOCKET_INVALID; } +bool Socket::is_valid() const +{ + return handle != SOCKET_INVALID; +} - int Socket::last_error() const { return lastError; } +int Socket::last_error() const +{ + return lastError; +} diff --git a/src/socket.h b/src/socket.h index 1531a43..70243bd 100644 --- a/src/socket.h +++ b/src/socket.h @@ -4,39 +4,39 @@ #include #ifdef _WIN32 - #include - #include +#include +#include using socket_handle = SOCKET; constexpr socket_handle SOCKET_INVALID = INVALID_SOCKET; #else - #include - #include - #include - #include +#include +#include +#include +#include using socket_handle = int; constexpr socket_handle SOCKET_INVALID = -1; #endif - enum SocketRole - { +enum SocketRole +{ SERVER, CLIENT - }; +}; - struct SocketAddress - { +struct SocketAddress +{ std::string host; unsigned short port = {}; - }; +}; - class Socket - { - private: +class Socket +{ +private: socket_handle handle; SocketRole role = {}; int lastError = 0; - public: +public: Socket(); ~Socket(); @@ -57,4 +57,4 @@ constexpr socket_handle SOCKET_INVALID = -1; void close(); bool is_valid() const; int last_error() const; - }; +}; diff --git a/src/state.cpp b/src/state.cpp index 1d79ceb..68816d7 100644 --- a/src/state.cpp +++ b/src/state.cpp @@ -15,23 +15,26 @@ #include "ui/toast.h" #include "ui/shortcut.h" - constexpr auto UPDATE_RATE = 120; - constexpr auto UPDATE_INTERVAL = (1000 / UPDATE_RATE); +constexpr auto UPDATE_RATE = 120; +constexpr auto UPDATE_INTERVAL = (1000 / UPDATE_RATE); - State::State(SDL_Window*& window, Settings& settings, std::vector& arguments) - { +State::State(SDL_Window*& window, Settings& settings, std::vector& arguments) +{ dialog = Dialog(window); for (auto& argument : arguments) - manager.open(path_from_utf8(argument)); + manager.open(path_from_utf8(argument)); manager.settings_apply(settings); - } +} - void State::tick(Settings& settings, float deltaSeconds) { dockspace.tick(manager, settings, deltaSeconds); } +void State::tick(Settings& settings, float deltaSeconds) +{ + dockspace.tick(manager, settings, deltaSeconds); +} - void State::update(SDL_Window*& window, Settings& settings) - { +void State::update(SDL_Window*& window, Settings& settings) +{ /* ImGui_ImplSDL3_NewFrame(); ImGui_ImplOpenGL3_NewFrame(); @@ -60,97 +63,97 @@ while (SDL_PollEvent(&event)) { - ImGui_ImplSDL3_ProcessEvent(&event); - switch (event.type) - { - case SDL_EVENT_DROP_BEGIN: - spritesheetDropPaths.clear(); - soundDropPaths.clear(); - break; - case SDL_EVENT_DROP_FILE: + ImGui_ImplSDL3_ProcessEvent(&event); + switch (event.type) { - std::string droppedFile = event.drop.data ? event.drop.data : ""; - if (droppedFile.empty()) break; - auto droppedPath = path_from_utf8(droppedFile); - if (is_path_extension(droppedPath, "anm2")) - { - if (manager.documents.empty()) - manager.open(droppedPath); - else + case SDL_EVENT_DROP_BEGIN: + spritesheetDropPaths.clear(); + soundDropPaths.clear(); + break; + case SDL_EVENT_DROP_FILE: { - if (std::find(manager.anm2DragDropPaths.begin(), manager.anm2DragDropPaths.end(), droppedPath) == - manager.anm2DragDropPaths.end()) - manager.anm2DragDropPaths.push_back(droppedPath); - manager.isAnm2DragDrop = true; + std::string droppedFile = event.drop.data ? event.drop.data : ""; + if (droppedFile.empty()) + break; + auto droppedPath = path_from_utf8(droppedFile); + if (is_path_extension(droppedPath, "anm2")) + { + if (manager.documents.empty()) + manager.open(droppedPath); + else + { + if (std::find(manager.anm2DragDropPaths.begin(), manager.anm2DragDropPaths.end(), + droppedPath) == manager.anm2DragDropPaths.end()) + manager.anm2DragDropPaths.push_back(droppedPath); + manager.isAnm2DragDrop = true; + } + SDL_FlashWindow(window, SDL_FLASH_UNTIL_FOCUSED); + } + else if (is_path_extension(droppedPath, PNG_EXTENSION) || is_path_extension(droppedPath, SVG_EXTENSION)) + { + spritesheetDropPaths.push_back(droppedPath); + } + else if (is_path_extension(droppedPath, "wav") || is_path_extension(droppedPath, "ogg")) + { + soundDropPaths.push_back(droppedPath); + } + break; } - SDL_FlashWindow(window, SDL_FLASH_UNTIL_FOCUSED); - } - else if (is_path_extension(droppedPath, PNG_EXTENSION) || - is_path_extension(droppedPath, SVG_EXTENSION)) - { - spritesheetDropPaths.push_back(droppedPath); - } - else if (is_path_extension(droppedPath, "wav") || is_path_extension(droppedPath, "ogg")) - { - soundDropPaths.push_back(droppedPath); - } - break; + case SDL_EVENT_DROP_COMPLETE: + { + if (auto document = manager.get(); document) + { + if (!spritesheetDropPaths.empty()) + { + auto paths = spritesheetDropPaths; + manager.command_push({manager.selected, [paths](Manager&, Document& document) { + document.spritesheets_add(paths); + }}); + } + if (!soundDropPaths.empty()) + { + auto paths = soundDropPaths; + manager.command_push( + {manager.selected, [paths](Manager&, Document& document) { document.sounds_add(paths); }}); + } + } + else + { + if (!spritesheetDropPaths.empty()) + toast_log(Level::WARNING, TOAST_ADD_SPRITESHEET_FAILED); + if (!soundDropPaths.empty()) + toast_log(Level::WARNING, TOAST_ADD_SOUND_FAILED); + } + spritesheetDropPaths.clear(); + soundDropPaths.clear(); + break; + } + case SDL_EVENT_USER: // Opening files + { + std::string droppedFile = event.user.data1 ? static_cast(event.user.data1) : ""; + if (event.user.data1) + SDL_free(event.user.data1); + if (droppedFile.empty()) + break; + auto droppedPath = path_from_utf8(droppedFile); + if (is_path_extension(droppedPath, "anm2")) + { + manager.open(droppedPath); + SDL_FlashWindow(window, SDL_FLASH_UNTIL_FOCUSED); + } + break; + } + case SDL_EVENT_QUIT: + isQuitting = true; + break; + // With detached windows open, closing the main window doesn't end the event loop by itself. + case SDL_EVENT_WINDOW_CLOSE_REQUESTED: + if (event.window.windowID == SDL_GetWindowID(window)) + isQuitting = true; + break; + default: + break; } - case SDL_EVENT_DROP_COMPLETE: - { - if (auto document = manager.get(); document) - { - if (!spritesheetDropPaths.empty()) - { - auto paths = spritesheetDropPaths; - manager.command_push( - {manager.selected, [paths](Manager&, Document& document) { document.spritesheets_add(paths); }}); - } - if (!soundDropPaths.empty()) - { - auto paths = soundDropPaths; - manager.command_push( - {manager.selected, [paths](Manager&, Document& document) { document.sounds_add(paths); }}); - } - } - else - { - if (!spritesheetDropPaths.empty()) - { - toast_log(Level::WARNING, TOAST_ADD_SPRITESHEET_FAILED); - } - if (!soundDropPaths.empty()) - { - toast_log(Level::WARNING, TOAST_ADD_SOUND_FAILED); - } - } - spritesheetDropPaths.clear(); - soundDropPaths.clear(); - break; - } - case SDL_EVENT_USER: // Opening files - { - std::string droppedFile = event.user.data1 ? static_cast(event.user.data1) : ""; - if (event.user.data1) SDL_free(event.user.data1); - if (droppedFile.empty()) break; - auto droppedPath = path_from_utf8(droppedFile); - if (is_path_extension(droppedPath, "anm2")) - { - manager.open(droppedPath); - SDL_FlashWindow(window, SDL_FLASH_UNTIL_FOCUSED); - } - break; - } - case SDL_EVENT_QUIT: - isQuitting = true; - break; - // With detached windows open, closing the main window doesn't end the event loop by itself. - case SDL_EVENT_WINDOW_CLOSE_REQUESTED: - if (event.window.windowID == SDL_GetWindowID(window)) isQuitting = true; - break; - default: - break; - } } ImGui_ImplSDL3_NewFrame(); @@ -161,18 +164,19 @@ if (ImGui::GetTopMostPopupModal() == nullptr) { - constexpr ImGuiKey DOCUMENT_SHORTCUT_KEYS[] = {ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, - ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, ImGuiKey_0}; - for (int i = 0; i < (int)(sizeof(DOCUMENT_SHORTCUT_KEYS) / sizeof(DOCUMENT_SHORTCUT_KEYS[0])); ++i) - { - if (i >= (int)manager.documents.size()) break; - if (ImGui::Shortcut(ImGuiMod_Ctrl | DOCUMENT_SHORTCUT_KEYS[i], ImGuiInputFlags_RouteGlobal)) + constexpr ImGuiKey DOCUMENT_SHORTCUT_KEYS[] = {ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, + ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, ImGuiKey_0}; + for (int i = 0; i < (int)(sizeof(DOCUMENT_SHORTCUT_KEYS) / sizeof(DOCUMENT_SHORTCUT_KEYS[0])); ++i) { - manager.set(i); - manager.pendingSelected = i; - break; + if (i >= (int)manager.documents.size()) + break; + if (ImGui::Shortcut(ImGuiMod_Ctrl | DOCUMENT_SHORTCUT_KEYS[i], ImGuiInputFlags_RouteGlobal)) + { + manager.set(i); + manager.pendingSelected = i; + break; + } } - } } taskbar.update(manager, settings, resources, dialog, isQuitting); @@ -181,14 +185,16 @@ if (!dockspace.is_canvas_focused_get()) { - float uiScaleDelta = 0; - if (shortcut(manager.chords[SHORTCUT_ZOOM_IN], SCOPE_GLOBAL)) uiScaleDelta += UI_SCALE_STEP; - if (shortcut(manager.chords[SHORTCUT_ZOOM_OUT], SCOPE_GLOBAL)) uiScaleDelta -= UI_SCALE_STEP; - if (uiScaleDelta != 0.0f) - { - settings.uiScale = std::clamp(settings.uiScale + uiScaleDelta, UI_SCALE_MIN, UI_SCALE_MAX); - ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); - } + float uiScaleDelta = 0; + if (shortcut(manager.chords[SHORTCUT_ZOOM_IN], SCOPE_GLOBAL)) + uiScaleDelta += UI_SCALE_STEP; + if (shortcut(manager.chords[SHORTCUT_ZOOM_OUT], SCOPE_GLOBAL)) + uiScaleDelta -= UI_SCALE_STEP; + if (uiScaleDelta != 0.0f) + { + settings.uiScale = std::clamp(settings.uiScale + uiScaleDelta, UI_SCALE_MIN, UI_SCALE_MAX); + ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); + } } toasts.update(); @@ -197,11 +203,12 @@ SDL_GetWindowSize(window, &settings.windowSize.x, &settings.windowSize.y); SDL_GetWindowPosition(window, &settings.windowPosition.x, &settings.windowPosition.y); - if (isQuitting && manager.documents.empty()) isQuit = true; - } + if (isQuitting && manager.documents.empty()) + isQuit = true; +} - void State::render(SDL_Window*& window, Settings& settings) - { +void State::render(SDL_Window*& window, Settings& settings) +{ glViewport(0, 0, settings.windowSize.x, settings.windowSize.y); glClear(GL_COLOR_BUFFER_BIT); @@ -211,19 +218,19 @@ // Windows dragged out of the main window are drawn into their own OS windows (and GL contexts). if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { - auto glContext = SDL_GL_GetCurrentContext(); - ImGui::UpdatePlatformWindows(); - ImGui::RenderPlatformWindowsDefault(); - SDL_GL_MakeCurrent(window, glContext); + auto glContext = SDL_GL_GetCurrentContext(); + ImGui::UpdatePlatformWindows(); + ImGui::RenderPlatformWindowsDefault(); + SDL_GL_MakeCurrent(window, glContext); } SDL_GL_SwapWindow(window); texture_garbage_collect(); SDL_GL_SetSwapInterval(settings.isVsync); - } +} - void State::loop(SDL_Window*& window, Settings& settings) - { +void State::loop(SDL_Window*& window, Settings& settings) +{ auto currentTick = SDL_GetTicks(); auto currentUpdate = SDL_GetTicks(); auto isRecording = manager.isRecording; @@ -232,13 +239,14 @@ if (isRecording != wasRecording) { - // Drop any accumulated backlog when entering/leaving recording mode. - tickAccumulatorMs = 0.0; - previousTick = currentTick; - wasRecording = isRecording; + // Drop any accumulated backlog when entering/leaving recording mode. + tickAccumulatorMs = 0.0; + previousTick = currentTick; + wasRecording = isRecording; } - if (previousTick == 0) previousTick = currentTick; + if (previousTick == 0) + previousTick = currentTick; auto tickDeltaMs = currentTick - previousTick; tickDeltaMs = std::min(tickDeltaMs, 250); tickAccumulatorMs += (double)tickDeltaMs; @@ -246,16 +254,16 @@ if (currentUpdate - previousUpdate >= UPDATE_INTERVAL) { - update(window, settings); - render(window, settings); - previousUpdate = currentUpdate; + update(window, settings); + render(window, settings); + previousUpdate = currentUpdate; } if (tickAccumulatorMs >= tickIntervalMs) { - tick(settings, (float)(tickIntervalMs / 1000.0)); - tickAccumulatorMs -= tickIntervalMs; + tick(settings, (float)(tickIntervalMs / 1000.0)); + tickAccumulatorMs -= tickIntervalMs; } SDL_Delay(1); - } +} diff --git a/src/state.h b/src/state.h index 2cd3951..b2cc6a7 100644 --- a/src/state.h +++ b/src/state.h @@ -7,13 +7,13 @@ #include "ui/dockspace.h" - class State - { +class State +{ void tick(Settings&, float); void update(SDL_Window*&, Settings&); void render(SDL_Window*&, Settings&); - public: +public: bool isQuit = false; bool isQuitting = false; Manager manager; @@ -35,4 +35,4 @@ State(SDL_Window*&, Settings& settings, std::vector&); void loop(SDL_Window*&, Settings&); - }; +}; diff --git a/src/subprocess.cpp b/src/subprocess.cpp index 7cacaba..bca84fa 100644 --- a/src/subprocess.cpp +++ b/src/subprocess.cpp @@ -1,28 +1,36 @@ #include "subprocess.h" #ifdef WIN32 - #include - #include +#include +#include #endif #ifdef WIN32 - std::wstring utf8_to_wstring(const char* text) - { - if (!text) return {}; +std::wstring utf8_to_wstring(const char* text) +{ + if (!text) + return {}; auto sizeRequired = MultiByteToWideChar(CP_UTF8, 0, text, -1, nullptr, 0); - if (sizeRequired <= 0) return {}; + if (sizeRequired <= 0) + return {}; std::wstring wide(static_cast(sizeRequired - 1), L'\0'); MultiByteToWideChar(CP_UTF8, 0, text, -1, wide.data(), sizeRequired); return wide; - } +} #endif - Process::Process(const char* command, const char* mode) { open(command, mode); } +Process::Process(const char* command, const char* mode) +{ + open(command, mode); +} - Process::~Process() { close(); } +Process::~Process() +{ + close(); +} - bool Process::open(const char* command, const char* mode) - { +bool Process::open(const char* command, const char* mode) +{ close(); #ifdef WIN32 @@ -33,39 +41,46 @@ pipe = popen(command, mode); #endif return pipe != nullptr; - } +} - int Process::close() - { +int Process::close() +{ if (pipe) { #ifdef WIN32 - auto result = _pclose(pipe); + auto result = _pclose(pipe); #else - auto result = pclose(pipe); + auto result = pclose(pipe); #endif - pipe = nullptr; + pipe = nullptr; - return result; + return result; } return -1; - } +} - std::string Process::output_get_and_close() - { +std::string Process::output_get_and_close() +{ std::string output; - if (!pipe) return {}; + if (!pipe) + return {}; char buffer[256]; while (fgets(buffer, sizeof(buffer), pipe)) - output += buffer; + output += buffer; close(); return output; - } +} - FILE* Process::get() const { return pipe; } +FILE* Process::get() const +{ + return pipe; +} - Process::operator bool() const { return pipe != nullptr; } +Process::operator bool() const +{ + return pipe != nullptr; +} diff --git a/src/subprocess.h b/src/subprocess.h index eb59c56..f9b974f 100644 --- a/src/subprocess.h +++ b/src/subprocess.h @@ -2,9 +2,9 @@ #include - class Process - { - public: +class Process +{ +public: Process() = default; Process(const char*, const char*); ~Process(); @@ -16,6 +16,6 @@ std::string output_get_and_close(); - private: +private: FILE* pipe = nullptr; - }; +}; diff --git a/src/texture.cpp b/src/texture.cpp index 3b15e54..cc281dd 100644 --- a/src/texture.cpp +++ b/src/texture.cpp @@ -5,22 +5,24 @@ #include #include - struct TextureEntry - { +struct TextureEntry +{ GLuint id = 0; bool isUsed = false; - }; +}; - static std::unordered_map entries; +static std::unordered_map entries; - GLuint texture_id_get(const Image& image) - { - if (!image.is_valid()) return 0; +GLuint texture_id_get(const Image& image) +{ + if (!image.is_valid()) + return 0; auto [it, isNew] = entries.try_emplace(image.uid); auto& entry = it->second; entry.isUsed = true; - if (!isNew) return entry.id; + if (!isNew) + return entry.id; auto filter = image.isLinear ? GL_LINEAR : GL_NEAREST; glGenTextures(1, &entry.id); @@ -34,24 +36,25 @@ image.pixels.data()); glBindTexture(GL_TEXTURE_2D, 0); return entry.id; - } +} - void texture_garbage_collect() - { - std::erase_if(entries, - [](auto& pair) - { - auto& entry = pair.second; - if (!entry.isUsed) glDeleteTextures(1, &entry.id); - return !std::exchange(entry.isUsed, false); - }); - } +void texture_garbage_collect() +{ + std::erase_if(entries, [](auto& pair) { + auto& entry = pair.second; + if (!entry.isUsed) + glDeleteTextures(1, &entry.id); + return !std::exchange(entry.isUsed, false); + }); +} - Image texture_svg_load(const char* data, size_t length, glm::ivec2 size) - { +Image texture_svg_load(const char* data, size_t length, glm::ivec2 size) +{ auto document = data ? lunasvg::Document::loadFromData(data, length) : nullptr; - if (!document) return {}; + if (!document) + return {}; auto bitmap = document->renderToBitmap(size.x, size.y, 0); - if (bitmap.width() == 0 || bitmap.height() == 0) return {}; + if (bitmap.width() == 0 || bitmap.height() == 0) + return {}; return Image(bitmap.data(), size, true); - } +} diff --git a/src/texture.h b/src/texture.h index bf4e1da..79cacbf 100644 --- a/src/texture.h +++ b/src/texture.h @@ -5,6 +5,6 @@ #include "image.h" // GPU copies of Images, uploaded on first use and evicted when a frame passes without them being drawn. - GLuint texture_id_get(const Image&); - void texture_garbage_collect(); - Image texture_svg_load(const char*, size_t, glm::ivec2); +GLuint texture_id_get(const Image&); +void texture_garbage_collect(); +Image texture_svg_load(const char*, size_t, glm::ivec2); diff --git a/src/timestamp.cpp b/src/timestamp.cpp index f4e0579..a5487a2 100644 --- a/src/timestamp.cpp +++ b/src/timestamp.cpp @@ -5,12 +5,12 @@ #include #include - std::string timestamp_get(const char* format) - { +std::string timestamp_get(const char* format) +{ auto now = std::chrono::system_clock::now(); auto time = std::chrono::system_clock::to_time_t(now); auto localTime = *std::localtime(&time); std::ostringstream timeString; timeString << std::put_time(&localTime, format); return timeString.str(); - } +} diff --git a/src/timestamp.h b/src/timestamp.h index 4d67c18..44e2c17 100644 --- a/src/timestamp.h +++ b/src/timestamp.h @@ -2,6 +2,6 @@ #include - constexpr auto SECOND_MINUTES = 60; +constexpr auto SECOND_MINUTES = 60; - std::string timestamp_get(const char*); +std::string timestamp_get(const char*); diff --git a/src/tool.h b/src/tool.h index ffbc28a..ffec59b 100644 --- a/src/tool.h +++ b/src/tool.h @@ -6,8 +6,8 @@ #include "settings.h" #include "localization.h" - enum Tool - { +enum Tool +{ TOOL_PAN, TOOL_MOVE, TOOL_ROTATE, @@ -21,17 +21,17 @@ TOOL_REDO, TOOL_COLOR, TOOL_COUNT - }; +}; - enum ToolArea - { +enum ToolArea +{ TOOL_AREA_ANIMATION_PREVIEW, TOOL_AREA_SPRITESHEET_EDITOR, TOOL_AREA_ALL - }; +}; - struct ToolInfo - { +struct ToolInfo +{ ImGuiMouseCursor cursor = ImGuiMouseCursor_None; Icon icon = {}; ShortcutType shortcut = {}; @@ -40,37 +40,36 @@ StringType tooltip = {}; bool isFrameRequired = false; bool isSpritesheetRequired = false; - }; +}; - constexpr ToolInfo TOOLS[] = { - {ImGuiMouseCursor_Hand, ICON_PAN, SHORTCUT_PAN, TOOL_AREA_ALL, "##Pan", TOOLTIP_TOOL_PAN}, +constexpr ToolInfo TOOLS[] = { + {ImGuiMouseCursor_Hand, ICON_PAN, SHORTCUT_PAN, TOOL_AREA_ALL, "##Pan", TOOLTIP_TOOL_PAN}, - {ImGuiMouseCursor_ResizeAll, ICON_MOVE, SHORTCUT_MOVE, TOOL_AREA_ALL, "##Move", TOOLTIP_TOOL_MOVE, true}, + {ImGuiMouseCursor_ResizeAll, ICON_MOVE, SHORTCUT_MOVE, TOOL_AREA_ALL, "##Move", TOOLTIP_TOOL_MOVE, true}, - {ImGuiMouseCursor_Arrow, ICON_ROTATE, SHORTCUT_ROTATE, TOOL_AREA_ANIMATION_PREVIEW, "##Rotate", - TOOLTIP_TOOL_ROTATE, true}, + {ImGuiMouseCursor_Arrow, ICON_ROTATE, SHORTCUT_ROTATE, TOOL_AREA_ANIMATION_PREVIEW, "##Rotate", TOOLTIP_TOOL_ROTATE, + true}, - {ImGuiMouseCursor_ResizeNESW, ICON_SCALE, SHORTCUT_SCALE, TOOL_AREA_ANIMATION_PREVIEW, "##Scale", - TOOLTIP_TOOL_SCALE, true}, + {ImGuiMouseCursor_ResizeNESW, ICON_SCALE, SHORTCUT_SCALE, TOOL_AREA_ANIMATION_PREVIEW, "##Scale", + TOOLTIP_TOOL_SCALE, true}, - {ImGuiMouseCursor_ResizeNESW, ICON_SKEW, SHORTCUT_SKEW, TOOL_AREA_ANIMATION_PREVIEW, "##Skew", TOOLTIP_TOOL_SKEW, - true}, + {ImGuiMouseCursor_ResizeNESW, ICON_SKEW, SHORTCUT_SKEW, TOOL_AREA_ANIMATION_PREVIEW, "##Skew", TOOLTIP_TOOL_SKEW, + true}, - {ImGuiMouseCursor_Arrow, ICON_CROP, SHORTCUT_CROP, TOOL_AREA_SPRITESHEET_EDITOR, "##Crop", TOOLTIP_TOOL_CROP, - true}, + {ImGuiMouseCursor_Arrow, ICON_CROP, SHORTCUT_CROP, TOOL_AREA_SPRITESHEET_EDITOR, "##Crop", TOOLTIP_TOOL_CROP, true}, - {ImGuiMouseCursor_Arrow, ICON_DRAW, SHORTCUT_DRAW, TOOL_AREA_SPRITESHEET_EDITOR, "##Draw", TOOLTIP_TOOL_DRAW, - false, true}, + {ImGuiMouseCursor_Arrow, ICON_DRAW, SHORTCUT_DRAW, TOOL_AREA_SPRITESHEET_EDITOR, "##Draw", TOOLTIP_TOOL_DRAW, false, + true}, - {ImGuiMouseCursor_Arrow, ICON_ERASE, SHORTCUT_ERASE, TOOL_AREA_SPRITESHEET_EDITOR, "##Erase", TOOLTIP_TOOL_ERASE, - false, true}, + {ImGuiMouseCursor_Arrow, ICON_ERASE, SHORTCUT_ERASE, TOOL_AREA_SPRITESHEET_EDITOR, "##Erase", TOOLTIP_TOOL_ERASE, + false, true}, - {ImGuiMouseCursor_Arrow, ICON_COLOR_PICKER, SHORTCUT_COLOR_PICKER, TOOL_AREA_SPRITESHEET_EDITOR, - "##Color Picker", TOOLTIP_TOOL_COLOR_PICKER, false, true}, + {ImGuiMouseCursor_Arrow, ICON_COLOR_PICKER, SHORTCUT_COLOR_PICKER, TOOL_AREA_SPRITESHEET_EDITOR, "##Color Picker", + TOOLTIP_TOOL_COLOR_PICKER, false, true}, - {ImGuiMouseCursor_None, ICON_UNDO, SHORTCUT_UNDO, TOOL_AREA_ALL, "##Undo", TOOLTIP_TOOL_UNDO}, + {ImGuiMouseCursor_None, ICON_UNDO, SHORTCUT_UNDO, TOOL_AREA_ALL, "##Undo", TOOLTIP_TOOL_UNDO}, - {ImGuiMouseCursor_None, ICON_REDO, SHORTCUT_REDO, TOOL_AREA_ALL, "##Redo", TOOLTIP_TOOL_REDO}, + {ImGuiMouseCursor_None, ICON_REDO, SHORTCUT_REDO, TOOL_AREA_ALL, "##Redo", TOOLTIP_TOOL_REDO}, - {ImGuiMouseCursor_None, ICON_NONE, SHORTCUT_COLOR, TOOL_AREA_ALL, "##Color", TOOLTIP_TOOL_COLOR}, - }; + {ImGuiMouseCursor_None, ICON_NONE, SHORTCUT_COLOR, TOOL_AREA_ALL, "##Color", TOOLTIP_TOOL_COLOR}, +}; diff --git a/src/types.h b/src/types.h index 4a6fd35..0bb9d97 100644 --- a/src/types.h +++ b/src/types.h @@ -2,62 +2,62 @@ #include - enum ShortcutScope - { +enum ShortcutScope +{ SCOPE_FOCUSED, SCOPE_GLOBAL, SCOPE_FOCUSED_SET, SCOPE_GLOBAL_SET - }; +}; - enum Destination - { +enum Destination +{ DESTINATION_ALL, DESTINATION_THIS - }; +}; - enum Source - { +enum Source +{ SOURCE_NEW, SOURCE_EXISTING - }; +}; - enum OverlayDrawOrder - { +enum OverlayDrawOrder +{ OVERLAY_OVER, OVERLAY_UNDER - }; +}; - enum Merge - { +enum Merge +{ MERGE_PREPEND, MERGE_APPEND, MERGE_REPLACE, MERGE_IGNORE - }; +}; - enum EditState - { +enum EditState +{ EDIT_STATE_NONE, EDIT_STATE_START, EDIT_STATE_DURING, EDIT_STATE_END, EDIT_STATE_COMPLETE - }; +}; - using namespace glm; +using namespace glm; - constexpr auto COLOR_WHITE = vec4(1.0); - constexpr auto COLOR_BLACK = vec4(0.0, 0.0, 0.0, 1.0); - constexpr auto COLOR_RED = vec4(1.0, 0.0, 0.0, 1.0); - constexpr auto COLOR_GREEN = vec4(0.0, 1.0, 0.0, 1.0); - constexpr auto COLOR_BLUE = vec4(0.0, 0.0, 1.0, 1.0); - constexpr auto COLOR_PINK = vec4(1.0, 0.0, 1.0, 1.0); +constexpr auto COLOR_WHITE = vec4(1.0); +constexpr auto COLOR_BLACK = vec4(0.0, 0.0, 0.0, 1.0); +constexpr auto COLOR_RED = vec4(1.0, 0.0, 0.0, 1.0); +constexpr auto COLOR_GREEN = vec4(0.0, 1.0, 0.0, 1.0); +constexpr auto COLOR_BLUE = vec4(0.0, 0.0, 1.0, 1.0); +constexpr auto COLOR_PINK = vec4(1.0, 0.0, 1.0, 1.0); - enum class OnionskinMode - { +enum class OnionskinMode +{ TIME, INDEX - }; +}; - constexpr auto ID_NONE = -1; +constexpr auto ID_NONE = -1; diff --git a/src/ui/about.cpp b/src/ui/about.cpp index 15ff7d9..9eb642b 100644 --- a/src/ui/about.cpp +++ b/src/ui/about.cpp @@ -21,156 +21,158 @@ using namespace glm; - // The credits roll, after the original editor's About box: lengths are its pixels (for 14 px text), at its 30 Hz. - enum RollEffect - { +// The credits roll, after the original editor's About box: lengths are its pixels (for 14 px text), at its 30 Hz. +enum RollEffect +{ EFFECT_NONE, EFFECT_SWAY, EFFECT_STRETCH, EFFECT_WAVE, EFFECT_COUNT - }; +}; - static constexpr float ROLL_FONT_SIZE = 14.0f; - static constexpr float ROLL_TICK = 1.0f / 30.0f; - static constexpr int ROLL_TICKS_MAX = 4; - static constexpr std::size_t ROLL_HISTORY_MAX = 72; - static constexpr float ROLL_SCROLL_STEP = 1.0f; - static constexpr float ROLL_SCROLL_GAP = 20.0f; - static constexpr float ROLL_FADE_HEIGHT = 30.0f; - static constexpr float ROLL_WAVE_FREQUENCY = 0.1f; - static constexpr float ROLL_SWAY_AMPLITUDE = 10.0f; - static constexpr float ROLL_WAVE_AMPLITUDE = 15.0f; - static constexpr float ROLL_STRETCH = 0.2f; - static constexpr int ROLL_TRAIL_ALPHA_SWAY = 25; - static constexpr int ROLL_TRAIL_ALPHA_STRETCH = 50; - static constexpr float ROLL_WEIGHT_MIN = 1.0f / 255.0f; - static constexpr float BAR_WIDTH = 30.0f; - // Bars are scaled to the loudest recent level (which decays slowly), so loud parts reach the top. - static constexpr float BAR_LEVEL_DECAY = 0.995f; - static constexpr float BAR_LEVEL_FLOOR = 0.05f; - static constexpr float BAR_GRADIENT_MIN = 50.0f; - static constexpr int BAR_TRAIL_ALPHA = 20; - static constexpr int BAR_RED_STEP = 100; - static constexpr ImU32 ROLL_BACKGROUND = IM_COL32(0, 0, 0, 255); - static constexpr ImU32 ROLL_CLEAR = IM_COL32(0, 0, 0, 0); - static constexpr ImU32 ROLL_HEADER_COLOR = IM_COL32(255, 255, 255, 255); - static constexpr ImU32 ROLL_NAME_COLOR = IM_COL32(200, 255, 255, 255); - static constexpr ImU32 BAR_BASE_COLOR = IM_COL32(255, 0, 0, 255); - // The original's robots stood 47 px tall in its 183 px box. - static constexpr float FRIEND_HEIGHT_RATIO = 47.0f / 183.0f; - static constexpr float FRIEND_PADDING_RATIO = 0.15f; - static constexpr float TITLE_SCALE = 2.0f; - static constexpr int FRIEND_ORDER_LEFT[] = {FRIEND_MEAT_BOY, FRIEND_ISAAC}; - static constexpr int FRIEND_ORDER_RIGHT[] = {FRIEND_STACY, FRIEND_ASH}; +static constexpr float ROLL_FONT_SIZE = 14.0f; +static constexpr float ROLL_TICK = 1.0f / 30.0f; +static constexpr int ROLL_TICKS_MAX = 4; +static constexpr std::size_t ROLL_HISTORY_MAX = 72; +static constexpr float ROLL_SCROLL_STEP = 1.0f; +static constexpr float ROLL_SCROLL_GAP = 20.0f; +static constexpr float ROLL_FADE_HEIGHT = 30.0f; +static constexpr float ROLL_WAVE_FREQUENCY = 0.1f; +static constexpr float ROLL_SWAY_AMPLITUDE = 10.0f; +static constexpr float ROLL_WAVE_AMPLITUDE = 15.0f; +static constexpr float ROLL_STRETCH = 0.2f; +static constexpr int ROLL_TRAIL_ALPHA_SWAY = 25; +static constexpr int ROLL_TRAIL_ALPHA_STRETCH = 50; +static constexpr float ROLL_WEIGHT_MIN = 1.0f / 255.0f; +static constexpr float BAR_WIDTH = 30.0f; +// Bars are scaled to the loudest recent level (which decays slowly), so loud parts reach the top. +static constexpr float BAR_LEVEL_DECAY = 0.995f; +static constexpr float BAR_LEVEL_FLOOR = 0.05f; +static constexpr float BAR_GRADIENT_MIN = 50.0f; +static constexpr int BAR_TRAIL_ALPHA = 20; +static constexpr int BAR_RED_STEP = 100; +static constexpr ImU32 ROLL_BACKGROUND = IM_COL32(0, 0, 0, 255); +static constexpr ImU32 ROLL_CLEAR = IM_COL32(0, 0, 0, 0); +static constexpr ImU32 ROLL_HEADER_COLOR = IM_COL32(255, 255, 255, 255); +static constexpr ImU32 ROLL_NAME_COLOR = IM_COL32(200, 255, 255, 255); +static constexpr ImU32 BAR_BASE_COLOR = IM_COL32(255, 0, 0, 255); +// The original's robots stood 47 px tall in its 183 px box. +static constexpr float FRIEND_HEIGHT_RATIO = 47.0f / 183.0f; +static constexpr float FRIEND_PADDING_RATIO = 0.15f; +static constexpr float TITLE_SCALE = 2.0f; +static constexpr int FRIEND_ORDER_LEFT[] = {FRIEND_MEAT_BOY, FRIEND_ISAAC}; +static constexpr int FRIEND_ORDER_RIGHT[] = {FRIEND_STACY, FRIEND_ASH}; - static constexpr About::Credit CREDITS[] = { - {"Anm2Ed", FONT_BOLD}, - {"License: GPLv3"}, - {""}, - {"Design/Programming", FONT_BOLD}, - {"Shweet"}, - {"OpenAI Codex"}, - {"Claude Code"}, - {""}, - {"Additional Help", FONT_BOLD}, - {"im-tem"}, - {""}, - {"Localization", FONT_BOLD}, - {"Gabriel Asencio (Spanish (Latin America))"}, - {"ExtremeThreat (Russian)"}, - {"CxRedix (Chinese)"}, - {"sawalk/사왈이 (Korean)"}, - {""}, - {"Based on the work of", FONT_BOLD}, - {"Adrian Gavrilita"}, - {"Simon Parzer"}, - {"Matt Kapuszczak"}, - {""}, - {"Music", FONT_BOLD}, - {"Soundbin"}, - {"\"Digital Antidepressant\""}, - {"https://www.newgrounds.com/audio/listen/1565433"}, - {"License: CC0"}, - {""}, - {"Dancing Characters", FONT_BOLD}, - {"Shweet"}, - {""}, - {"Libraries", FONT_BOLD}, - {"Dear ImGui"}, - {"https://github.com/ocornut/imgui"}, - {"License: MIT"}, - {""}, - {"SDL"}, - {"https://github.com/libsdl-org/SDL"}, - {"License: zlib"}, - {""}, - {"SDL_mixer"}, - {"https://github.com/libsdl-org/SDL_mixer"}, - {"License: zlib"}, - {""}, - {"pugixml"}, - {"https://github.com/zeux/pugixml"}, - {"License: MIT"}, - {""}, - {"simdjson"}, - {"https://github.com/simdjson/simdjson"}, - {"License: Apache-2.0 or MIT"}, - {""}, - {"glm"}, - {"https://github.com/g-truc/glm"}, - {"License: MIT"}, - {""}, - {"lunasvg"}, - {"https://github.com/sammycage/lunasvg"}, - {"License: MIT"}, - {""}, - {"Icons", FONT_BOLD}, - {"Remix Icons"}, - {"remixicon.com"}, - {"License: Apache"}, - {""}, - {"Font", FONT_BOLD}, - {"Noto Sans"}, - {"https://fonts.google.com/noto/specimen/Noto+Sans"}, - {"License: OFL"}, - {""}, - {"Special Thanks", FONT_BOLD}, - {"Edmund McMillen"}, - {"Florian Himsl"}, - {"Tyrone Rodriguez"}, - {"The-Vinh Truong (_kilburn)"}, - {"Isaac Reflashed team"}, - {"Everyone who waited patiently for this to be finished"}, - {"Everyone else who has worked on The Binding of Isaac!"}, - {""}, - {""}, - {""}, - {""}, - {""}, - {"enjoy the jams :)"}, - {""}, - {""}, - {""}, - {""}, - {""}, - }; - static constexpr auto CREDIT_COUNT = (int)(sizeof(CREDITS) / sizeof(About::Credit)); +static constexpr About::Credit CREDITS[] = { + {"Anm2Ed", FONT_BOLD}, + {"License: GPLv3"}, + {""}, + {"Design/Programming", FONT_BOLD}, + {"Shweet"}, + {"OpenAI Codex"}, + {"Claude Code"}, + {""}, + {"Additional Help", FONT_BOLD}, + {"im-tem"}, + {""}, + {"Localization", FONT_BOLD}, + {"Gabriel Asencio (Spanish (Latin America))"}, + {"ExtremeThreat (Russian)"}, + {"CxRedix (Chinese)"}, + {"sawalk/사왈이 (Korean)"}, + {""}, + {"Based on the work of", FONT_BOLD}, + {"Adrian Gavrilita"}, + {"Simon Parzer"}, + {"Matt Kapuszczak"}, + {""}, + {"Music", FONT_BOLD}, + {"Soundbin"}, + {"\"Digital Antidepressant\""}, + {"https://www.newgrounds.com/audio/listen/1565433"}, + {"License: CC0"}, + {""}, + {"Dancing Characters", FONT_BOLD}, + {"Shweet"}, + {""}, + {"Libraries", FONT_BOLD}, + {"Dear ImGui"}, + {"https://github.com/ocornut/imgui"}, + {"License: MIT"}, + {""}, + {"SDL"}, + {"https://github.com/libsdl-org/SDL"}, + {"License: zlib"}, + {""}, + {"SDL_mixer"}, + {"https://github.com/libsdl-org/SDL_mixer"}, + {"License: zlib"}, + {""}, + {"pugixml"}, + {"https://github.com/zeux/pugixml"}, + {"License: MIT"}, + {""}, + {"simdjson"}, + {"https://github.com/simdjson/simdjson"}, + {"License: Apache-2.0 or MIT"}, + {""}, + {"glm"}, + {"https://github.com/g-truc/glm"}, + {"License: MIT"}, + {""}, + {"lunasvg"}, + {"https://github.com/sammycage/lunasvg"}, + {"License: MIT"}, + {""}, + {"Icons", FONT_BOLD}, + {"Remix Icons"}, + {"remixicon.com"}, + {"License: Apache"}, + {""}, + {"Font", FONT_BOLD}, + {"Noto Sans"}, + {"https://fonts.google.com/noto/specimen/Noto+Sans"}, + {"License: OFL"}, + {""}, + {"Special Thanks", FONT_BOLD}, + {"Edmund McMillen"}, + {"Florian Himsl"}, + {"Tyrone Rodriguez"}, + {"The-Vinh Truong (_kilburn)"}, + {"Isaac Reflashed team"}, + {"Everyone who waited patiently for this to be finished"}, + {"Everyone else who has worked on The Binding of Isaac!"}, + {""}, + {""}, + {""}, + {""}, + {""}, + {"enjoy the jams :)"}, + {""}, + {""}, + {""}, + {""}, + {""}, +}; - static const Animation* friend_animation_get(const About::FriendState& state) - { +static constexpr auto CREDIT_COUNT = (int)(sizeof(CREDITS) / sizeof(About::Credit)); + +static const Animation* friend_animation_get(const About::FriendState& state) +{ auto animations = state.model.animations_get(); for (auto [index, animation] : animations) - if (animation->name == state.model.animations.defaultAnimation) return animation; + if (animation->name == state.model.animations.defaultAnimation) + return animation; return animations.empty() ? nullptr : animations.front().second; - } +} - static void friend_state_load(About::FriendState& state, const FriendInfo& info) - { +static void friend_state_load(About::FriendState& state, const FriendInfo& info) +{ if (!state.canvas) { - state.canvas = std::make_unique(vec2(1.0f, 1.0f)); - state.canvas->filter = GL_NEAREST; + state.canvas = std::make_unique(vec2(1.0f, 1.0f)); + state.canvas->filter = GL_NEAREST; } state.model = Model{}; @@ -183,56 +185,62 @@ using namespace glm; std::string errorString; if (!model_load_string(state.model, std::string_view((const char*)info.anm2->data, info.anm2->size), &errorString)) { - logger.error(std::format("Unable to load friend animation {}: {}", info.name, errorString)); - return; + logger.error(std::format("Unable to load friend animation {}: {}", info.name, errorString)); + return; } - if (state.model.info.fps > 0) state.fps = (float)state.model.info.fps; + if (state.model.info.fps > 0) + state.fps = (float)state.model.info.fps; for (auto& spritesheet : state.model.content.spritesheets) - state.textures[spritesheet.id] = Image(info.png->data, info.png->size); + state.textures[spritesheet.id] = Image(info.png->data, info.png->size); auto animation = friend_animation_get(state); if (!animation) { - logger.error(std::format("Friend animation {} has no animation.", info.name)); - return; + logger.error(std::format("Friend animation {} has no animation.", info.name)); + return; } state.rect = animation_rect(state.model, *animation, true); state.isLoaded = state.rect != vec4(-1.0f) && !state.textures.empty(); - } +} - static void friend_state_tick(About::FriendState& state, float delta) - { - if (!state.isLoaded) return; +static void friend_state_tick(About::FriendState& state, float delta) +{ + if (!state.isLoaded) + return; auto animation = friend_animation_get(state); - if (!animation || animation->frameNum <= 0) return; + if (!animation || animation->frameNum <= 0) + return; state.time = std::fmod(state.time + delta * state.fps, (float)animation->frameNum); - if (state.time < 0.0f) state.time += (float)animation->frameNum; - } + if (state.time < 0.0f) + state.time += (float)animation->frameNum; +} - static ImVec2 friend_size_get(const About::FriendState& state, float height) - { +static ImVec2 friend_size_get(const About::FriendState& state, float height) +{ auto width = height; - if (state.rect.w > 0.0f && state.rect.z > 0.0f) width = height * (state.rect.z / state.rect.w); + if (state.rect.w > 0.0f && state.rect.z > 0.0f) + width = height * (state.rect.z / state.rect.w); return ImVec2(std::max(width, 1.0f), std::max(height, 1.0f)); - } +} - // The animation's bounds with some room around them. - static vec4 friend_rect_get(const About::FriendState& state) - { +// The animation's bounds with some room around them. +static vec4 friend_rect_get(const About::FriendState& state) +{ auto rect = state.rect; auto padding = std::max(2.0f, std::max(rect.z, rect.w) * FRIEND_PADDING_RATIO); return {rect.x - padding, rect.y - padding, rect.z + padding * 2.0f, rect.w + padding * 2.0f}; - } +} - // Rendered 1:1 into its canvas, which is drawn scaled up with nearest filtering so the pixels stay sharp. - static void friend_canvas_draw(About::FriendState& state, Resources& resources) - { - if (!state.isLoaded || !state.canvas) return; +// Rendered 1:1 into its canvas, which is drawn scaled up with nearest filtering so the pixels stay sharp. +static void friend_canvas_draw(About::FriendState& state, Resources& resources) +{ + if (!state.isLoaded || !state.canvas) + return; auto rect = friend_rect_get(state); state.canvas->size_set(glm::max(vec2(rect.z, rect.w), vec2(1.0f))); @@ -243,8 +251,8 @@ using namespace glm; auto animation = friend_animation_get(state); if (!animation) { - state.canvas->unbind(); - return; + state.canvas->unbind(); + return; } float zoom = 100.0f; @@ -253,18 +261,17 @@ using namespace glm; state.canvas->layers_render(resources.shaders[SHADER_TEXTURE], state.model, *animation, {.time = state.time, .isRootTransform = true}, state.canvas->transform_get(zoom, pan), - [&](const Draw& draw) - { - auto texture = state.textures.find(draw.spritesheetId); - return texture == state.textures.end() ? nullptr : &texture->second; + [&](const Draw& draw) { + auto texture = state.textures.find(draw.spritesheetId); + return texture == state.textures.end() ? nullptr : &texture->second; }); state.canvas->unbind(); - } +} - // The application name, as large as fits its row. - static void title_draw(About& about, Resources& resources, const char* title, float width) - { +// The application name, as large as fits its row. +static void title_draw(About& about, Resources& resources, const char* title, float width) +{ auto font = resources.fonts[FONT_BOLD].get(); auto fontSize = (float)FONT_SIZE_LARGE * TITLE_SCALE; fontSize *= std::min(1.0f, width / font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, title).x); @@ -276,43 +283,42 @@ using namespace glm; font, fontSize, ImVec2(min.x + (width - textSize.x) * 0.5f, min.y + (rowHeight - textSize.y) * 0.5f), color, title); ImGui::Dummy(ImVec2(width, rowHeight)); - } +} - // The dancing characters stand in the credits box's bottom corners, inside the volume bars. - static void friends_draw(About& about, Resources& resources, ImDrawList* drawList, ImVec2 min, ImVec2 max, float inset) - { +// The dancing characters stand in the credits box's bottom corners, inside the volume bars. +static void friends_draw(About& about, Resources& resources, ImDrawList* drawList, ImVec2 min, ImVec2 max, float inset) +{ auto height = (max.y - min.y) * FRIEND_HEIGHT_RATIO; - auto row_draw = [&](std::span indices, float left) - { - for (auto index : indices) - { - auto& state = about.friendStates[index]; - auto size = friend_size_get(state, height); - friend_canvas_draw(state, resources); - if (state.isLoaded) - image_premultiplied_draw(drawList, (ImTextureID)(intptr_t)state.canvas->texture, ImVec2(left, max.y - size.y), - ImVec2(left + size.x, max.y)); - left += size.x; - } + auto row_draw = [&](std::span indices, float left) { + for (auto index : indices) + { + auto& state = about.friendStates[index]; + auto size = friend_size_get(state, height); + friend_canvas_draw(state, resources); + if (state.isLoaded) + image_premultiplied_draw(drawList, (ImTextureID)(intptr_t)state.canvas->texture, + ImVec2(left, max.y - size.y), ImVec2(left + size.x, max.y)); + left += size.x; + } }; auto rightWidth = 0.0f; for (auto index : FRIEND_ORDER_RIGHT) - rightWidth += friend_size_get(about.friendStates[index], height).x; + rightWidth += friend_size_get(about.friendStates[index], height).x; row_draw(FRIEND_ORDER_LEFT, min.x + inset); row_draw(FRIEND_ORDER_RIGHT, max.x - inset - rightWidth); - } +} - // One tick: the credits scroll up (a new pass, and effect, once they are gone) and the bars follow the music. - static void roll_tick(About::RollState& roll, Resources& resources, float boxHeight, float textHeight) - { +// One tick: the credits scroll up (a new pass, and effect, once they are gone) and the bars follow the music. +static void roll_tick(About::RollState& roll, Resources& resources, float boxHeight, float textHeight) +{ auto levels = audio_levels_get(resources.music_track()); roll.levelPeak = std::max({roll.levelPeak * BAR_LEVEL_DECAY, levels.x, levels.y, BAR_LEVEL_FLOOR}); levels *= boxHeight / roll.levelPeak; roll.scroll -= ROLL_SCROLL_STEP; if (roll.scroll < -(textHeight + ROLL_SCROLL_GAP)) { - roll.scroll = boxHeight; - ++roll.pass; + roll.scroll = boxHeight; + ++roll.pass; } ++roll.tick; @@ -324,92 +330,98 @@ using namespace glm; IM_COL32((roll.pass * BAR_RED_STEP) % 256, 255 - roll.tick % 256, roll.tick % 256, 255)}; if (frame.effect == EFFECT_SWAY) { - frame.trailAlpha = ROLL_TRAIL_ALPHA_SWAY; - frame.offsetX = std::sin(roll.scroll * ROLL_WAVE_FREQUENCY) * ROLL_SWAY_AMPLITUDE; + frame.trailAlpha = ROLL_TRAIL_ALPHA_SWAY; + frame.offsetX = std::sin(roll.scroll * ROLL_WAVE_FREQUENCY) * ROLL_SWAY_AMPLITUDE; } if (frame.effect == EFFECT_STRETCH) { - frame.trailAlpha = ROLL_TRAIL_ALPHA_STRETCH; - frame.stretch = 1.0f + (levels.x + levels.y) / boxHeight * ROLL_STRETCH; + frame.trailAlpha = ROLL_TRAIL_ALPHA_STRETCH; + frame.stretch = 1.0f + (levels.x + levels.y) / boxHeight * ROLL_STRETCH; } // While the credits stretch, the title flashes random colors. roll.titleColor = frame.effect == EFFECT_STRETCH ? IM_COL32(std::rand() % 256, std::rand() % 256, std::rand() % 256, 255) : 0; roll.history.push_front(frame); - if (roll.history.size() > ROLL_HISTORY_MAX) roll.history.pop_back(); - } + if (roll.history.size() > ROLL_HISTORY_MAX) + roll.history.pop_back(); +} - static ImU32 color_weighted_get(ImU32 color, float weight) - { +static ImU32 color_weighted_get(ImU32 color, float weight) +{ auto value = ImGui::ColorConvertU32ToFloat4(color); value.w *= weight; return ImGui::ColorConvertFloat4ToU32(value); - } +} - // The credits as one tick drew them; `weight` fades the copies that linger as trails. - static void roll_text_draw(ImDrawList* drawList, Resources& resources, const About::RollFrame& frame, ImVec2 min, ImVec2 max, - float scale, float lineHeight, float weight) - { +// The credits as one tick drew them. `weight` fades the copies that linger as trails. +static void roll_text_draw(ImDrawList* drawList, Resources& resources, const About::RollFrame& frame, ImVec2 min, + ImVec2 max, float scale, float lineHeight, float weight) +{ auto centerX = (min.x + max.x) * 0.5f; for (int i = 0; i < CREDIT_COUNT; ++i) { - auto& credit = CREDITS[i]; - auto y = min.y + frame.scroll * scale + (float)i * lineHeight; - if (!*credit.string || y + lineHeight < min.y || y > max.y) continue; + auto& credit = CREDITS[i]; + auto y = min.y + frame.scroll * scale + (float)i * lineHeight; + if (!*credit.string || y + lineHeight < min.y || y > max.y) + continue; - auto font = resources.fonts[credit.font].get(); - auto x = centerX - font->CalcTextSizeA(lineHeight, FLT_MAX, 0.0f, credit.string).x * 0.5f + frame.offsetX * scale; - if (frame.effect == EFFECT_WAVE) - x += std::round(std::sin((y - min.y) / scale * ROLL_WAVE_FREQUENCY) * ROLL_WAVE_AMPLITUDE) * scale; - auto color = credit.font == FONT_BOLD ? ROLL_HEADER_COLOR : ROLL_NAME_COLOR; + auto font = resources.fonts[credit.font].get(); + auto x = + centerX - font->CalcTextSizeA(lineHeight, FLT_MAX, 0.0f, credit.string).x * 0.5f + frame.offsetX * scale; + if (frame.effect == EFFECT_WAVE) + x += std::round(std::sin((y - min.y) / scale * ROLL_WAVE_FREQUENCY) * ROLL_WAVE_AMPLITUDE) * scale; + auto color = credit.font == FONT_BOLD ? ROLL_HEADER_COLOR : ROLL_NAME_COLOR; - auto vertexStart = drawList->VtxBuffer.Size; - drawList->AddText(font, lineHeight, ImVec2(x, y), color_weighted_get(color, weight), credit.string); - if (frame.stretch != 1.0f) - for (int vertex = vertexStart; vertex < drawList->VtxBuffer.Size; ++vertex) - drawList->VtxBuffer[vertex].pos.x = centerX + (drawList->VtxBuffer[vertex].pos.x - centerX) * frame.stretch; + auto vertexStart = drawList->VtxBuffer.Size; + drawList->AddText(font, lineHeight, ImVec2(x, y), color_weighted_get(color, weight), credit.string); + if (frame.stretch != 1.0f) + for (int vertex = vertexStart; vertex < drawList->VtxBuffer.Size; ++vertex) + drawList->VtxBuffer[vertex].pos.x = + centerX + (drawList->VtxBuffer[vertex].pos.x - centerX) * frame.stretch; } - } +} - // A volume bar's color at a height: red at the bottom into the tick's color at its gradient height. - static ImU32 bar_color_get(const About::RollFrame& frame, float height, float weight) - { +// A volume bar's color at a height: red at the bottom into the tick's color at its gradient height. +static ImU32 bar_color_get(const About::RollFrame& frame, float height, float weight) +{ auto color = ImLerp(ImGui::ColorConvertU32ToFloat4(BAR_BASE_COLOR), ImGui::ColorConvertU32ToFloat4(frame.gradientColor), height / frame.gradientHeight); color.w = weight; return ImGui::ColorConvertFloat4ToU32(color); - } +} - // The left and right volume bars; older, taller bars show above newer ones, fading as they age. - static void roll_bars_draw(ImDrawList* drawList, const std::deque& history, ImVec2 min, ImVec2 max, - float scale) - { +// The left and right volume bars. Older, taller bars show above newer ones, fading as they age. +static void roll_bars_draw(ImDrawList* drawList, const std::deque& history, ImVec2 min, ImVec2 max, + float scale) +{ auto width = BAR_WIDTH * scale; for (int side = 0; side < 2; ++side) { - auto left = side == 0 ? min.x : max.x - width; - auto covered = 0.0f; - auto weight = 1.0f; - for (auto& frame : history) - { - if (weight < ROLL_WEIGHT_MIN) break; - auto height = frame.levels[side]; - if (height > covered) + auto left = side == 0 ? min.x : max.x - width; + auto covered = 0.0f; + auto weight = 1.0f; + for (auto& frame : history) { - auto top = bar_color_get(frame, height, weight); - auto bottom = bar_color_get(frame, covered, weight); - drawList->AddRectFilledMultiColor(ImVec2(left, max.y - height * scale), - ImVec2(left + width, max.y - covered * scale), top, top, bottom, bottom); - covered = height; + if (weight < ROLL_WEIGHT_MIN) + break; + auto height = frame.levels[side]; + if (height > covered) + { + auto top = bar_color_get(frame, height, weight); + auto bottom = bar_color_get(frame, covered, weight); + drawList->AddRectFilledMultiColor(ImVec2(left, max.y - height * scale), + ImVec2(left + width, max.y - covered * scale), top, top, bottom, + bottom); + covered = height; + } + weight *= 1.0f - (float)BAR_TRAIL_ALPHA / 255.0f; } - weight *= 1.0f - (float)BAR_TRAIL_ALPHA / 255.0f; - } } - } +} - static void roll_draw(About& about, Resources& resources, ImVec2 min, ImVec2 size) - { +static void roll_draw(About& about, Resources& resources, ImVec2 min, ImVec2 size) +{ auto& roll = about.roll; auto max = ImVec2(min.x + size.x, min.y + size.y); auto lineHeight = ImGui::GetFontSize(); @@ -419,28 +431,30 @@ using namespace glm; if (roll.history.empty()) { - roll.scroll = boxHeight; - roll_tick(roll, resources, boxHeight, textHeight); + roll.scroll = boxHeight; + roll_tick(roll, resources, boxHeight, textHeight); } roll.tickTime += ImGui::GetIO().DeltaTime; for (int i = 0; roll.tickTime >= ROLL_TICK; ++i, roll.tickTime -= ROLL_TICK) - if (i < ROLL_TICKS_MAX) roll_tick(roll, resources, boxHeight, textHeight); + if (i < ROLL_TICKS_MAX) + roll_tick(roll, resources, boxHeight, textHeight); auto drawList = ImGui::GetWindowDrawList(); drawList->PushClipRect(min, max, true); drawList->AddRectFilled(min, max, ROLL_BACKGROUND); - // Each tick faded what came before it by its trail alpha; the copies still visible are drawn oldest first. + // Each tick faded what came before it by its trail alpha. The copies still visible are drawn oldest first. std::vector> copies; auto weight = 1.0f; for (auto& frame : roll.history) { - if (weight < ROLL_WEIGHT_MIN) break; - copies.emplace_back(&frame, weight); - weight *= 1.0f - (float)frame.trailAlpha / 255.0f; + if (weight < ROLL_WEIGHT_MIN) + break; + copies.emplace_back(&frame, weight); + weight *= 1.0f - (float)frame.trailAlpha / 255.0f; } for (auto it = copies.rbegin(); it != copies.rend(); ++it) - roll_text_draw(drawList, resources, *it->first, min, max, scale, lineHeight, it->second); + roll_text_draw(drawList, resources, *it->first, min, max, scale, lineHeight, it->second); auto barWidth = BAR_WIDTH * scale; drawList->AddRectFilledMultiColor(ImVec2(min.x + barWidth, min.y), @@ -450,28 +464,29 @@ using namespace glm; friends_draw(about, resources, drawList, min, max, barWidth); drawList->PopClipRect(); ImGui::Dummy(size); - } +} - void About::reset(Resources& resources) - { +void About::reset(Resources& resources) +{ audio_play(resources.music_track(), true); roll = {}; for (int i = 0; i < FRIEND_COUNT; ++i) - friend_state_load(friendStates[i], FRIENDS[i]); - } + friend_state_load(friendStates[i], FRIENDS[i]); +} - void About::update(Resources& resources) - { +void About::update(Resources& resources) +{ auto size = ImGui::GetContentRegionAvail(); auto titleLabel = localize.get(LABEL_APPLICATION_NAME); auto delta = ImGui::GetIO().DeltaTime; for (auto& friendState : friendStates) - friend_state_tick(friendState, delta); + friend_state_tick(friendState, delta); title_draw(*this, resources, titleLabel, size.x); auto rollSize = ImGui::GetContentRegionAvail(); - if (rollSize.x > 0.0f && rollSize.y > 0.0f) roll_draw(*this, resources, ImGui::GetCursorScreenPos(), rollSize); - } + if (rollSize.x > 0.0f && rollSize.y > 0.0f) + roll_draw(*this, resources, ImGui::GetCursorScreenPos(), rollSize); +} diff --git a/src/ui/about.h b/src/ui/about.h index 6db7220..f918c84 100644 --- a/src/ui/about.h +++ b/src/ui/about.h @@ -13,51 +13,51 @@ #include "friends.h" #include "resources.h" - class About - { - public: +class About +{ +public: struct Credit { - const char* string = nullptr; - FontStyle font = FONT_REGULAR; + const char* string = nullptr; + FontStyle font = FONT_REGULAR; }; // One 30 Hz tick of the credits roll, after the original editor's About box. Lengths are in its pixels (for - // 14 px text); `trailAlpha` is how much of what was drawn before this tick it faded out (255 clears it). + // 14 px text). `trailAlpha` is how much of what was drawn before this tick it faded out (255 clears it). struct RollFrame { - float scroll = 0; - float offsetX = 0; - float stretch = 1.0f; - int effect = 0; - int trailAlpha = 255; - glm::vec2 levels{}; - float gradientHeight = 0; - ImU32 gradientColor = 0; + float scroll = 0; + float offsetX = 0; + float stretch = 1.0f; + int effect = 0; + int trailAlpha = 255; + glm::vec2 levels{}; + float gradientHeight = 0; + ImU32 gradientColor = 0; }; // The credits scroll up through a box, one of four effects per pass (none, sway, stretch to the music, wave), - // between volume bars; recent ticks are kept to draw the trails they leave. + // between volume bars. Recent ticks are kept to draw the trails they leave. struct RollState { - std::deque history; - float scroll = 0; - float tickTime = 0; - int tick = 0; - int pass = 0; - float levelPeak = 0; - ImU32 titleColor = 0; + std::deque history; + float scroll = 0; + float tickTime = 0; + int tick = 0; + int pass = 0; + float levelPeak = 0; + ImU32 titleColor = 0; }; struct FriendState { - Model model = {}; - std::unique_ptr canvas; - std::unordered_map textures; - glm::vec4 rect{-1.0f}; - float time = 0; - float fps = 30.0f; - bool isLoaded = false; + Model model = {}; + std::unique_ptr canvas; + std::unordered_map textures; + glm::vec4 rect{-1.0f}; + float time = 0; + float fps = 30.0f; + bool isLoaded = false; }; RollState roll = {}; @@ -65,5 +65,4 @@ void reset(Resources& resources); void update(Resources& resources); - }; - +}; diff --git a/src/ui/actions.cpp b/src/ui/actions.cpp index f0fec62..99e6c47 100644 --- a/src/ui/actions.cpp +++ b/src/ui/actions.cpp @@ -5,25 +5,33 @@ #include "ui/layout.h" #include "ui/shortcut.h" - static bool is_action_shortcut_valid(int shortcutType) { return shortcutType >= 0 && shortcutType < SHORTCUT_COUNT; } +static bool is_action_shortcut_valid(int shortcutType) +{ + return shortcutType >= 0 && shortcutType < SHORTCUT_COUNT; +} - static std::string action_shortcut_text_get(const Action& action, Settings& settings) - { - if (!is_action_shortcut_valid(action.shortcut)) return {}; +static std::string action_shortcut_text_get(const Action& action, Settings& settings) +{ + if (!is_action_shortcut_valid(action.shortcut)) + return {}; return settings.*SHORTCUT_MEMBERS[action.shortcut]; - } +} - static ImGuiKeyChord action_chord_get(const Action& action, Manager& manager) - { - if (!is_action_shortcut_valid(action.shortcut)) return ImGuiKey_None; +static ImGuiKeyChord action_chord_get(const Action& action, Manager& manager) +{ + if (!is_action_shortcut_valid(action.shortcut)) + return ImGuiKey_None; return manager.chords[action.shortcut]; - } +} - bool is_action_enabled(const Action& action) { return !action.isEnabled || action.isEnabled(); } +bool is_action_enabled(const Action& action) +{ + return !action.isEnabled || action.isEnabled(); +} - Action action_make(ActionType type, std::function isEnabled, std::function run, StringType tooltip, - int shortcut) - { +Action action_make(ActionType type, std::function isEnabled, std::function run, StringType tooltip, + int shortcut) +{ auto info = ACTION_INFOS[type]; return {.type = type, .label = info.label, @@ -31,110 +39,131 @@ .shortcut = shortcut == ACTION_COUNT ? info.shortcut : shortcut, .isEnabled = std::move(isEnabled), .run = std::move(run)}; - } +} - void Actions::add(Action action) { items.push_back(std::move(action)); } +void Actions::add(Action action) +{ + items.push_back(std::move(action)); +} - void Actions::add(ActionType type, std::function isEnabled, std::function run, StringType tooltip, - int shortcut) - { +void Actions::add(ActionType type, std::function isEnabled, std::function run, StringType tooltip, + int shortcut) +{ add(action_make(type, std::move(isEnabled), std::move(run), tooltip, shortcut)); - } +} - void Actions::separator() { items.push_back({.isSeparator = true}); } +void Actions::separator() +{ + items.push_back({.isSeparator = true}); +} - void actions_undo_redo_add(Actions& actions, Manager& manager, Document& document) - { +void actions_undo_redo_add(Actions& actions, Manager& manager, Document& document) +{ actions.add( - ACTION_UNDO, [&document]() { return document.is_able_to_undo(); }, [&manager]() - { manager.command_push({manager.selected, [](Manager&, Document& document) { document.undo(); }}); }); + ACTION_UNDO, [&document]() { return document.is_able_to_undo(); }, + [&manager]() { + manager.command_push({manager.selected, [](Manager&, Document& document) { document.undo(); }}); + }); actions.add( - ACTION_REDO, [&document]() { return document.is_able_to_redo(); }, [&manager]() - { manager.command_push({manager.selected, [](Manager&, Document& document) { document.redo(); }}); }); - } + ACTION_REDO, [&document]() { return document.is_able_to_redo(); }, + [&manager]() { + manager.command_push({manager.selected, [](Manager&, Document& document) { document.redo(); }}); + }); +} - static void action_items_menu_draw(std::vector& items, Settings& settings) - { +static void action_items_menu_draw(std::vector& items, Settings& settings) +{ bool isPreviousSeparator = false; for (auto& action : items) { - if (action.isSeparator) - { - if (!isPreviousSeparator) ImGui::Separator(); - isPreviousSeparator = true; - continue; - } - isPreviousSeparator = false; - - if (!action.children.empty()) - { - if (ImGui::BeginMenu(localize.get(action.label), is_action_enabled(action))) + if (action.isSeparator) { - action_items_menu_draw(action.children, settings); - ImGui::EndMenu(); + if (!isPreviousSeparator) + ImGui::Separator(); + isPreviousSeparator = true; + continue; } - continue; - } + isPreviousSeparator = false; - auto shortcutText = action_shortcut_text_get(action, settings); - auto shortcutLabel = shortcutText.empty() ? nullptr : shortcutText.c_str(); - if (ImGui::MenuItem(localize.get(action.label), shortcutLabel, false, is_action_enabled(action)) && action.run) - action.run(); - if (action.tooltip != STRING_UNDEFINED && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) - ImGui::SetItemTooltip("%s", localize.get(action.tooltip)); + if (!action.children.empty()) + { + if (ImGui::BeginMenu(localize.get(action.label), is_action_enabled(action))) + { + action_items_menu_draw(action.children, settings); + ImGui::EndMenu(); + } + continue; + } + + auto shortcutText = action_shortcut_text_get(action, settings); + auto shortcutLabel = shortcutText.empty() ? nullptr : shortcutText.c_str(); + if (ImGui::MenuItem(localize.get(action.label), shortcutLabel, false, is_action_enabled(action)) && action.run) + action.run(); + if (action.tooltip != STRING_UNDEFINED && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetItemTooltip("%s", localize.get(action.tooltip)); } - } +} - void actions_menu_draw(Actions& actions, Settings& settings) { action_items_menu_draw(actions.items, settings); } +void actions_menu_draw(Actions& actions, Settings& settings) +{ + action_items_menu_draw(actions.items, settings); +} - bool actions_context_window_draw(const char* label, Actions& actions, Settings& settings, ImGuiPopupFlags flags, - ImGuiHoveredFlags hoveredFlags) - { +bool actions_context_window_draw(const char* label, Actions& actions, Settings& settings, ImGuiPopupFlags flags, + ImGuiHoveredFlags hoveredFlags) +{ auto mouseButton = flags & ImGuiPopupFlags_MouseButtonMask_; if (ImGui::IsMouseReleased(mouseButton) && ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | hoveredFlags)) - if (!(flags & ImGuiPopupFlags_NoOpenOverItems) || !ImGui::IsAnyItemHovered()) ImGui::OpenPopup(label, flags); + if (!(flags & ImGuiPopupFlags_NoOpenOverItems) || !ImGui::IsAnyItemHovered()) + ImGui::OpenPopup(label, flags); - if (!ImGui::BeginPopup(label, ImGuiWindowFlags_NoMove)) return false; + if (!ImGui::BeginPopup(label, ImGuiWindowFlags_NoMove)) + return false; actions_menu_draw(actions, settings); ImGui::EndPopup(); return true; - } +} - bool actions_popup_draw(const char* label, Actions& actions, Settings& settings) - { - if (!ImGui::BeginPopup(label, ImGuiWindowFlags_NoMove)) return false; +bool actions_popup_draw(const char* label, Actions& actions, Settings& settings) +{ + if (!ImGui::BeginPopup(label, ImGuiWindowFlags_NoMove)) + return false; actions_menu_draw(actions, settings); ImGui::EndPopup(); return true; - } +} - void actions_shortcuts_update(Actions& actions, Manager& manager, ShortcutScope shortcutType) - { +void actions_shortcuts_update(Actions& actions, Manager& manager, ShortcutScope shortcutType) +{ for (auto& action : actions.items) { - if (action.isSeparator || !action.run || !is_action_enabled(action)) continue; - auto chord = action_chord_get(action, manager); - if (!shortcut(chord, shortcutType)) continue; - action.run(); - break; + if (action.isSeparator || !action.run || !is_action_enabled(action)) + continue; + auto chord = action_chord_get(action, manager); + if (!shortcut(chord, shortcutType)) + continue; + action.run(); + break; } - } +} - void action_button_draw(Action& action, Manager& manager, Settings& settings, ImVec2 widgetSize, bool& isSameLine) - { - if (isSameLine) ImGui::SameLine(); +void action_button_draw(Action& action, Manager& manager, Settings& settings, ImVec2 widgetSize, bool& isSameLine) +{ + if (isSameLine) + ImGui::SameLine(); ImGui::BeginDisabled(!is_action_enabled(action)); shortcut(action_chord_get(action, manager)); - if (ImGui::Button(localize.get(action.label), widgetSize) && action.run) action.run(); + if (ImGui::Button(localize.get(action.label), widgetSize) && action.run) + action.run(); ImGui::EndDisabled(); if (action.tooltip != STRING_UNDEFINED) { - auto shortcutText = action_shortcut_text_get(action, settings); - if (shortcutText.empty()) - ImGui::SetItemTooltip("%s", localize.get(action.tooltip)); - else - set_item_tooltip_shortcut(localize.get(action.tooltip), shortcutText); + auto shortcutText = action_shortcut_text_get(action, settings); + if (shortcutText.empty()) + ImGui::SetItemTooltip("%s", localize.get(action.tooltip)); + else + set_item_tooltip_shortcut(localize.get(action.tooltip), shortcutText); } isSameLine = true; - } +} diff --git a/src/ui/actions.h b/src/ui/actions.h index c6b61cd..be1e724 100644 --- a/src/ui/actions.h +++ b/src/ui/actions.h @@ -9,58 +9,58 @@ #include "settings.h" #define ACTIONS(X) \ - X(ACTION_UNDO, SHORTCUT_STRING_UNDO, SHORTCUT_UNDO) \ - X(ACTION_REDO, SHORTCUT_STRING_REDO, SHORTCUT_REDO) \ - X(ACTION_ADD, BASIC_ADD, SHORTCUT_ADD) \ - X(ACTION_REMOVE, BASIC_REMOVE, SHORTCUT_REMOVE) \ - X(ACTION_DUPLICATE, BASIC_DUPLICATE, SHORTCUT_DUPLICATE) \ - X(ACTION_MERGE, BASIC_MERGE, SHORTCUT_MERGE) \ - X(ACTION_GROUP, BASIC_GROUP, SHORTCUT_GROUP) \ - X(ACTION_DEFAULT, BASIC_DEFAULT, SHORTCUT_DEFAULT) \ - X(ACTION_RENAME, BASIC_RENAME, SHORTCUT_RENAME) \ - X(ACTION_PROPERTIES, BASIC_PROPERTIES, -1) \ - X(ACTION_REVERSE, BASIC_REVERSE, -1) \ - X(ACTION_CUT, BASIC_CUT, SHORTCUT_CUT) \ - X(ACTION_COPY, BASIC_COPY, SHORTCUT_COPY) \ - X(ACTION_PASTE, BASIC_PASTE, SHORTCUT_PASTE) \ - X(ACTION_RELOAD, BASIC_RELOAD, -1) \ - X(ACTION_REPLACE, BASIC_REPLACE, -1) \ - X(ACTION_SAVE, BASIC_SAVE, -1) \ - X(ACTION_EXPORT, BASIC_EXPORT, -1) \ - X(ACTION_OPEN, BASIC_OPEN, -1) \ - X(ACTION_OPEN_DIRECTORY, BASIC_OPEN_DIRECTORY, -1) \ - X(ACTION_SET_FILE_PATH, BASIC_SET_FILE_PATH, -1) \ - X(ACTION_PACK, BASIC_PACK, -1) \ - X(ACTION_RASTERIZE, LABEL_RASTERIZE, -1) \ - X(ACTION_TRIM, BASIC_TRIM, -1) \ - X(ACTION_PLAY, LABEL_PLAY, SHORTCUT_PLAY_PAUSE) \ - X(ACTION_CENTER_VIEW, LABEL_CENTER_VIEW, SHORTCUT_CENTER_VIEW) \ - X(ACTION_FIT_VIEW, LABEL_FIT, SHORTCUT_FIT) \ - X(ACTION_ZOOM_IN, SHORTCUT_STRING_ZOOM_IN, SHORTCUT_ZOOM_IN) \ - X(ACTION_ZOOM_OUT, SHORTCUT_STRING_ZOOM_OUT, SHORTCUT_ZOOM_OUT) + X(ACTION_UNDO, SHORTCUT_STRING_UNDO, SHORTCUT_UNDO) \ + X(ACTION_REDO, SHORTCUT_STRING_REDO, SHORTCUT_REDO) \ + X(ACTION_ADD, BASIC_ADD, SHORTCUT_ADD) \ + X(ACTION_REMOVE, BASIC_REMOVE, SHORTCUT_REMOVE) \ + X(ACTION_DUPLICATE, BASIC_DUPLICATE, SHORTCUT_DUPLICATE) \ + X(ACTION_MERGE, BASIC_MERGE, SHORTCUT_MERGE) \ + X(ACTION_GROUP, BASIC_GROUP, SHORTCUT_GROUP) \ + X(ACTION_DEFAULT, BASIC_DEFAULT, SHORTCUT_DEFAULT) \ + X(ACTION_RENAME, BASIC_RENAME, SHORTCUT_RENAME) \ + X(ACTION_PROPERTIES, BASIC_PROPERTIES, -1) \ + X(ACTION_REVERSE, BASIC_REVERSE, -1) \ + X(ACTION_CUT, BASIC_CUT, SHORTCUT_CUT) \ + X(ACTION_COPY, BASIC_COPY, SHORTCUT_COPY) \ + X(ACTION_PASTE, BASIC_PASTE, SHORTCUT_PASTE) \ + X(ACTION_RELOAD, BASIC_RELOAD, -1) \ + X(ACTION_REPLACE, BASIC_REPLACE, -1) \ + X(ACTION_SAVE, BASIC_SAVE, -1) \ + X(ACTION_EXPORT, BASIC_EXPORT, -1) \ + X(ACTION_OPEN, BASIC_OPEN, -1) \ + X(ACTION_OPEN_DIRECTORY, BASIC_OPEN_DIRECTORY, -1) \ + X(ACTION_SET_FILE_PATH, BASIC_SET_FILE_PATH, -1) \ + X(ACTION_PACK, BASIC_PACK, -1) \ + X(ACTION_RASTERIZE, LABEL_RASTERIZE, -1) \ + X(ACTION_TRIM, BASIC_TRIM, -1) \ + X(ACTION_PLAY, LABEL_PLAY, SHORTCUT_PLAY_PAUSE) \ + X(ACTION_CENTER_VIEW, LABEL_CENTER_VIEW, SHORTCUT_CENTER_VIEW) \ + X(ACTION_FIT_VIEW, LABEL_FIT, SHORTCUT_FIT) \ + X(ACTION_ZOOM_IN, SHORTCUT_STRING_ZOOM_IN, SHORTCUT_ZOOM_IN) \ + X(ACTION_ZOOM_OUT, SHORTCUT_STRING_ZOOM_OUT, SHORTCUT_ZOOM_OUT) - enum ActionType - { +enum ActionType +{ #define X(name, label, shortcut) name, ACTIONS(X) #undef X ACTION_COUNT - }; +}; - struct ActionInfo - { +struct ActionInfo +{ StringType label = {}; int shortcut = -1; - }; +}; - constexpr ActionInfo ACTION_INFOS[] = { +constexpr ActionInfo ACTION_INFOS[] = { #define X(name, label, shortcut) {label, shortcut}, - ACTIONS(X) + ACTIONS(X) #undef X - }; +}; - struct Action - { +struct Action +{ ActionType type = {}; StringType label = STRING_UNDEFINED; StringType tooltip = STRING_UNDEFINED; @@ -69,25 +69,25 @@ std::function isEnabled{}; std::function run{}; std::vector children; // a submenu, in menus - }; +}; - struct Actions - { +struct Actions +{ std::vector items; void add(Action); void add(ActionType, std::function, std::function, StringType = STRING_UNDEFINED, int = ACTION_COUNT); void separator(); - }; +}; - bool is_action_enabled(const Action&); - Action action_make(ActionType, std::function, std::function, StringType = STRING_UNDEFINED, - int = ACTION_COUNT); - void actions_undo_redo_add(Actions&, Manager&, Document&); - void actions_menu_draw(Actions&, Settings&); - bool actions_context_window_draw(const char*, Actions&, Settings&, ImGuiPopupFlags = ImGuiPopupFlags_MouseButtonRight, - ImGuiHoveredFlags = ImGuiHoveredFlags_None); - bool actions_popup_draw(const char*, Actions&, Settings&); - void actions_shortcuts_update(Actions&, Manager&, ShortcutScope = SCOPE_FOCUSED); - void action_button_draw(Action&, Manager&, Settings&, ImVec2, bool&); +bool is_action_enabled(const Action&); +Action action_make(ActionType, std::function, std::function, StringType = STRING_UNDEFINED, + int = ACTION_COUNT); +void actions_undo_redo_add(Actions&, Manager&, Document&); +void actions_menu_draw(Actions&, Settings&); +bool actions_context_window_draw(const char*, Actions&, Settings&, ImGuiPopupFlags = ImGuiPopupFlags_MouseButtonRight, + ImGuiHoveredFlags = ImGuiHoveredFlags_None); +bool actions_popup_draw(const char*, Actions&, Settings&); +void actions_shortcuts_update(Actions&, Manager&, ShortcutScope = SCOPE_FOCUSED); +void action_button_draw(Action&, Manager&, Settings&, ImVec2, bool&); diff --git a/src/ui/animation_preview.cpp b/src/ui/animation_preview.cpp index 9304287..7558b03 100644 --- a/src/ui/animation_preview.cpp +++ b/src/ui/animation_preview.cpp @@ -32,212 +32,220 @@ using namespace glm; - constexpr auto NULL_RECT_COLOR = vec4(0.0f, 0.0f, 1.0f, 0.90f); - constexpr auto SELECTED_LAYER_BORDER_COLOR = vec4(1.0f, 0.1059f, 0.5882f, 1.0f); - constexpr auto TARGET_SIZE = vec2(32, 32); - constexpr auto PARENT_DIM_ALPHA = 0.65f; // how much a stepped-into child's parent fades - constexpr auto POINT_SIZE = vec2(4, 4); - constexpr auto TRIGGER_TEXT_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); - constexpr auto TRIGGER_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.5f); - struct OverlayAnimationOption - { +constexpr auto NULL_RECT_COLOR = vec4(0.0f, 0.0f, 1.0f, 0.90f); +constexpr auto SELECTED_LAYER_BORDER_COLOR = vec4(1.0f, 0.1059f, 0.5882f, 1.0f); +constexpr auto TARGET_SIZE = vec2(32, 32); +constexpr auto PARENT_DIM_ALPHA = 0.65f; // how much a stepped-into child's parent fades +constexpr auto POINT_SIZE = vec2(4, 4); +constexpr auto TRIGGER_TEXT_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); +constexpr auto TRIGGER_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.5f); +struct OverlayAnimationOption +{ uint64_t documentId = 0; int animationIndex = -1; std::string label; - }; +}; - static std::vector overlay_animation_options_get(Manager& manager) - { +static std::vector overlay_animation_options_get(Manager& manager) +{ std::vector options{{.label = std::string(localize.get(BASIC_NONE))}}; for (auto& document : manager.documents) { - auto documentLabel = path_to_utf8(document.filename_get()); - for (auto [animationIndex, animation] : document.model.animations_get()) - { - auto label = std::format("{} ({})", animation->name, documentLabel); - options.push_back({.documentId = document.tabId, .animationIndex = animationIndex, .label = label}); - } + auto documentLabel = path_to_utf8(document.filename_get()); + for (auto [animationIndex, animation] : document.model.animations_get()) + { + auto label = std::format("{} ({})", animation->name, documentLabel); + options.push_back({.documentId = document.tabId, .animationIndex = animationIndex, .label = label}); + } } return options; - } +} - static std::vector overlay_animation_option_labels_get(std::vector& options) - { +static std::vector overlay_animation_option_labels_get(std::vector& options) +{ std::vector labels; labels.reserve(options.size()); for (auto& option : options) - labels.push_back(option.label.c_str()); + labels.push_back(option.label.c_str()); return labels; - } +} - static int overlay_animation_option_index_get(const Document& document, const std::vector& options) - { - if (document.overlayIndex == -1) return 0; +static int overlay_animation_option_index_get(const Document& document, + const std::vector& options) +{ + if (document.overlayIndex == -1) + return 0; auto documentId = document.overlayDocumentId ? document.overlayDocumentId : document.tabId; for (int i = 1; i < (int)options.size(); ++i) - if (options[i].documentId == documentId && options[i].animationIndex == document.overlayIndex) return i; + if (options[i].documentId == documentId && options[i].animationIndex == document.overlayIndex) + return i; return -1; - } +} - static Document* overlay_animation_document_get(Manager& manager, const Document& document) - { - if (document.overlayIndex == -1) return nullptr; +static Document* overlay_animation_document_get(Manager& manager, const Document& document) +{ + if (document.overlayIndex == -1) + return nullptr; auto documentId = document.overlayDocumentId ? document.overlayDocumentId : document.tabId; for (auto& candidate : manager.documents) - if (candidate.tabId == documentId) return &candidate; + if (candidate.tabId == documentId) + return &candidate; return nullptr; - } +} - static std::optional animation_rects_merge(std::optional rect, vec4 next) - { - if (next == vec4(-1.0f)) return rect; - if (!rect) return next; +static std::optional animation_rects_merge(std::optional rect, vec4 next) +{ + if (next == vec4(-1.0f)) + return rect; + if (!rect) + return next; auto minPoint = glm::min(vec2(rect->x, rect->y), vec2(next.x, next.y)); auto maxPoint = glm::max(vec2(rect->x + rect->z, rect->y + rect->w), vec2(next.x + next.z, next.y + next.w)); return vec4(minPoint, maxPoint - minPoint); - } +} - static std::optional animation_render_rect_get(Manager& manager, Document& document, const Animation* animation, - bool isRootTransform) - { +static std::optional animation_render_rect_get(Manager& manager, Document& document, const Animation* animation, + bool isRootTransform) +{ std::optional rect{}; if (animation) - rect = animation_rects_merge( - rect, animation_rect(document.model, *animation, isRootTransform, document.library_resolver_get())); + rect = animation_rects_merge( + rect, animation_rect(document.model, *animation, isRootTransform, document.library_resolver_get())); if (auto overlayDocument = overlay_animation_document_get(manager, document)) - if (auto overlayAnimation = overlayDocument->model.animation_get(document.overlayIndex)) - rect = animation_rects_merge(rect, - animation_rect(overlayDocument->model, *overlayAnimation, isRootTransform, + if (auto overlayAnimation = overlayDocument->model.animation_get(document.overlayIndex)) + rect = + animation_rects_merge(rect, animation_rect(overlayDocument->model, *overlayAnimation, isRootTransform, overlayDocument->library_resolver_get())); return rect; - } +} - void AnimationPreview::tick(Manager& manager, Settings& settings, float deltaSeconds) - { +void AnimationPreview::tick(Manager& manager, Settings& settings, float deltaSeconds) +{ auto& document = *manager.get(); auto& model = document.model; auto& playback = document.playback; auto& frameTime = document.frameTime; - auto stop_all_sounds = [&]() - { - for (auto sound : document.sounds_get()) - audio_stop(*sound, mixer); + auto stop_all_sounds = [&]() { + for (auto sound : document.sounds_get()) + audio_stop(*sound, mixer); }; if (manager.isRecording) { - if (recorder.is_done()) - { - recorder.finish(document, audioStream); - recording_stop(manager, document); - } - stop_all_sounds(); - wasPlaybackPlaying = false; - return; + if (recorder.is_done()) + { + recorder.finish(document, audioStream); + recording_stop(manager, document); + } + stop_all_sounds(); + wasPlaybackPlaying = false; + return; } if (playback.isPlaying) { - auto animation = model.animation_get(document.reference_get().animationIndex); - auto& isSound = settings.timelineIsSound; + auto animation = model.animation_get(document.reference_get().animationIndex); + auto& isSound = settings.timelineIsSound; - if (!animation) - { - playback.isPlaying = false; - playback.isFinished = false; - playback.timing_reset(); - } - else - { - auto fps = std::max(model.info.fps, 1); - auto range = animation_play_range_get(*animation); - if (!wasPlaybackPlaying) soundFrame = (int)std::floor(playback.time) - 1; - playback.tick(fps, range.x, range.y, (animation->isLoop || settings.playbackIsLoop) && !manager.isRecording, - deltaSeconds); - - // Each frame playback reaches plays its trigger's sound once, however many ticks it lasts or skips. - auto frame = (int)std::floor(playback.time); - for (int step = 0; soundFrame != frame && step < range.y - range.x; ++step) + if (!animation) { - soundFrame = soundFrame + 1 >= range.y || soundFrame + 1 < range.x ? range.x : soundFrame + 1; - if (manager.isRecording || !isSound) continue; - for (auto sound : document.trigger_sounds_get(*animation, soundFrame)) - audio_play(*sound, false, mixer); + playback.isPlaying = false; + playback.isFinished = false; + playback.timing_reset(); } + else + { + auto fps = std::max(model.info.fps, 1); + auto range = animation_play_range_get(*animation); + if (!wasPlaybackPlaying) + soundFrame = (int)std::floor(playback.time) - 1; + playback.tick(fps, range.x, range.y, (animation->isLoop || settings.playbackIsLoop) && !manager.isRecording, + deltaSeconds); - frameTime = playback.time; - } + // Each frame playback reaches plays its trigger's sound once, however many ticks it lasts or skips. + auto frame = (int)std::floor(playback.time); + for (int step = 0; soundFrame != frame && step < range.y - range.x; ++step) + { + soundFrame = soundFrame + 1 >= range.y || soundFrame + 1 < range.x ? range.x : soundFrame + 1; + if (manager.isRecording || !isSound) + continue; + for (auto sound : document.trigger_sounds_get(*animation, soundFrame)) + audio_play(*sound, false, mixer); + } + + frameTime = playback.time; + } } - if (wasPlaybackPlaying && !playback.isPlaying) stop_all_sounds(); + if (wasPlaybackPlaying && !playback.isPlaying) + stop_all_sounds(); wasPlaybackPlaying = playback.isPlaying; - } +} - void AnimationPreview::recording_stop(Manager& manager, Document& document) - { +void AnimationPreview::recording_stop(Manager& manager, Document& document) +{ document.playback.isPlaying = false; document.playback.isFinished = false; manager.isRecording = false; manager.isRecordingStart = false; manager.progressPopup.close(); - } +} - // Starts a render from the render settings; a bounded render frames the animation (and overlay) at the render scale. - void AnimationPreview::recording_start(Manager& manager, Settings& settings, Document& document, - const Animation* animation) - { +// Starts a render from the render settings. A bounded render frames the animation (and overlay) at the render scale. +void AnimationPreview::recording_start(Manager& manager, Settings& settings, Document& document, + const Animation* animation) +{ auto animationFps = std::max(document.model.info.fps, 1); - RecorderOptions options{ - .type = (RenderType)settings.renderType, - .path = settings.renderPath, - .format = settings.renderFormat, - .ffmpegPath = settings.renderFFmpegPath, - .start = manager.recordingStart, - .end = manager.recordingEnd, - .animationFps = animationFps, - .fps = fps_get(settings.renderFpsMode, animationFps, settings.playbackTickRate), - .rows = settings.renderRows, - .columns = settings.renderColumns, - .isSound = settings.timelineIsSound, - .isIsolated = settings.renderIsUseIsolatedAnimation, - .isBounded = settings.renderIsUseAnimationBounds}; + RecorderOptions options{.type = (RenderType)settings.renderType, + .path = settings.renderPath, + .format = settings.renderFormat, + .ffmpegPath = settings.renderFFmpegPath, + .start = manager.recordingStart, + .end = manager.recordingEnd, + .animationFps = animationFps, + .fps = fps_get(settings.renderFpsMode, animationFps, settings.playbackTickRate), + .rows = settings.renderRows, + .columns = settings.renderColumns, + .isSound = settings.timelineIsSound, + .isIsolated = settings.renderIsUseIsolatedAnimation, + .isBounded = settings.renderIsUseAnimationBounds}; if (options.isBounded) { - recordSize = size; - recordZoom = document.previewZoom; - recordPan = document.previewPan; - if (auto rect = animation_render_rect_get(manager, document, animation, settings.previewIsRootTransform)) - { - recordSize = glm::vec2(rect->z, rect->w) * percent_to_unit(settings.renderScale); - auto previousSize = size; - size = recordSize; - set_to_rect(recordZoom, recordPan, *rect); - size = previousSize; - } + recordSize = size; + recordZoom = document.previewZoom; + recordPan = document.previewPan; + if (auto rect = animation_render_rect_get(manager, document, animation, settings.previewIsRootTransform)) + { + recordSize = glm::vec2(rect->z, rect->w) * percent_to_unit(settings.renderScale); + auto previousSize = size; + size = recordSize; + set_to_rect(recordZoom, recordPan, *rect); + size = previousSize; + } } manager.isRecordingStart = false; manager.isRecording = true; if (!recorder.start(options)) { - toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, path_to_utf8(options.path)); - return recording_stop(manager, document); + toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, path_to_utf8(options.path)); + return recording_stop(manager, document); } document.playback.isPlaying = true; document.playback.timing_reset(); document.playback.time = recorder.time_get(); document.frameTime = document.playback.time; - } +} - void AnimationPreview::update(Manager& manager, Settings& settings, Resources& resources) - { +void AnimationPreview::update(Manager& manager, Settings& settings, Resources& resources) +{ isFocused = false; auto& document = *manager.get(); @@ -271,615 +279,655 @@ using namespace glm; auto& shaderGrid = resources.shaders[SHADER_GRID]; auto& shaderTexture = resources.shaders[SHADER_TEXTURE]; auto& shaderDashed = resources.shaders[SHADER_DASHED]; - auto center_view = [&]() { pan = vec2(); }; + auto center_view = [&]() { + pan = vec2(); + }; - auto fit_view = [&]() - { - if (animation) - set_to_rect(zoom, pan, - animation_rect(model, *animation, isRootTransform, document.library_resolver_get())); + auto fit_view = [&]() { + if (animation) + set_to_rect(zoom, pan, animation_rect(model, *animation, isRootTransform, document.library_resolver_get())); }; manager.isAbleToRecord = false; if (ImGui::Begin(localize.get(LABEL_ANIMATION_PREVIEW_WINDOW), &settings.windowIsAnimationPreview)) { - isFocused = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); - manager.isAbleToRecord = true; + isFocused = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); + manager.isAbleToRecord = true; - auto childSize = ImVec2(row_widget_width_get(4), - (ImGui::GetTextLineHeightWithSpacing() * 4) + (ImGui::GetStyle().WindowPadding.y * 2)); + auto childSize = ImVec2(row_widget_width_get(4), + (ImGui::GetTextLineHeightWithSpacing() * 4) + (ImGui::GetStyle().WindowPadding.y * 2)); - grid_child_draw(childSize, isGrid, gridColor, gridSize, gridOffset); - - ImGui::SameLine(); - - if (ImGui::BeginChild("##View Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) - { - ImGui::InputFloat(localize.get(BASIC_ZOOM), &zoom, 0.0f, 0.0f, "%.0f%%"); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PREVIEW_ZOOM)); - - view_buttons_draw(manager, settings, center_view, fit_view); - - auto readoutSize = ImVec2(row_widget_width_get(2), ImGui::GetTextLineHeightWithSpacing()); - auto mousePosInt = ivec2(mousePos); - auto positionText = - std::vformat(localize.get(FORMAT_POSITION_SPACED), std::make_format_args(mousePosInt.x, mousePosInt.y)); - if (ImGui::BeginChild("##Position Readout", readoutSize, false, ImGuiWindowFlags_NoScrollbar)) - { - ImGui::TextUnformatted(positionText.c_str()); - if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", positionText.c_str()); - } - ImGui::EndChild(); + grid_child_draw(childSize, isGrid, gridColor, gridSize, gridOffset); ImGui::SameLine(); - auto sizeInt = ivec2(size); - auto sizeText = std::vformat(localize.get(FORMAT_SIZE_SPACED), std::make_format_args(sizeInt.x, sizeInt.y)); - if (ImGui::BeginChild("##Size Readout", readoutSize, false, ImGuiWindowFlags_NoScrollbar)) + if (ImGui::BeginChild("##View Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) { - ImGui::TextUnformatted(sizeText.c_str()); - if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", sizeText.c_str()); - } - ImGui::EndChild(); - } - ImGui::EndChild(); + ImGui::InputFloat(localize.get(BASIC_ZOOM), &zoom, 0.0f, 0.0f, "%.0f%%"); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PREVIEW_ZOOM)); - ImGui::SameLine(); + view_buttons_draw(manager, settings, center_view, fit_view); - if (ImGui::BeginChild("##Background Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) - { - ImGui::BeginDisabled(isTransparent); - { - ImGui::ColorEdit3(localize.get(LABEL_BACKGROUND_COLOR), value_ptr(backgroundColor), - ImGuiColorEditFlags_NoInputs); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BACKGROUND_COLOR)); - } - ImGui::EndDisabled(); - ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_AXES), &isAxes); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AXES)); - ImGui::SameLine(); - ImGui::ColorEdit4(localize.get(BASIC_COLOR), value_ptr(axesColor), ImGuiColorEditFlags_NoInputs); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AXES_COLOR)); - - auto overlayOptions = overlay_animation_options_get(manager); - auto overlayLabels = overlay_animation_option_labels_get(overlayOptions); - auto overlayOptionIndex = overlay_animation_option_index_get(document, overlayOptions); - if (overlayOptionIndex == -1) - { - overlayIndex = -1; - overlayDocumentId = 0; - overlayOptionIndex = 0; - } - if (ImGui::Combo(localize.get(LABEL_OVERLAY), &overlayOptionIndex, overlayLabels.data(), - (int)overlayLabels.size())) - { - auto& option = overlayOptions[overlayOptionIndex]; - overlayIndex = option.animationIndex; - overlayDocumentId = overlayIndex == -1 ? 0 : option.documentId; - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY)); - - overlayDrawOrder = glm::clamp(overlayDrawOrder, (int)OVERLAY_OVER, (int)OVERLAY_UNDER); - overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f); - auto orderIconSize = icon_size_get(); - auto orderButtonWidth = orderIconSize.x + ImGui::GetStyle().FramePadding.x * 2.0f; - auto alphaWidth = std::max(ImGui::GetContentRegionAvail().x - (orderButtonWidth * 2.0f) - - (ImGui::GetStyle().ItemSpacing.x * 2.0f), - ImGui::GetFrameHeight()); - auto overlayIconTint = isLightTheme ? ImVec4(0.0f, 0.0f, 0.0f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - ImGui::PushItemWidth(alphaWidth); - ImGui::DragFloat("##Overlay Alpha", &overlayTransparency, DRAG_SPEED, 0, 100, "%.0f%%"); - ImGui::PopItemWidth(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_ALPHA)); - overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f); - - ImGui::SameLine(); - radio_button_icon("##Overlay Over", &overlayDrawOrder, OVERLAY_OVER, - resources.icon_id_get(ICON_OVER), orderIconSize, overlayIconTint); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_OVER)); - - ImGui::SameLine(); - radio_button_icon("##Overlay Under", &overlayDrawOrder, OVERLAY_UNDER, - resources.icon_id_get(ICON_UNDER), orderIconSize, overlayIconTint); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_UNDER)); - } - ImGui::EndChild(); - - ImGui::SameLine(); - - if (ImGui::BeginChild("##Helpers Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) - { - auto helpersChildSize = ImVec2(row_widget_width_get(2), ImGui::GetContentRegionAvail().y); - - if (ImGui::BeginChild("##Helpers Child 1", helpersChildSize)) - { - ImGui::Checkbox(localize.get(LABEL_ROOT_TRANSFORM), &isRootTransform); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROOT_TRANSFORM)); - ImGui::Checkbox(localize.get(LABEL_PIVOTS), &isPivots); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PIVOTS)); - ImGui::Checkbox(localize.get(LABEL_TRANSPARENT), &isTransparent); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PREVIEW_TRANSPARENT)); - } - ImGui::EndChild(); - - ImGui::SameLine(); - - if (ImGui::BeginChild("##Helpers Child 2", helpersChildSize)) - { - ImGui::Checkbox(localize.get(LABEL_ALT_ICONS), &isAltIcons); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ALT_ICONS)); - ImGui::Checkbox(localize.get(LABEL_BORDER), &isBorder); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BORDER)); - } - ImGui::EndChild(); - } - ImGui::EndChild(); - - if (manager.isRecordingStart) recording_start(manager, settings, document, animation); - auto isRecordingFrame = manager.isRecording && !recorder.is_done(); - if (isRecordingFrame) - { - playback.isPlaying = true; - playback.isFinished = false; - playback.time = recorder.time_get(); - document.frameTime = playback.time; - } - - // A render of an isolated animation hides helpers, overlay and onion skin; a bounded one draws its own view. - auto isIsolated = manager.isRecording && recorder.options.isIsolated; - auto isBounded = manager.isRecording && recorder.options.isBounded; - auto viewZoom = isBounded ? recordZoom : zoom; - auto viewPan = isBounded ? recordPan : pan; - auto isViewTransparent = isTransparent || isIsolated; - auto isViewOnlyLayers = isOnlyShowLayers || isIsolated; - - if (isBounded) - size_set(recordSize); - else - { - auto nextSize = to_vec2(ImGui::GetContentRegionAvail()); - bool isCanvasResized = ivec2(nextSize) != ivec2(size); - size_set(nextSize); - if (isCanvasResized && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) - { - auto resizeSizeInt = ivec2(size); - auto resizeSizeText = - std::vformat(localize.get(FORMAT_SIZE_SPACED), std::make_format_args(resizeSizeInt.x, resizeSizeInt.y)); - ImGui::SetTooltip("%s", resizeSizeText.c_str()); - } - } - - auto cursorScreenPos = ImGui::GetCursorScreenPos(); - auto min = cursorScreenPos; - auto max = to_imvec2(to_vec2(min) + size); - auto referenceItemType = static_cast(reference.itemType); - - if (is_canvas_hovered(min, max)) - { - auto input = canvas_input_get(manager, isFocused); - mousePos = position_translate(zoom, pan, to_vec2(ImGui::GetMousePos()) - to_vec2(cursorScreenPos)); - auto selectedFrameReferences = document.frame_references_get(); - std::erase_if(selectedFrameReferences, [](const Reference& frameReference) - { return frameReference.itemType == NONE || frameReference.itemType == TRIGGER; }); - auto editReference = reference; - if ((referenceItemType == ItemType::TRIGGER || !selectedFrameReferences.contains(reference)) && - !selectedFrameReferences.empty()) - editReference = *selectedFrameReferences.begin(); - - auto frame = selectedFrameReferences.empty() ? nullptr : model.frame_get(editReference); - auto selectedNull = - editReference.itemType == NULL_ ? item_get(model.content.nulls, editReference.itemID) : nullptr; - bool isSelectedNullRect = selectedNull && selectedNull->isShowRect; - auto null_rect_top_left = [](const Frame& frame) { return frame.position - (frame.scale * 0.5f); }; - - auto useTool = (Tool)tool; - if (input.isMiddleDown) useTool = TOOL_PAN; - if (tool == TOOL_MOVE && input.isRightDown) useTool = TOOL_SCALE; - if (tool == TOOL_SCALE && input.isRightDown) useTool = TOOL_MOVE; - - // A tool swapped in by the right button is driven by the right button. - auto isSwapped = useTool != tool && useTool != TOOL_PAN; - auto isToolClicked = isSwapped ? input.isRightClicked : input.isLeftClicked; - auto isToolDown = isSwapped ? input.isRightDown : input.isLeftDown; - auto isToolReleased = isSwapped ? input.isRightReleased : input.isLeftReleased; - auto isBegin = isToolClicked || input.isArrowBegin; - auto isDuring = isToolDown || input.isArrowDown; - auto isEnd = isToolReleased || input.isArrowEnd; - auto arrow = input.arrow * input.step; - auto isArrow = arrow != vec2(); - - // Changes apply to every selected frame; absolute values are applied as the difference from the edited frame. - auto frames_change = [&](FrameChange change, ChangeType type = ChangeType::ADD) - { frames_change_push(manager, selectedFrameReferences, change, type); }; - auto null_rect_set = [&](vec2 minPoint, vec2 maxPoint) - { - auto rectSize = maxPoint - minPoint; - frames_change({.positionX = minPoint.x + rectSize.x * 0.5f - frame->position.x, - .positionY = minPoint.y + rectSize.y * 0.5f - frame->position.y, - .scaleX = rectSize.x - frame->scale.x, - .scaleY = rectSize.y - frame->scale.y}); - }; - - tool_cursor_update(useTool, TOOL_AREA_ANIMATION_PREVIEW, frame != nullptr, true, - input.isLeftDown || input.isRightDown || input.isMiddleDown || input.isArrowDown, - TEXT_SELECT_FRAME); - if (useTool != TOOL_MOVE) isMoveDragging = false; - if (useTool == TOOL_PAN && (input.isLeftDown || input.isRightDown || input.isMiddleDown)) - pan += input.mouseDelta; - - if (frame && useTool == TOOL_MOVE) - { - if (isBegin) edit_begin_push(manager, EDIT_FRAME_POSITION); - if (isToolClicked) - { - auto origin = isSelectedNullRect ? null_rect_top_left(*frame) : frame->position; - moveOffset = settings.inputIsMoveToolSnapToMouse ? vec2() : mousePos - origin; - isMoveDragging = true; - } - if (isToolDown && isMoveDragging) - { - auto position = vec2(ivec2(mousePos - moveOffset + (isSelectedNullRect ? frame->scale * 0.5f : vec2()))); - frames_change({.positionX = position.x - frame->position.x, .positionY = position.y - frame->position.y}); - } - if (isArrow) frames_change({.positionX = arrow.x, .positionY = arrow.y}); - if (isToolReleased) isMoveDragging = false; - if (isDuring) tooltip_lines_draw({localize_format(FORMAT_POSITION, frame->position.x, frame->position.y)}); - if (isEnd) document_change_push(manager); - } - - if (frame && useTool == TOOL_SCALE) - { - if (isBegin) edit_begin_push(manager, EDIT_FRAME_SCALE); - if (isToolClicked && isSelectedNullRect) nullRectScaleAnchor = null_rect_top_left(*frame); - if (isToolDown && isSelectedNullRect) - { - auto rectSize = mousePos - nullRectScaleAnchor; - if (input.isMod) + auto readoutSize = ImVec2(row_widget_width_get(2), ImGui::GetTextLineHeightWithSpacing()); + auto mousePosInt = ivec2(mousePos); + auto positionText = + std::vformat(localize.get(FORMAT_POSITION_SPACED), std::make_format_args(mousePosInt.x, mousePosInt.y)); + if (ImGui::BeginChild("##Position Readout", readoutSize, false, ImGuiWindowFlags_NoScrollbar)) { - auto squareSize = std::max(std::abs(rectSize.x), std::abs(rectSize.y)); - rectSize = {std::copysign(squareSize, rectSize.x), std::copysign(squareSize, rectSize.y)}; + ImGui::TextUnformatted(positionText.c_str()); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", positionText.c_str()); } - auto [minPoint, maxPoint] = rect_snap(nullRectScaleAnchor, nullRectScaleAnchor + rectSize, false, {}, {}); - null_rect_set(minPoint, maxPoint); - } - else if (isToolDown) - frames_change( - {.scaleX = input.mouseDelta.x, - .scaleY = input.isMod ? frame->scale.x + input.mouseDelta.x - frame->scale.y : input.mouseDelta.y}); - if (isArrow) - frames_change({.positionX = isSelectedNullRect ? arrow.x * 0.5f : 0.0f, - .positionY = isSelectedNullRect ? arrow.y * 0.5f : 0.0f, - .scaleX = arrow.x, - .scaleY = arrow.y}); - if (isDuring) tooltip_lines_draw({localize_format(FORMAT_SCALE, frame->scale.x, frame->scale.y)}); - if (isEnd && isSelectedNullRect) - { - auto topLeft = null_rect_top_left(*frame); - auto [minPoint, maxPoint] = rect_snap(topLeft, topLeft + frame->scale, false, {}, {}); - null_rect_set(minPoint, maxPoint); - } - if (isEnd) document_change_push(manager); - } + ImGui::EndChild(); - if (frame && useTool == TOOL_ROTATE) - { - if (isBegin) edit_begin_push(manager, EDIT_FRAME_ROTATION); - if (isToolDown) frames_change({.rotation = input.mouseDelta.x}); - if (auto turn = glm::sign(input.arrow.x - input.arrow.y); turn != 0.0f) - frames_change({.rotation = turn * input.step}); - if (isDuring) tooltip_lines_draw({localize_format(FORMAT_ROTATION, frame->rotation)}); - if (isEnd) document_change_push(manager); - } + ImGui::SameLine(); - if (frame && useTool == TOOL_SKEW) - { - if (isBegin) edit_begin_push(manager, EDIT_FRAME_SKEW); - if (isToolDown) - { - auto delta = input.mouseDelta; - if (input.isMod) (std::abs(delta.x) >= std::abs(delta.y) ? delta.y : delta.x) = 0.0f; - frames_change({.skewX = delta.x, .skewY = delta.y}); - } - if (isArrow) frames_change({.skewX = arrow.x, .skewY = arrow.y}); - if (isDuring) tooltip_lines_draw({localize_format(FORMAT_SKEW, frame->skew.x, frame->skew.y)}); - if (isEnd) document_change_push(manager); - } - - if (input.wheel != 0 || input.isZoomIn || input.isZoomOut) - zoom_step(zoom, pan, vec2(mousePos), - (input.wheel > 0 || input.isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP); - } - - bind(); - viewport_set(); - clear(isViewTransparent ? vec4(0) : vec4(backgroundColor, 1.0f)); - - if (isAxes && !isIsolated) axes_render(shaderAxes, viewZoom, viewPan, axesColor); - if (isGrid && !isIsolated) grid_render(shaderGrid, viewZoom, viewPan, gridSize, gridOffset, gridColor); - - auto baseTransform = transform_get(viewZoom, viewPan); - auto frameTime = document.frameTime > -1 && !playback.isPlaying ? document.frameTime : playback.time; - - DrawOptions drawOptions{.time = frameTime, - .isRootTransform = isRootTransform, - .isIndexSampled = settings.onionskinMode == (int)OnionskinMode::INDEX}; - std::vector sampleColors{}; - std::vector sampleAlphas; - auto samples_add = [&](int count, int direction, vec3 color) - { - for (int i = 1; i <= count; ++i) - { - drawOptions.samples.push_back({.timeOffset = (float)(direction * i), .indexOffset = direction * i}); - sampleColors.push_back(color); - sampleAlphas.push_back((1.0f / (count + 1)) * i); - } - }; - if (settings.onionskinIsEnabled && !isIsolated) - { - samples_add(settings.onionskinBeforeCount, -1, settings.onionskinBeforeColor); - samples_add(settings.onionskinAfterCount, 1, settings.onionskinAfterColor); - } - - auto is_layer_selected = [&](int id) - { - auto is_layer = [&](const Reference& itemReference) - { - return itemReference.animationIndex == reference.animationIndex && itemReference.itemType == LAYER && - itemReference.itemID == id; - }; - return (reference.animationIndex != -1 && is_layer(reference)) || - std::ranges::any_of(document.selected_get(SelectionKind::TRACKS), is_layer) || - std::ranges::any_of(document.frame_references_get(Document::FrameReferenceFallback::NONE), is_layer); - }; - - // The item the reference points at: the root (or a group's root), a layer or a null. - auto is_draw_selected = [&](const Draw& draw) - { - switch (draw.type) - { - case DrawType::ROOT: - return referenceItemType == ItemType::ROOT && reference.groupId == -1; - case DrawType::GROUP_ROOT: - return referenceItemType == ItemType::ROOT && reference.groupType == draw.groupType && - reference.groupId == draw.id; - case DrawType::LAYER: - return referenceItemType == ItemType::LAYER && reference.itemID == draw.id; - default: - return referenceItemType == ItemType::NULL_ && reference.itemID == draw.id; - } - }; - auto isOnlySelected = settings.onionskinIsOnlySelected; - - // Draws an animation's draw list; onion-skin samples are tinted and faded, `alphaOffset` fades the overlay. A - // parent around a stepped-into child is drawn in the child's space (`scene`), its layers only, without the - // animation layer playing the child (`skipLayerId`). - auto render = [&](Document& sampleDocument, const Animation& sampleAnimation, float alphaOffset, - const DrawOptions& options, const mat4& scene = mat4(1.0f), int skipLayerId = -1) - { - auto isActiveDocument = &sampleDocument == &document && skipLayerId == -1; - auto isParent = skipLayerId != -1; - auto& sampleModel = sampleDocument.model; - auto targetIcon = resources.icon_id_get(isAltIcons && !isIsolated ? ICON_TARGET_ALT : ICON_TARGET); - auto sampleOptions = options; - sampleOptions.library_get = sampleDocument.library_resolver_get(); - for (auto& draw : animation_draws_get(sampleModel, sampleAnimation, sampleOptions)) - { - if (isParent && (draw.type != DrawType::LAYER || draw.id == skipLayerId)) continue; - auto isOnion = draw.sample != -1; - if (isOnion && isOnlySelected && !(isActiveDocument && is_draw_selected(draw))) continue; - auto sampleColor = isOnion ? sampleColors[draw.sample] : vec3(); - auto sampleAlpha = isOnion ? sampleAlphas[draw.sample] : 0.0f; - auto onionColor = vec4(sampleColor, 1.0f - sampleAlpha); - auto& frame = draw.frame; - auto transform = baseTransform * scene * draw.parent; - auto marker_model_get = [&](vec2 markerSize) - { - return quad_model_get(markerSize, frame.position, markerSize * 0.5f, - percent_to_unit(frame.scale), frame.rotation, - percent_to_unit(frame.skew)); - }; - - if (draw.type == DrawType::ROOT || draw.type == DrawType::GROUP_ROOT) - { - if (isViewOnlyLayers) continue; - auto isSelected = isActiveDocument && draw.type == DrawType::GROUP_ROOT && - referenceItemType == ItemType::ROOT && reference.groupType == draw.groupType && - reference.groupId == draw.id; - auto color = isOnion ? vec4(sampleColor, sampleAlpha) - : draw.type == DrawType::ROOT ? COLOR_GREEN - : isSelected ? COLOR_RED - : ROOT_COLOR; - auto markerModel = isRootTransform ? quad_model_get(TARGET_SIZE, {}, TARGET_SIZE * 0.5f) - : marker_model_get(TARGET_SIZE); - texture_render(shaderTexture, targetIcon, transform * markerModel, color); - } - else if (draw.type == DrawType::LAYER) - { - auto layerTexture = - sampleDocument.draw_image_get(draw, percent_to_unit(viewZoom) * draw_scale_get(draw)); - if (!layerTexture || !layerTexture->is_valid() || layerTexture->size.x <= 0 || layerTexture->size.y <= 0) - continue; - auto textureSize = layerTexture->unit_size_get(); - auto layerModel = draw_quad_model_get(draw); - auto layerTransform = transform * layerModel; - auto tint = frame.tint; - tint.a = std::max(0.0f, tint.a - (alphaOffset + sampleAlpha)); - auto customShader = sampleDocument.shader_get(frame.shaderId); - layer_render(customShader ? *customShader : shaderTexture, texture_id_get(*layerTexture), - textureSize, baseTransform * scene, draw, tint, frame.colorOffset + vec4(sampleColor, 0.0f)); - if (isParent) continue; - - auto color = isOnion ? onionColor - : isActiveDocument && is_layer_selected(draw.id) ? SELECTED_LAYER_BORDER_COLOR - : COLOR_RED; - if (isBorder && !isIsolated) rect_render(shaderLine, layerTransform, layerModel, color); - if (isPivots && !isIsolated) - texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), - transform * marker_model_get(PIVOT_SIZE), color); - } - else if (!isViewOnlyLayers) - { - auto isShowRect = item_get(sampleModel.content.nulls, draw.id)->isShowRect; - auto isSelected = isActiveDocument && draw.id == reference.itemID && referenceItemType == ItemType::NULL_; - auto color = isOnion ? onionColor : isSelected ? COLOR_RED : NULL_RECT_COLOR; - auto markerSize = isShowRect ? POINT_SIZE : TARGET_SIZE; - texture_render(shaderTexture, isShowRect ? resources.icon_id_get(ICON_POINT) : targetIcon, - transform * marker_model_get(markerSize), color); - if (!isShowRect) continue; - auto rectModel = quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), - frame.rotation, percent_to_unit(frame.skew)); - rect_render(shaderLine, transform * rectModel, rectModel, color); - } - } - }; - - if (animation) - { - auto overlay_render = [&]() - { - if (auto overlayDocument = isIsolated ? nullptr : overlay_animation_document_get(manager, document)) - if (auto overlayAnimation = overlayDocument->model.animation_get(overlayIndex)) - render(*overlayDocument, *overlayAnimation, 1.0f - percent_to_unit(overlayTransparency), - drawOptions); - }; - - // Editing a stepped-into child: its parent, dimmed and frozen where it was stepped in, around it. - if (auto& steps = document.childSteps; - !isIsolated && !steps.empty() && steps.back().childAnimationIndex == reference.animationIndex) - { - auto& step = steps.back(); - auto parentIndex = manager.tab_index_get(step.tabId); - auto parentDocument = parentIndex == -1 ? nullptr : manager.get(parentIndex); - auto parentAnimation = parentDocument ? parentDocument->model.animation_get(step.animationIndex) : nullptr; - auto placement = parentAnimation ? layer_child_transform_get(*parentAnimation, step.layer.itemID, - step.frameTime, isRootTransform) - : std::nullopt; - if (placement && glm::determinant(*placement) != 0.0f) - render(*parentDocument, *parentAnimation, PARENT_DIM_ALPHA, - {.time = step.frameTime, .isRootTransform = isRootTransform}, glm::inverse(*placement), - step.layer.itemID); - } - - if (overlayDrawOrder == OVERLAY_UNDER) overlay_render(); - render(document, *animation, 0.0f, drawOptions); - if (overlayDrawOrder == OVERLAY_OVER) overlay_render(); - - if (settings.onionskinIsEnabled && settings.onionskinIsPivotPath && !isIsolated) - { - auto key = std::tuple{document.hash, document.librariesRevision, reference.animationIndex, isRootTransform}; - if (key != pivotPathsKey || pivotPaths.empty()) - { - pivotPathsKey = key; - pivotPaths.clear(); - for (int time = 0; time < animation->frameNum; ++time) - for (auto& draw : animation_draws_get(model, *animation, - {.time = (float)time, - .isRootTransform = isRootTransform, - .library_get = document.library_resolver_get()})) - { - auto path = std::ranges::find_if(pivotPaths, - [&](const PivotPath& path) - { - return path.item.type == draw.type && path.item.id == draw.id && - path.item.groupType == draw.groupType; - }); - if (path == pivotPaths.end()) path = pivotPaths.insert(pivotPaths.end(), {.item = draw}); - path->points.push_back(vec2(draw.parent * vec4(draw.frame.position, 0.0f, 1.0f))); - } - } - - auto pointIcon = resources.icon_id_get(ICON_POINT); - for (auto& path : pivotPaths) - { - if (isOnlySelected && !is_draw_selected(path.item)) continue; - for (std::size_t i = 0; i < path.points.size(); ++i) + auto sizeInt = ivec2(size); + auto sizeText = std::vformat(localize.get(FORMAT_SIZE_SPACED), std::make_format_args(sizeInt.x, sizeInt.y)); + if (ImGui::BeginChild("##Size Readout", readoutSize, false, ImGuiWindowFlags_NoScrollbar)) { - if (i > 0) line_render(shaderDashed, baseTransform, path.points[i - 1], path.points[i], COLOR_RED); - texture_render(shaderTexture, pointIcon, - baseTransform * quad_model_get(POINT_SIZE, path.points[i], POINT_SIZE * 0.5f), - COLOR_RED); + ImGui::TextUnformatted(sizeText.c_str()); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", sizeText.c_str()); } - } + ImGui::EndChild(); } - } + ImGui::EndChild(); - if (isRecordingFrame) - { - auto sounds = settings.timelineIsSound && animation && recorder.is_sound_frame() - ? document.trigger_sounds_get(*animation, (int)frameTime, recorder.index) - : std::vector{}; - if (!recorder.frame_capture(pixels_get(), size, sounds)) + ImGui::SameLine(); + + if (ImGui::BeginChild("##Background Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) { - toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, path_to_utf8(recorder.options.path)); - recorder.cancel(); - recording_stop(manager, document); + ImGui::BeginDisabled(isTransparent); + { + ImGui::ColorEdit3(localize.get(LABEL_BACKGROUND_COLOR), value_ptr(backgroundColor), + ImGuiColorEditFlags_NoInputs); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BACKGROUND_COLOR)); + } + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_AXES), &isAxes); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AXES)); + ImGui::SameLine(); + ImGui::ColorEdit4(localize.get(BASIC_COLOR), value_ptr(axesColor), ImGuiColorEditFlags_NoInputs); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AXES_COLOR)); + + auto overlayOptions = overlay_animation_options_get(manager); + auto overlayLabels = overlay_animation_option_labels_get(overlayOptions); + auto overlayOptionIndex = overlay_animation_option_index_get(document, overlayOptions); + if (overlayOptionIndex == -1) + { + overlayIndex = -1; + overlayDocumentId = 0; + overlayOptionIndex = 0; + } + if (ImGui::Combo(localize.get(LABEL_OVERLAY), &overlayOptionIndex, overlayLabels.data(), + (int)overlayLabels.size())) + { + auto& option = overlayOptions[overlayOptionIndex]; + overlayIndex = option.animationIndex; + overlayDocumentId = overlayIndex == -1 ? 0 : option.documentId; + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY)); + + overlayDrawOrder = glm::clamp(overlayDrawOrder, (int)OVERLAY_OVER, (int)OVERLAY_UNDER); + overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f); + auto orderIconSize = icon_size_get(); + auto orderButtonWidth = orderIconSize.x + ImGui::GetStyle().FramePadding.x * 2.0f; + auto alphaWidth = std::max(ImGui::GetContentRegionAvail().x - (orderButtonWidth * 2.0f) - + (ImGui::GetStyle().ItemSpacing.x * 2.0f), + ImGui::GetFrameHeight()); + auto overlayIconTint = isLightTheme ? ImVec4(0.0f, 0.0f, 0.0f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + ImGui::PushItemWidth(alphaWidth); + ImGui::DragFloat("##Overlay Alpha", &overlayTransparency, DRAG_SPEED, 0, 100, "%.0f%%"); + ImGui::PopItemWidth(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_ALPHA)); + overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f); + + ImGui::SameLine(); + radio_button_icon("##Overlay Over", &overlayDrawOrder, OVERLAY_OVER, resources.icon_id_get(ICON_OVER), + orderIconSize, overlayIconTint); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_OVER)); + + ImGui::SameLine(); + radio_button_icon("##Overlay Under", &overlayDrawOrder, OVERLAY_UNDER, resources.icon_id_get(ICON_UNDER), + orderIconSize, overlayIconTint); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_UNDER)); } - } + ImGui::EndChild(); - unbind(); + ImGui::SameLine(); - if (isViewTransparent) - { - checker_pan_sync(zoom, pan); - render_checker_background(ImGui::GetWindowDrawList(), min, max, -size - checkerPan, CHECKER_SIZE); - } - image_premultiplied_draw(texture, to_imvec2(size)); + if (ImGui::BeginChild("##Helpers Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) + { + auto helpersChildSize = ImVec2(row_widget_width_get(2), ImGui::GetContentRegionAvail().y); - // The events triggers (the animation's and its children's) fire on this frame. - std::string names; - if (animation && !isOnlyShowLayers && !manager.isRecording) - for (auto& [source, trigger, layerId] : - animation_triggers_get(model, *animation, (int)frameTime, document.library_resolver_get())) - for (auto eventId : trigger.eventIds) - if (auto event = item_get(source->content.events, eventId)) - names += (names.empty() ? "" : ", ") + event->name; - if (!names.empty()) - { - auto clipMin = ImGui::GetItemRectMin(); - auto clipMax = ImGui::GetItemRectMax(); - auto drawList = ImGui::GetWindowDrawList(); - auto textPos = to_imvec2(to_vec2(cursorScreenPos) + to_vec2(ImGui::GetStyle().WindowPadding)); + if (ImGui::BeginChild("##Helpers Child 1", helpersChildSize)) + { + ImGui::Checkbox(localize.get(LABEL_ROOT_TRANSFORM), &isRootTransform); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROOT_TRANSFORM)); + ImGui::Checkbox(localize.get(LABEL_PIVOTS), &isPivots); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PIVOTS)); + ImGui::Checkbox(localize.get(LABEL_TRANSPARENT), &isTransparent); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PREVIEW_TRANSPARENT)); + } + ImGui::EndChild(); - drawList->PushClipRect(clipMin, clipMax); - ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE_LARGE); - auto triggerTextColor = isLightTheme ? TRIGGER_TEXT_COLOR_LIGHT : TRIGGER_TEXT_COLOR_DARK; - drawList->AddText(textPos, ImGui::GetColorU32(triggerTextColor), names.c_str()); - ImGui::PopFont(); - drawList->PopClipRect(); - } + ImGui::SameLine(); + + if (ImGui::BeginChild("##Helpers Child 2", helpersChildSize)) + { + ImGui::Checkbox(localize.get(LABEL_ALT_ICONS), &isAltIcons); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ALT_ICONS)); + ImGui::Checkbox(localize.get(LABEL_BORDER), &isBorder); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BORDER)); + } + ImGui::EndChild(); + } + ImGui::EndChild(); + + if (manager.isRecordingStart) + recording_start(manager, settings, document, animation); + auto isRecordingFrame = manager.isRecording && !recorder.is_done(); + if (isRecordingFrame) + { + playback.isPlaying = true; + playback.isFinished = false; + playback.time = recorder.time_get(); + document.frameTime = playback.time; + } + + // A render of an isolated animation hides helpers, overlay and onion skin. A bounded one draws its own view. + auto isIsolated = manager.isRecording && recorder.options.isIsolated; + auto isBounded = manager.isRecording && recorder.options.isBounded; + auto viewZoom = isBounded ? recordZoom : zoom; + auto viewPan = isBounded ? recordPan : pan; + auto isViewTransparent = isTransparent || isIsolated; + auto isViewOnlyLayers = isOnlyShowLayers || isIsolated; + + if (isBounded) + size_set(recordSize); + else + { + auto nextSize = to_vec2(ImGui::GetContentRegionAvail()); + bool isCanvasResized = ivec2(nextSize) != ivec2(size); + size_set(nextSize); + if (isCanvasResized && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + auto resizeSizeInt = ivec2(size); + auto resizeSizeText = std::vformat(localize.get(FORMAT_SIZE_SPACED), + std::make_format_args(resizeSizeInt.x, resizeSizeInt.y)); + ImGui::SetTooltip("%s", resizeSizeText.c_str()); + } + } + + auto cursorScreenPos = ImGui::GetCursorScreenPos(); + auto min = cursorScreenPos; + auto max = to_imvec2(to_vec2(min) + size); + auto referenceItemType = static_cast(reference.itemType); + + if (is_canvas_hovered(min, max)) + { + auto input = canvas_input_get(manager, isFocused); + mousePos = position_translate(zoom, pan, to_vec2(ImGui::GetMousePos()) - to_vec2(cursorScreenPos)); + auto selectedFrameReferences = document.frame_references_get(); + std::erase_if(selectedFrameReferences, [](const Reference& frameReference) { + return frameReference.itemType == NONE || frameReference.itemType == TRIGGER; + }); + auto editReference = reference; + if ((referenceItemType == ItemType::TRIGGER || !selectedFrameReferences.contains(reference)) && + !selectedFrameReferences.empty()) + editReference = *selectedFrameReferences.begin(); + + auto frame = selectedFrameReferences.empty() ? nullptr : model.frame_get(editReference); + auto selectedNull = + editReference.itemType == NULL_ ? item_get(model.content.nulls, editReference.itemID) : nullptr; + bool isSelectedNullRect = selectedNull && selectedNull->isShowRect; + auto null_rect_top_left = [](const Frame& frame) { + return frame.position - (frame.scale * 0.5f); + }; + + auto useTool = (Tool)tool; + if (input.isMiddleDown) + useTool = TOOL_PAN; + if (tool == TOOL_MOVE && input.isRightDown) + useTool = TOOL_SCALE; + if (tool == TOOL_SCALE && input.isRightDown) + useTool = TOOL_MOVE; + + // A tool swapped in by the right button is driven by the right button. + auto isSwapped = useTool != tool && useTool != TOOL_PAN; + auto isToolClicked = isSwapped ? input.isRightClicked : input.isLeftClicked; + auto isToolDown = isSwapped ? input.isRightDown : input.isLeftDown; + auto isToolReleased = isSwapped ? input.isRightReleased : input.isLeftReleased; + auto isBegin = isToolClicked || input.isArrowBegin; + auto isDuring = isToolDown || input.isArrowDown; + auto isEnd = isToolReleased || input.isArrowEnd; + auto arrow = input.arrow * input.step; + auto isArrow = arrow != vec2(); + + // Changes apply to every selected frame. Absolute values are applied as the difference from the edited + // frame. + auto frames_change = [&](FrameChange change, ChangeType type = ChangeType::ADD) { + frames_change_push(manager, selectedFrameReferences, change, type); + }; + auto null_rect_set = [&](vec2 minPoint, vec2 maxPoint) { + auto rectSize = maxPoint - minPoint; + frames_change({.positionX = minPoint.x + rectSize.x * 0.5f - frame->position.x, + .positionY = minPoint.y + rectSize.y * 0.5f - frame->position.y, + .scaleX = rectSize.x - frame->scale.x, + .scaleY = rectSize.y - frame->scale.y}); + }; + + tool_cursor_update(useTool, TOOL_AREA_ANIMATION_PREVIEW, frame != nullptr, true, + input.isLeftDown || input.isRightDown || input.isMiddleDown || input.isArrowDown, + TEXT_SELECT_FRAME); + if (useTool != TOOL_MOVE) + isMoveDragging = false; + if (useTool == TOOL_PAN && (input.isLeftDown || input.isRightDown || input.isMiddleDown)) + pan += input.mouseDelta; + + if (frame && useTool == TOOL_MOVE) + { + if (isBegin) + edit_begin_push(manager, EDIT_FRAME_POSITION); + if (isToolClicked) + { + auto origin = isSelectedNullRect ? null_rect_top_left(*frame) : frame->position; + moveOffset = settings.inputIsMoveToolSnapToMouse ? vec2() : mousePos - origin; + isMoveDragging = true; + } + if (isToolDown && isMoveDragging) + { + auto position = + vec2(ivec2(mousePos - moveOffset + (isSelectedNullRect ? frame->scale * 0.5f : vec2()))); + frames_change( + {.positionX = position.x - frame->position.x, .positionY = position.y - frame->position.y}); + } + if (isArrow) + frames_change({.positionX = arrow.x, .positionY = arrow.y}); + if (isToolReleased) + isMoveDragging = false; + if (isDuring) + tooltip_lines_draw({localize_format(FORMAT_POSITION, frame->position.x, frame->position.y)}); + if (isEnd) + document_change_push(manager); + } + + if (frame && useTool == TOOL_SCALE) + { + if (isBegin) + edit_begin_push(manager, EDIT_FRAME_SCALE); + if (isToolClicked && isSelectedNullRect) + nullRectScaleAnchor = null_rect_top_left(*frame); + if (isToolDown && isSelectedNullRect) + { + auto rectSize = mousePos - nullRectScaleAnchor; + if (input.isMod) + { + auto squareSize = std::max(std::abs(rectSize.x), std::abs(rectSize.y)); + rectSize = {std::copysign(squareSize, rectSize.x), std::copysign(squareSize, rectSize.y)}; + } + auto [minPoint, maxPoint] = + rect_snap(nullRectScaleAnchor, nullRectScaleAnchor + rectSize, false, {}, {}); + null_rect_set(minPoint, maxPoint); + } + else if (isToolDown) + frames_change({.scaleX = input.mouseDelta.x, + .scaleY = input.isMod ? frame->scale.x + input.mouseDelta.x - frame->scale.y + : input.mouseDelta.y}); + if (isArrow) + frames_change({.positionX = isSelectedNullRect ? arrow.x * 0.5f : 0.0f, + .positionY = isSelectedNullRect ? arrow.y * 0.5f : 0.0f, + .scaleX = arrow.x, + .scaleY = arrow.y}); + if (isDuring) + tooltip_lines_draw({localize_format(FORMAT_SCALE, frame->scale.x, frame->scale.y)}); + if (isEnd && isSelectedNullRect) + { + auto topLeft = null_rect_top_left(*frame); + auto [minPoint, maxPoint] = rect_snap(topLeft, topLeft + frame->scale, false, {}, {}); + null_rect_set(minPoint, maxPoint); + } + if (isEnd) + document_change_push(manager); + } + + if (frame && useTool == TOOL_ROTATE) + { + if (isBegin) + edit_begin_push(manager, EDIT_FRAME_ROTATION); + if (isToolDown) + frames_change({.rotation = input.mouseDelta.x}); + if (auto turn = glm::sign(input.arrow.x - input.arrow.y); turn != 0.0f) + frames_change({.rotation = turn * input.step}); + if (isDuring) + tooltip_lines_draw({localize_format(FORMAT_ROTATION, frame->rotation)}); + if (isEnd) + document_change_push(manager); + } + + if (frame && useTool == TOOL_SKEW) + { + if (isBegin) + edit_begin_push(manager, EDIT_FRAME_SKEW); + if (isToolDown) + { + auto delta = input.mouseDelta; + if (input.isMod) + (std::abs(delta.x) >= std::abs(delta.y) ? delta.y : delta.x) = 0.0f; + frames_change({.skewX = delta.x, .skewY = delta.y}); + } + if (isArrow) + frames_change({.skewX = arrow.x, .skewY = arrow.y}); + if (isDuring) + tooltip_lines_draw({localize_format(FORMAT_SKEW, frame->skew.x, frame->skew.y)}); + if (isEnd) + document_change_push(manager); + } + + if (input.wheel != 0 || input.isZoomIn || input.isZoomOut) + zoom_step(zoom, pan, vec2(mousePos), + (input.wheel > 0 || input.isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP); + } + + bind(); + viewport_set(); + clear(isViewTransparent ? vec4(0) : vec4(backgroundColor, 1.0f)); + + if (isAxes && !isIsolated) + axes_render(shaderAxes, viewZoom, viewPan, axesColor); + if (isGrid && !isIsolated) + grid_render(shaderGrid, viewZoom, viewPan, gridSize, gridOffset, gridColor); + + auto baseTransform = transform_get(viewZoom, viewPan); + auto frameTime = document.frameTime > -1 && !playback.isPlaying ? document.frameTime : playback.time; + + DrawOptions drawOptions{.time = frameTime, + .isRootTransform = isRootTransform, + .isIndexSampled = settings.onionskinMode == (int)OnionskinMode::INDEX}; + std::vector sampleColors{}; + std::vector sampleAlphas; + auto samples_add = [&](int count, int direction, vec3 color) { + for (int i = 1; i <= count; ++i) + { + drawOptions.samples.push_back({.timeOffset = (float)(direction * i), .indexOffset = direction * i}); + sampleColors.push_back(color); + sampleAlphas.push_back((1.0f / (count + 1)) * i); + } + }; + if (settings.onionskinIsEnabled && !isIsolated) + { + samples_add(settings.onionskinBeforeCount, -1, settings.onionskinBeforeColor); + samples_add(settings.onionskinAfterCount, 1, settings.onionskinAfterColor); + } + + auto is_layer_selected = [&](int id) { + auto is_layer = [&](const Reference& itemReference) { + return itemReference.animationIndex == reference.animationIndex && itemReference.itemType == LAYER && + itemReference.itemID == id; + }; + return (reference.animationIndex != -1 && is_layer(reference)) || + std::ranges::any_of(document.selected_get(SelectionKind::TRACKS), is_layer) || + std::ranges::any_of(document.frame_references_get(Document::FrameReferenceFallback::NONE), is_layer); + }; + + // The item the reference points at: the root (or a group's root), a layer or a null. + auto is_draw_selected = [&](const Draw& draw) { + switch (draw.type) + { + case DrawType::ROOT: + return referenceItemType == ItemType::ROOT && reference.groupId == -1; + case DrawType::GROUP_ROOT: + return referenceItemType == ItemType::ROOT && reference.groupType == draw.groupType && + reference.groupId == draw.id; + case DrawType::LAYER: + return referenceItemType == ItemType::LAYER && reference.itemID == draw.id; + default: + return referenceItemType == ItemType::NULL_ && reference.itemID == draw.id; + } + }; + auto isOnlySelected = settings.onionskinIsOnlySelected; + + // Draws an animation's draw list. Onion-skin samples are tinted and faded, `alphaOffset` fades the overlay. A + // parent around a stepped-into child is drawn in the child's space (`scene`), its layers only, without the + // animation layer playing the child (`skipLayerId`). + auto render = [&](Document& sampleDocument, const Animation& sampleAnimation, float alphaOffset, + const DrawOptions& options, const mat4& scene = mat4(1.0f), int skipLayerId = -1) { + auto isActiveDocument = &sampleDocument == &document && skipLayerId == -1; + auto isParent = skipLayerId != -1; + auto& sampleModel = sampleDocument.model; + auto targetIcon = resources.icon_id_get(isAltIcons && !isIsolated ? ICON_TARGET_ALT : ICON_TARGET); + auto sampleOptions = options; + sampleOptions.library_get = sampleDocument.library_resolver_get(); + for (auto& draw : animation_draws_get(sampleModel, sampleAnimation, sampleOptions)) + { + if (isParent && (draw.type != DrawType::LAYER || draw.id == skipLayerId)) + continue; + auto isOnion = draw.sample != -1; + if (isOnion && isOnlySelected && !(isActiveDocument && is_draw_selected(draw))) + continue; + auto sampleColor = isOnion ? sampleColors[draw.sample] : vec3(); + auto sampleAlpha = isOnion ? sampleAlphas[draw.sample] : 0.0f; + auto onionColor = vec4(sampleColor, 1.0f - sampleAlpha); + auto& frame = draw.frame; + auto transform = baseTransform * scene * draw.parent; + auto marker_model_get = [&](vec2 markerSize) { + return quad_model_get(markerSize, frame.position, markerSize * 0.5f, percent_to_unit(frame.scale), + frame.rotation, percent_to_unit(frame.skew)); + }; + + if (draw.type == DrawType::ROOT || draw.type == DrawType::GROUP_ROOT) + { + if (isViewOnlyLayers) + continue; + auto isSelected = isActiveDocument && draw.type == DrawType::GROUP_ROOT && + referenceItemType == ItemType::ROOT && reference.groupType == draw.groupType && + reference.groupId == draw.id; + auto color = isOnion ? vec4(sampleColor, sampleAlpha) + : draw.type == DrawType::ROOT ? COLOR_GREEN + : isSelected ? COLOR_RED + : ROOT_COLOR; + auto markerModel = isRootTransform ? quad_model_get(TARGET_SIZE, {}, TARGET_SIZE * 0.5f) + : marker_model_get(TARGET_SIZE); + texture_render(shaderTexture, targetIcon, transform * markerModel, color); + } + else if (draw.type == DrawType::LAYER) + { + auto layerTexture = + sampleDocument.draw_image_get(draw, percent_to_unit(viewZoom) * draw_scale_get(draw)); + if (!layerTexture || !layerTexture->is_valid() || layerTexture->size.x <= 0 || + layerTexture->size.y <= 0) + continue; + auto textureSize = layerTexture->unit_size_get(); + auto layerModel = draw_quad_model_get(draw); + auto layerTransform = transform * layerModel; + auto tint = frame.tint; + tint.a = std::max(0.0f, tint.a - (alphaOffset + sampleAlpha)); + auto customShader = sampleDocument.shader_get(frame.shaderId); + layer_render(customShader ? *customShader : shaderTexture, texture_id_get(*layerTexture), + textureSize, baseTransform * scene, draw, tint, + frame.colorOffset + vec4(sampleColor, 0.0f)); + if (isParent) + continue; + + auto color = isOnion ? onionColor + : isActiveDocument && is_layer_selected(draw.id) ? SELECTED_LAYER_BORDER_COLOR + : COLOR_RED; + if (isBorder && !isIsolated) + rect_render(shaderLine, layerTransform, layerModel, color); + if (isPivots && !isIsolated) + texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), + transform * marker_model_get(PIVOT_SIZE), color); + } + else if (!isViewOnlyLayers) + { + auto isShowRect = item_get(sampleModel.content.nulls, draw.id)->isShowRect; + auto isSelected = + isActiveDocument && draw.id == reference.itemID && referenceItemType == ItemType::NULL_; + auto color = isOnion ? onionColor : isSelected ? COLOR_RED : NULL_RECT_COLOR; + auto markerSize = isShowRect ? POINT_SIZE : TARGET_SIZE; + texture_render(shaderTexture, isShowRect ? resources.icon_id_get(ICON_POINT) : targetIcon, + transform * marker_model_get(markerSize), color); + if (!isShowRect) + continue; + auto rectModel = quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), + frame.rotation, percent_to_unit(frame.skew)); + rect_render(shaderLine, transform * rectModel, rectModel, color); + } + } + }; + + if (animation) + { + auto overlay_render = [&]() { + if (auto overlayDocument = isIsolated ? nullptr : overlay_animation_document_get(manager, document)) + if (auto overlayAnimation = overlayDocument->model.animation_get(overlayIndex)) + render(*overlayDocument, *overlayAnimation, 1.0f - percent_to_unit(overlayTransparency), + drawOptions); + }; + + // Editing a stepped-into child: its parent, dimmed and frozen where it was stepped in, around it. + if (auto& steps = document.childSteps; + !isIsolated && !steps.empty() && steps.back().childAnimationIndex == reference.animationIndex) + { + auto& step = steps.back(); + auto parentIndex = manager.tab_index_get(step.tabId); + auto parentDocument = parentIndex == -1 ? nullptr : manager.get(parentIndex); + auto parentAnimation = + parentDocument ? parentDocument->model.animation_get(step.animationIndex) : nullptr; + auto placement = parentAnimation ? layer_child_transform_get(*parentAnimation, step.layer.itemID, + step.frameTime, isRootTransform) + : std::nullopt; + if (placement && glm::determinant(*placement) != 0.0f) + render(*parentDocument, *parentAnimation, PARENT_DIM_ALPHA, + {.time = step.frameTime, .isRootTransform = isRootTransform}, glm::inverse(*placement), + step.layer.itemID); + } + + if (overlayDrawOrder == OVERLAY_UNDER) + overlay_render(); + render(document, *animation, 0.0f, drawOptions); + if (overlayDrawOrder == OVERLAY_OVER) + overlay_render(); + + if (settings.onionskinIsEnabled && settings.onionskinIsPivotPath && !isIsolated) + { + auto key = + std::tuple{document.hash, document.librariesRevision, reference.animationIndex, isRootTransform}; + if (key != pivotPathsKey || pivotPaths.empty()) + { + pivotPathsKey = key; + pivotPaths.clear(); + for (int time = 0; time < animation->frameNum; ++time) + for (auto& draw : animation_draws_get(model, *animation, + {.time = (float)time, + .isRootTransform = isRootTransform, + .library_get = document.library_resolver_get()})) + { + auto path = std::ranges::find_if(pivotPaths, [&](const PivotPath& path) { + return path.item.type == draw.type && path.item.id == draw.id && + path.item.groupType == draw.groupType; + }); + if (path == pivotPaths.end()) + path = pivotPaths.insert(pivotPaths.end(), {.item = draw}); + path->points.push_back(vec2(draw.parent * vec4(draw.frame.position, 0.0f, 1.0f))); + } + } + + auto pointIcon = resources.icon_id_get(ICON_POINT); + for (auto& path : pivotPaths) + { + if (isOnlySelected && !is_draw_selected(path.item)) + continue; + for (std::size_t i = 0; i < path.points.size(); ++i) + { + if (i > 0) + line_render(shaderDashed, baseTransform, path.points[i - 1], path.points[i], COLOR_RED); + texture_render(shaderTexture, pointIcon, + baseTransform * quad_model_get(POINT_SIZE, path.points[i], POINT_SIZE * 0.5f), + COLOR_RED); + } + } + } + } + + if (isRecordingFrame) + { + auto sounds = settings.timelineIsSound && animation && recorder.is_sound_frame() + ? document.trigger_sounds_get(*animation, (int)frameTime, recorder.index) + : std::vector{}; + if (!recorder.frame_capture(pixels_get(), size, sounds)) + { + toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, path_to_utf8(recorder.options.path)); + recorder.cancel(); + recording_stop(manager, document); + } + } + + unbind(); + + if (isViewTransparent) + { + checker_pan_sync(zoom, pan); + render_checker_background(ImGui::GetWindowDrawList(), min, max, -size - checkerPan, CHECKER_SIZE); + } + image_premultiplied_draw(texture, to_imvec2(size)); + + // The events triggers (the animation's and its children's) fire on this frame. + std::string names; + if (animation && !isOnlyShowLayers && !manager.isRecording) + for (auto& [source, trigger, layerId] : + animation_triggers_get(model, *animation, (int)frameTime, document.library_resolver_get())) + for (auto eventId : trigger.eventIds) + if (auto event = item_get(source->content.events, eventId)) + names += (names.empty() ? "" : ", ") + event->name; + if (!names.empty()) + { + auto clipMin = ImGui::GetItemRectMin(); + auto clipMax = ImGui::GetItemRectMax(); + auto drawList = ImGui::GetWindowDrawList(); + auto textPos = to_imvec2(to_vec2(cursorScreenPos) + to_vec2(ImGui::GetStyle().WindowPadding)); + + drawList->PushClipRect(clipMin, clipMax); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE_LARGE); + auto triggerTextColor = isLightTheme ? TRIGGER_TEXT_COLOR_LIGHT : TRIGGER_TEXT_COLOR_DARK; + drawList->AddText(textPos, ImGui::GetColorU32(triggerTextColor), names.c_str()); + ImGui::PopFont(); + drawList->PopClipRect(); + } } if (tool == TOOL_PAN) - view_context_menu_draw("##Animation Preview Context Menu", manager, settings, document, zoom, pan, center_view, - fit_view, animation != nullptr); + view_context_menu_draw("##Animation Preview Context Menu", manager, settings, document, zoom, pan, center_view, + fit_view, animation != nullptr); manager.progressPopup.trigger(); if (ImGui::BeginPopupModal(manager.progressPopup.label(), &manager.progressPopup.isOpen, ImGuiWindowFlags_NoResize)) { - ImGui::ProgressBar(recorder.count > 0 ? (float)recorder.index / (float)recorder.count : 0.0f); - ImGui::TextUnformatted(localize.get(TEXT_RECORDING_PROGRESS)); + ImGui::ProgressBar(recorder.count > 0 ? (float)recorder.index / (float)recorder.count : 0.0f); + ImGui::TextUnformatted(localize.get(TEXT_RECORDING_PROGRESS)); - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), ImVec2(ImGui::GetContentRegionAvail().x, 0))) - { - recorder.cancel(); - recording_stop(manager, document); - } + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), ImVec2(ImGui::GetContentRegionAvail().x, 0))) + { + recorder.cancel(); + recording_stop(manager, document); + } - ImGui::EndPopup(); + ImGui::EndPopup(); } if (!document.isAnimationPreviewSet) { - center_view(); - zoom = settings.previewStartZoom; - checker_pan_reset(zoom, pan); - document.isAnimationPreviewSet = true; + center_view(); + zoom = settings.previewStartZoom; + checker_pan_reset(zoom, pan); + document.isAnimationPreviewSet = true; } settings.previewStartZoom = zoom; ImGui::End(); - } +} diff --git a/src/ui/animation_preview.h b/src/ui/animation_preview.h index 6fd7b1b..67f3664 100644 --- a/src/ui/animation_preview.h +++ b/src/ui/animation_preview.h @@ -11,8 +11,8 @@ #include "resources.h" #include "settings.h" - class AnimationPreview : public CanvasView - { +class AnimationPreview : public CanvasView +{ MIX_Mixer* mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr); AudioStream audioStream = AudioStream(mixer); bool wasPlaybackPlaying = false; @@ -28,8 +28,8 @@ // Where each item's pivot is at every frame of the animation, kept until the document or view changes. struct PivotPath { - Draw item = {}; - std::vector points{}; + Draw item = {}; + std::vector points{}; }; std::vector pivotPaths; std::tuple pivotPathsKey; @@ -37,7 +37,7 @@ void recording_start(Manager&, Settings&, Document&, const Animation*); void recording_stop(Manager&, Document&); - public: +public: void tick(Manager&, Settings&, float); void update(Manager&, Settings&, Resources&); - }; +}; diff --git a/src/ui/animations.cpp b/src/ui/animations.cpp index 0386b15..50f04b2 100644 --- a/src/ui/animations.cpp +++ b/src/ui/animations.cpp @@ -9,193 +9,207 @@ #include "ui/shortcut.h" #include "ui/tree.h" - constexpr const char* ANIMATION_DRAG_DROP = "Animation Drag Drop"; - constexpr float DROP_ZONE_FRACTION = 1.0f / 3.0f; - constexpr int MERGE_OPTIONS_ROWS = 2; - constexpr float MERGE_OPTIONS_HALF = 0.5f; - constexpr int MERGE_POPUP_CHILD_COUNT = 3; - constexpr int GROUP_KEY_OFFSET = 2; +constexpr const char* ANIMATION_DRAG_DROP = "Animation Drag Drop"; +constexpr float DROP_ZONE_FRACTION = 1.0f / 3.0f; +constexpr int MERGE_OPTIONS_ROWS = 2; +constexpr float MERGE_OPTIONS_HALF = 0.5f; +constexpr int MERGE_POPUP_CHILD_COUNT = 3; +constexpr int GROUP_KEY_OFFSET = 2; - // Animation groups share the key space with animation indices as negative keys. - constexpr int group_key_get(int groupId) { return -groupId - GROUP_KEY_OFFSET; } - constexpr int group_id_from_key_get(int key) { return -key - GROUP_KEY_OFFSET; } - constexpr bool is_group_key(int key) { return key <= -GROUP_KEY_OFFSET; } +// Animation groups share the key space with animation indices as negative keys. +constexpr int group_key_get(int groupId) +{ + return -groupId - GROUP_KEY_OFFSET; +} - enum class AnimationDropZone - { +constexpr int group_id_from_key_get(int key) +{ + return -key - GROUP_KEY_OFFSET; +} + +constexpr bool is_group_key(int key) +{ + return key <= -GROUP_KEY_OFFSET; +} + +enum class AnimationDropZone +{ BEFORE, INSIDE, AFTER - }; +}; - struct AnimationDragDropItem - { +struct AnimationDragDropItem +{ bool isGroup = false; int id = -1; bool operator==(const AnimationDragDropItem&) const = default; - }; +}; - struct AnimationMergeOptions - { +struct AnimationMergeOptions +{ std::set selection; int reference = -1; Merge type = {}; bool isDeleteAnimationsAfter = false; - }; +}; - // Calls back for each top-level entry: (animation index, animation) for loose animations, (index, group) for groups. - template static void animation_entries_each(const Model& model, Callback&& callback) - { +// Calls back for each top-level entry: (animation index, animation) for loose animations, (index, group) for groups. +template static void animation_entries_each(const Model& model, Callback&& callback) +{ int index = 0; for (auto& entry : model.animations.entries) - if (auto animation = std::get_if>(&entry)) - callback(index++, animation->get(), (const AnimationGroup*)nullptr); - else - { - auto& group = std::get(entry); - callback(index, (const Animation*)nullptr, &group); - index += (int)group.animations.size(); - } - } + if (auto animation = std::get_if>(&entry)) + callback(index++, animation->get(), (const AnimationGroup*)nullptr); + else + { + auto& group = std::get(entry); + callback(index, (const Animation*)nullptr, &group); + index += (int)group.animations.size(); + } +} - // The flat index of a group's first animation. - static int animation_group_first_index_get(const Model& model, int groupId) - { +// The flat index of a group's first animation. +static int animation_group_first_index_get(const Model& model, int groupId) +{ int first = -1; - animation_entries_each(model, - [&](int index, auto*, const AnimationGroup* group) - { - if (group && group->id == groupId) first = index; - }); + animation_entries_each(model, [&](int index, auto*, const AnimationGroup* group) { + if (group && group->id == groupId) + first = index; + }); return first; - } +} - static std::set animation_groups_selected_get(const Document& document) - { +static std::set animation_groups_selected_get(const Document& document) +{ std::set groupIds; auto uids = document.selection.uids.find(SelectionKind::ANIMATION_GROUPS); - if (uids == document.selection.uids.end()) return groupIds; + if (uids == document.selection.uids.end()) + return groupIds; for (auto& entry : document.model.animations.entries) - if (auto group = std::get_if(&entry); group && uids->second.contains(group->uid)) - groupIds.insert(group->id); + if (auto group = std::get_if(&entry); group && uids->second.contains(group->uid)) + groupIds.insert(group->id); return groupIds; - } +} - static void animations_selection_set(Document& document, const std::set& indices, const std::set& groupIds) - { +static void animations_selection_set(Document& document, const std::set& indices, const std::set& groupIds) +{ document.animations_selected_set(indices); auto& groupUids = document.selection.uids[SelectionKind::ANIMATION_GROUPS]; groupUids.clear(); for (auto& entry : document.model.animations.entries) - if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) - groupUids.insert(group->uid); - } + if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) + groupUids.insert(group->uid); +} - // Selected animations plus every animation of a selected group. - static std::set animation_selected_indices_get(const Document& document) - { +// Selected animations plus every animation of a selected group. +static std::set animation_selected_indices_get(const Document& document) +{ auto result = document.animations_selected_get(); for (auto groupId : animation_groups_selected_get(document)) - result.merge(animation_group_indices_get(document.model, groupId)); + result.merge(animation_group_indices_get(document.model, groupId)); return result; - } +} - static std::vector animation_groupable_indices_get(const Document& document) - { +static std::vector animation_groupable_indices_get(const Document& document) +{ std::vector result; for (auto index : document.animations_selected_get()) { - if (!document.model.animation_get(index) || document.model.animation_group_id_get(index) != -1) return {}; - result.push_back(index); + if (!document.model.animation_get(index) || document.model.animation_group_id_get(index) != -1) + return {}; + result.push_back(index); } return result; - } +} - static std::set animation_merge_indices_get(const Document& document, const std::set& keys, int reference) - { +static std::set animation_merge_indices_get(const Document& document, const std::set& keys, int reference) +{ std::set result; for (auto key : keys) - if (!is_group_key(key)) - result.insert(key); - else - result.merge(animation_group_indices_get(document.model, group_id_from_key_get(key))); + if (!is_group_key(key)) + result.insert(key); + else + result.merge(animation_group_indices_get(document.model, group_id_from_key_get(key))); result.erase(reference); return result; - } +} - static void animation_overlay_reset(Document& document, const std::set& indices) - { +static void animation_overlay_reset(Document& document, const std::set& indices) +{ auto isOverlayDocument = document.overlayDocumentId == 0 || document.overlayDocumentId == document.tabId; - if (!isOverlayDocument || !indices.contains(document.overlayIndex)) return; + if (!isOverlayDocument || !indices.contains(document.overlayIndex)) + return; document.overlayIndex = -1; document.overlayDocumentId = 0; - } +} - static void animations_erase(Document& document, const std::set& indices, const std::set& groupIds, - StringType label) - { - document.edit_apply(label, - [&](Model& model) - { - animation_overlay_reset(document, indices); - animations_selection_set(document, {}, {}); - return animations_remove(model, indices, groupIds); - }); - } +static void animations_erase(Document& document, const std::set& indices, const std::set& groupIds, + StringType label) +{ + document.edit_apply(label, [&](Model& model) { + animation_overlay_reset(document, indices); + animations_selection_set(document, {}, {}); + return animations_remove(model, indices, groupIds); + }); +} - static std::set animation_indices_get(Document& document, const Uids& uids) - { +static std::set animation_indices_get(Document& document, const Uids& uids) +{ std::set indices; for (auto reference : document.references_get(uids)) - indices.insert(reference.animationIndex); + indices.insert(reference.animationIndex); return indices; - } +} - static std::string animation_clipboard_text_get(const Document& document) - { +static std::string animation_clipboard_text_get(const Document& document) +{ std::string clipboardText; auto& model = document.model; auto groupIds = animation_groups_selected_get(document); auto selection = document.animations_selected_get(); for (auto& entry : model.animations.entries) - if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) - clipboardText += animation_group_to_string(*group); + if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) + clipboardText += animation_group_to_string(*group); for (int i = 0; i < model.animations_count_get(); ++i) { - auto groupId = model.animation_group_id_get(i); - if (selection.contains(i) || groupIds.contains(groupId)) - clipboardText += animation_to_string(*model.animation_get(i), groupId); + auto groupId = model.animation_group_id_get(i); + if (selection.contains(i) || groupIds.contains(groupId)) + clipboardText += animation_to_string(*model.animation_get(i), groupId); } return clipboardText; - } +} - static void animations_insert(PanelState& state, Document& document, const std::string& text, int start, int targetGroupId, - StringType edit) - { +static void animations_insert(PanelState& state, Document& document, const std::string& text, int start, + int targetGroupId, StringType edit) +{ std::set groupIds; std::string errorString; - document.edit_apply(edit, - [&](Model& model) - { - auto uids = animations_paste(model, text, start, targetGroupId, groupIds, &errorString); - if (uids.empty()) return uids; - auto indices = animation_indices_get(document, uids); - animations_selection_set(document, groupIds.empty() ? indices : std::set{}, groupIds); - document.reference_set({}); - if (indices.empty()) return uids; - state.scrollId = *indices.rbegin(); - if (!groupIds.empty()) return uids; - document.reference_set({*indices.rbegin()}); - if (indices.size() == 1) state.newId = *indices.rbegin(); - return uids; - }); - if (!errorString.empty()) toast_log(Level::ERROR, TOAST_DESERIALIZE_ANIMATIONS_FAILED, errorString); - } + document.edit_apply(edit, [&](Model& model) { + auto uids = animations_paste(model, text, start, targetGroupId, groupIds, &errorString); + if (uids.empty()) + return uids; + auto indices = animation_indices_get(document, uids); + animations_selection_set(document, groupIds.empty() ? indices : std::set{}, groupIds); + document.reference_set({}); + if (indices.empty()) + return uids; + state.scrollId = *indices.rbegin(); + if (!groupIds.empty()) + return uids; + document.reference_set({*indices.rbegin()}); + if (indices.size() == 1) + state.newId = *indices.rbegin(); + return uids; + }); + if (!errorString.empty()) + toast_log(Level::ERROR, TOAST_DESERIALIZE_ANIMATIONS_FAILED, errorString); +} - // Merges into options.reference; without a merge-popup selection, the selected animations merge into the first. - static int animations_merge(Document& document, const AnimationMergeOptions& options) - { +// Merges into options.reference. Without a merge-popup selection, the selected animations merge into the first. +static int animations_merge(Document& document, const AnimationMergeOptions& options) +{ auto isQuick = options.selection.empty(); auto target = options.reference; auto sources = isQuick ? animation_selected_indices_get(document) @@ -206,66 +220,67 @@ if (isQuick) { - auto count = document.model.animations_count_get(); - if (sources.empty()) return -1; - if (sources.size() == 1 && ungroupIds.empty() && *sources.begin() != count - 1) - sources.insert(*sources.begin() + 1); - if (sources.size() == 1 && ungroupIds.empty()) return -1; - target = *sources.begin(); + auto count = document.model.animations_count_get(); + if (sources.empty()) + return -1; + if (sources.size() == 1 && ungroupIds.empty() && *sources.begin() != count - 1) + sources.insert(*sources.begin() + 1); + if (sources.size() == 1 && ungroupIds.empty()) + return -1; + target = *sources.begin(); } else if (sources.empty()) - return -1; + return -1; int merged = -1; - document.edit_apply(EDIT_MERGE_ANIMATIONS, - [&](Model& model) - { - animation_overlay_reset(document, sources); - auto uids = animations_merge(model, target, sources, type, isDeleteAfter, ungroupIds); - auto indices = animation_indices_get(document, uids); - if (indices.empty()) return uids; - merged = *indices.begin(); - animations_selection_set(document, {merged}, {}); - document.reference_set({merged}); - return uids; - }); + document.edit_apply(EDIT_MERGE_ANIMATIONS, [&](Model& model) { + animation_overlay_reset(document, sources); + auto uids = animations_merge(model, target, sources, type, isDeleteAfter, ungroupIds); + auto indices = animation_indices_get(document, uids); + if (indices.empty()) + return uids; + merged = *indices.begin(); + animations_selection_set(document, {merged}, {}); + document.reference_set({merged}); + return uids; + }); return merged; - } +} - static AnimationDropZone animation_drop_zone_get(ImVec2 min, ImVec2 max) - { +static AnimationDropZone animation_drop_zone_get(ImVec2 min, ImVec2 max) +{ auto zoneHeight = (max.y - min.y) * DROP_ZONE_FRACTION; auto mouseY = ImGui::GetIO().MousePos.y; - if (mouseY < min.y + zoneHeight) return AnimationDropZone::BEFORE; - if (mouseY >= max.y - zoneHeight) return AnimationDropZone::AFTER; + if (mouseY < min.y + zoneHeight) + return AnimationDropZone::BEFORE; + if (mouseY >= max.y - zoneHeight) + return AnimationDropZone::AFTER; return AnimationDropZone::INSIDE; - } +} - static void animation_move_command_push(const Panel& panel, std::vector items, - AnimationTarget target) - { - if (items.empty()) return; - command_push(panel, - [items, target](Document& document) - { - std::set indices; - std::set groupIds; - for (auto item : items) - (item.isGroup ? groupIds : indices).insert(item.id); - document.edit_apply(EDIT_MOVE_ANIMATIONS, - [&](Model& model) - { - auto uids = animations_move(model, indices, groupIds, target); - if (uids.empty() && groupIds.empty()) return; - animations_selection_set(document, animation_indices_get(document, uids), - groupIds); - }); - }); - } +static void animation_move_command_push(const Panel& panel, std::vector items, + AnimationTarget target) +{ + if (items.empty()) + return; + command_push(panel, [items, target](Document& document) { + std::set indices; + std::set groupIds; + for (auto item : items) + (item.isGroup ? groupIds : indices).insert(item.id); + document.edit_apply(EDIT_MOVE_ANIMATIONS, [&](Model& model) { + auto uids = animations_move(model, indices, groupIds, target); + if (uids.empty() && groupIds.empty()) + return; + animations_selection_set(document, animation_indices_get(document, uids), groupIds); + }); + }); +} - static void animation_drag_drop_source_update(const Document& document, AnimationDragDropItem fallback) - { - if (!ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) return; +static void animation_drag_drop_source_update(const Document& document, AnimationDragDropItem fallback) +{ + if (!ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) + return; static std::vector items; items.clear(); @@ -273,101 +288,103 @@ auto selection = document.animations_selected_get(); if (fallback.isGroup ? groupIds.contains(fallback.id) : selection.contains(fallback.id)) { - for (auto groupId : groupIds) - items.push_back({true, groupId}); - for (auto index : selection) - if (document.model.animation_get(index)) items.push_back({false, index}); + for (auto groupId : groupIds) + items.push_back({true, groupId}); + for (auto index : selection) + if (document.model.animation_get(index)) + items.push_back({false, index}); } - if (items.empty() && fallback.id >= 0) items.push_back(fallback); + if (items.empty() && fallback.id >= 0) + items.push_back(fallback); ImGui::SetDragDropPayload(ANIMATION_DRAG_DROP, items.data(), items.size() * sizeof(AnimationDragDropItem)); ImGui::EndDragDropSource(); - } +} - static std::vector animation_drag_drop_target_items_get() - { +static std::vector animation_drag_drop_target_items_get() +{ auto payload = ImGui::AcceptDragDropPayload(ANIMATION_DRAG_DROP, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect); - if (!payload || payload->DataSize % (int)sizeof(AnimationDragDropItem) != 0) return {}; + if (!payload || payload->DataSize % (int)sizeof(AnimationDragDropItem) != 0) + return {}; auto items = static_cast(payload->Data); return {items, items + payload->DataSize / sizeof(AnimationDragDropItem)}; - } +} - static bool animation_group_drag_drop_update(const Panel& panel, int groupId, ImVec2 itemMin, ImVec2 itemMax) - { - if (!ImGui::BeginDragDropTarget()) return false; +static bool animation_group_drag_drop_update(const Panel& panel, int groupId, ImVec2 itemMin, ImVec2 itemMax) +{ + if (!ImGui::BeginDragDropTarget()) + return false; auto items = animation_drag_drop_target_items_get(); auto isDelivered = false; if (!items.empty()) { - auto dropZone = animation_drop_zone_get(itemMin, itemMax); - auto isGroupDragged = std::ranges::any_of(items, &AnimationDragDropItem::isGroup); - auto isDropIntoGroup = dropZone == AnimationDropZone::INSIDE && !isGroupDragged; - if (isDropIntoGroup) - drop_box_draw(ImGui::GetWindowDrawList(), itemMin, itemMax); - else - drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, dropZone != AnimationDropZone::BEFORE); + auto dropZone = animation_drop_zone_get(itemMin, itemMax); + auto isGroupDragged = std::ranges::any_of(items, &AnimationDragDropItem::isGroup); + auto isDropIntoGroup = dropZone == AnimationDropZone::INSIDE && !isGroupDragged; + if (isDropIntoGroup) + drop_box_draw(ImGui::GetWindowDrawList(), itemMin, itemMax); + else + drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, dropZone != AnimationDropZone::BEFORE); - isDelivered = ImGui::GetDragDropPayload()->IsDelivery(); - if (isDelivered) - animation_move_command_push( - panel, items, - {.groupId = groupId, .isAfter = dropZone != AnimationDropZone::BEFORE, .isInto = isDropIntoGroup}); + isDelivered = ImGui::GetDragDropPayload()->IsDelivery(); + if (isDelivered) + animation_move_command_push( + panel, items, + {.groupId = groupId, .isAfter = dropZone != AnimationDropZone::BEFORE, .isInto = isDropIntoGroup}); } ImGui::EndDragDropTarget(); return isDelivered; - } +} - static bool animation_row_drag_drop_update(const Panel& panel, int index) - { +static bool animation_row_drag_drop_update(const Panel& panel, int index) +{ animation_drag_drop_source_update(panel.document, {false, index}); - if (!ImGui::BeginDragDropTarget()) return false; + if (!ImGui::BeginDragDropTarget()) + return false; auto items = animation_drag_drop_target_items_get(); auto isDelivered = false; if (!items.empty()) { - auto itemMin = ImGui::GetItemRectMin(); - auto itemMax = ImGui::GetItemRectMax(); - auto isDropAfter = is_drop_after(itemMin, itemMax); - drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, isDropAfter); - isDelivered = ImGui::GetDragDropPayload()->IsDelivery(); - if (isDelivered) animation_move_command_push(panel, items, {.animationIndex = index, .isAfter = isDropAfter}); + auto itemMin = ImGui::GetItemRectMin(); + auto itemMax = ImGui::GetItemRectMax(); + auto isDropAfter = is_drop_after(itemMin, itemMax); + drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, isDropAfter); + isDelivered = ImGui::GetDragDropPayload()->IsDelivery(); + if (isDelivered) + animation_move_command_push(panel, items, {.animationIndex = index, .isAfter = isDropAfter}); } ImGui::EndDragDropTarget(); return isDelivered; - } +} - static void animation_group_set_push(const Panel& panel, int groupId, StringType edit, std::optional name, - std::optional isExpanded) - { - command_push(panel, - [groupId, edit, name, isExpanded](Document& document) - { - auto first = animation_group_first_index_get(document.model, groupId); - auto group = document.model.animation_group_get(first); - if (!group || (name.value_or(group->name) == group->name && - isExpanded.value_or(group->isExpanded) == group->isExpanded)) - return; - document.edit_apply(edit, - [&](Model& model) - { - auto group = model.animation_group_edit(first); - group->name = name.value_or(group->name); - group->isExpanded = isExpanded.value_or(group->isExpanded); - }); - }); - } +static void animation_group_set_push(const Panel& panel, int groupId, StringType edit, std::optional name, + std::optional isExpanded) +{ + command_push(panel, [groupId, edit, name, isExpanded](Document& document) { + auto first = animation_group_first_index_get(document.model, groupId); + auto group = document.model.animation_group_get(first); + if (!group || + (name.value_or(group->name) == group->name && isExpanded.value_or(group->isExpanded) == group->isExpanded)) + return; + document.edit_apply(edit, [&](Model& model) { + auto group = model.animation_group_edit(first); + group->name = name.value_or(group->name); + group->isExpanded = isExpanded.value_or(group->isExpanded); + }); + }); +} - // A group's tree node (renamable, a drop target) and, when expanded, its animations' rows. - static bool animation_group_draw(Panel& panel, std::set& selection, std::set& groupSelection, int& focus, - const ListRows& rows, const AnimationGroup& group, int firstIndex, int arrowKey) - { +// A group's tree node (renamable, a drop target) and, when expanded, its animations' rows. +static bool animation_group_draw(Panel& panel, std::set& selection, std::set& groupSelection, int& focus, + const ListRows& rows, const AnimationGroup& group, int firstIndex, int arrowKey) +{ auto& state = panel.state; auto key = group_key_get(group.id); if (state.newId == key) { - state.renameState = RENAME_FORCE_EDIT; - state.newId = -1; + state.renameState = RENAME_FORCE_EDIT; + state.newId = -1; } auto isRenaming = state.renameId == key; @@ -384,36 +401,37 @@ auto itemMax = ImGui::GetItemRectMax(); if (tree.isRenameStarted) { - state.renameId = key; - state.renameText = group.name; + state.renameId = key; + state.renameText = group.name; } else if (tree.isRenameFinished) { - if (isRenaming) animation_group_set_push(panel, group.id, EDIT_RENAME_GROUP, state.renameText, std::nullopt); - state.renameId = -1; - state.renameText.clear(); + if (isRenaming) + animation_group_set_push(panel, group.id, EDIT_RENAME_GROUP, state.renameText, std::nullopt); + state.renameId = -1; + state.renameText.clear(); } if (tree.isOpen != group.isExpanded && !is_drag_drop_active() && !ImGui::IsMouseDragging(ImGuiMouseButton_Left)) - animation_group_set_push(panel, group.id, EDIT_TOGGLE_GROUP_EXPANDED, std::nullopt, tree.isOpen); + animation_group_set_push(panel, group.id, EDIT_TOGGLE_GROUP_EXPANDED, std::nullopt, tree.isOpen); if (tree.isClicked) { - auto isCtrl = ImGui::GetIO().KeyCtrl; - auto isDeselected = isCtrl && groupSelection.contains(group.id); - if (!isCtrl) - { - selection.clear(); - groupSelection.clear(); - } - if (isDeselected) - groupSelection.erase(group.id); - else - groupSelection.insert(group.id); - if (isDeselected ? selection.empty() && groupSelection.empty() : !isCtrl || selection.empty()) - { - panel.document.reference_set({}); - panel.document.frame_references_clear(); - } + auto isCtrl = ImGui::GetIO().KeyCtrl; + auto isDeselected = isCtrl && groupSelection.contains(group.id); + if (!isCtrl) + { + selection.clear(); + groupSelection.clear(); + } + if (isDeselected) + groupSelection.erase(group.id); + else + groupSelection.insert(group.id); + if (isDeselected ? selection.empty() && groupSelection.empty() : !isCtrl || selection.empty()) + { + panel.document.reference_set({}); + panel.document.frame_references_clear(); + } } animation_drag_drop_source_update(panel.document, {true, group.id}); @@ -421,48 +439,47 @@ if (tree.isOpen) { - for (int i = 0; i < (int)group.animations.size() && !isRowsDone; ++i) - isRowsDone = row_draw(panel, selection, focus, rows, firstIndex + i, firstIndex + i, arrowKey); - ImGui::TreePop(); + for (int i = 0; i < (int)group.animations.size() && !isRowsDone; ++i) + isRowsDone = row_draw(panel, selection, focus, rows, firstIndex + i, firstIndex + i, arrowKey); + ImGui::TreePop(); } ImGui::PopID(); ImGui::PopID(); return isRowsDone; - } +} - static void animations_merge_popup_update(Panel& panel, AnimationsPanel& animations) - { +static void animations_merge_popup_update(Panel& panel, AnimationsPanel& animations) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& popup = animations.mergePopup; auto& mergeSelection = animations.mergeSelection; auto mergeReference = animations.mergeReference; popup.trigger(); - if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) + return popup.end(); struct AnimationMergeCandidate { - int key = 0; - std::string label; + int key = 0; + std::string label; }; std::vector candidates; - auto candidate_animation_push = [&](const Animation& animation, int animationIndex, bool isGrouped) - { - if (animationIndex != mergeReference) - candidates.push_back({animationIndex, isGrouped ? std::format(" {}", animation.name) : animation.name}); + auto candidate_animation_push = [&](const Animation& animation, int animationIndex, bool isGrouped) { + if (animationIndex != mergeReference) + candidates.push_back({animationIndex, isGrouped ? std::format(" {}", animation.name) : animation.name}); }; - animation_entries_each(document.model, - [&](int index, const Animation* animation, const AnimationGroup* group) - { - if (animation) return candidate_animation_push(*animation, index, false); - auto isReferenceOnly = group->animations.size() == 1 && index == mergeReference; - if (group->animations.empty() || isReferenceOnly) return; - candidates.push_back( - {group_key_get(group->id), - group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name}); - for (int i = 0; i < (int)group->animations.size(); ++i) - candidate_animation_push(*group->animations[i], index + i, true); - }); + animation_entries_each(document.model, [&](int index, const Animation* animation, const AnimationGroup* group) { + if (animation) + return candidate_animation_push(*animation, index, false); + auto isReferenceOnly = group->animations.size() == 1 && index == mergeReference; + if (group->animations.empty() || isReferenceOnly) + return; + candidates.push_back( + {group_key_get(group->id), group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name}); + for (int i = 0; i < (int)group->animations.size(); ++i) + candidate_animation_push(*group->animations[i], index + i, true); + }); auto footerSize = footer_size_get(); auto optionsSize = child_size_get(MERGE_OPTIONS_ROWS); @@ -473,312 +490,287 @@ if (ImGui::BeginChild(localize.get(LABEL_ANIMATIONS_CHILD), animationsSize, ImGuiChildFlags_Borders)) { - animations.mergeKeys.clear(); - for (auto& candidate : candidates) - animations.mergeKeys.push_back(candidate.key); - mergeSelection.set_index_map(&animations.mergeKeys); - mergeSelection.start(candidates.size()); - for (int i = 0; i < (int)candidates.size(); ++i) - { - ImGui::PushID(candidates[i].key); - ImGui::SetNextItemSelectionUserData(i); - ImGui::Selectable(candidates[i].label.c_str(), mergeSelection.contains(candidates[i].key)); - ImGui::PopID(); - } - mergeSelection.finish(); - mergeSelection.set_index_map(nullptr); + animations.mergeKeys.clear(); + for (auto& candidate : candidates) + animations.mergeKeys.push_back(candidate.key); + mergeSelection.set_index_map(&animations.mergeKeys); + mergeSelection.start(candidates.size()); + for (int i = 0; i < (int)candidates.size(); ++i) + { + ImGui::PushID(candidates[i].key); + ImGui::SetNextItemSelectionUserData(i); + ImGui::Selectable(candidates[i].label.c_str(), mergeSelection.contains(candidates[i].key)); + ImGui::PopID(); + } + mergeSelection.finish(); + mergeSelection.set_index_map(nullptr); } ImGui::EndChild(); if (ImGui::BeginChild("##Merge Options", optionsSize, ImGuiChildFlags_Borders)) { - auto size = ImVec2(optionsSize.x * MERGE_OPTIONS_HALF, optionsSize.y - ImGui::GetStyle().WindowPadding.y * 2); - if (ImGui::BeginChild("##Merge Options 1", size)) - { - ImGui::RadioButton(localize.get(LABEL_APPEND_FRAMES), &settings.mergeType, MERGE_APPEND); - ImGui::RadioButton(localize.get(LABEL_PREPEND_FRAMES), &settings.mergeType, MERGE_PREPEND); - } - ImGui::EndChild(); - ImGui::SameLine(); - if (ImGui::BeginChild("##Merge Options 2", size)) - { - ImGui::RadioButton(localize.get(LABEL_REPLACE_FRAMES), &settings.mergeType, MERGE_REPLACE); - ImGui::RadioButton(localize.get(LABEL_IGNORE_FRAMES), &settings.mergeType, MERGE_IGNORE); - } - ImGui::EndChild(); + auto size = ImVec2(optionsSize.x * MERGE_OPTIONS_HALF, optionsSize.y - ImGui::GetStyle().WindowPadding.y * 2); + if (ImGui::BeginChild("##Merge Options 1", size)) + { + ImGui::RadioButton(localize.get(LABEL_APPEND_FRAMES), &settings.mergeType, MERGE_APPEND); + ImGui::RadioButton(localize.get(LABEL_PREPEND_FRAMES), &settings.mergeType, MERGE_PREPEND); + } + ImGui::EndChild(); + ImGui::SameLine(); + if (ImGui::BeginChild("##Merge Options 2", size)) + { + ImGui::RadioButton(localize.get(LABEL_REPLACE_FRAMES), &settings.mergeType, MERGE_REPLACE); + ImGui::RadioButton(localize.get(LABEL_IGNORE_FRAMES), &settings.mergeType, MERGE_IGNORE); + } + ImGui::EndChild(); } ImGui::EndChild(); if (ImGui::BeginChild("##Merge Delete After", deleteAfterSize, ImGuiChildFlags_Borders)) - ImGui::Checkbox(localize.get(LABEL_DELETE_ANIMATIONS_AFTER), &settings.mergeIsDeleteAnimationsAfter); + ImGui::Checkbox(localize.get(LABEL_DELETE_ANIMATIONS_AFTER), &settings.mergeIsDeleteAnimationsAfter); ImGui::EndChild(); auto result = popup_buttons_draw(manager, localize.get(LABEL_MERGE), !animation_merge_indices_get(document, mergeSelection, mergeReference).empty(), LABEL_CLOSE); if (result == PopupButton::CONFIRM) - command_push(panel, - [options = AnimationMergeOptions{.selection = mergeSelection, + command_push( + panel, [options = AnimationMergeOptions{.selection = mergeSelection, .reference = mergeReference, .type = (Merge)settings.mergeType, .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}]( Document& document) { animations_merge(document, options); }); if (result != PopupButton::NONE) { - mergeSelection.clear(); - popup.close(); + mergeSelection.clear(); + popup.close(); } ImGui::EndPopup(); popup.end(); - } +} - void animations_update(Panel& panel, AnimationsPanel& animations) - { +void animations_update(Panel& panel, AnimationsPanel& animations) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& model = document.model; if (ImGui::Begin(localize.get(LABEL_ANIMATIONS_WINDOW), &settings.windowIsAnimations)) { - auto selection = document.animations_selected_get(); - auto groupSelection = animation_groups_selected_get(document); - auto groupIds = animation_group_ids_get(model); - auto count = model.animations_count_get(); - auto isItemSelected = [&]() { return !selection.empty() || !groupSelection.empty(); }; - // A single selected group is where adds and pastes go. - auto targetGroupId = [&]() - { - return groupSelection.size() == 1 && groupIds.contains(*groupSelection.begin()) ? *groupSelection.begin() : -1; - }; - auto group_end_get = [&](int groupId) - { - auto indices = groupId != -1 ? animation_group_indices_get(model, groupId) : std::set{}; - return indices.empty() ? count : std::min(*indices.rbegin() + 1, count); - }; - - Actions actions = {}; - actions.add( - ACTION_RENAME, [&]() { return selection.size() == 1 || (selection.empty() && groupSelection.size() == 1); }, - [&]() { state.newId = selection.size() == 1 ? *selection.begin() : group_key_get(*groupSelection.begin()); }); - actions.add( - ACTION_ADD, {}, - [&]() - { - auto index = !selection.empty() ? std::min(*selection.rbegin() + 1, count) : group_end_get(targetGroupId()); - auto groupId = selection.empty() ? targetGroupId() : model.animation_group_id_get(*selection.rbegin()); - command_push(panel, - [&state, index, groupId](Document& document) - { - document.edit_apply(EDIT_ADD_ANIMATION, - [&](Model& model) - { - auto uids = animation_add( - model, index, groupId, document.reference_get().animationIndex, - localize.get(TEXT_NEW_ANIMATION)); - animations_selection_set(document, {index}, {}); - document.reference_set({index}); - state.newId = index; - return uids; - }); - }); - }, - TOOLTIP_ADD_ANIMATION); - actions.add( - ACTION_DUPLICATE, isItemSelected, - [&]() - { - auto indices = animation_selected_indices_get(document); - auto start = indices.empty() ? count : std::min(*indices.rbegin() + 1, count); - command_push(panel, - [&state, start](Document& document) - { - auto text = animation_clipboard_text_get(document); - if (!text.empty()) - animations_insert(state, document, text, start, -1, EDIT_DUPLICATE_ANIMATIONS); - }); - }, - TOOLTIP_DUPLICATE_ANIMATION); - actions.add( - ACTION_MERGE, [&]() { return !animation_selected_indices_get(document).empty(); }, - [&]() - { - command_push(panel, - [&state](Document& document) - { - auto merged = animations_merge(document, {}); - if (merged != -1) state.scrollId = merged; - }); - }, - TOOLTIP_OPEN_MERGE_POPUP); - actions.add( - ACTION_GROUP, [&]() { return !animation_groupable_indices_get(document).empty(); }, - [&]() - { - auto targets = animation_groupable_indices_get(document); - command_push(panel, - [&state, targets = std::set(targets.begin(), targets.end())](Document& document) - { - auto groupIds = animation_group_ids_get(document.model); - auto groupId = groupIds.empty() ? 0 : *groupIds.rbegin() + 1; - document.edit_apply(EDIT_GROUP_ITEMS, - [&](Model& model) - { - auto uids = animations_group(model, targets, - localize.get(TEXT_NEW_GROUP)); - animations_selection_set(document, targets, {groupId}); - document.reference_set({*targets.begin()}); - state.scrollId = *targets.begin(); - return uids; - }); - }); - }); - actions.add( - ACTION_REMOVE, isItemSelected, - [&]() - { - command_push(panel, - [selection, groupSelection](Document& document) - { - animations_erase(document, selection, groupSelection, - groupSelection.empty() ? EDIT_REMOVE_ANIMATIONS : EDIT_REMOVE_GROUP); - }); - }, - TOOLTIP_REMOVE_ANIMATION); - actions.add( - ACTION_DEFAULT, [&]() { return selection.size() == 1; }, - [&]() - { - command_push(panel, - [index = *selection.begin()](Document& document) - { - auto animation = document.model.animation_get(index); - if (!animation) return; - document.edit_apply(EDIT_DEFAULT_ANIMATION, [name = animation->name](Model& model) - { model.animations.defaultAnimation = name; }); - }); - }, - TOOLTIP_SET_DEFAULT_ANIMATION); - actions.separator(); - actions.add(ACTION_CUT, isItemSelected, - [&]() - { - clipboard.set(animation_clipboard_text_get(document)); - command_push( - panel, [indices = animation_selected_indices_get(document), groupSelection](Document& document) - { animations_erase(document, indices, groupSelection, EDIT_CUT_ANIMATIONS); }); - }); - actions.add(ACTION_COPY, isItemSelected, [&]() { clipboard.set(animation_clipboard_text_get(document)); }); - actions.add( - ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, - [&]() - { - auto groupId = selection.empty() ? targetGroupId() : -1; - auto start = !selection.empty() ? *selection.rbegin() + 1 : group_end_get(groupId); - command_push(panel, [&state, text = clipboard.get(), start, groupId](Document& document) - { animations_insert(state, document, text, start, groupId, EDIT_PASTE_ANIMATIONS); }); - }); - - // The footer's merge opens the merge popup (merging into the first selected animation). - auto footerActions = actions; - if (groupSelection.empty()) - std::ranges::find(footerActions.items, ACTION_MERGE, &Action::type)->run = [&]() - { - if (selection.empty()) return; - animations.mergeSelection.clear(); - animations.mergeReference = *selection.begin(); - animations.mergePopup.open(); + auto selection = document.animations_selected_get(); + auto groupSelection = animation_groups_selected_get(document); + auto groupIds = animation_group_ids_get(model); + auto count = model.animations_count_get(); + auto isItemSelected = [&]() { + return !selection.empty() || !groupSelection.empty(); + }; + // A single selected group is where adds and pastes go. + auto targetGroupId = [&]() { + return groupSelection.size() == 1 && groupIds.contains(*groupSelection.begin()) ? *groupSelection.begin() + : -1; + }; + auto group_end_get = [&](int groupId) { + auto indices = groupId != -1 ? animation_group_indices_get(model, groupId) : std::set{}; + return indices.empty() ? count : std::min(*indices.rbegin() + 1, count); }; - ListRows rows{.label_get = [&](int index) { return model.animation_get(index)->name; }, - .name_get = [&](int index) { return model.animation_get(index)->name; }, - .rename = - [&](int index, const std::string& name) + Actions actions = {}; + actions.add( + ACTION_RENAME, [&]() { return selection.size() == 1 || (selection.empty() && groupSelection.size() == 1); }, + [&]() { + state.newId = selection.size() == 1 ? *selection.begin() : group_key_get(*groupSelection.begin()); + }); + actions.add( + ACTION_ADD, {}, + [&]() { + auto index = + !selection.empty() ? std::min(*selection.rbegin() + 1, count) : group_end_get(targetGroupId()); + auto groupId = selection.empty() ? targetGroupId() : model.animation_group_id_get(*selection.rbegin()); + command_push(panel, [&state, index, groupId](Document& document) { + document.edit_apply(EDIT_ADD_ANIMATION, [&](Model& model) { + auto uids = animation_add(model, index, groupId, document.reference_get().animationIndex, + localize.get(TEXT_NEW_ANIMATION)); + animations_selection_set(document, {index}, {}); + document.reference_set({index}); + state.newId = index; + return uids; + }); + }); + }, + TOOLTIP_ADD_ANIMATION); + actions.add( + ACTION_DUPLICATE, isItemSelected, + [&]() { + auto indices = animation_selected_indices_get(document); + auto start = indices.empty() ? count : std::min(*indices.rbegin() + 1, count); + command_push(panel, [&state, start](Document& document) { + auto text = animation_clipboard_text_get(document); + if (!text.empty()) + animations_insert(state, document, text, start, -1, EDIT_DUPLICATE_ANIMATIONS); + }); + }, + TOOLTIP_DUPLICATE_ANIMATION); + actions.add( + ACTION_MERGE, [&]() { return !animation_selected_indices_get(document).empty(); }, + [&]() { + command_push(panel, [&state](Document& document) { + auto merged = animations_merge(document, {}); + if (merged != -1) + state.scrollId = merged; + }); + }, + TOOLTIP_OPEN_MERGE_POPUP); + actions.add( + ACTION_GROUP, [&]() { return !animation_groupable_indices_get(document).empty(); }, + [&]() { + auto targets = animation_groupable_indices_get(document); + command_push(panel, + [&state, targets = std::set(targets.begin(), targets.end())](Document& document) { + auto groupIds = animation_group_ids_get(document.model); + auto groupId = groupIds.empty() ? 0 : *groupIds.rbegin() + 1; + document.edit_apply(EDIT_GROUP_ITEMS, [&](Model& model) { + auto uids = animations_group(model, targets, localize.get(TEXT_NEW_GROUP)); + animations_selection_set(document, targets, {groupId}); + document.reference_set({*targets.begin()}); + state.scrollId = *targets.begin(); + return uids; + }); + }); + }); + actions.add( + ACTION_REMOVE, isItemSelected, + [&]() { + command_push(panel, [selection, groupSelection](Document& document) { + animations_erase(document, selection, groupSelection, + groupSelection.empty() ? EDIT_REMOVE_ANIMATIONS : EDIT_REMOVE_GROUP); + }); + }, + TOOLTIP_REMOVE_ANIMATION); + actions.add( + ACTION_DEFAULT, [&]() { return selection.size() == 1; }, + [&]() { + command_push(panel, [index = *selection.begin()](Document& document) { + auto animation = document.model.animation_get(index); + if (!animation) + return; + document.edit_apply(EDIT_DEFAULT_ANIMATION, [name = animation->name](Model& model) { + model.animations.defaultAnimation = name; + }); + }); + }, + TOOLTIP_SET_DEFAULT_ANIMATION); + actions.separator(); + actions.add(ACTION_CUT, isItemSelected, [&]() { + clipboard.set(animation_clipboard_text_get(document)); + command_push(panel, + [indices = animation_selected_indices_get(document), groupSelection](Document& document) { + animations_erase(document, indices, groupSelection, EDIT_CUT_ANIMATIONS); + }); + }); + actions.add(ACTION_COPY, isItemSelected, [&]() { clipboard.set(animation_clipboard_text_get(document)); }); + actions.add( + ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, + [&]() { + auto groupId = selection.empty() ? targetGroupId() : -1; + auto start = !selection.empty() ? *selection.rbegin() + 1 : group_end_get(groupId); + command_push(panel, [&state, text = clipboard.get(), start, groupId](Document& document) { + animations_insert(state, document, text, start, groupId, EDIT_PASTE_ANIMATIONS); + }); + }); + + // The footer's merge opens the merge popup (merging into the first selected animation). + auto footerActions = actions; + if (groupSelection.empty()) + std::ranges::find(footerActions.items, ACTION_MERGE, &Action::type)->run = [&]() { + if (selection.empty()) + return; + animations.mergeSelection.clear(); + animations.mergeReference = *selection.begin(); + animations.mergePopup.open(); + }; + + ListRows rows{ + .label_get = [&](int index) { return model.animation_get(index)->name; }, + .name_get = [&](int index) { return model.animation_get(index)->name; }, + .rename = + [&](int index, const std::string& name) { + command_push(panel, [index, name](Document& document) { + document.edit_apply(SNAPSHOT_RENAME_ANIMATION, [&](Model& model) { + auto animation = model.animation_edit(index); + if (!animation) + return; + if (model.animations_count_get() == 1) + model.animations.defaultAnimation = name; + animation->name = name; + }); + }); + }, + .font_get = + [&](int index) { + auto animation = model.animation_get(index); + auto isDefault = animation && model.animations.defaultAnimation == animation->name; + auto isFocused = document.reference_get().animationIndex == index; + return isDefault && isFocused ? FONT_BOLD_ITALICS + : isDefault ? FONT_BOLD + : isFocused ? FONT_ITALICS + : FONT_REGULAR; + }, + .tooltip_draw = + [&](int index) { + auto& animation = *model.animation_get(index); + tooltip_name_draw(resources, animation.name); + if (model.animations.defaultAnimation == animation.name) { - command_push(panel, - [index, name](Document& document) - { - document.edit_apply(SNAPSHOT_RENAME_ANIMATION, - [&](Model& model) - { - auto animation = model.animation_edit(index); - if (!animation) return; - if (model.animations_count_get() == 1) - model.animations.defaultAnimation = name; - animation->name = name; - }); - }); - }, - .font_get = - [&](int index) - { - auto animation = model.animation_get(index); - auto isDefault = animation && model.animations.defaultAnimation == animation->name; - auto isFocused = document.reference_get().animationIndex == index; - return isDefault && isFocused ? FONT_BOLD_ITALICS - : isDefault ? FONT_BOLD - : isFocused ? FONT_ITALICS - : FONT_REGULAR; - }, - .tooltip_draw = - [&](int index) - { - auto& animation = *model.animation_get(index); - tooltip_name_draw(resources, animation.name); - if (model.animations.defaultAnimation == animation.name) - { ImGui::PushFont(resources.fonts[FONT_ITALICS].get(), FONT_SIZE); ImGui::TextUnformatted(localize.get(BASIC_DEFAULT)); ImGui::PopFont(); - } - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_LENGTH), std::make_format_args(animation.frameNum)).c_str()); - auto loopLabel = localize.get(animation.isLoop ? BASIC_YES : BASIC_NO); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_LOOP), std::make_format_args(loopLabel)).c_str()); - }, - .select = - [&](int index) - { - auto& io = ImGui::GetIO(); - if (!io.KeyCtrl && !io.KeyShift) groupSelection.clear(); - document.reference_set({index}); - document.frame_references_clear(); - }, - .drag_drop_update = [&](int index, int) { return animation_row_drag_drop_update(panel, index); }}; + } + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_LENGTH), std::make_format_args(animation.frameNum)).c_str()); + auto loopLabel = localize.get(animation.isLoop ? BASIC_YES : BASIC_NO); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_LOOP), std::make_format_args(loopLabel)).c_str()); + }, + .select = + [&](int index) { + auto& io = ImGui::GetIO(); + if (!io.KeyCtrl && !io.KeyShift) + groupSelection.clear(); + document.reference_set({index}); + document.frame_references_clear(); + }, + .drag_drop_update = [&](int index, int) { return animation_row_drag_drop_update(panel, index); }}; - list_panel_draw( - panel, actions, {{ACTION_ADD, ACTION_DUPLICATE, ACTION_MERGE, ACTION_REMOVE, ACTION_DEFAULT}}, - [&]() - { - std::vector visibleKeys; - state.keys.clear(); - for (int i = 0; i < count; ++i) - state.keys.push_back(i); - animation_entries_each(model, - [&](int index, const Animation* animation, const AnimationGroup* group) - { - if (animation) visibleKeys.push_back(index); - if (group && group->isExpanded) - for (int i = 0; i < (int)group->animations.size(); ++i) - visibleKeys.push_back(index + i); - }); + list_panel_draw( + panel, actions, {{ACTION_ADD, ACTION_DUPLICATE, ACTION_MERGE, ACTION_REMOVE, ACTION_DEFAULT}}, + [&]() { + std::vector visibleKeys; + state.keys.clear(); + for (int i = 0; i < count; ++i) + state.keys.push_back(i); + animation_entries_each(model, [&](int index, const Animation* animation, const AnimationGroup* group) { + if (animation) + visibleKeys.push_back(index); + if (group && group->isExpanded) + for (int i = 0; i < (int)group->animations.size(); ++i) + visibleKeys.push_back(index + i); + }); - auto focus = document.reference_get().animationIndex; - auto arrowKey = list_select_begin(panel, selection, focus, rows, visibleKeys); - auto isRowsDone = false; - animation_entries_each(model, - [&](int index, const Animation* animation, const AnimationGroup* group) - { - if (isRowsDone) return; - if (group) - isRowsDone = animation_group_draw(panel, selection, groupSelection, focus, rows, - *group, index, arrowKey); - else if (animation) - isRowsDone = row_draw(panel, selection, focus, rows, index, index, arrowKey); - }); - list_select_end(panel, selection, focus, rows, arrowKey); - animations_selection_set(document, selection, groupSelection); - }, - false, &footerActions); + auto focus = document.reference_get().animationIndex; + auto arrowKey = list_select_begin(panel, selection, focus, rows, visibleKeys); + auto isRowsDone = false; + animation_entries_each(model, [&](int index, const Animation* animation, const AnimationGroup* group) { + if (isRowsDone) + return; + if (group) + isRowsDone = animation_group_draw(panel, selection, groupSelection, focus, rows, *group, index, + arrowKey); + else if (animation) + isRowsDone = row_draw(panel, selection, focus, rows, index, index, arrowKey); + }); + list_select_end(panel, selection, focus, rows, arrowKey); + animations_selection_set(document, selection, groupSelection); + }, + false, &footerActions); } ImGui::End(); @@ -787,10 +779,11 @@ auto isNext = shortcut(manager.chords[SHORTCUT_NEXT_ANIMATION], SCOPE_GLOBAL); auto isPrevious = shortcut(manager.chords[SHORTCUT_PREVIOUS_ANIMATION], SCOPE_GLOBAL); auto count = model.animations_count_get(); - if ((!isPrevious && !isNext) || count <= 0) return; + if ((!isPrevious && !isNext) || count <= 0) + return; auto reference = document.reference_get(); reference.animationIndex = std::clamp(reference.animationIndex + (isNext ? 1 : -1), 0, count - 1); document.reference_set(reference); animations_selection_set(document, {reference.animationIndex}, animation_groups_selected_get(document)); state.scrollId = reference.animationIndex; - } +} diff --git a/src/ui/autosave_restore.cpp b/src/ui/autosave_restore.cpp index 98c80f7..b1d0314 100644 --- a/src/ui/autosave_restore.cpp +++ b/src/ui/autosave_restore.cpp @@ -5,52 +5,53 @@ #include "path.h" #include "ui/layout.h" - void AutosaveRestore::update(Manager& manager) - { +void AutosaveRestore::update(Manager& manager) +{ if (!isInitialized) { - isInitialized = true; - isRestoreAvailable = !manager.autosaveFiles.empty(); - if (isRestoreAvailable) popup.open(); + isInitialized = true; + isRestoreAvailable = !manager.autosaveFiles.empty(); + if (isRestoreAvailable) + popup.open(); } popup.trigger(); if (isRestoreAvailable && ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) { - ImGui::TextUnformatted(localize.get(LABEL_RESTORE_AUTOSAVES_PROMPT)); + ImGui::TextUnformatted(localize.get(LABEL_RESTORE_AUTOSAVES_PROMPT)); - auto childSize = child_size_get(5); + auto childSize = child_size_get(5); - if (ImGui::BeginChild("##Restore Files Child", childSize, ImGuiChildFlags_Borders, - ImGuiWindowFlags_HorizontalScrollbar)) - { - for (auto& file : manager.autosaveFiles) + if (ImGui::BeginChild("##Restore Files Child", childSize, ImGuiChildFlags_Borders, + ImGuiWindowFlags_HorizontalScrollbar)) { - auto label = std::format(FILE_LABEL_FORMAT, path_to_utf8(file.filename()), path_to_utf8(file)); - ImGui::TextUnformatted(label.c_str()); + for (auto& file : manager.autosaveFiles) + { + auto label = std::format(FILE_LABEL_FORMAT, path_to_utf8(file.filename()), path_to_utf8(file)); + ImGui::TextUnformatted(label.c_str()); + } } - } - ImGui::EndChild(); + ImGui::EndChild(); - auto widgetSize = widget_size_with_row_get(2); + auto widgetSize = widget_size_with_row_get(2); - if (ImGui::Button(localize.get(BASIC_YES), widgetSize)) - { - manager.autosave_files_open(); - isRestoreAvailable = false; - popup.close(); - } + if (ImGui::Button(localize.get(BASIC_YES), widgetSize)) + { + manager.autosave_files_open(); + isRestoreAvailable = false; + popup.close(); + } - ImGui::SameLine(); + ImGui::SameLine(); - if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) - { - manager.autosave_files_clear(true); - isRestoreAvailable = false; - popup.close(); - } + if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) + { + manager.autosave_files_clear(true); + isRestoreAvailable = false; + popup.close(); + } - ImGui::EndPopup(); + ImGui::EndPopup(); } - } +} diff --git a/src/ui/autosave_restore.h b/src/ui/autosave_restore.h index c024af7..308bddf 100644 --- a/src/ui/autosave_restore.h +++ b/src/ui/autosave_restore.h @@ -3,12 +3,12 @@ #include "manager.h" #include "localization.h" - class AutosaveRestore - { +class AutosaveRestore +{ PopupHelper popup = PopupHelper(LABEL_WELCOME_RESTORE_POPUP, POPUP_SMALL_NO_HEIGHT); bool isInitialized = false; bool isRestoreAvailable = false; - public: +public: void update(Manager&); - }; +}; diff --git a/src/ui/canvas_view.cpp b/src/ui/canvas_view.cpp index 82b09f7..c31be03 100644 --- a/src/ui/canvas_view.cpp +++ b/src/ui/canvas_view.cpp @@ -10,14 +10,14 @@ using namespace glm; - CanvasInput canvas_input_get(Manager& manager, bool isFocused) - { - auto key_axis_get = [](ImGuiKey negative, ImGuiKey positive) - { return (float)ImGui::IsKeyPressed(positive) - (float)ImGui::IsKeyPressed(negative); }; - auto is_any = [](auto&& is_key) - { - return is_key(ImGuiKey_LeftArrow) || is_key(ImGuiKey_RightArrow) || is_key(ImGuiKey_UpArrow) || - is_key(ImGuiKey_DownArrow); +CanvasInput canvas_input_get(Manager& manager, bool isFocused) +{ + auto key_axis_get = [](ImGuiKey negative, ImGuiKey positive) { + return (float)ImGui::IsKeyPressed(positive) - (float)ImGui::IsKeyPressed(negative); + }; + auto is_any = [](auto&& is_key) { + return is_key(ImGuiKey_LeftArrow) || is_key(ImGuiKey_RightArrow) || is_key(ImGuiKey_UpArrow) || + is_key(ImGuiKey_DownArrow); }; auto& io = ImGui::GetIO(); auto isMod = ImGui::IsKeyDown(ImGuiMod_Shift); @@ -39,59 +39,62 @@ using namespace glm; .isZoomIn = isFocused && shortcut(manager.chords[SHORTCUT_ZOOM_IN], SCOPE_GLOBAL), .isZoomOut = isFocused && shortcut(manager.chords[SHORTCUT_ZOOM_OUT], SCOPE_GLOBAL), .isMod = isMod}; - } +} - // Whether the canvas rectangle is hovered, known before the canvas image is drawn so input applies this frame. - bool is_canvas_hovered(ImVec2 min, ImVec2 max) - { +// Whether the canvas rectangle is hovered, known before the canvas image is drawn so input applies this frame. +bool is_canvas_hovered(ImVec2 min, ImVec2 max) +{ return ImGui::IsWindowHovered() && ImGui::IsMouseHoveringRect(min, max); - } +} - void edit_begin_push(Manager& manager, StringType label) - { +void edit_begin_push(Manager& manager, StringType label) +{ manager.command_push({manager.selected, [label](Manager&, Document& document) { document.edit_begin(label); }}); - } +} - void document_change_push(Manager& manager) - { +void document_change_push(Manager& manager) +{ manager.command_push({manager.selected, [](Manager&, Document& document) { document.change(); }}); - } +} - void frames_change_push(Manager& manager, const std::set& frames, FrameChange change, ChangeType type) - { - manager.command_push({manager.selected, [=](Manager&, Document& document) - { frames_change_apply(document.model, {.references = frames}, change, type); }}); - } +void frames_change_push(Manager& manager, const std::set& frames, FrameChange change, ChangeType type) +{ + manager.command_push({manager.selected, [=](Manager&, Document& document) { + frames_change_apply(document.model, {.references = frames}, change, type); + }}); +} - // The rectangle spanned by two corners, grown outward to the grid when snapping, in whole pixels. - std::pair rect_snap(vec2 corner, vec2 otherCorner, bool isSnap, ivec2 gridSize, ivec2 gridOffset) - { +// The rectangle spanned by two corners, grown outward to the grid when snapping, in whole pixels. +std::pair rect_snap(vec2 corner, vec2 otherCorner, bool isSnap, ivec2 gridSize, ivec2 gridOffset) +{ auto minPoint = glm::min(corner, otherCorner); auto maxPoint = glm::max(corner, otherCorner); for (int axis = 0; axis < 2 && isSnap; ++axis) { - if (gridSize[axis] == 0) continue; - auto offset = (float)gridOffset[axis]; - auto size = (float)gridSize[axis]; - minPoint[axis] = std::floor((minPoint[axis] - offset) / size) * size + offset; - maxPoint[axis] = std::ceil((maxPoint[axis] - offset) / size) * size + offset; + if (gridSize[axis] == 0) + continue; + auto offset = (float)gridOffset[axis]; + auto size = (float)gridSize[axis]; + minPoint[axis] = std::floor((minPoint[axis] - offset) / size) * size + offset; + maxPoint[axis] = std::ceil((maxPoint[axis] - offset) / size) * size + offset; } return {vec2(ivec2(minPoint)), vec2(ivec2(maxPoint))}; - } +} - void tooltip_lines_draw(std::initializer_list lines) - { - if (!ImGui::BeginTooltip()) return; +void tooltip_lines_draw(std::initializer_list lines) +{ + if (!ImGui::BeginTooltip()) + return; for (auto& line : lines) - ImGui::TextUnformatted(line.c_str()); + ImGui::TextUnformatted(line.c_str()); ImGui::EndTooltip(); - } +} - // The tool's cursor, or a not-allowed cursor and (while in use) why: the tool belongs to the other canvas, or needs - // a spritesheet or a frame first. - void tool_cursor_update(Tool type, ToolArea area, bool isFrameAvailable, bool isSpritesheetAvailable, - bool isUsing, StringType frameHint) - { +// The tool's cursor, or a not-allowed cursor and (while in use) why: the tool belongs to the other canvas, or needs +// a spritesheet or a frame first. +void tool_cursor_update(Tool type, ToolArea area, bool isFrameAvailable, bool isSpritesheetAvailable, bool isUsing, + StringType frameHint) +{ auto& info = TOOLS[type]; auto isAreaAllowed = info.areaType == TOOL_AREA_ALL || info.areaType == area; auto isFrameMissing = info.isFrameRequired && !isFrameAvailable; @@ -99,90 +102,103 @@ using namespace glm; auto isAvailable = isAreaAllowed && !isFrameMissing && !isSpritesheetMissing; ImGui::SetMouseCursor(isAvailable ? info.cursor : ImGuiMouseCursor_NotAllowed); ImGui::SetKeyboardFocusHere(); - if (!isUsing || type == TOOL_PAN || isAvailable) return; + if (!isUsing || type == TOOL_PAN || isAvailable) + return; auto hint = !isAreaAllowed ? (area == TOOL_AREA_ANIMATION_PREVIEW ? TEXT_TOOL_SPRITESHEET_EDITOR : TEXT_TOOL_ANIMATION_PREVIEW) : isSpritesheetMissing ? TEXT_SELECT_SPRITESHEET : frameHint; tooltip_lines_draw({localize.get(hint)}); - } +} - CanvasView::CanvasView() : Canvas(vec2()) {} +CanvasView::CanvasView() : Canvas(vec2()) +{} - bool CanvasView::is_focused_get() const { return isFocused; } +bool CanvasView::is_focused_get() const +{ + return isFocused; +} - void CanvasView::checker_pan_reset(float zoom, vec2 pan) - { +void CanvasView::checker_pan_reset(float zoom, vec2 pan) +{ checkerPan = pan; checkerSyncPan = pan; checkerSyncZoom = zoom; isCheckerPanInitialized = true; hasPendingZoomPanAdjust = false; - } +} - void CanvasView::checker_pan_sync(float zoom, vec2 pan) - { - if (!isCheckerPanInitialized) return checker_pan_reset(zoom, pan); - if (pan == checkerSyncPan && zoom == checkerSyncZoom) return; +void CanvasView::checker_pan_sync(float zoom, vec2 pan) +{ + if (!isCheckerPanInitialized) + return checker_pan_reset(zoom, pan); + if (pan == checkerSyncPan && zoom == checkerSyncZoom) + return; auto isPanDeltaIgnored = hasPendingZoomPanAdjust && zoom != checkerSyncZoom; - if (!isPanDeltaIgnored) checkerPan += pan - checkerSyncPan; + if (!isPanDeltaIgnored) + checkerPan += pan - checkerSyncPan; checkerSyncPan = pan; checkerSyncZoom = zoom; - if (isPanDeltaIgnored) hasPendingZoomPanAdjust = false; - } + if (isPanDeltaIgnored) + hasPendingZoomPanAdjust = false; +} - void CanvasView::zoom_step(float& zoom, vec2& pan, vec2 focus, int levelDelta) - { +void CanvasView::zoom_step(float& zoom, vec2& pan, vec2 focus, int levelDelta) +{ auto previousZoom = zoom; zoom_level_adjust(zoom, pan, focus, levelDelta); - if (zoom != previousZoom) hasPendingZoomPanAdjust = true; - } + if (zoom != previousZoom) + hasPendingZoomPanAdjust = true; +} - void CanvasView::grid_child_draw(ImVec2 childSize, bool& isGrid, vec4& gridColor, ivec2& gridSize, ivec2& gridOffset, - bool* isGridSnap) - { +void CanvasView::grid_child_draw(ImVec2 childSize, bool& isGrid, vec4& gridColor, ivec2& gridSize, ivec2& gridOffset, + bool* isGridSnap) +{ if (ImGui::BeginChild("##Grid Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) { - ImGui::Checkbox(localize.get(BASIC_GRID), &isGrid); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_VISIBILITY)); - if (isGridSnap) - { + ImGui::Checkbox(localize.get(BASIC_GRID), &isGrid); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_VISIBILITY)); + if (isGridSnap) + { + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_SNAP), isGridSnap); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_SNAP)); + } ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_SNAP), isGridSnap); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_SNAP)); - } - ImGui::SameLine(); - ImGui::ColorEdit4(localize.get(BASIC_COLOR), value_ptr(gridColor), ImGuiColorEditFlags_NoInputs); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_COLOR)); + ImGui::ColorEdit4(localize.get(BASIC_COLOR), value_ptr(gridColor), ImGuiColorEditFlags_NoInputs); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_COLOR)); - input_int2_range(localize.get(BASIC_SIZE), gridSize, ivec2(GRID_SIZE_MIN), ivec2(GRID_SIZE_MAX)); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_SIZE)); - input_int2_range(localize.get(BASIC_OFFSET), gridOffset, ivec2(GRID_OFFSET_MIN), ivec2(GRID_OFFSET_MAX)); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_OFFSET)); + input_int2_range(localize.get(BASIC_SIZE), gridSize, ivec2(GRID_SIZE_MIN), ivec2(GRID_SIZE_MAX)); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_SIZE)); + input_int2_range(localize.get(BASIC_OFFSET), gridOffset, ivec2(GRID_OFFSET_MIN), ivec2(GRID_OFFSET_MAX)); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_OFFSET)); } ImGui::EndChild(); - } +} - void CanvasView::view_buttons_draw(Manager& manager, Settings& settings, const std::function& center, - const std::function& fit) - { +void CanvasView::view_buttons_draw(Manager& manager, Settings& settings, const std::function& center, + const std::function& fit) +{ auto widgetSize = widget_size_with_row_get(2); shortcut(manager.chords[SHORTCUT_CENTER_VIEW]); - if (ImGui::Button(localize.get(LABEL_CENTER_VIEW), widgetSize)) center(); + if (ImGui::Button(localize.get(LABEL_CENTER_VIEW), widgetSize)) + center(); set_item_tooltip_shortcut(localize.get(TOOLTIP_CENTER_VIEW), settings.shortcutCenterView); ImGui::SameLine(); shortcut(manager.chords[SHORTCUT_FIT]); - if (ImGui::Button(localize.get(LABEL_FIT), widgetSize)) fit(); + if (ImGui::Button(localize.get(LABEL_FIT), widgetSize)) + fit(); set_item_tooltip_shortcut(localize.get(TOOLTIP_FIT), settings.shortcutFit); - } +} - void CanvasView::view_context_menu_draw(const char* label, Manager& manager, Settings& settings, Document& document, - float& zoom, vec2& pan, const std::function& center, - const std::function& fit, bool isFitEnabled) - { - auto zoom_center_step = [&](int levelDelta) - { zoom_step(zoom, pan, position_translate(zoom, pan, size * 0.5f), levelDelta); }; +void CanvasView::view_context_menu_draw(const char* label, Manager& manager, Settings& settings, Document& document, + float& zoom, vec2& pan, const std::function& center, + const std::function& fit, bool isFitEnabled) +{ + auto zoom_center_step = [&](int levelDelta) { + zoom_step(zoom, pan, position_translate(zoom, pan, size * 0.5f), levelDelta); + }; Actions actions = {}; actions_undo_redo_add(actions, manager, document); @@ -193,4 +209,4 @@ using namespace glm; actions.add(ACTION_ZOOM_IN, []() { return true; }, [&]() { zoom_center_step(ZOOM_LEVEL_STEP); }); actions.add(ACTION_ZOOM_OUT, []() { return true; }, [&]() { zoom_center_step(-ZOOM_LEVEL_STEP); }); actions_context_window_draw(label, actions, settings); - } +} diff --git a/src/ui/canvas_view.h b/src/ui/canvas_view.h index c50ee2b..7e8bfba 100644 --- a/src/ui/canvas_view.h +++ b/src/ui/canvas_view.h @@ -13,9 +13,9 @@ #include "settings.h" #include "tool.h" - // One frame of canvas input. `arrow` is the arrow keys pressed this frame (with key repeat), x right and y down. - struct CanvasInput - { +// One frame of canvas input. `arrow` is the arrow keys pressed this frame (with key repeat), x right and y down. +struct CanvasInput +{ glm::vec2 arrow{}; glm::vec2 mouseDelta{}; float wheel = 0; @@ -33,20 +33,20 @@ bool isZoomIn = false; bool isZoomOut = false; bool isMod = false; - }; +}; - CanvasInput canvas_input_get(Manager&, bool); - bool is_canvas_hovered(ImVec2, ImVec2); - void edit_begin_push(Manager&, StringType); - void document_change_push(Manager&); - void frames_change_push(Manager&, const std::set&, FrameChange, ChangeType = ChangeType::ADJUST); - std::pair rect_snap(glm::vec2, glm::vec2, bool, glm::ivec2, glm::ivec2); - void tooltip_lines_draw(std::initializer_list); - void tool_cursor_update(Tool, ToolArea, bool, bool, bool, StringType); +CanvasInput canvas_input_get(Manager&, bool); +bool is_canvas_hovered(ImVec2, ImVec2); +void edit_begin_push(Manager&, StringType); +void document_change_push(Manager&); +void frames_change_push(Manager&, const std::set&, FrameChange, ChangeType = ChangeType::ADJUST); +std::pair rect_snap(glm::vec2, glm::vec2, bool, glm::ivec2, glm::ivec2); +void tooltip_lines_draw(std::initializer_list); +void tool_cursor_update(Tool, ToolArea, bool, bool, bool, StringType); - class CanvasView : public Canvas - { - protected: +class CanvasView : public Canvas +{ +protected: glm::vec2 mousePos{}; glm::vec2 checkerPan{}; glm::vec2 checkerSyncPan{}; @@ -63,7 +63,7 @@ void view_context_menu_draw(const char*, Manager&, Settings&, Document&, float&, glm::vec2&, const std::function&, const std::function&, bool); - public: +public: CanvasView(); bool is_focused_get() const; - }; +}; diff --git a/src/ui/change_all_frame_properties.cpp b/src/ui/change_all_frame_properties.cpp index b036aff..a6e854c 100644 --- a/src/ui/change_all_frame_properties.cpp +++ b/src/ui/change_all_frame_properties.cpp @@ -16,48 +16,48 @@ using namespace glm; - constexpr int CHANGE_TYPE_COUNT = 5; - constexpr const char* COLOR_COMPONENT_FORMATS[] = {"R:%d", "G:%d", "B:%d", "A:%d"}; +constexpr int CHANGE_TYPE_COUNT = 5; +constexpr const char* COLOR_COMPONENT_FORMATS[] = {"R:%d", "G:%d", "B:%d", "A:%d"}; - enum ChangeDestination - { +enum ChangeDestination +{ CHANGE_DESTINATION_FRAMES, CHANGE_DESTINATION_ANIMATIONS, CHANGE_DESTINATION_ITEMS, - }; +}; - struct ChangeButton - { +struct ChangeButton +{ const char* symbol; StringType label; StringType tooltip; ChangeType type; - }; +}; - constexpr ChangeButton CHANGE_BUTTONS[CHANGE_TYPE_COUNT] = { - {"=", LABEL_ADJUST, TOOLTIP_ADJUST, ChangeType::ADJUST}, - {"+", BASIC_ADD, TOOLTIP_ADD_VALUES, ChangeType::ADD}, - {"-", LABEL_SUBTRACT, TOOLTIP_SUBTRACT_VALUES, ChangeType::SUBTRACT}, - {"\u00D7", LABEL_MULTIPLY, TOOLTIP_MULTIPLY_VALUES, ChangeType::MULTIPLY}, - {"\u00F7", LABEL_DIVIDE, TOOLTIP_DIVIDE_VALUES, ChangeType::DIVIDE}}; +constexpr ChangeButton CHANGE_BUTTONS[CHANGE_TYPE_COUNT] = { + {"=", LABEL_ADJUST, TOOLTIP_ADJUST, ChangeType::ADJUST}, + {"+", BASIC_ADD, TOOLTIP_ADD_VALUES, ChangeType::ADD}, + {"-", LABEL_SUBTRACT, TOOLTIP_SUBTRACT_VALUES, ChangeType::SUBTRACT}, + {"\u00D7", LABEL_MULTIPLY, TOOLTIP_MULTIPLY_VALUES, ChangeType::MULTIPLY}, + {"\u00F7", LABEL_DIVIDE, TOOLTIP_DIVIDE_VALUES, ChangeType::DIVIDE}}; - struct ComponentRow - { +struct ComponentRow +{ StringType label; std::vector isEnabled; float* values; bool isLayerOnly; - }; +}; - static void property_toggle_begin(bool& isEnabled) - { +static void property_toggle_begin(bool& isEnabled) +{ ImGui::Checkbox("##Is Enabled", &isEnabled); ImGui::SameLine(); ImGui::BeginDisabled(!isEnabled); - } +} - static void components_draw(const ComponentRow& row, bool isColor) - { +static void components_draw(const ComponentRow& row, bool isColor) +{ auto count = (int)row.isEnabled.size(); auto label = localize.get(row.label); auto& style = ImGui::GetStyle(); @@ -68,35 +68,38 @@ using namespace glm; ImGui::PushItemWidth(width); for (int i = 0; i < count; ++i) { - ImGui::PushID(i); - if (i > 0) ImGui::SameLine(); - property_toggle_begin(*row.isEnabled[i]); - auto valueLabel = !isColor && i == count - 1 ? label : "##Value"; - if (isColor) - { - auto value = float_to_uint8(row.values[i]); - if (ImGui::DragInt(valueLabel, &value, DRAG_SPEED, 0, 0, COLOR_COMPONENT_FORMATS[i])) - row.values[i] = uint8_to_float(value); - } - else - ImGui::DragFloat(valueLabel, &row.values[i], DRAG_SPEED, 0.0f, 0.0f, float_format_get(row.values[i])); - ImGui::EndDisabled(); - ImGui::PopID(); + ImGui::PushID(i); + if (i > 0) + ImGui::SameLine(); + property_toggle_begin(*row.isEnabled[i]); + auto valueLabel = !isColor && i == count - 1 ? label : "##Value"; + if (isColor) + { + auto value = float_to_uint8(row.values[i]); + if (ImGui::DragInt(valueLabel, &value, DRAG_SPEED, 0, 0, COLOR_COMPONENT_FORMATS[i])) + row.values[i] = uint8_to_float(value); + } + else + ImGui::DragFloat(valueLabel, &row.values[i], DRAG_SPEED, 0.0f, 0.0f, float_format_get(row.values[i])); + ImGui::EndDisabled(); + ImGui::PopID(); } ImGui::PopItemWidth(); - if (!isColor) return; + if (!isColor) + return; ImVec4 buttonColor = {0.0f, 0.0f, 0.0f, 1.0f}; for (int i = 0; i < count; ++i) - if (*row.isEnabled[i]) (&buttonColor.x)[i] = glm::clamp(row.values[i], 0.0f, 1.0f); + if (*row.isEnabled[i]) + (&buttonColor.x)[i] = glm::clamp(row.values[i], 0.0f, 1.0f); ImGui::SameLine(); ImGui::ColorButton(label, buttonColor); ImGui::SameLine(); ImGui::TextUnformatted(label); - } +} - void ChangeAllFrameProperties::update(Manager& manager, Document& document, Settings& settings, bool isFromWizard) - { +void ChangeAllFrameProperties::update(Manager& manager, Document& document, Settings& settings, bool isFromWizard) +{ isChanged = false; auto animations = document.animations_selected_get(); @@ -109,8 +112,8 @@ using namespace glm; auto selectedItemReferences = document.selected_get(SelectionKind::TRACKS); if (auto reference = document.reference_get(); selectedItemReferences.empty() && reference.itemType != NONE) { - reference.frameIndex = -1; - selectedItemReferences.insert(reference); + reference.frameIndex = -1; + selectedItemReferences.insert(reference); } std::erase_if(selectedItemReferences, [](const Reference& reference) { return reference.itemType == TRIGGER; }); @@ -119,43 +122,44 @@ using namespace glm; bool isSelectedAnimationsAvailable = !animations.empty(); if (isFromWizard) { - if (destination == CHANGE_DESTINATION_FRAMES && !isSelectedFramesAvailable) - destination = isSelectedItemsAvailable ? CHANGE_DESTINATION_ITEMS : CHANGE_DESTINATION_ANIMATIONS; - if (destination == CHANGE_DESTINATION_ITEMS && !isSelectedItemsAvailable) - destination = isSelectedFramesAvailable ? CHANGE_DESTINATION_FRAMES : CHANGE_DESTINATION_ANIMATIONS; - if (destination == CHANGE_DESTINATION_ANIMATIONS && !isSelectedAnimationsAvailable && isSelectedItemsAvailable) - destination = CHANGE_DESTINATION_ITEMS; - if (destination == CHANGE_DESTINATION_ANIMATIONS && !isSelectedAnimationsAvailable && isSelectedFramesAvailable) - destination = CHANGE_DESTINATION_FRAMES; + if (destination == CHANGE_DESTINATION_FRAMES && !isSelectedFramesAvailable) + destination = isSelectedItemsAvailable ? CHANGE_DESTINATION_ITEMS : CHANGE_DESTINATION_ANIMATIONS; + if (destination == CHANGE_DESTINATION_ITEMS && !isSelectedItemsAvailable) + destination = isSelectedFramesAvailable ? CHANGE_DESTINATION_FRAMES : CHANGE_DESTINATION_ANIMATIONS; + if (destination == CHANGE_DESTINATION_ANIMATIONS && !isSelectedAnimationsAvailable && isSelectedItemsAvailable) + destination = CHANGE_DESTINATION_ITEMS; + if (destination == CHANGE_DESTINATION_ANIMATIONS && !isSelectedAnimationsAvailable && isSelectedFramesAvailable) + destination = CHANGE_DESTINATION_FRAMES; } bool isFramesDestination = !isFromWizard || destination == CHANGE_DESTINATION_FRAMES; bool isItemsDestination = isFromWizard && destination == CHANGE_DESTINATION_ITEMS; - auto is_layer = [](const Reference& reference) { return reference.itemType == LAYER; }; + auto is_layer = [](const Reference& reference) { + return reference.itemType == LAYER; + }; auto isLayerPropertyAvailable = isFramesDestination ? std::ranges::any_of(selectedFrameReferences, is_layer) : isItemsDestination ? std::ranges::any_of(selectedItemReferences, is_layer) : settings.changeIsLayers; - // Child properties reach animation layers only; their choices are every such layer's animations. - auto animation_layer_get = [&](const Reference& reference) -> const Layer* - { - auto layer = is_layer(reference) ? item_get(document.model.content.layers, reference.itemID) : nullptr; - return layer && layer->is_animation() ? layer : nullptr; + // Child properties reach animation layers only. Their choices are every such layer's animations. + auto animation_layer_get = [&](const Reference& reference) -> const Layer* { + auto layer = is_layer(reference) ? item_get(document.model.content.layers, reference.itemID) : nullptr; + return layer && layer->is_animation() ? layer : nullptr; }; std::set childAnimations; bool isChildPropertyAvailable = false; - auto child_layer_add = [&](const Layer* layer) - { - if (!layer || !layer->is_animation()) return; - isChildPropertyAvailable = true; - for (auto& name : document.animation_names_get(layer->libraryId)) - childAnimations.insert(name); + auto child_layer_add = [&](const Layer* layer) { + if (!layer || !layer->is_animation()) + return; + isChildPropertyAvailable = true; + for (auto& name : document.animation_names_get(layer->libraryId)) + childAnimations.insert(name); }; if (isFramesDestination || isItemsDestination) - for (auto& reference : isFramesDestination ? selectedFrameReferences : selectedItemReferences) - child_layer_add(animation_layer_get(reference)); + for (auto& reference : isFramesDestination ? selectedFrameReferences : selectedItemReferences) + child_layer_add(animation_layer_get(reference)); else if (settings.changeIsLayers) - for (auto& layer : document.model.content.layers) - child_layer_add(&layer); + for (auto& layer : document.model.content.layers) + child_layer_add(&layer); ComponentRow componentRows[] = { {BASIC_CROP, {&settings.changeIsCropX, &settings.changeIsCropY}, value_ptr(settings.changeCrop), true}, @@ -180,49 +184,48 @@ using namespace glm; value_ptr(settings.changeColorOffset), false}}; - auto rows_draw = [&](std::span rows, bool isColor) - { - for (auto& row : rows) - { - ImGui::PushID(row.label); - ImGui::BeginDisabled(row.isLayerOnly && !isLayerPropertyAvailable); - components_draw(row, isColor); - ImGui::EndDisabled(); - ImGui::PopID(); - } + auto rows_draw = [&](std::span rows, bool isColor) { + for (auto& row : rows) + { + ImGui::PushID(row.label); + ImGui::BeginDisabled(row.isLayerOnly && !isLayerPropertyAvailable); + components_draw(row, isColor); + ImGui::EndDisabled(); + ImGui::PopID(); + } }; auto combo_draw = [&](const char* id, StringType label, bool& isEnabled, int& value, const std::vector& ids, - const std::vector& labels) - { - ImGui::PushID(id); - if (std::ranges::find(ids, value) == ids.end()) value = ids.front(); - property_toggle_begin(isEnabled); - combo_id_mapped(localize.get(label), &value, ids, labels); - ImGui::EndDisabled(); - ImGui::PopID(); + const std::vector& labels) { + ImGui::PushID(id); + if (std::ranges::find(ids, value) == ids.end()) + value = ids.front(); + property_toggle_begin(isEnabled); + combo_id_mapped(localize.get(label), &value, ids, labels); + ImGui::EndDisabled(); + ImGui::PopID(); }; - auto bool_draw = [&](const char* id, StringType label, bool& isEnabled, bool& value) - { - ImGui::PushID(id); - property_toggle_begin(isEnabled); - ImGui::Checkbox(localize.get(label), &value); - ImGui::EndDisabled(); - ImGui::PopID(); + auto bool_draw = [&](const char* id, StringType label, bool& isEnabled, bool& value) { + ImGui::PushID(id); + property_toggle_begin(isEnabled); + ImGui::Checkbox(localize.get(label), &value); + ImGui::EndDisabled(); + ImGui::PopID(); }; std::vector interpolationIds; std::vector interpolationLabels; for (int i = 0; i < (int)std::size(INTERPOLATION_LABELS); ++i) { - interpolationIds.push_back(i); - interpolationLabels.push_back(localize.get(INTERPOLATION_LABELS[i])); + interpolationIds.push_back(i); + interpolationLabels.push_back(localize.get(INTERPOLATION_LABELS[i])); } auto regions = document.choices_get( SelectionKind::REGIONS, document.reference_get().itemType == LAYER ? document.reference_get().itemID : -1); auto shaders = document.choices_get(SelectionKind::SHADERS); - if (!isLayerPropertyAvailable) regionId = shaderId = -1; + if (!isLayerPropertyAvailable) + regionId = shaderId = -1; ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImGui::GetStyle().ItemInnerSpacing); rows_draw(componentRows, false); @@ -259,128 +262,143 @@ using namespace glm; ImGui::SeparatorText(localize.get(LABEL_CHILD)); ImGui::BeginDisabled(!isChildPropertyAvailable); { - std::vector values{std::string{}}; - std::vector labels{localize.get(TEXT_LAYER_ANIMATION)}; - values.insert(values.end(), childAnimations.begin(), childAnimations.end()); - labels.insert(labels.end(), childAnimations.begin(), childAnimations.end()); - ImGui::PushID("Child Animation"); - property_toggle_begin(settings.changeIsChildAnimation); - combo_string_mapped(localize.get(LABEL_ANIMATION), &settings.changeChildAnimation, values, labels); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_ANIMATION)); - ImGui::EndDisabled(); - ImGui::PopID(); + std::vector values{std::string{}}; + std::vector labels{localize.get(TEXT_LAYER_ANIMATION)}; + values.insert(values.end(), childAnimations.begin(), childAnimations.end()); + labels.insert(labels.end(), childAnimations.begin(), childAnimations.end()); + ImGui::PushID("Child Animation"); + property_toggle_begin(settings.changeIsChildAnimation); + combo_string_mapped(localize.get(LABEL_ANIMATION), &settings.changeChildAnimation, values, labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_ANIMATION)); + ImGui::EndDisabled(); + ImGui::PopID(); - std::vector modeIds; - std::vector modeLabels; - for (int i = 0; i < (int)std::size(CHILD_MODE_LABELS); ++i) - { - modeIds.push_back(i); - modeLabels.push_back(localize.get(CHILD_MODE_LABELS[i])); - } - combo_draw("Child Mode", BASIC_MODE, settings.changeIsChildMode, settings.changeChildMode, modeIds, modeLabels); + std::vector modeIds; + std::vector modeLabels; + for (int i = 0; i < (int)std::size(CHILD_MODE_LABELS); ++i) + { + modeIds.push_back(i); + modeLabels.push_back(localize.get(CHILD_MODE_LABELS[i])); + } + combo_draw("Child Mode", BASIC_MODE, settings.changeIsChildMode, settings.changeChildMode, modeIds, modeLabels); - ImGui::PushID("Child Start"); - property_toggle_begin(settings.changeIsChildStart); - input_int_range(localize.get(LABEL_START_FRAME), settings.changeChildStart, 0, FRAME_NUM_MAX, STEP, STEP_FAST); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_START)); - ImGui::EndDisabled(); - ImGui::PopID(); + ImGui::PushID("Child Start"); + property_toggle_begin(settings.changeIsChildStart); + input_int_range(localize.get(LABEL_START_FRAME), settings.changeChildStart, 0, FRAME_NUM_MAX, STEP, STEP_FAST); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_START)); + ImGui::EndDisabled(); + ImGui::PopID(); - bool_draw("Child Random", LABEL_RANDOM, settings.changeIsChildStartRandomSet, settings.changeIsChildStartRandom); - ImGui::SameLine(); - bool_draw("Child Restart", LABEL_RESTART, settings.changeIsChildRestartSet, settings.changeIsChildRestart); + bool_draw("Child Random", LABEL_RANDOM, settings.changeIsChildStartRandomSet, + settings.changeIsChildStartRandom); + ImGui::SameLine(); + bool_draw("Child Restart", LABEL_RESTART, settings.changeIsChildRestartSet, settings.changeIsChildRestart); } ImGui::EndDisabled(); ImGui::PopStyleVar(); - auto frame_change = [&](ChangeType changeType) - { - auto isColorScaled = changeType == ChangeType::MULTIPLY || changeType == ChangeType::DIVIDE; - FrameChange frameChange; + auto frame_change = [&](ChangeType changeType) { + auto isColorScaled = changeType == ChangeType::MULTIPLY || changeType == ChangeType::DIVIDE; + FrameChange frameChange; #define X(name, member, isLayerOnly, isColor, isEnabled, value) \ - if (settings.isEnabled) \ - frameChange.name = isColor && isColorScaled ? (float)float_to_uint8(settings.value) : settings.value; - FRAME_CHANGE_SCALARS + if (settings.isEnabled) \ + frameChange.name = isColor && isColorScaled ? (float)float_to_uint8(settings.value) : settings.value; + FRAME_CHANGE_SCALARS #undef X - if (settings.changeIsDuration) frameChange.duration = settings.changeDuration; - if (settings.changeIsDepth) frameChange.depth = settings.changeDepth; - if (settings.changeIsRegion) frameChange.regionId = regionId; - if (settings.changeIsShader) frameChange.shaderId = shaderId; - if (settings.changeIsVisibleSet) frameChange.isVisible = settings.changeIsVisible; - if (settings.changeIsInterpolationSet) frameChange.interpolation = (Interpolation)settings.changeInterpolation; - if (settings.changeIsFlipXSet) frameChange.isFlipX = settings.changeIsFlipX; - if (settings.changeIsFlipYSet) frameChange.isFlipY = settings.changeIsFlipY; - if (isChildPropertyAvailable) - { - if (settings.changeIsChildAnimation) frameChange.childAnimation = settings.changeChildAnimation; - if (settings.changeIsChildMode) frameChange.childMode = (ChildMode)settings.changeChildMode; - if (settings.changeIsChildStart) frameChange.childStart = settings.changeChildStart; - if (settings.changeIsChildStartRandomSet) frameChange.isChildStartRandom = settings.changeIsChildStartRandom; - if (settings.changeIsChildRestartSet) frameChange.isChildRestart = settings.changeIsChildRestart; - } + if (settings.changeIsDuration) + frameChange.duration = settings.changeDuration; + if (settings.changeIsDepth) + frameChange.depth = settings.changeDepth; + if (settings.changeIsRegion) + frameChange.regionId = regionId; + if (settings.changeIsShader) + frameChange.shaderId = shaderId; + if (settings.changeIsVisibleSet) + frameChange.isVisible = settings.changeIsVisible; + if (settings.changeIsInterpolationSet) + frameChange.interpolation = (Interpolation)settings.changeInterpolation; + if (settings.changeIsFlipXSet) + frameChange.isFlipX = settings.changeIsFlipX; + if (settings.changeIsFlipYSet) + frameChange.isFlipY = settings.changeIsFlipY; + if (isChildPropertyAvailable) + { + if (settings.changeIsChildAnimation) + frameChange.childAnimation = settings.changeChildAnimation; + if (settings.changeIsChildMode) + frameChange.childMode = (ChildMode)settings.changeChildMode; + if (settings.changeIsChildStart) + frameChange.childStart = settings.changeChildStart; + if (settings.changeIsChildStartRandomSet) + frameChange.isChildStartRandom = settings.changeIsChildStartRandom; + if (settings.changeIsChildRestartSet) + frameChange.isChildRestart = settings.changeIsChildRestart; + } - manager.command_push( - {manager.selected, - [=, queuedAnimations = std::set(animations.begin(), animations.end()), isRoot = settings.changeIsRoot, - isLayers = settings.changeIsLayers, isNulls = settings.changeIsNulls](Manager&, Document& document) - { - ChangeTargets targets = {.isRoot = isRoot, .isLayers = isLayers, .isNulls = isNulls}; - if (isFramesDestination) - targets.references = {selectedFrameReferences.begin(), selectedFrameReferences.end()}; - else if (isItemsDestination) - targets.references = {selectedItemReferences.begin(), selectedItemReferences.end()}; - else - targets.animations = queuedAnimations; - document.edit_apply(EDIT_CHANGE_FRAME_PROPERTIES, [&](Model& model) - { return frames_change_apply(model, targets, frameChange, changeType); }); - }}); - isChanged = true; + manager.command_push( + {manager.selected, + [=, queuedAnimations = std::set(animations.begin(), animations.end()), isRoot = settings.changeIsRoot, + isLayers = settings.changeIsLayers, isNulls = settings.changeIsNulls](Manager&, Document& document) { + ChangeTargets targets = {.isRoot = isRoot, .isLayers = isLayers, .isNulls = isNulls}; + if (isFramesDestination) + targets.references = {selectedFrameReferences.begin(), selectedFrameReferences.end()}; + else if (isItemsDestination) + targets.references = {selectedItemReferences.begin(), selectedItemReferences.end()}; + else + targets.animations = queuedAnimations; + document.edit_apply(EDIT_CHANGE_FRAME_PROPERTIES, [&](Model& model) { + return frames_change_apply(model, targets, frameChange, changeType); + }); + }}); + isChanged = true; }; ImGui::Separator(); if (isFromWizard) { - ImGui::SeparatorText(localize.get(LABEL_DESTINATION)); - struct DestinationOption - { - StringType label; - StringType tooltip; - ChangeDestination value; - bool isAvailable; - }; - DestinationOption destinationOptions[] = { - {BASIC_FRAMES, TOOLTIP_CHANGE_ALL_DESTINATION_FRAMES, CHANGE_DESTINATION_FRAMES, isSelectedFramesAvailable}, - {LABEL_ITEMS, TOOLTIP_CHANGE_ALL_DESTINATION_ITEMS, CHANGE_DESTINATION_ITEMS, isSelectedItemsAvailable}, - {LABEL_ANIMATIONS_CHILD, TOOLTIP_CHANGE_ALL_DESTINATION_ANIMATIONS, CHANGE_DESTINATION_ANIMATIONS, - isSelectedAnimationsAvailable}}; - for (auto& option : destinationOptions) - { - if (option.value != CHANGE_DESTINATION_FRAMES) ImGui::SameLine(); - ImGui::BeginDisabled(!option.isAvailable); - ImGui::RadioButton(localize.get(option.label), &destination, option.value); - ImGui::SetItemTooltip("%s", localize.get(option.tooltip)); - ImGui::EndDisabled(); - } + ImGui::SeparatorText(localize.get(LABEL_DESTINATION)); + struct DestinationOption + { + StringType label; + StringType tooltip; + ChangeDestination value; + bool isAvailable; + }; + DestinationOption destinationOptions[] = { + {BASIC_FRAMES, TOOLTIP_CHANGE_ALL_DESTINATION_FRAMES, CHANGE_DESTINATION_FRAMES, isSelectedFramesAvailable}, + {LABEL_ITEMS, TOOLTIP_CHANGE_ALL_DESTINATION_ITEMS, CHANGE_DESTINATION_ITEMS, isSelectedItemsAvailable}, + {LABEL_ANIMATIONS_CHILD, TOOLTIP_CHANGE_ALL_DESTINATION_ANIMATIONS, CHANGE_DESTINATION_ANIMATIONS, + isSelectedAnimationsAvailable}}; + for (auto& option : destinationOptions) + { + if (option.value != CHANGE_DESTINATION_FRAMES) + ImGui::SameLine(); + ImGui::BeginDisabled(!option.isAvailable); + ImGui::RadioButton(localize.get(option.label), &destination, option.value); + ImGui::SetItemTooltip("%s", localize.get(option.tooltip)); + ImGui::EndDisabled(); + } - struct TargetOption - { - StringType label; - StringType tooltip; - bool& value; - }; - TargetOption targetOptions[] = {{LABEL_ROOT, TOOLTIP_CHANGE_ALL_ROOT, settings.changeIsRoot}, - {LABEL_LAYERS, TOOLTIP_CHANGE_ALL_LAYERS, settings.changeIsLayers}, - {LABEL_NULLS, TOOLTIP_CHANGE_ALL_NULLS, settings.changeIsNulls}}; - ImGui::BeginDisabled(isFramesDestination || isItemsDestination); - for (auto& option : targetOptions) - { - if (&option != targetOptions) ImGui::SameLine(); - ImGui::Checkbox(localize.get(option.label), &option.value); - ImGui::SetItemTooltip("%s", localize.get(option.tooltip)); - } - ImGui::EndDisabled(); - ImGui::Separator(); + struct TargetOption + { + StringType label; + StringType tooltip; + bool& value; + }; + TargetOption targetOptions[] = {{LABEL_ROOT, TOOLTIP_CHANGE_ALL_ROOT, settings.changeIsRoot}, + {LABEL_LAYERS, TOOLTIP_CHANGE_ALL_LAYERS, settings.changeIsLayers}, + {LABEL_NULLS, TOOLTIP_CHANGE_ALL_NULLS, settings.changeIsNulls}}; + ImGui::BeginDisabled(isFramesDestination || isItemsDestination); + for (auto& option : targetOptions) + { + if (&option != targetOptions) + ImGui::SameLine(); + ImGui::Checkbox(localize.get(option.label), &option.value); + ImGui::SetItemTooltip("%s", localize.get(option.tooltip)); + } + ImGui::EndDisabled(); + ImGui::Separator(); } bool isAnyProperty = @@ -404,10 +422,11 @@ using namespace glm; ImGui::BeginDisabled(!isAnyProperty || !isDestinationValid); for (auto& button : CHANGE_BUTTONS) { - if (&button != CHANGE_BUTTONS) ImGui::SameLine(); - if (ImGui::Button(std::format("{} {}", button.symbol, localize.get(button.label)).c_str(), rowWidgetSize)) - frame_change(button.type); - ImGui::SetItemTooltip("%s", localize.get(button.tooltip)); + if (&button != CHANGE_BUTTONS) + ImGui::SameLine(); + if (ImGui::Button(std::format("{} {}", button.symbol, localize.get(button.label)).c_str(), rowWidgetSize)) + frame_change(button.type); + ImGui::SetItemTooltip("%s", localize.get(button.tooltip)); } ImGui::EndDisabled(); - } +} diff --git a/src/ui/change_all_frame_properties.h b/src/ui/change_all_frame_properties.h index ec2faf0..dbdd7f3 100644 --- a/src/ui/change_all_frame_properties.h +++ b/src/ui/change_all_frame_properties.h @@ -4,14 +4,14 @@ #include "manager.h" #include "settings.h" - inline constexpr StringType INTERPOLATION_LABELS[] = {BASIC_NONE, BASIC_LINEAR, BASIC_EASE_IN, BASIC_EASE_OUT, - BASIC_EASE_IN_OUT}; - inline constexpr StringType CHILD_MODE_LABELS[] = {LABEL_LOOP, LABEL_ONCE, LABEL_HOLD}; +inline constexpr StringType INTERPOLATION_LABELS[] = {BASIC_NONE, BASIC_LINEAR, BASIC_EASE_IN, BASIC_EASE_OUT, + BASIC_EASE_IN_OUT}; +inline constexpr StringType CHILD_MODE_LABELS[] = {LABEL_LOOP, LABEL_ONCE, LABEL_HOLD}; - class ChangeAllFrameProperties - { - public: +class ChangeAllFrameProperties +{ +public: bool isChanged = false; void update(Manager&, Document&, Settings&, bool = false); - }; +}; diff --git a/src/ui/configure.cpp b/src/ui/configure.cpp index 5b8cc60..bc2e4b5 100644 --- a/src/ui/configure.cpp +++ b/src/ui/configure.cpp @@ -7,178 +7,186 @@ #include "ui/shortcut.h" #include "ui/theme.h" - void Configure::reset(Settings& settings) { temporary = settings; } +void Configure::reset(Settings& settings) +{ + temporary = settings; +} - void Configure::update(Manager& manager, Settings& settings) - { +void Configure::update(Manager& manager, Settings& settings) +{ isSet = false; auto childSize = size_without_footer_get(2); if (ImGui::BeginTabBar("##Configure Tabs")) { - if (ImGui::BeginTabItem(localize.get(LABEL_DISPLAY))) - { - if (ImGui::BeginChild("##Tab Child", childSize, true)) + if (ImGui::BeginTabItem(localize.get(LABEL_DISPLAY))) { - ImGui::SeparatorText(localize.get(LABEL_WINDOW_MENU)); - input_float_range(localize.get(LABEL_UI_SCALE), temporary.uiScale, UI_SCALE_MIN, UI_SCALE_MAX, UI_SCALE_STEP, - UI_SCALE_STEP, "%.0f%%"); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_UI_SCALE)); - ImGui::Checkbox(localize.get(LABEL_VSYNC), &temporary.isVsync); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_VSYNC)); - ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_DETACHABLE_WINDOWS), &temporary.isDetachableWindows); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DETACHABLE_WINDOWS)); - - ImGui::SeparatorText(localize.get(LABEL_PLAYBACK_MENU)); - ImGui::RadioButton("30 Hz", &temporary.playbackTickRate, 30); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PLAYBACK_TICK_RATE)); - ImGui::SameLine(); - ImGui::RadioButton("60 Hz", &temporary.playbackTickRate, 60); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PLAYBACK_TICK_RATE)); - - ImGui::SeparatorText(localize.get(LABEL_LOCALIZATION)); - ImGui::Combo(localize.get(LABEL_LANGUAGE), &temporary.language, LANGUAGE_STRINGS, LANGUAGE_COUNT); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LANGUAGE)); - - ImGui::SeparatorText(localize.get(LABEL_THEME)); - - for (int i = 0; i < THEME_COUNT; i++) - { - ImGui::RadioButton(localize.get(THEME_STRINGS[i]), &temporary.theme, i); - ImGui::SameLine(); - } - } - ImGui::EndChild(); - - ImGui::EndTabItem(); - } - - if (ImGui::BeginTabItem(localize.get(LABEL_FILE_MENU))) - { - if (ImGui::BeginChild("##Tab Child", childSize, true)) - { - ImGui::SeparatorText(localize.get(LABEL_AUTOSAVE)); - - ImGui::Checkbox(localize.get(BASIC_ENABLED), &temporary.fileIsAutosave); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTOSAVE_ENABLED)); - - ImGui::SeparatorText(localize.get(LABEL_AUTO_RESOURCE_RELOAD)); - ImGui::PushID(LABEL_AUTO_RESOURCE_RELOAD); - ImGui::Checkbox(localize.get(BASIC_ENABLED), &temporary.fileIsAutoReloadResources); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTO_RESOURCE_RELOAD)); - ImGui::PopID(); - - ImGui::SeparatorText(localize.get(LABEL_SNAPSHOTS)); - input_int_range(localize.get(LABEL_STACK_SIZE), temporary.fileSnapshotStackSize, 0, 100); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_STACK_SIZE)); - - ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); - ImGui::Checkbox(localize.get(LABEL_OVERWRITE_WARNING), &temporary.fileIsWarnOverwrite); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERWRITE_WARNING)); - ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_ISAAC_COMPATIBILITY_WARNING), &temporary.fileIsWarnIsaac); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ISAAC_COMPATIBILITY_WARNING)); - - ImGui::SeparatorText(localize.get(LABEL_SERIALIZATION)); - ImGui::Checkbox(localize.get(LABEL_SAVE_AS_JSON), &temporary.fileIsJson); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SAVE_AS_JSON)); - } - ImGui::EndChild(); - - ImGui::EndTabItem(); - } - - if (ImGui::BeginTabItem(localize.get(LABEL_INPUT))) - { - if (ImGui::BeginChild("##Tab Child", childSize, true)) - { - ImGui::SeparatorText(localize.get(LABEL_KEYBOARD)); - - input_float_range(localize.get(LABEL_REPEAT_DELAY), temporary.keyboardRepeatDelay, 0.05f, 1.0f, 0.05f, 0.05f, - "%.2f"); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REPEAT_DELAY)); - - input_float_range(localize.get(LABEL_REPEAT_RATE), temporary.keyboardRepeatRate, 0.005f, 1.0f, 0.005f, 0.005f, - "%.3f"); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REPEAT_DELAY)); - - ImGui::SeparatorText(localize.get(LABEL_TOOL)); - - ImGui::Checkbox(localize.get(LABEL_MOVE_TOOL_SNAP), &temporary.inputIsMoveToolSnapToMouse); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MOVE_TOOL_SNAP)); - } - ImGui::EndChild(); - - ImGui::EndTabItem(); - } - - if (ImGui::BeginTabItem(localize.get(LABEL_SHORTCUTS_TAB))) - { - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - - if (ImGui::BeginChild("##Tab Child", childSize, true)) - { - if (ImGui::BeginTable(localize.get(LABEL_SHORTCUTS_TAB), 2, - ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) - { - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn(localize.get(LABEL_SHORTCUT_COLUMN)); - ImGui::TableSetupColumn(localize.get(LABEL_VALUE_COLUMN)); - ImGui::TableHeadersRow(); - - for (int i = 0; i < SHORTCUT_COUNT; ++i) + if (ImGui::BeginChild("##Tab Child", childSize, true)) { - bool isSelected = selectedShortcut == i; + ImGui::SeparatorText(localize.get(LABEL_WINDOW_MENU)); + input_float_range(localize.get(LABEL_UI_SCALE), temporary.uiScale, UI_SCALE_MIN, UI_SCALE_MAX, + UI_SCALE_STEP, UI_SCALE_STEP, "%.0f%%"); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_UI_SCALE)); + ImGui::Checkbox(localize.get(LABEL_VSYNC), &temporary.isVsync); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_VSYNC)); + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_DETACHABLE_WINDOWS), &temporary.isDetachableWindows); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DETACHABLE_WINDOWS)); - ShortcutMember member = SHORTCUT_MEMBERS[i]; - std::string* settingString = &(temporary.*member); - std::string chordString = isSelected ? "" : *settingString; + ImGui::SeparatorText(localize.get(LABEL_PLAYBACK_MENU)); + ImGui::RadioButton("30 Hz", &temporary.playbackTickRate, 30); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PLAYBACK_TICK_RATE)); + ImGui::SameLine(); + ImGui::RadioButton("60 Hz", &temporary.playbackTickRate, 60); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PLAYBACK_TICK_RATE)); - ImGui::PushID(i); - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - ImGui::TextUnformatted(localize.get(SHORTCUT_STRING_TYPES[i])); - ImGui::TableSetColumnIndex(1); + ImGui::SeparatorText(localize.get(LABEL_LOCALIZATION)); + ImGui::Combo(localize.get(LABEL_LANGUAGE), &temporary.language, LANGUAGE_STRINGS, LANGUAGE_COUNT); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LANGUAGE)); - if (ImGui::Selectable(chordString.c_str(), isSelected)) selectedShortcut = i; + ImGui::SeparatorText(localize.get(LABEL_THEME)); - ImGui::PopID(); - - if (isSelected) - { - ImGuiKeyChord chord = ImGuiKey_None; - - if (ImGui::IsKeyDown(ImGuiMod_Ctrl)) chord |= ImGuiMod_Ctrl; - if (ImGui::IsKeyDown(ImGuiMod_Shift)) chord |= ImGuiMod_Shift; - if (ImGui::IsKeyDown(ImGuiMod_Alt)) chord |= ImGuiMod_Alt; - if (ImGui::IsKeyDown(ImGuiMod_Super)) chord |= ImGuiMod_Super; - - for (auto& entry : KEY_MAP) + for (int i = 0; i < THEME_COUNT; i++) { - auto key = entry.second; - if (ImGui::IsKeyPressed(key)) - { - chord |= key; - *settingString = chord_to_string(chord); - selectedShortcut = -1; - break; - } + ImGui::RadioButton(localize.get(THEME_STRINGS[i]), &temporary.theme, i); + ImGui::SameLine(); } - } } - ImGui::EndTable(); - } - ImGui::EndChild(); + ImGui::EndChild(); - ImGui::PopStyleVar(); - - ImGui::EndTabItem(); + ImGui::EndTabItem(); } - } - ImGui::EndTabBar(); + if (ImGui::BeginTabItem(localize.get(LABEL_FILE_MENU))) + { + if (ImGui::BeginChild("##Tab Child", childSize, true)) + { + ImGui::SeparatorText(localize.get(LABEL_AUTOSAVE)); + + ImGui::Checkbox(localize.get(BASIC_ENABLED), &temporary.fileIsAutosave); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTOSAVE_ENABLED)); + + ImGui::SeparatorText(localize.get(LABEL_AUTO_RESOURCE_RELOAD)); + ImGui::PushID(LABEL_AUTO_RESOURCE_RELOAD); + ImGui::Checkbox(localize.get(BASIC_ENABLED), &temporary.fileIsAutoReloadResources); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTO_RESOURCE_RELOAD)); + ImGui::PopID(); + + ImGui::SeparatorText(localize.get(LABEL_SNAPSHOTS)); + input_int_range(localize.get(LABEL_STACK_SIZE), temporary.fileSnapshotStackSize, 0, 100); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_STACK_SIZE)); + + ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); + ImGui::Checkbox(localize.get(LABEL_OVERWRITE_WARNING), &temporary.fileIsWarnOverwrite); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERWRITE_WARNING)); + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_ISAAC_COMPATIBILITY_WARNING), &temporary.fileIsWarnIsaac); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ISAAC_COMPATIBILITY_WARNING)); + + ImGui::SeparatorText(localize.get(LABEL_SERIALIZATION)); + ImGui::Checkbox(localize.get(LABEL_SAVE_AS_JSON), &temporary.fileIsJson); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SAVE_AS_JSON)); + } + ImGui::EndChild(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem(localize.get(LABEL_INPUT))) + { + if (ImGui::BeginChild("##Tab Child", childSize, true)) + { + ImGui::SeparatorText(localize.get(LABEL_KEYBOARD)); + + input_float_range(localize.get(LABEL_REPEAT_DELAY), temporary.keyboardRepeatDelay, 0.05f, 1.0f, 0.05f, + 0.05f, "%.2f"); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REPEAT_DELAY)); + + input_float_range(localize.get(LABEL_REPEAT_RATE), temporary.keyboardRepeatRate, 0.005f, 1.0f, 0.005f, + 0.005f, "%.3f"); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REPEAT_DELAY)); + + ImGui::SeparatorText(localize.get(LABEL_TOOL)); + + ImGui::Checkbox(localize.get(LABEL_MOVE_TOOL_SNAP), &temporary.inputIsMoveToolSnapToMouse); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MOVE_TOOL_SNAP)); + } + ImGui::EndChild(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem(localize.get(LABEL_SHORTCUTS_TAB))) + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + + if (ImGui::BeginChild("##Tab Child", childSize, true)) + { + if (ImGui::BeginTable(localize.get(LABEL_SHORTCUTS_TAB), 2, + ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) + { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn(localize.get(LABEL_SHORTCUT_COLUMN)); + ImGui::TableSetupColumn(localize.get(LABEL_VALUE_COLUMN)); + ImGui::TableHeadersRow(); + + for (int i = 0; i < SHORTCUT_COUNT; ++i) + { + bool isSelected = selectedShortcut == i; + + ShortcutMember member = SHORTCUT_MEMBERS[i]; + std::string* settingString = &(temporary.*member); + std::string chordString = isSelected ? "" : *settingString; + + ImGui::PushID(i); + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::TextUnformatted(localize.get(SHORTCUT_STRING_TYPES[i])); + ImGui::TableSetColumnIndex(1); + + if (ImGui::Selectable(chordString.c_str(), isSelected)) + selectedShortcut = i; + + ImGui::PopID(); + + if (isSelected) + { + ImGuiKeyChord chord = ImGuiKey_None; + + if (ImGui::IsKeyDown(ImGuiMod_Ctrl)) + chord |= ImGuiMod_Ctrl; + if (ImGui::IsKeyDown(ImGuiMod_Shift)) + chord |= ImGuiMod_Shift; + if (ImGui::IsKeyDown(ImGuiMod_Alt)) + chord |= ImGuiMod_Alt; + if (ImGui::IsKeyDown(ImGuiMod_Super)) + chord |= ImGuiMod_Super; + + for (auto& entry : KEY_MAP) + { + auto key = entry.second; + if (ImGui::IsKeyPressed(key)) + { + chord |= key; + *settingString = chord_to_string(chord); + selectedShortcut = -1; + break; + } + } + } + } + ImGui::EndTable(); + } + ImGui::EndChild(); + + ImGui::PopStyleVar(); + + ImGui::EndTabItem(); + } + } + + ImGui::EndTabBar(); } auto widgetSize = widget_size_with_row_get(3); @@ -186,38 +194,40 @@ shortcut(manager.chords[SHORTCUT_CONFIRM]); if (ImGui::Button(localize.get(BASIC_SAVE), widgetSize)) { - auto settingsPath = preferences_directory_get() / "settings.ini"; - settings = temporary; + auto settingsPath = preferences_directory_get() / "settings.ini"; + settings = temporary; - ImGui::GetIO().KeyRepeatDelay = settings.keyboardRepeatDelay; - ImGui::GetIO().KeyRepeatRate = settings.keyboardRepeatRate; - ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); - if (settings.isDetachableWindows) - ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; - else - ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable; - SnapshotStack::max_size_set(settings.fileSnapshotStackSize); - theme_set((Theme)settings.theme); - localize.language = (Language)settings.language; - manager.settings_apply(settings); + ImGui::GetIO().KeyRepeatDelay = settings.keyboardRepeatDelay; + ImGui::GetIO().KeyRepeatRate = settings.keyboardRepeatRate; + ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); + if (settings.isDetachableWindows) + ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; + else + ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable; + SnapshotStack::max_size_set(settings.fileSnapshotStackSize); + theme_set((Theme)settings.theme); + localize.language = (Language)settings.language; + manager.settings_apply(settings); - for (auto& document : manager.documents) - document.snapshots.apply_limit(); + for (auto& document : manager.documents) + document.snapshots.apply_limit(); - settings.save(settingsPath, ImGui::SaveIniSettingsToMemory(nullptr)); + settings.save(settingsPath, ImGui::SaveIniSettingsToMemory(nullptr)); - isSet = true; + isSet = true; } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SETTINGS_SAVE)); ImGui::SameLine(); - if (ImGui::Button(localize.get(LABEL_USE_DEFAULT_SETTINGS), widgetSize)) temporary = Settings(); + if (ImGui::Button(localize.get(LABEL_USE_DEFAULT_SETTINGS), widgetSize)) + temporary = Settings(); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_USE_DEFAULT_SETTINGS)); ImGui::SameLine(); shortcut(manager.chords[SHORTCUT_CLOSE]); - if (ImGui::Button(localize.get(LABEL_CLOSE), widgetSize)) isSet = true; + if (ImGui::Button(localize.get(LABEL_CLOSE), widgetSize)) + isSet = true; ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CLOSE_SETTINGS)); - } +} diff --git a/src/ui/configure.h b/src/ui/configure.h index d30a06e..775f910 100644 --- a/src/ui/configure.h +++ b/src/ui/configure.h @@ -2,14 +2,14 @@ #include "manager.h" - class Configure - { +class Configure +{ Settings temporary = {}; int selectedShortcut = -1; - public: +public: bool isSet = false; void reset(Settings&); void update(Manager&, Settings&); - }; +}; diff --git a/src/ui/dockspace.cpp b/src/ui/dockspace.cpp index ab424d4..8f0e994 100644 --- a/src/ui/dockspace.cpp +++ b/src/ui/dockspace.cpp @@ -1,32 +1,40 @@ #include "ui/dockspace.h" - bool Dockspace::is_canvas_focused_get() const { return isCanvasFocused; } +bool Dockspace::is_canvas_focused_get() const +{ + return isCanvasFocused; +} - void Dockspace::tick(Manager& manager, Settings& settings, float deltaSeconds) - { +void Dockspace::tick(Manager& manager, Settings& settings, float deltaSeconds) +{ if (auto document = manager.get(); document) - if (settings.windowIsAnimationPreview) animationPreview.tick(manager, settings, deltaSeconds); + if (settings.windowIsAnimationPreview) + animationPreview.tick(manager, settings, deltaSeconds); // Spritesheets and libraries changed on disk are picked up every few seconds. - if (!settings.fileIsAutoReloadResources) return; + if (!settings.fileIsAutoReloadResources) + return; reloadTime += deltaSeconds; - if (reloadTime < AUTO_RELOAD_INTERVAL) return; + if (reloadTime < AUTO_RELOAD_INTERVAL) + return; reloadTime = 0.0f; for (auto& document : manager.documents) { - document.libraries_reload(); - if (auto ids = document.spritesheets_changed_get(); !ids.empty()) document.spritesheets_reload(ids); + document.libraries_reload(); + if (auto ids = document.spritesheets_changed_get(); !ids.empty()) + document.spritesheets_reload(ids); } - } +} - void Dockspace::update(Taskbar& taskbar, Documents& documents, Manager& manager, Settings& settings, - Resources& resources, Dialog& dialog, Clipboard& clipboard) - { +void Dockspace::update(Taskbar& taskbar, Documents& documents, Manager& manager, Settings& settings, + Resources& resources, Dialog& dialog, Clipboard& clipboard) +{ isCanvasFocused = false; auto viewport = ImGui::GetMainViewport(); auto windowHeight = viewport->Size.y - taskbar.height - documents.height; - if (windowHeight < 1.0f) windowHeight = 1.0f; + if (windowHeight < 1.0f) + windowHeight = 1.0f; ImGui::SetNextWindowViewport(viewport->ID); ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + taskbar.height + documents.height)); @@ -37,56 +45,67 @@ ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus)) { - if (auto document = manager.get(); document) - { - if (ImGui::DockSpace(ImGui::GetID("##DockSpace"), ImVec2(), ImGuiDockNodeFlags_PassthruCentralNode)) + if (auto document = manager.get(); document) { - auto panel_make = [&](PanelState& state) - { return Panel{manager, settings, resources, dialog, clipboard, *document, state}; }; - auto panel_update = [&](PanelState& state, void (*update)(Panel&)) - { - auto panel = panel_make(state); - update(panel); - }; - if (settings.windowIsAnimationPreview) animationPreview.update(manager, settings, resources); - if (settings.windowIsAnimations) - { - auto panel = panel_make(animations.state); - animations_update(panel, animations); - } - if (settings.windowIsRegions) - { - auto panel = panel_make(regions.state); - regions_update(panel, regions); - } - if (settings.windowIsEvents) panel_update(events, events_update); - if (settings.windowIsFrameProperties) frame_properties_update(manager, settings, frameProperties); - if (settings.windowIsLayers) panel_update(layers, layers_update); - if (settings.windowIsNulls) panel_update(nulls, nulls_update); - if (settings.windowIsOnionskin) onionskin_update(manager, settings); - if (settings.windowIsShaders) - { - auto panel = panel_make(shaders.state); - shaders_update(panel, shaders); - } - if (settings.windowIsSounds) panel_update(sounds, sounds_update); - if (settings.windowIsLibraries) panel_update(libraries, libraries_update); - if (settings.windowIsSpritesheetEditor) spritesheetEditor.update(manager, settings, resources); - if (settings.windowIsSpritesheets) - { - auto panel = panel_make(spritesheets.state); - spritesheets_update(panel, spritesheets); - } - if (settings.windowIsTimeline) timeline.update(manager, settings, resources, clipboard); - if (settings.windowIsTools) tools_update(manager, settings, resources, toolsColorEditPopup); - isCanvasFocused = (settings.windowIsAnimationPreview && animationPreview.is_focused_get()) || - (settings.windowIsSpritesheetEditor && spritesheetEditor.is_focused_get()); + if (ImGui::DockSpace(ImGui::GetID("##DockSpace"), ImVec2(), ImGuiDockNodeFlags_PassthruCentralNode)) + { + auto panel_make = [&](PanelState& state) { + return Panel{manager, settings, resources, dialog, clipboard, *document, state}; + }; + auto panel_update = [&](PanelState& state, void (*update)(Panel&)) { + auto panel = panel_make(state); + update(panel); + }; + if (settings.windowIsAnimationPreview) + animationPreview.update(manager, settings, resources); + if (settings.windowIsAnimations) + { + auto panel = panel_make(animations.state); + animations_update(panel, animations); + } + if (settings.windowIsRegions) + { + auto panel = panel_make(regions.state); + regions_update(panel, regions); + } + if (settings.windowIsEvents) + panel_update(events, events_update); + if (settings.windowIsFrameProperties) + frame_properties_update(manager, settings, frameProperties); + if (settings.windowIsLayers) + panel_update(layers, layers_update); + if (settings.windowIsNulls) + panel_update(nulls, nulls_update); + if (settings.windowIsOnionskin) + onionskin_update(manager, settings); + if (settings.windowIsShaders) + { + auto panel = panel_make(shaders.state); + shaders_update(panel, shaders); + } + if (settings.windowIsSounds) + panel_update(sounds, sounds_update); + if (settings.windowIsLibraries) + panel_update(libraries, libraries_update); + if (settings.windowIsSpritesheetEditor) + spritesheetEditor.update(manager, settings, resources); + if (settings.windowIsSpritesheets) + { + auto panel = panel_make(spritesheets.state); + spritesheets_update(panel, spritesheets); + } + if (settings.windowIsTimeline) + timeline.update(manager, settings, resources, clipboard); + if (settings.windowIsTools) + tools_update(manager, settings, resources, toolsColorEditPopup); + isCanvasFocused = (settings.windowIsAnimationPreview && animationPreview.is_focused_get()) || + (settings.windowIsSpritesheetEditor && spritesheetEditor.is_focused_get()); + } } - } - else - welcome_update(manager, resources, dialog, taskbar, documents); + else + welcome_update(manager, resources, dialog, taskbar, documents); - autosaveRestore.update(manager); + autosaveRestore.update(manager); } ImGui::End(); - } +} diff --git a/src/ui/dockspace.h b/src/ui/dockspace.h index 809494a..1230cb9 100644 --- a/src/ui/dockspace.h +++ b/src/ui/dockspace.h @@ -9,8 +9,8 @@ #include "ui/spritesheet_editor.h" #include "ui/timeline.h" - class Dockspace - { +class Dockspace +{ AnimationPreview animationPreview; bool isCanvasFocused = false; float reloadTime = 0; @@ -29,8 +29,8 @@ PopupHelper toolsColorEditPopup = PopupHelper(LABEL_TOOLS_COLOR_EDIT_POPUP, POPUP_TO_CONTENT, POPUP_BY_ITEM); AutosaveRestore autosaveRestore; - public: +public: bool is_canvas_focused_get() const; void tick(Manager&, Settings&, float); void update(Taskbar&, Documents&, Manager&, Settings&, Resources&, Dialog&, Clipboard&); - }; +}; diff --git a/src/ui/documents.cpp b/src/ui/documents.cpp index 7db15c6..75ab711 100644 --- a/src/ui/documents.cpp +++ b/src/ui/documents.cpp @@ -15,79 +15,76 @@ #include "ui/layout.h" #include "ui/shortcut.h" - struct DocumentTab - { +struct DocumentTab +{ ImGuiID imguiId = 0; uint64_t documentId = 0; - }; +}; #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_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_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_REPLACE_MATCHING, BASIC_REPLACE, TOOLTIP_MERGE_PRESET_REPLACE_MATCHING) - constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_LABELS[FILE_MERGE_PRESET_COUNT] = { +constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_LABELS[FILE_MERGE_PRESET_COUNT] = { #define X(preset, label, tooltip) label, - ANM2_DRAG_DROP_MERGE_PRESETS + ANM2_DRAG_DROP_MERGE_PRESETS #undef X - }; +}; - constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[FILE_MERGE_PRESET_COUNT] = { +constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[FILE_MERGE_PRESET_COUNT] = { #define X(preset, label, tooltip) tooltip, - ANM2_DRAG_DROP_MERGE_PRESETS + ANM2_DRAG_DROP_MERGE_PRESETS #undef X - }; +}; #undef ANM2_DRAG_DROP_MERGE_PRESETS - static void anm2_drag_drop_merge_queue(Manager& manager, const std::vector& paths, - FileMergePreset preset) - { - manager.command_push({manager.selected, [paths, preset](Manager&, Document& document) - { - document.edit_apply(EDIT_MERGE_ANM2, - [&](Model& model) - { - for (auto& path : paths) - file_merge(model, path, document.directory_get(), preset); - }); +static void anm2_drag_drop_merge_queue(Manager& manager, const std::vector& paths, + FileMergePreset preset) +{ + manager.command_push({manager.selected, [paths, preset](Manager&, Document& document) { + document.edit_apply(EDIT_MERGE_ANM2, [&](Model& model) { + for (auto& path : paths) + file_merge(model, path, document.directory_get(), preset); + }); }}); - } +} - void Documents::pending_document_order_apply(Manager& manager) - { +void Documents::pending_document_order_apply(Manager& manager) +{ if (pendingDocumentTabIds.size() != manager.documents.size()) { - pendingDocumentTabIds.clear(); - return; + pendingDocumentTabIds.clear(); + return; } std::vector order; order.reserve(manager.documents.size()); for (auto documentId : pendingDocumentTabIds) { - auto it = std::ranges::find_if(manager.documents, - [documentId](const Document& document) { return document.tabId == documentId; }); - if (it == manager.documents.end()) - { - pendingDocumentTabIds.clear(); - return; - } - order.push_back((int)std::distance(manager.documents.begin(), it)); + auto it = std::ranges::find_if(manager.documents, + [documentId](const Document& document) { return document.tabId == documentId; }); + if (it == manager.documents.end()) + { + pendingDocumentTabIds.clear(); + return; + } + order.push_back((int)std::distance(manager.documents.begin(), it)); } bool isOrdered = true; for (auto [i, index] : std::views::enumerate(order)) - if ((int)i != index) - { - isOrdered = false; - break; - } + if ((int)i != index) + { + isOrdered = false; + break; + } if (isOrdered) { - pendingDocumentTabIds.clear(); - return; + pendingDocumentTabIds.clear(); + return; } std::vector remap(manager.documents.size(), -1); @@ -95,16 +92,15 @@ documents.reserve(manager.documents.size()); for (auto [i, index] : std::views::enumerate(order)) { - remap[index] = (int)i; - documents.push_back(std::move(manager.documents[index])); + remap[index] = (int)i; + documents.push_back(std::move(manager.documents[index])); } - auto index_remap = [&](int& index) - { - if (index < 0 || index >= (int)remap.size()) - index = -1; - else - index = remap[index]; + auto index_remap = [&](int& index) { + if (index < 0 || index >= (int)remap.size()) + index = -1; + else + index = remap[index]; }; manager.documents = std::move(documents); @@ -112,16 +108,17 @@ index_remap(manager.pendingSelected); index_remap(closeDocumentIndex); for (auto& index : manager.selectionHistory) - index_remap(index); + index_remap(index); for (auto& command : manager.commands) - if (!command.runManager) index_remap(command.documentIndex); + if (!command.runManager) + index_remap(command.documentIndex); std::erase(manager.selectionHistory, -1); pendingDocumentTabIds.clear(); - } +} - void Documents::update(Taskbar& taskbar, Manager& manager, Settings& settings, Resources& resources, bool& isQuitting) - { +void Documents::update(Taskbar& taskbar, Manager& manager, Settings& settings, Resources& resources, bool& isQuitting) +{ pending_document_order_apply(manager); auto viewport = ImGui::GetMainViewport(); @@ -134,23 +131,21 @@ ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, windowHeight)); if (isLightTheme) { - ImGui::PushStyleColor(ImGuiCol_WindowBg, ImGui::GetStyleColorVec4(ImGuiCol_TitleBgActive)); - pushedStyle = true; + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImGui::GetStyleColorVec4(ImGuiCol_TitleBgActive)); + pushedStyle = true; } for (auto i = 0; i < (int)manager.documents.size(); ++i) { - auto& document = manager.documents[i]; - auto isDirty = (document.is_dirty() || document.isForceDirty || document.spritesheet_any_dirty()) && - document.is_autosave_dirty(); - if (isDirty) - { - document.lastAutosaveTime += ImGui::GetIO().DeltaTime; - if (document.lastAutosaveTime > SECOND_MINUTES) + auto& document = manager.documents[i]; + auto isDirty = (document.is_dirty() || document.isForceDirty || document.spritesheet_any_dirty()) && + document.is_autosave_dirty(); + if (isDirty) { - manager.command_push({i, [](Manager& manager, Document& document) { manager.autosave(document); }}); + document.lastAutosaveTime += ImGui::GetIO().DeltaTime; + if (document.lastAutosaveTime > SECOND_MINUTES) + manager.command_push({i, [](Manager& manager, Document& document) { manager.autosave(document); }}); } - } } if (ImGui::Begin("##Documents", nullptr, @@ -159,313 +154,323 @@ ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { - height = ImGui::GetWindowSize().y; + height = ImGui::GetWindowSize().y; - if (ImGui::BeginTabBar("##Documents Bar", ImGuiTabBarFlags_Reorderable)) - { - auto documentsCount = (int)manager.documents.size(); - bool isCloseShortcut = shortcut(manager.chords[SHORTCUT_CLOSE], SCOPE_GLOBAL) && !closePopup.is_open(); - int closeShortcutIndex = - isCloseShortcut && manager.selected >= 0 && manager.selected < documentsCount ? manager.selected : -1; - - std::vector closeIndices; - closeIndices.reserve(documentsCount); - std::vector documentTabs; - documentTabs.reserve(documentsCount); - - for (int i = 0; i < documentsCount; ++i) + if (ImGui::BeginTabBar("##Documents Bar", ImGuiTabBarFlags_Reorderable)) { - auto& document = manager.documents[i]; - auto isDocumentDirty = document.is_dirty() || document.isForceDirty; - auto isSpritesheetDirty = document.spritesheet_any_dirty(); - auto isDirty = isDocumentDirty || isSpritesheetDirty; + auto documentsCount = (int)manager.documents.size(); + bool isCloseShortcut = shortcut(manager.chords[SHORTCUT_CLOSE], SCOPE_GLOBAL) && !closePopup.is_open(); + int closeShortcutIndex = + isCloseShortcut && manager.selected >= 0 && manager.selected < documentsCount ? manager.selected : -1; - if (!closePopup.is_open()) - { - if (isQuitting) - document.isOpen = false; - else if (i == closeShortcutIndex) - document.isOpen = false; - } + std::vector closeIndices; + closeIndices.reserve(documentsCount); + std::vector documentTabs; + documentTabs.reserve(documentsCount); - if (!closePopup.is_open() && !document.isOpen) - { - if (isDirty) + for (int i = 0; i < documentsCount; ++i) { - closePopup.open(); - closeDocumentIndex = i; - document.isOpen = true; - } - else - { - closeIndices.push_back(i); - continue; - } - } + auto& document = manager.documents[i]; + auto isDocumentDirty = document.is_dirty() || document.isForceDirty; + auto isSpritesheetDirty = document.spritesheet_any_dirty(); + auto isDirty = isDocumentDirty || isSpritesheetDirty; - auto isRequested = i == manager.pendingSelected; - auto font = isDocumentDirty ? FONT_ITALICS : FONT_REGULAR; - auto filename = path_to_utf8(document.filename_get()); - auto string = isDocumentDirty ? std::vformat(localize.get(FORMAT_NOT_SAVED), std::make_format_args(filename)) - : filename; - auto label = std::format("{}###Document{}", string, document.tabId); - auto imguiId = ImGui::GetCurrentWindow()->GetID(label.c_str()); - documentTabs.push_back({imguiId, document.tabId}); - - auto flags = isDocumentDirty ? ImGuiTabItemFlags_UnsavedDocument : 0; - if (isRequested) flags |= ImGuiTabItemFlags_SetSelected; - - ImGui::PushFont(resources.fonts[font].get(), FONT_SIZE); - if (ImGui::BeginTabItem(label.c_str(), &document.isOpen, flags)) - { - if (manager.selected != i) manager.set(i); - - if (isRequested) manager.pendingSelected = -1; - - ImGui::EndTabItem(); - } - auto pathUtf8 = path_to_utf8(document.path); - ImGui::SetItemTooltip("%s", pathUtf8.c_str()); - - ImGui::PopFont(); - } - - if (auto tabBar = ImGui::GetCurrentTabBar(); tabBar && documentTabs.size() == manager.documents.size()) - { - std::vector documentTabIds; - documentTabIds.reserve(manager.documents.size()); - for (auto& tab : tabBar->Tabs) - { - auto it = std::ranges::find_if(documentTabs, [&](const DocumentTab& documentTab) - { return documentTab.imguiId == tab.ID; }); - if (it != documentTabs.end()) documentTabIds.push_back(it->documentId); - } - - if (documentTabIds.size() == manager.documents.size()) - { - bool isOrdered = true; - for (auto [i, documentId] : std::views::enumerate(documentTabIds)) - if (manager.documents[i].tabId != documentId) - { - isOrdered = false; - break; - } - if (!isOrdered) pendingDocumentTabIds = std::move(documentTabIds); - } - } - - for (auto it = closeIndices.rbegin(); it != closeIndices.rend(); ++it) - { - if (closePopup.is_open() && closeDocumentIndex > *it) --closeDocumentIndex; - auto index = *it; - manager.command_push({.runManager = [index](Manager& manager) { manager.close(index); }}); - } - - ImGui::EndTabBar(); - } - - closePopup.trigger(); - - if (ImGui::BeginPopupModal(closePopup.label(), &closePopup.isOpen, ImGuiWindowFlags_NoResize)) - { - if (closeDocumentIndex >= 0 && closeDocumentIndex < (int)manager.documents.size()) - { - auto& closeDocument = manager.documents[closeDocumentIndex]; - - auto filename = path_to_utf8(closeDocument.filename_get()); - auto isDocumentDirty = closeDocument.is_dirty() || closeDocument.isForceDirty; - auto isSpritesheetDirty = closeDocument.spritesheet_any_dirty(); - auto promptLabel = - isDocumentDirty && isSpritesheetDirty - ? LABEL_DOCUMENT_AND_SPRITESHEETS_MODIFIED_PROMPT - : (isDocumentDirty ? LABEL_DOCUMENT_MODIFIED_PROMPT : LABEL_SPRITESHEETS_MODIFIED_PROMPT); - auto prompt = std::vformat(localize.get(promptLabel), std::make_format_args(filename)); - ImGui::TextUnformatted(prompt.c_str()); - - auto widgetSize = widget_size_with_row_get(3); - - auto close = [&]() - { - closeDocumentIndex = -1; - closePopup.close(); - }; - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(localize.get(BASIC_YES), widgetSize)) - { - // A failed save keeps the document (and its popup) open. - auto isSaved = !isDocumentDirty || taskbar.save_manual(manager, settings, closeDocumentIndex); - if (isSaved) - { - if (isSpritesheetDirty) - for (auto& spritesheet : closeDocument.model.content.spritesheets) + if (!closePopup.is_open()) { - auto id = spritesheet.id; - auto texture = closeDocument.texture_get(id); - if (texture && closeDocument.spritesheet_is_dirty(id)) - { - auto pathString = path_to_utf8(spritesheet.path); - auto savePath = closeDocument.directory_get() / spritesheet.path; - path_ensure_directory(savePath.parent_path()); - if (texture->write(savePath)) + if (isQuitting) + document.isOpen = false; + else if (i == closeShortcutIndex) + document.isOpen = false; + } + + if (!closePopup.is_open() && !document.isOpen) + { + if (isDirty) { - closeDocument.spritesheet_hash_set_saved(id); - toast_log(Level::INFO, TOAST_SAVE_SPRITESHEET, id, pathString); + closePopup.open(); + closeDocumentIndex = i; + document.isOpen = true; } else { - toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); + closeIndices.push_back(i); + continue; } - } } - auto index = closeDocumentIndex; - manager.command_push({.runManager = [index](Manager& manager) { manager.close(index); }}); - close(); + + auto isRequested = i == manager.pendingSelected; + auto font = isDocumentDirty ? FONT_ITALICS : FONT_REGULAR; + auto filename = path_to_utf8(document.filename_get()); + auto string = isDocumentDirty + ? std::vformat(localize.get(FORMAT_NOT_SAVED), std::make_format_args(filename)) + : filename; + auto label = std::format("{}###Document{}", string, document.tabId); + auto imguiId = ImGui::GetCurrentWindow()->GetID(label.c_str()); + documentTabs.push_back({imguiId, document.tabId}); + + auto flags = isDocumentDirty ? ImGuiTabItemFlags_UnsavedDocument : 0; + if (isRequested) + flags |= ImGuiTabItemFlags_SetSelected; + + ImGui::PushFont(resources.fonts[font].get(), FONT_SIZE); + if (ImGui::BeginTabItem(label.c_str(), &document.isOpen, flags)) + { + if (manager.selected != i) + manager.set(i); + + if (isRequested) + manager.pendingSelected = -1; + + ImGui::EndTabItem(); + } + auto pathUtf8 = path_to_utf8(document.path); + ImGui::SetItemTooltip("%s", pathUtf8.c_str()); + + ImGui::PopFont(); } - } - ImGui::SameLine(); + if (auto tabBar = ImGui::GetCurrentTabBar(); tabBar && documentTabs.size() == manager.documents.size()) + { + std::vector documentTabIds; + documentTabIds.reserve(manager.documents.size()); + for (auto& tab : tabBar->Tabs) + { + auto it = std::ranges::find_if( + documentTabs, [&](const DocumentTab& documentTab) { return documentTab.imguiId == tab.ID; }); + if (it != documentTabs.end()) + documentTabIds.push_back(it->documentId); + } - if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) - { - auto index = closeDocumentIndex; - manager.command_push({.runManager = [index](Manager& manager) - { - manager.autosave_file_clear(index); - manager.close(index); - }}); - close(); - } + if (documentTabIds.size() == manager.documents.size()) + { + bool isOrdered = true; + for (auto [i, documentId] : std::views::enumerate(documentTabIds)) + if (manager.documents[i].tabId != documentId) + { + isOrdered = false; + break; + } + if (!isOrdered) + pendingDocumentTabIds = std::move(documentTabIds); + } + } - ImGui::SameLine(); + for (auto it = closeIndices.rbegin(); it != closeIndices.rend(); ++it) + { + if (closePopup.is_open() && closeDocumentIndex > *it) + --closeDocumentIndex; + auto index = *it; + manager.command_push({.runManager = [index](Manager& manager) { manager.close(index); }}); + } - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) - { - isQuitting = false; - close(); - } + ImGui::EndTabBar(); } - else + + closePopup.trigger(); + + if (ImGui::BeginPopupModal(closePopup.label(), &closePopup.isOpen, ImGuiWindowFlags_NoResize)) { - closeDocumentIndex = -1; - closePopup.close(); - } + if (closeDocumentIndex >= 0 && closeDocumentIndex < (int)manager.documents.size()) + { + auto& closeDocument = manager.documents[closeDocumentIndex]; - ImGui::EndPopup(); - } + auto filename = path_to_utf8(closeDocument.filename_get()); + auto isDocumentDirty = closeDocument.is_dirty() || closeDocument.isForceDirty; + auto isSpritesheetDirty = closeDocument.spritesheet_any_dirty(); + auto promptLabel = + isDocumentDirty && isSpritesheetDirty + ? LABEL_DOCUMENT_AND_SPRITESHEETS_MODIFIED_PROMPT + : (isDocumentDirty ? LABEL_DOCUMENT_MODIFIED_PROMPT : LABEL_SPRITESHEETS_MODIFIED_PROMPT); + auto prompt = std::vformat(localize.get(promptLabel), std::make_format_args(filename)); + ImGui::TextUnformatted(prompt.c_str()); + + auto widgetSize = widget_size_with_row_get(3); + + auto close = [&]() { + closeDocumentIndex = -1; + closePopup.close(); + }; + + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(localize.get(BASIC_YES), widgetSize)) + { + // A failed save keeps the document (and its popup) open. + auto isSaved = !isDocumentDirty || taskbar.save_manual(manager, settings, closeDocumentIndex); + if (isSaved) + { + if (isSpritesheetDirty) + for (auto& spritesheet : closeDocument.model.content.spritesheets) + { + auto id = spritesheet.id; + auto texture = closeDocument.texture_get(id); + if (texture && closeDocument.spritesheet_is_dirty(id)) + { + auto pathString = path_to_utf8(spritesheet.path); + auto savePath = closeDocument.directory_get() / spritesheet.path; + path_ensure_directory(savePath.parent_path()); + if (texture->write(savePath)) + { + closeDocument.spritesheet_hash_set_saved(id); + toast_log(Level::INFO, TOAST_SAVE_SPRITESHEET, id, pathString); + } + else + { + toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); + } + } + } + auto index = closeDocumentIndex; + manager.command_push({.runManager = [index](Manager& manager) { manager.close(index); }}); + close(); + } + } + + ImGui::SameLine(); + + if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) + { + auto index = closeDocumentIndex; + manager.command_push({.runManager = [index](Manager& manager) { + manager.autosave_file_clear(index); + manager.close(index); + }}); + close(); + } + + ImGui::SameLine(); + + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) + { + isQuitting = false; + close(); + } + } + else + { + closeDocumentIndex = -1; + closePopup.close(); + } + + ImGui::EndPopup(); + } } ImGui::End(); - if (pushedStyle) ImGui::PopStyleColor(); + if (pushedStyle) + ImGui::PopStyleColor(); if (manager.isAnm2DragDrop) { - auto drag_drop_reset = [&]() - { - manager.isAnm2DragDrop = false; - manager.anm2DragDropPaths.clear(); - manager.anm2DragDropPopup.close(); - manager.anm2DragDropMergePopup.close(); - manager.anm2DragDropMergePreset = FILE_MERGE_PRESET_MERGE_BY_NAME; - }; + auto drag_drop_reset = [&]() { + manager.isAnm2DragDrop = false; + manager.anm2DragDropPaths.clear(); + manager.anm2DragDropPopup.close(); + manager.anm2DragDropMergePopup.close(); + manager.anm2DragDropMergePreset = FILE_MERGE_PRESET_MERGE_BY_NAME; + }; - if (manager.anm2DragDropPaths.empty()) - drag_drop_reset(); - else if (manager.anm2DragDropMergePopup.is_open()) - { - manager.anm2DragDropMergePopup.trigger(); - - if (ImGui::BeginPopupModal(manager.anm2DragDropMergePopup.label(), &manager.anm2DragDropMergePopup.isOpen, - ImGuiWindowFlags_NoResize)) - { - auto document = manager.get(); - manager.anm2DragDropMergePreset = std::clamp(manager.anm2DragDropMergePreset, 0, FILE_MERGE_PRESET_COUNT - 1); - - for (int preset = 0; preset < FILE_MERGE_PRESET_COUNT; ++preset) - { - ImGui::PushID(preset); - ImGui::RadioButton(localize.get(ANM2_DRAG_DROP_MERGE_PRESET_LABELS[preset]), - &manager.anm2DragDropMergePreset, preset); - ImGui::SetItemTooltip("%s", localize.get(ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[preset])); - ImGui::PopID(); - } - - auto widgetSize = widget_size_with_row_get(2); - shortcut(manager.chords[SHORTCUT_CONFIRM]); - ImGui::BeginDisabled(!document); - if (ImGui::Button(localize.get(BASIC_MERGE), widgetSize)) - { - auto paths = manager.anm2DragDropPaths; - auto preset = (FileMergePreset)manager.anm2DragDropMergePreset; - anm2_drag_drop_merge_queue(manager, paths, preset); + if (manager.anm2DragDropPaths.empty()) drag_drop_reset(); - } - ImGui::EndDisabled(); - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) drag_drop_reset(); - - manager.anm2DragDropMergePopup.end(); - ImGui::EndPopup(); - - if (manager.isAnm2DragDrop && !manager.anm2DragDropMergePopup.is_open()) drag_drop_reset(); - } - else if (!ImGui::IsPopupOpen(manager.anm2DragDropMergePopup.label())) - drag_drop_reset(); - } - else - { - if (!manager.anm2DragDropPopup.is_open()) manager.anm2DragDropPopup.open(); - - manager.anm2DragDropPopup.trigger(); - - if (ImGui::BeginPopup(manager.anm2DragDropPopup.label(), ImGuiWindowFlags_NoMove)) + else if (manager.anm2DragDropMergePopup.is_open()) { - auto document = manager.get(); - if (ImGui::MenuItem(manager.anm2DragDropPaths.size() > 1 ? localize.get(LABEL_DOCUMENTS_OPEN_MANY) - : localize.get(LABEL_DOCUMENTS_OPEN_NEW))) - { - auto paths = manager.anm2DragDropPaths; - manager.command_push({.runManager = [paths](Manager& manager) - { - for (auto& path : paths) - manager.open(path); - }}); - drag_drop_reset(); - } + manager.anm2DragDropMergePopup.trigger(); - if (ImGui::MenuItem(localize.get(LABEL_DOCUMENTS_MERGE_INTO_CURRENT), nullptr, false, - document && !manager.anm2DragDropPaths.empty())) - { - if (document) + if (ImGui::BeginPopupModal(manager.anm2DragDropMergePopup.label(), &manager.anm2DragDropMergePopup.isOpen, + ImGuiWindowFlags_NoResize)) { - manager.anm2DragDropPopup.close(); - manager.anm2DragDropMergePopup.open(); - ImGui::CloseCurrentPopup(); + auto document = manager.get(); + manager.anm2DragDropMergePreset = + std::clamp(manager.anm2DragDropMergePreset, 0, FILE_MERGE_PRESET_COUNT - 1); + + for (int preset = 0; preset < FILE_MERGE_PRESET_COUNT; ++preset) + { + ImGui::PushID(preset); + ImGui::RadioButton(localize.get(ANM2_DRAG_DROP_MERGE_PRESET_LABELS[preset]), + &manager.anm2DragDropMergePreset, preset); + ImGui::SetItemTooltip("%s", localize.get(ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[preset])); + ImGui::PopID(); + } + + auto widgetSize = widget_size_with_row_get(2); + shortcut(manager.chords[SHORTCUT_CONFIRM]); + ImGui::BeginDisabled(!document); + if (ImGui::Button(localize.get(BASIC_MERGE), widgetSize)) + { + auto paths = manager.anm2DragDropPaths; + auto preset = (FileMergePreset)manager.anm2DragDropMergePreset; + anm2_drag_drop_merge_queue(manager, paths, preset); + drag_drop_reset(); + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) + drag_drop_reset(); + + manager.anm2DragDropMergePopup.end(); + ImGui::EndPopup(); + + if (manager.isAnm2DragDrop && !manager.anm2DragDropMergePopup.is_open()) + drag_drop_reset(); } - } - - if (ImGui::MenuItem(localize.get(LABEL_DOCUMENTS_ADD_AS_LIBRARY), nullptr, false, document)) - { - manager.command_push({manager.selected, [paths = manager.anm2DragDropPaths](Manager&, Document& document) - { document.libraries_add(paths); }}); - drag_drop_reset(); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LIBRARY_ADD)); - - ImGui::Separator(); - - if (ImGui::MenuItem(localize.get(BASIC_CANCEL))) drag_drop_reset(); - - manager.anm2DragDropPopup.end(); - ImGui::EndPopup(); + else if (!ImGui::IsPopupOpen(manager.anm2DragDropMergePopup.label())) + drag_drop_reset(); } - else if (!ImGui::IsPopupOpen(manager.anm2DragDropPopup.label())) - drag_drop_reset(); - } - } - } + else + { + if (!manager.anm2DragDropPopup.is_open()) + manager.anm2DragDropPopup.open(); + manager.anm2DragDropPopup.trigger(); + + if (ImGui::BeginPopup(manager.anm2DragDropPopup.label(), ImGuiWindowFlags_NoMove)) + { + auto document = manager.get(); + if (ImGui::MenuItem(manager.anm2DragDropPaths.size() > 1 ? localize.get(LABEL_DOCUMENTS_OPEN_MANY) + : localize.get(LABEL_DOCUMENTS_OPEN_NEW))) + { + auto paths = manager.anm2DragDropPaths; + manager.command_push({.runManager = [paths](Manager& manager) { + for (auto& path : paths) + manager.open(path); + }}); + drag_drop_reset(); + } + + if (ImGui::MenuItem(localize.get(LABEL_DOCUMENTS_MERGE_INTO_CURRENT), nullptr, false, + document && !manager.anm2DragDropPaths.empty())) + { + if (document) + { + manager.anm2DragDropPopup.close(); + manager.anm2DragDropMergePopup.open(); + ImGui::CloseCurrentPopup(); + } + } + + if (ImGui::MenuItem(localize.get(LABEL_DOCUMENTS_ADD_AS_LIBRARY), nullptr, false, document)) + { + manager.command_push( + {manager.selected, [paths = manager.anm2DragDropPaths](Manager&, Document& document) { + document.libraries_add(paths); + }}); + drag_drop_reset(); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LIBRARY_ADD)); + + ImGui::Separator(); + + if (ImGui::MenuItem(localize.get(BASIC_CANCEL))) + drag_drop_reset(); + + manager.anm2DragDropPopup.end(); + ImGui::EndPopup(); + } + else if (!ImGui::IsPopupOpen(manager.anm2DragDropPopup.label())) + drag_drop_reset(); + } + } +} diff --git a/src/ui/documents.h b/src/ui/documents.h index c9ef81c..2428628 100644 --- a/src/ui/documents.h +++ b/src/ui/documents.h @@ -9,15 +9,15 @@ #include "localization.h" #include "ui/taskbar.h" - class Documents - { +class Documents +{ int closeDocumentIndex = -1; std::vector pendingDocumentTabIds; PopupHelper closePopup = PopupHelper(LABEL_DOCUMENT_CLOSE, POPUP_TO_CONTENT); - public: +public: float height = 0; void pending_document_order_apply(Manager&); void update(Taskbar&, Manager&, Settings&, Resources&, bool&); - }; +}; diff --git a/src/ui/draw.cpp b/src/ui/draw.cpp index 92291d1..ce78394 100644 --- a/src/ui/draw.cpp +++ b/src/ui/draw.cpp @@ -4,68 +4,72 @@ #include - constexpr ImU32 DROP_LINE_COLOR = IM_COL32(255, 255, 0, 255); - constexpr float DROP_LINE_THICKNESS = 2.0f; +constexpr ImU32 DROP_LINE_COLOR = IM_COL32(255, 255, 0, 255); +constexpr float DROP_LINE_THICKNESS = 2.0f; - struct CheckerStart - { +struct CheckerStart +{ float position = 0; long long index = {}; - }; +}; - static CheckerStart checker_start(float minCoord, float offset, float step) - { +static CheckerStart checker_start(float minCoord, float offset, float step) +{ float world = minCoord + offset; long long index = static_cast(std::floor(world / step)); float first = minCoord - (world - static_cast(index) * step); return {first, index}; - } +} - bool is_drop_after(ImVec2 min, ImVec2 max) - { +bool is_drop_after(ImVec2 min, ImVec2 max) +{ return ImGui::GetIO().MousePos.y >= (min.y + max.y) * 0.5f; - } +} - void drop_box_draw(ImDrawList* drawList, ImVec2 min, ImVec2 max) - { - if (!drawList) return; +void drop_box_draw(ImDrawList* drawList, ImVec2 min, ImVec2 max) +{ + if (!drawList) + return; auto offset = DROP_LINE_THICKNESS * 0.5f; - drawList->AddRect(ImVec2(min.x + offset, min.y + offset), ImVec2(max.x - offset, max.y - offset), - DROP_LINE_COLOR, 0.0f, 0, DROP_LINE_THICKNESS); - } + drawList->AddRect(ImVec2(min.x + offset, min.y + offset), ImVec2(max.x - offset, max.y - offset), DROP_LINE_COLOR, + 0.0f, 0, DROP_LINE_THICKNESS); +} - void drop_line_draw(ImDrawList* drawList, ImVec2 min, ImVec2 max, bool isAfter) - { - if (!drawList) return; +void drop_line_draw(ImDrawList* drawList, ImVec2 min, ImVec2 max, bool isAfter) +{ + if (!drawList) + return; auto offset = DROP_LINE_THICKNESS * 0.5f; auto y = std::floor(isAfter ? max.y - offset : min.y + offset) + 0.5f; drawList->AddLine(ImVec2(min.x, y), ImVec2(max.x, y), DROP_LINE_COLOR, DROP_LINE_THICKNESS); - } +} - static void image_premultiplied_blend_set(const ImDrawList*, const ImDrawCmd*) - { +static void image_premultiplied_blend_set(const ImDrawList*, const ImDrawCmd*) +{ glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - } +} - void image_premultiplied_draw(ImTextureID texture, ImVec2 size) - { +void image_premultiplied_draw(ImTextureID texture, ImVec2 size) +{ auto drawList = ImGui::GetWindowDrawList(); drawList->AddCallback(image_premultiplied_blend_set, nullptr); ImGui::Image(texture, size); drawList->AddCallback(ImDrawCallback_ResetRenderState, nullptr); - } +} - void image_premultiplied_draw(ImDrawList* drawList, ImTextureID texture, ImVec2 min, ImVec2 max) - { - if (!drawList) return; +void image_premultiplied_draw(ImDrawList* drawList, ImTextureID texture, ImVec2 min, ImVec2 max) +{ + if (!drawList) + return; drawList->AddCallback(image_premultiplied_blend_set, nullptr); drawList->AddImage(texture, min, max); drawList->AddCallback(ImDrawCallback_ResetRenderState, nullptr); - } +} - void render_checker_background(ImDrawList* drawList, ImVec2 min, ImVec2 max, glm::vec2 offset, float step) - { - if (!drawList || step <= 0.0f) return; +void render_checker_background(ImDrawList* drawList, ImVec2 min, ImVec2 max, glm::vec2 offset, float step) +{ + if (!drawList || step <= 0.0f) + return; const ImU32 colorLight = IM_COL32(204, 204, 204, 255); const ImU32 colorDark = IM_COL32(128, 128, 128, 255); @@ -73,19 +77,21 @@ auto [startY, rowIndex] = checker_start(min.y, offset.y, step); for (float y = startY; y < max.y; y += step, ++rowIndex) { - float y1 = glm::max(y, min.y); - float y2 = glm::min(y + step, max.y); - if (y2 <= y1) continue; + float y1 = glm::max(y, min.y); + float y2 = glm::min(y + step, max.y); + if (y2 <= y1) + continue; - auto [startX, columnIndex] = checker_start(min.x, offset.x, step); - for (float x = startX; x < max.x; x += step, ++columnIndex) - { - float x1 = glm::max(x, min.x); - float x2 = glm::min(x + step, max.x); - if (x2 <= x1) continue; + auto [startX, columnIndex] = checker_start(min.x, offset.x, step); + for (float x = startX; x < max.x; x += step, ++columnIndex) + { + float x1 = glm::max(x, min.x); + float x2 = glm::min(x + step, max.x); + if (x2 <= x1) + continue; - bool isDark = ((rowIndex + columnIndex) & 1LL) != 0; - drawList->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), isDark ? colorDark : colorLight); - } + bool isDark = ((rowIndex + columnIndex) & 1LL) != 0; + drawList->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), isDark ? colorDark : colorLight); + } } - } +} diff --git a/src/ui/draw.h b/src/ui/draw.h index 5e2c55c..914f09f 100644 --- a/src/ui/draw.h +++ b/src/ui/draw.h @@ -3,9 +3,9 @@ #include #include - bool is_drop_after(ImVec2, ImVec2); - void drop_box_draw(ImDrawList*, ImVec2, ImVec2); - void drop_line_draw(ImDrawList*, ImVec2, ImVec2, bool); - void image_premultiplied_draw(ImTextureID, ImVec2); - void image_premultiplied_draw(ImDrawList*, ImTextureID, ImVec2, ImVec2); - void render_checker_background(ImDrawList*, ImVec2, ImVec2, glm::vec2, float); +bool is_drop_after(ImVec2, ImVec2); +void drop_box_draw(ImDrawList*, ImVec2, ImVec2); +void drop_line_draw(ImDrawList*, ImVec2, ImVec2, bool); +void image_premultiplied_draw(ImTextureID, ImVec2); +void image_premultiplied_draw(ImDrawList*, ImTextureID, ImVec2, ImVec2); +void render_checker_background(ImDrawList*, ImVec2, ImVec2, glm::vec2, float); diff --git a/src/ui/frame_properties.cpp b/src/ui/frame_properties.cpp index 8439a11..06a8886 100644 --- a/src/ui/frame_properties.cpp +++ b/src/ui/frame_properties.cpp @@ -14,383 +14,404 @@ using namespace glm; - constexpr int TRIGGER_EVENTS_ROWS = 3; +constexpr int TRIGGER_EVENTS_ROWS = 3; - struct Vec2Field - { +struct Vec2Field +{ StringType label; StringType tooltip; StringType edit; vec2 Frame::* member; bool isRegionField; - }; +}; - constexpr Vec2Field VEC2_FIELDS[] = { - {BASIC_CROP, TOOLTIP_CROP, EDIT_FRAME_CROP, &Frame::crop, true}, - {BASIC_SIZE, TOOLTIP_SIZE, EDIT_FRAME_SIZE, &Frame::size, true}, - {BASIC_POSITION, TOOLTIP_POSITION, EDIT_FRAME_POSITION, &Frame::position, false}, - {BASIC_PIVOT, TOOLTIP_PIVOT, EDIT_FRAME_PIVOT, &Frame::pivot, true}, - {BASIC_SCALE, TOOLTIP_SCALE, EDIT_FRAME_SCALE, &Frame::scale, false}, - {BASIC_SKEW, TOOLTIP_SKEW, EDIT_FRAME_SKEW, &Frame::skew, false}}; +constexpr Vec2Field VEC2_FIELDS[] = {{BASIC_CROP, TOOLTIP_CROP, EDIT_FRAME_CROP, &Frame::crop, true}, + {BASIC_SIZE, TOOLTIP_SIZE, EDIT_FRAME_SIZE, &Frame::size, true}, + {BASIC_POSITION, TOOLTIP_POSITION, EDIT_FRAME_POSITION, &Frame::position, false}, + {BASIC_PIVOT, TOOLTIP_PIVOT, EDIT_FRAME_PIVOT, &Frame::pivot, true}, + {BASIC_SCALE, TOOLTIP_SCALE, EDIT_FRAME_SCALE, &Frame::scale, false}, + {BASIC_SKEW, TOOLTIP_SKEW, EDIT_FRAME_SKEW, &Frame::skew, false}}; - struct FlipButton - { +struct FlipButton +{ StringType label; StringType edit; StringType tooltip; - }; +}; - constexpr FlipButton FLIP_BUTTONS[] = {{LABEL_FLIP_X, EDIT_FRAME_FLIP_X, TOOLTIP_FLIP_X}, - {LABEL_FLIP_Y, EDIT_FRAME_FLIP_Y, TOOLTIP_FLIP_Y}}; +constexpr FlipButton FLIP_BUTTONS[] = {{LABEL_FLIP_X, EDIT_FRAME_FLIP_X, TOOLTIP_FLIP_X}, + {LABEL_FLIP_Y, EDIT_FRAME_FLIP_Y, TOOLTIP_FLIP_Y}}; - void frame_properties_update(Manager& manager, Settings& settings, FramePropertiesPanel& panel) - { +void frame_properties_update(Manager& manager, Settings& settings, FramePropertiesPanel& panel) +{ auto& [changeAllFrameProperties, isBatchMode] = panel; auto& document = *manager.get(); auto frameSelectionCount = document.frame_references_get(Document::FrameReferenceFallback::NONE).size(); - if (frameSelectionCount == 0 && document.reference_get().frameIndex >= 0) frameSelectionCount = 1; + if (frameSelectionCount == 0 && document.reference_get().frameIndex >= 0) + frameSelectionCount = 1; auto isSingleFrameSelection = frameSelectionCount == 1; auto isMultiFrameSelection = frameSelectionCount > 1; auto isSingleFrameBatchMode = isSingleFrameSelection && document.reference_get().itemType != TRIGGER && isBatchMode; auto isBatchFrameProperties = isMultiFrameSelection || isSingleFrameBatchMode; auto windowLabel = std::string( localize.get(isBatchFrameProperties ? LABEL_CHANGE_ALL_FRAME_PROPERTIES : LABEL_FRAME_PROPERTIES_WINDOW)); - if (isBatchFrameProperties) windowLabel += "###Frame Properties"; + if (isBatchFrameProperties) + windowLabel += "###Frame Properties"; if (ImGui::Begin(windowLabel.c_str(), &settings.windowIsFrameProperties)) { - auto& model = document.model; - auto reference = document.reference_get(); - auto& type = reference.itemType; - auto frame = model.frame_get(reference); + auto& model = document.model; + auto reference = document.reference_get(); + auto& type = reference.itemType; + auto frame = model.frame_get(reference); - auto frame_edit = [&](EditState state, StringType message, auto behavior) - { - if (state == EDIT_STATE_NONE) return; - manager.command_push({manager.selected, [=, queuedReference = reference](Manager&, Document& document) mutable - { - if (!document.model.frame_get(queuedReference)) return; - if (state == EDIT_STATE_START || state == EDIT_STATE_COMPLETE) - document.edit_begin(message); - auto item = document.model.track_edit(queuedReference); - behavior(document, item->frames[queuedReference.frameIndex], item, queuedReference); - if (state == EDIT_STATE_END || state == EDIT_STATE_COMPLETE) document.change(); - }}); - }; + auto frame_edit = [&](EditState state, StringType message, auto behavior) { + if (state == EDIT_STATE_NONE) + return; + manager.command_push( + {manager.selected, [=, queuedReference = reference](Manager&, Document& document) mutable { + if (!document.model.frame_get(queuedReference)) + return; + if (state == EDIT_STATE_START || state == EDIT_STATE_COMPLETE) + document.edit_begin(message); + auto item = document.model.track_edit(queuedReference); + behavior(document, item->frames[queuedReference.frameIndex], item, queuedReference); + if (state == EDIT_STATE_END || state == EDIT_STATE_COMPLETE) + document.change(); + }}); + }; - auto regions = document.choices_get(SelectionKind::REGIONS, type == LAYER ? reference.itemID : -1); - auto events = document.choices_get(SelectionKind::EVENTS); - auto sounds = document.choices_get(SelectionKind::SOUNDS); - auto shaders = document.choices_get(SelectionKind::SHADERS); - std::vector interpolationLabels; - for (auto label : INTERPOLATION_LABELS) - interpolationLabels.push_back(localize.get(label)); + auto regions = document.choices_get(SelectionKind::REGIONS, type == LAYER ? reference.itemID : -1); + auto events = document.choices_get(SelectionKind::EVENTS); + auto sounds = document.choices_get(SelectionKind::SOUNDS); + auto shaders = document.choices_get(SelectionKind::SHADERS); + std::vector interpolationLabels; + for (auto label : INTERPOLATION_LABELS) + interpolationLabels.push_back(localize.get(label)); - auto mode_selector_draw = [&]() - { - if (!isSingleFrameSelection || type == TRIGGER) return; - ImGui::SeparatorText(localize.get(BASIC_MODE)); - int mode = isBatchMode ? 1 : 0; - ImGui::RadioButton(localize.get(BASIC_SINGLE), &mode, 0); - ImGui::SameLine(); - ImGui::RadioButton(localize.get(BASIC_BATCH), &mode, 1); - isBatchMode = mode == 1; - }; + auto mode_selector_draw = [&]() { + if (!isSingleFrameSelection || type == TRIGGER) + return; + ImGui::SeparatorText(localize.get(BASIC_MODE)); + int mode = isBatchMode ? 1 : 0; + ImGui::RadioButton(localize.get(BASIC_SINGLE), &mode, 0); + ImGui::SameLine(); + ImGui::RadioButton(localize.get(BASIC_BATCH), &mode, 1); + isBatchMode = mode == 1; + }; - if (isSingleFrameBatchMode) - { - changeAllFrameProperties.update(manager, document, settings); - mode_selector_draw(); - } - else if (!isMultiFrameSelection) - { - auto useFrame = frame ? *frame : Frame(); - auto displayFrame = frame && type == LAYER && reference.itemID != -1 - ? model.frame_effective(reference.itemID, *frame) - : useFrame; - - ImGui::BeginDisabled(!frame); + if (isSingleFrameBatchMode) { - if (type == TRIGGER) - { - if (input_int_range(localize.get(BASIC_AT_FRAME), frame ? useFrame.atFrame : dummy_value(), 0, - std::numeric_limits::max(), STEP, STEP_FAST, - !frame ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0) && - frame) - { - auto atFrame = useFrame.atFrame; - frame_edit(EDIT_STATE_COMPLETE, EDIT_TRIGGER_AT_FRAME, - [atFrame](Document& document, Frame& frame, Track* item, const Reference&) - { - frame.atFrame = atFrame; - if (!item) return; - frames_sort_by_at_frame(*item); - auto reference = document.reference_get(); - reference.frameIndex = frame_index_from_at_frame_get(*item, atFrame); - document.reference_set(reference); - document.frame_references_set({reference}); - }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRIGGER_AT_FRAME)); - - if (ImGui::Checkbox(localize.get(BASIC_VISIBLE), frame ? &useFrame.isVisible : &dummy_value()) && - frame) - { - auto isVisible = useFrame.isVisible; - frame_edit(EDIT_STATE_COMPLETE, EDIT_TRIGGER_VISIBILITY, - [isVisible](Document&, Frame& frame, Track*, const Reference&) - { frame.isVisible = isVisible; }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRIGGER_VISIBILITY)); - - // A trigger's events or sounds: a combo for each, then Add and Remove (the last). - auto trigger_ids_draw = [&](StringType label, std::vector Frame::* member, - const Choices& choices, ImVec2 size, StringType tooltip, StringType setEdit, - StringType addEdit, StringType addTooltip, StringType removeEdit, - StringType removeTooltip) - { - ImGui::PushID(label); - ImGui::SeparatorText(localize.get(label)); - if (ImGui::BeginChild("##Child", size, ImGuiChildFlags_Borders)) - for (auto [i, id] : std::views::enumerate(useFrame.*member)) - { - ImGui::PushID(i); - if (combo_id_mapped("##Choice", &id, choices.ids, choices.labels) && frame) - frame_edit(EDIT_STATE_COMPLETE, setEdit, - [index = (std::size_t)i, id, member](Document&, Frame& frame, Track*, - const Reference&) - { - if (index < (frame.*member).size()) (frame.*member)[index] = id; - }); - ImGui::SetItemTooltip("%s", localize.get(tooltip)); - ImGui::PopID(); - } - ImGui::EndChild(); - - auto widgetSize = widget_size_with_row_get(2); - if (ImGui::Button(localize.get(BASIC_ADD), widgetSize) && frame) - frame_edit(EDIT_STATE_COMPLETE, addEdit, - [member](Document&, Frame& frame, Track*, const Reference&) - { (frame.*member).push_back(-1); }); - ImGui::SetItemTooltip("%s", localize.get(addTooltip)); - ImGui::SameLine(); - ImGui::BeginDisabled((useFrame.*member).empty()); - if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize) && frame) - frame_edit(EDIT_STATE_COMPLETE, removeEdit, - [member](Document&, Frame& frame, Track*, const Reference&) - { - if (!(frame.*member).empty()) (frame.*member).pop_back(); - }); - ImGui::SetItemTooltip("%s", localize.get(removeTooltip)); - ImGui::EndDisabled(); - ImGui::PopID(); - }; - - trigger_ids_draw(LABEL_EVENTS, &Frame::eventIds, events, child_size_get(TRIGGER_EVENTS_ROWS), - TOOLTIP_TRIGGER_EVENT, EDIT_TRIGGER_EVENT, EDIT_ADD_TRIGGER_EVENT, - TOOLTIP_ADD_TRIGGER_EVENT, EDIT_REMOVE_TRIGGER_EVENT, TOOLTIP_REMOVE_TRIGGER_EVENT); - trigger_ids_draw(LABEL_SOUNDS, &Frame::soundIds, sounds, size_without_footer_get(), - TOOLTIP_TRIGGER_SOUND, EDIT_TRIGGER_SOUND, EDIT_ADD_TRIGGER_SOUND, - TOOLTIP_ADD_TRIGGER_SOUND, EDIT_REMOVE_TRIGGER_SOUND, TOOLTIP_REMOVE_TRIGGER_SOUND); - } - else - { - auto layer = type == LAYER ? item_get(model.content.layers, reference.itemID) : nullptr; - auto isAnimationLayer = layer && layer->is_animation(); - bool isRegionSet = frame && displayFrame.regionId != -1 && displayFrame.crop == frame->crop && - displayFrame.size == frame->size && displayFrame.pivot == frame->pivot; - for (auto& field : VEC2_FIELDS) - { - auto& source = field.isRegionField ? displayFrame : useFrame; - auto value = frame ? source.*field.member : vec2(); - // An animation layer's pivot is where its child's origin goes; it has no crop or size. - ImGui::BeginDisabled(field.isRegionField && (type == ROOT || type == NULL_ || isRegionSet || - (isAnimationLayer && field.member != &Frame::pivot))); - auto state = - drag_float2_persistent(localize.get(field.label), frame ? &value : &dummy_value(), DRAG_SPEED, - 0.0f, 0.0f, frame ? vec2_format_get(source.*field.member) : ""); - frame_edit(state, field.edit, - [value, member = field.member](Document&, Frame& frame, Track*, const Reference&) - { frame.*member = value; }); - ImGui::SetItemTooltip("%s", localize.get(field.tooltip)); - ImGui::EndDisabled(); - } - - auto rotationEdit = - drag_float_persistent(localize.get(BASIC_ROTATION), frame ? &useFrame.rotation : &dummy_value(), - DRAG_SPEED, 0.0f, 0.0f, frame ? float_format_get(frame->rotation) : ""); - frame_edit(rotationEdit, EDIT_FRAME_ROTATION, - [rotation = useFrame.rotation](Document&, Frame& frame, Track*, const Reference&) - { frame.rotation = rotation; }); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROTATION)); - - if (input_int_range(localize.get(BASIC_DURATION), frame ? useFrame.duration : dummy_value(), - frame ? FRAME_DURATION_MIN : 0, FRAME_DURATION_MAX, STEP, STEP_FAST, - !frame ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0) && - frame) - { - auto duration = useFrame.duration; - frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_DURATION, - [duration](Document&, Frame& frame, Track*, const Reference&) - { frame.duration = duration; }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DURATION)); - - ImGui::BeginDisabled(type != LAYER); - if (input_int_range(localize.get(BASIC_DEPTH), frame && type == LAYER ? useFrame.depth : dummy_value(), - -FRAME_DEPTH_MAX, FRAME_DEPTH_MAX, STEP, STEP_FAST, - !frame ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0) && - frame) - { - auto depth = useFrame.depth; - frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_DEPTH, - [depth](Document&, Frame& frame, Track*, const Reference&) - { frame.depth = depth; }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DEPTH)); - ImGui::EndDisabled(); - - auto tintEdit = - color_edit4_persistent(localize.get(BASIC_TINT), frame ? &useFrame.tint : &dummy_value()); - frame_edit(tintEdit, EDIT_FRAME_TINT, - [tint = useFrame.tint](Document&, Frame& frame, Track*, const Reference&) - { frame.tint = tint; }); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TINT)); - - auto colorOffsetEdit = color_edit4_persistent(localize.get(BASIC_COLOR_OFFSET), - frame ? &useFrame.colorOffset : &dummy_value()); - frame_edit(colorOffsetEdit, EDIT_FRAME_COLOR_OFFSET, - [colorOffset = useFrame.colorOffset](Document&, Frame& frame, Track*, - const Reference&) { frame.colorOffset = colorOffset; }); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_COLOR_OFFSET)); - - ImGui::BeginDisabled(type != LAYER); - auto blurEdit = - drag_float_persistent(localize.get(BASIC_BLUR), frame ? &useFrame.blur : &dummy_value(), - DRAG_SPEED, 0.0f, FRAME_BLUR_MAX, frame ? float_format_get(frame->blur) : ""); - frame_edit(blurEdit, EDIT_FRAME_BLUR, - [blur = useFrame.blur](Document&, Frame& frame, Track*, const Reference&) - { frame.blur = std::clamp(blur, 0.0f, FRAME_BLUR_MAX); }); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BLUR)); - ImGui::EndDisabled(); - - ImGui::BeginDisabled(type != LAYER || isAnimationLayer); - if (combo_id_mapped(localize.get(BASIC_REGION), frame ? &useFrame.regionId : &dummy_value_negative(), - regions.ids, regions.labels) && - frame) - { - auto regionId = useFrame.regionId; - frame_edit(EDIT_STATE_COMPLETE, EDIT_SET_REGION_PROPERTIES, - [regionId](Document& document, Frame& frame, Track*, const Reference& reference) - { - frame.regionId = regionId; - auto effectiveFrame = document.model.frame_effective(reference.itemID, frame); - frame.crop = effectiveFrame.crop; - frame.size = effectiveFrame.size; - frame.pivot = effectiveFrame.pivot; - }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REGION)); - ImGui::EndDisabled(); - - auto interpolationValue = frame ? static_cast(useFrame.interpolation) : dummy_value(); - if (ImGui::Combo(localize.get(BASIC_INTERPOLATED), &interpolationValue, interpolationLabels.data(), - (int)interpolationLabels.size()) && - frame) - frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_INTERPOLATION, - [interpolationValue](Document&, Frame& frame, Track*, const Reference&) - { frame.interpolation = static_cast(interpolationValue); }); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_INTERPOLATION)); - - ImGui::BeginDisabled(type != LAYER || isAnimationLayer); - if (combo_id_mapped(localize.get(BASIC_SHADER), frame ? &useFrame.shaderId : &dummy_value_negative(), - shaders.ids, shaders.labels) && - frame) - { - auto shaderId = useFrame.shaderId; - frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_SHADER, - [shaderId](Document&, Frame& frame, Track*, const Reference&) - { frame.shaderId = shaderId; }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_SHADER)); - ImGui::EndDisabled(); - - if (ImGui::Checkbox(localize.get(BASIC_VISIBLE), frame ? &useFrame.isVisible : &dummy_value()) && - frame) - { - auto isVisible = useFrame.isVisible; - frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_VISIBILITY, - [isVisible](Document&, Frame& frame, Track*, const Reference&) - { frame.isVisible = isVisible; }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_VISIBILITY)); - - auto widgetSize = widget_size_with_row_get(2); - - for (int axis = 0; axis < (int)std::size(FLIP_BUTTONS); ++axis) - { - if (axis > 0) ImGui::SameLine(); - if (ImGui::Button(localize.get(FLIP_BUTTONS[axis].label), widgetSize) && frame) - frame_edit(EDIT_STATE_COMPLETE, FLIP_BUTTONS[axis].edit, - [axis, isPositionFlipped = ImGui::IsKeyDown(ImGuiMod_Ctrl)](Document&, Frame& frame, - Track*, const Reference&) - { - frame.scale[axis] = -frame.scale[axis]; - if (isPositionFlipped) frame.position[axis] = -frame.position[axis]; - }); - ImGui::SetItemTooltip("%s", localize.get(FLIP_BUTTONS[axis].tooltip)); - } - - if (isAnimationLayer && frame) - { - ImGui::SeparatorText(localize.get(LABEL_CHILD)); - auto values = document.animation_names_get(layer->libraryId); - auto labels = values; - values.insert(values.begin(), std::string{}); - labels.insert(labels.begin(), localize.get(TEXT_LAYER_ANIMATION)); - bool isChildChanged = - combo_string_mapped(localize.get(LABEL_ANIMATION), &useFrame.childAnimation, values, labels); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_ANIMATION)); - - std::vector modeLabels; - for (auto label : CHILD_MODE_LABELS) - modeLabels.push_back(localize.get(label)); - auto mode = (int)useFrame.childMode; - if (ImGui::Combo(localize.get(BASIC_MODE), &mode, modeLabels.data(), (int)modeLabels.size())) - { - useFrame.childMode = (ChildMode)mode; - isChildChanged = true; - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_MODE)); - - ImGui::BeginDisabled(useFrame.isChildStartRandom); - isChildChanged |= input_int_range(localize.get(LABEL_START_FRAME), useFrame.childStart, 0, FRAME_NUM_MAX, - STEP, STEP_FAST); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_START)); - ImGui::EndDisabled(); - - isChildChanged |= ImGui::Checkbox(localize.get(LABEL_RANDOM), &useFrame.isChildStartRandom); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_START_RANDOM)); - ImGui::SameLine(); - isChildChanged |= ImGui::Checkbox(localize.get(LABEL_RESTART), &useFrame.isChildRestart); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_RESTART)); - - if (isChildChanged) - frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_CHILD, - [child = useFrame](Document&, Frame& frame, Track*, const Reference&) - { frame_property_copy(frame, child, FrameProperty::CHILD); }); - } - - ImGui::Separator(); - ImGui::Dummy(ImVec2(0.0f, ImGui::GetFrameHeight())); - } + changeAllFrameProperties.update(manager, document, settings); + mode_selector_draw(); } - ImGui::EndDisabled(); + else if (!isMultiFrameSelection) + { + auto useFrame = frame ? *frame : Frame(); + auto displayFrame = frame && type == LAYER && reference.itemID != -1 + ? model.frame_effective(reference.itemID, *frame) + : useFrame; - mode_selector_draw(); - } - else - changeAllFrameProperties.update(manager, document, settings); + ImGui::BeginDisabled(!frame); + { + if (type == TRIGGER) + { + if (input_int_range(localize.get(BASIC_AT_FRAME), frame ? useFrame.atFrame : dummy_value(), 0, + std::numeric_limits::max(), STEP, STEP_FAST, + !frame ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0) && + frame) + { + auto atFrame = useFrame.atFrame; + frame_edit(EDIT_STATE_COMPLETE, EDIT_TRIGGER_AT_FRAME, + [atFrame](Document& document, Frame& frame, Track* item, const Reference&) { + frame.atFrame = atFrame; + if (!item) + return; + frames_sort_by_at_frame(*item); + auto reference = document.reference_get(); + reference.frameIndex = frame_index_from_at_frame_get(*item, atFrame); + document.reference_set(reference); + document.frame_references_set({reference}); + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRIGGER_AT_FRAME)); + + if (ImGui::Checkbox(localize.get(BASIC_VISIBLE), + frame ? &useFrame.isVisible : &dummy_value()) && + frame) + { + auto isVisible = useFrame.isVisible; + frame_edit(EDIT_STATE_COMPLETE, EDIT_TRIGGER_VISIBILITY, + [isVisible](Document&, Frame& frame, Track*, const Reference&) { + frame.isVisible = isVisible; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRIGGER_VISIBILITY)); + + // A trigger's events or sounds: a combo for each, then Add and Remove (the last). + auto trigger_ids_draw = [&](StringType label, std::vector Frame::* member, + const Choices& choices, ImVec2 size, StringType tooltip, + StringType setEdit, StringType addEdit, StringType addTooltip, + StringType removeEdit, StringType removeTooltip) { + ImGui::PushID(label); + ImGui::SeparatorText(localize.get(label)); + if (ImGui::BeginChild("##Child", size, ImGuiChildFlags_Borders)) + for (auto [i, id] : std::views::enumerate(useFrame.*member)) + { + ImGui::PushID(i); + if (combo_id_mapped("##Choice", &id, choices.ids, choices.labels) && frame) + frame_edit(EDIT_STATE_COMPLETE, setEdit, + [index = (std::size_t)i, id, member](Document&, Frame& frame, Track*, + const Reference&) { + if (index < (frame.*member).size()) + (frame.*member)[index] = id; + }); + ImGui::SetItemTooltip("%s", localize.get(tooltip)); + ImGui::PopID(); + } + ImGui::EndChild(); + + auto widgetSize = widget_size_with_row_get(2); + if (ImGui::Button(localize.get(BASIC_ADD), widgetSize) && frame) + frame_edit(EDIT_STATE_COMPLETE, addEdit, + [member](Document&, Frame& frame, Track*, const Reference&) { + (frame.*member).push_back(-1); + }); + ImGui::SetItemTooltip("%s", localize.get(addTooltip)); + ImGui::SameLine(); + ImGui::BeginDisabled((useFrame.*member).empty()); + if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize) && frame) + frame_edit(EDIT_STATE_COMPLETE, removeEdit, + [member](Document&, Frame& frame, Track*, const Reference&) { + if (!(frame.*member).empty()) + (frame.*member).pop_back(); + }); + ImGui::SetItemTooltip("%s", localize.get(removeTooltip)); + ImGui::EndDisabled(); + ImGui::PopID(); + }; + + trigger_ids_draw(LABEL_EVENTS, &Frame::eventIds, events, child_size_get(TRIGGER_EVENTS_ROWS), + TOOLTIP_TRIGGER_EVENT, EDIT_TRIGGER_EVENT, EDIT_ADD_TRIGGER_EVENT, + TOOLTIP_ADD_TRIGGER_EVENT, EDIT_REMOVE_TRIGGER_EVENT, + TOOLTIP_REMOVE_TRIGGER_EVENT); + trigger_ids_draw(LABEL_SOUNDS, &Frame::soundIds, sounds, size_without_footer_get(), + TOOLTIP_TRIGGER_SOUND, EDIT_TRIGGER_SOUND, EDIT_ADD_TRIGGER_SOUND, + TOOLTIP_ADD_TRIGGER_SOUND, EDIT_REMOVE_TRIGGER_SOUND, + TOOLTIP_REMOVE_TRIGGER_SOUND); + } + else + { + auto layer = type == LAYER ? item_get(model.content.layers, reference.itemID) : nullptr; + auto isAnimationLayer = layer && layer->is_animation(); + bool isRegionSet = frame && displayFrame.regionId != -1 && displayFrame.crop == frame->crop && + displayFrame.size == frame->size && displayFrame.pivot == frame->pivot; + for (auto& field : VEC2_FIELDS) + { + auto& source = field.isRegionField ? displayFrame : useFrame; + auto value = frame ? source.*field.member : vec2(); + // An animation layer's pivot is where its child's origin goes. It has no crop or size. + ImGui::BeginDisabled(field.isRegionField && + (type == ROOT || type == NULL_ || isRegionSet || + (isAnimationLayer && field.member != &Frame::pivot))); + auto state = drag_float2_persistent(localize.get(field.label), + frame ? &value : &dummy_value(), DRAG_SPEED, 0.0f, + 0.0f, frame ? vec2_format_get(source.*field.member) : ""); + frame_edit(state, field.edit, + [value, member = field.member](Document&, Frame& frame, Track*, const Reference&) { + frame.*member = value; + }); + ImGui::SetItemTooltip("%s", localize.get(field.tooltip)); + ImGui::EndDisabled(); + } + + auto rotationEdit = drag_float_persistent( + localize.get(BASIC_ROTATION), frame ? &useFrame.rotation : &dummy_value(), DRAG_SPEED, + 0.0f, 0.0f, frame ? float_format_get(frame->rotation) : ""); + frame_edit(rotationEdit, EDIT_FRAME_ROTATION, + [rotation = useFrame.rotation](Document&, Frame& frame, Track*, const Reference&) { + frame.rotation = rotation; + }); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROTATION)); + + if (input_int_range(localize.get(BASIC_DURATION), frame ? useFrame.duration : dummy_value(), + frame ? FRAME_DURATION_MIN : 0, FRAME_DURATION_MAX, STEP, STEP_FAST, + !frame ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0) && + frame) + { + auto duration = useFrame.duration; + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_DURATION, + [duration](Document&, Frame& frame, Track*, const Reference&) { + frame.duration = duration; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DURATION)); + + ImGui::BeginDisabled(type != LAYER); + if (input_int_range(localize.get(BASIC_DEPTH), + frame && type == LAYER ? useFrame.depth : dummy_value(), -FRAME_DEPTH_MAX, + FRAME_DEPTH_MAX, STEP, STEP_FAST, + !frame ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0) && + frame) + { + auto depth = useFrame.depth; + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_DEPTH, + [depth](Document&, Frame& frame, Track*, const Reference&) { frame.depth = depth; }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DEPTH)); + ImGui::EndDisabled(); + + auto tintEdit = + color_edit4_persistent(localize.get(BASIC_TINT), frame ? &useFrame.tint : &dummy_value()); + frame_edit(tintEdit, EDIT_FRAME_TINT, + [tint = useFrame.tint](Document&, Frame& frame, Track*, const Reference&) { + frame.tint = tint; + }); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TINT)); + + auto colorOffsetEdit = color_edit4_persistent(localize.get(BASIC_COLOR_OFFSET), + frame ? &useFrame.colorOffset : &dummy_value()); + frame_edit(colorOffsetEdit, EDIT_FRAME_COLOR_OFFSET, + [colorOffset = useFrame.colorOffset](Document&, Frame& frame, Track*, const Reference&) { + frame.colorOffset = colorOffset; + }); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_COLOR_OFFSET)); + + ImGui::BeginDisabled(type != LAYER); + auto blurEdit = drag_float_persistent( + localize.get(BASIC_BLUR), frame ? &useFrame.blur : &dummy_value(), DRAG_SPEED, 0.0f, + FRAME_BLUR_MAX, frame ? float_format_get(frame->blur) : ""); + frame_edit(blurEdit, EDIT_FRAME_BLUR, + [blur = useFrame.blur](Document&, Frame& frame, Track*, const Reference&) { + frame.blur = std::clamp(blur, 0.0f, FRAME_BLUR_MAX); + }); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BLUR)); + ImGui::EndDisabled(); + + ImGui::BeginDisabled(type != LAYER || isAnimationLayer); + if (combo_id_mapped(localize.get(BASIC_REGION), + frame ? &useFrame.regionId : &dummy_value_negative(), regions.ids, + regions.labels) && + frame) + { + auto regionId = useFrame.regionId; + frame_edit(EDIT_STATE_COMPLETE, EDIT_SET_REGION_PROPERTIES, + [regionId](Document& document, Frame& frame, Track*, const Reference& reference) { + frame.regionId = regionId; + auto effectiveFrame = document.model.frame_effective(reference.itemID, frame); + frame.crop = effectiveFrame.crop; + frame.size = effectiveFrame.size; + frame.pivot = effectiveFrame.pivot; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REGION)); + ImGui::EndDisabled(); + + auto interpolationValue = frame ? static_cast(useFrame.interpolation) : dummy_value(); + if (ImGui::Combo(localize.get(BASIC_INTERPOLATED), &interpolationValue, interpolationLabels.data(), + (int)interpolationLabels.size()) && + frame) + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_INTERPOLATION, + [interpolationValue](Document&, Frame& frame, Track*, const Reference&) { + frame.interpolation = static_cast(interpolationValue); + }); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_INTERPOLATION)); + + ImGui::BeginDisabled(type != LAYER || isAnimationLayer); + if (combo_id_mapped(localize.get(BASIC_SHADER), + frame ? &useFrame.shaderId : &dummy_value_negative(), shaders.ids, + shaders.labels) && + frame) + { + auto shaderId = useFrame.shaderId; + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_SHADER, + [shaderId](Document&, Frame& frame, Track*, const Reference&) { + frame.shaderId = shaderId; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_SHADER)); + ImGui::EndDisabled(); + + if (ImGui::Checkbox(localize.get(BASIC_VISIBLE), + frame ? &useFrame.isVisible : &dummy_value()) && + frame) + { + auto isVisible = useFrame.isVisible; + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_VISIBILITY, + [isVisible](Document&, Frame& frame, Track*, const Reference&) { + frame.isVisible = isVisible; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_VISIBILITY)); + + auto widgetSize = widget_size_with_row_get(2); + + for (int axis = 0; axis < (int)std::size(FLIP_BUTTONS); ++axis) + { + if (axis > 0) + ImGui::SameLine(); + if (ImGui::Button(localize.get(FLIP_BUTTONS[axis].label), widgetSize) && frame) + frame_edit(EDIT_STATE_COMPLETE, FLIP_BUTTONS[axis].edit, + [axis, isPositionFlipped = ImGui::IsKeyDown(ImGuiMod_Ctrl)]( + Document&, Frame& frame, Track*, const Reference&) { + frame.scale[axis] = -frame.scale[axis]; + if (isPositionFlipped) + frame.position[axis] = -frame.position[axis]; + }); + ImGui::SetItemTooltip("%s", localize.get(FLIP_BUTTONS[axis].tooltip)); + } + + if (isAnimationLayer && frame) + { + ImGui::SeparatorText(localize.get(LABEL_CHILD)); + auto values = document.animation_names_get(layer->libraryId); + auto labels = values; + values.insert(values.begin(), std::string{}); + labels.insert(labels.begin(), localize.get(TEXT_LAYER_ANIMATION)); + bool isChildChanged = combo_string_mapped(localize.get(LABEL_ANIMATION), + &useFrame.childAnimation, values, labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_ANIMATION)); + + std::vector modeLabels; + for (auto label : CHILD_MODE_LABELS) + modeLabels.push_back(localize.get(label)); + auto mode = (int)useFrame.childMode; + if (ImGui::Combo(localize.get(BASIC_MODE), &mode, modeLabels.data(), (int)modeLabels.size())) + { + useFrame.childMode = (ChildMode)mode; + isChildChanged = true; + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_MODE)); + + ImGui::BeginDisabled(useFrame.isChildStartRandom); + isChildChanged |= input_int_range(localize.get(LABEL_START_FRAME), useFrame.childStart, 0, + FRAME_NUM_MAX, STEP, STEP_FAST); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_START)); + ImGui::EndDisabled(); + + isChildChanged |= ImGui::Checkbox(localize.get(LABEL_RANDOM), &useFrame.isChildStartRandom); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_START_RANDOM)); + ImGui::SameLine(); + isChildChanged |= ImGui::Checkbox(localize.get(LABEL_RESTART), &useFrame.isChildRestart); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_RESTART)); + + if (isChildChanged) + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_CHILD, + [child = useFrame](Document&, Frame& frame, Track*, const Reference&) { + frame_property_copy(frame, child, FrameProperty::CHILD); + }); + } + + ImGui::Separator(); + ImGui::Dummy(ImVec2(0.0f, ImGui::GetFrameHeight())); + } + } + ImGui::EndDisabled(); + + mode_selector_draw(); + } + else + changeAllFrameProperties.update(manager, document, settings); } ImGui::End(); @@ -400,4 +421,4 @@ using namespace glm; dummy_value() = 0; dummy_value() = vec2(); dummy_value() = vec4(); - } +} diff --git a/src/ui/generate_animation_from_grid.cpp b/src/ui/generate_animation_from_grid.cpp index fd1268b..6b46590 100644 --- a/src/ui/generate_animation_from_grid.cpp +++ b/src/ui/generate_animation_from_grid.cpp @@ -13,10 +13,11 @@ using namespace glm; - GenerateAnimationFromGrid::GenerateAnimationFromGrid() : Canvas(vec2()) {} +GenerateAnimationFromGrid::GenerateAnimationFromGrid() : Canvas(vec2()) +{} - void GenerateAnimationFromGrid::update(Manager& manager, Document& document, Resources& resources, Settings& settings) - { +void GenerateAnimationFromGrid::update(Manager& manager, Document& document, Resources& resources, Settings& settings) +{ isEnd = false; auto& model = document.model; @@ -34,30 +35,30 @@ using namespace glm; auto layerReferences = document.layer_references_get(); auto previewReference = layerReferences.empty() ? Reference{} : layerReferences.front(); for (auto itemReference : layerReferences) - if (itemReference.animationIndex == reference.animationIndex && itemReference.itemType == reference.itemType && - itemReference.itemID == reference.itemID) - previewReference = itemReference; + if (itemReference.animationIndex == reference.animationIndex && itemReference.itemType == reference.itemType && + itemReference.itemID == reference.itemID) + previewReference = itemReference; auto childSize = ImVec2(row_widget_width_get(2), size_without_footer_get().y); if (ImGui::BeginChild("##Options Child", childSize, ImGuiChildFlags_Borders)) { - ImGui::InputInt2(localize.get(LABEL_GENERATE_START_POSITION), value_ptr(startPosition)); - ImGui::InputInt2(localize.get(LABEL_GENERATE_FRAME_SIZE), value_ptr(size)); - ImGui::InputFloat2(localize.get(BASIC_PIVOT), value_ptr(pivot), vec2_format_get(pivot)); - ImGui::InputInt(localize.get(LABEL_GENERATE_ROWS), &rows, STEP, STEP_FAST); - ImGui::InputInt(localize.get(LABEL_GENERATE_COLUMNS), &columns, STEP, STEP_FAST); + ImGui::InputInt2(localize.get(LABEL_GENERATE_START_POSITION), value_ptr(startPosition)); + ImGui::InputInt2(localize.get(LABEL_GENERATE_FRAME_SIZE), value_ptr(size)); + ImGui::InputFloat2(localize.get(BASIC_PIVOT), value_ptr(pivot), vec2_format_get(pivot)); + ImGui::InputInt(localize.get(LABEL_GENERATE_ROWS), &rows, STEP, STEP_FAST); + ImGui::InputInt(localize.get(LABEL_GENERATE_COLUMNS), &columns, STEP, STEP_FAST); - input_int_range(localize.get(LABEL_GENERATE_COUNT), count, FRAME_NUM_MIN, rows * columns); + input_int_range(localize.get(LABEL_GENERATE_COUNT), count, FRAME_NUM_MIN, rows * columns); - ImGui::InputInt(localize.get(BASIC_DURATION), &delay, STEP, STEP_FAST); - ImGui::Separator(); - ImGui::Checkbox(localize.get(LABEL_GENERATE_MAKE_REGIONS), &isMakeRegions); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GENERATE_MAKE_REGIONS)); - ImGui::BeginDisabled(!isMakeRegions); - input_text_string(localize.get(LABEL_FORMAT), ®ionNameFormat); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GENERATE_REGION_NAME_FORMAT)); - ImGui::EndDisabled(); + ImGui::InputInt(localize.get(BASIC_DURATION), &delay, STEP, STEP_FAST); + ImGui::Separator(); + ImGui::Checkbox(localize.get(LABEL_GENERATE_MAKE_REGIONS), &isMakeRegions); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GENERATE_MAKE_REGIONS)); + ImGui::BeginDisabled(!isMakeRegions); + input_text_string(localize.get(LABEL_FORMAT), ®ionNameFormat); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GENERATE_REGION_NAME_FORMAT)); + ImGui::EndDisabled(); } ImGui::EndChild(); @@ -70,61 +71,60 @@ using namespace glm; if (ImGui::BeginChild("##Preview Child", childSize, ImGuiChildFlags_Borders)) { - auto& backgroundColor = settings.previewBackgroundColor; - auto& isTransparent = settings.animationPreviewTransparent; - auto& shaderTexture = resources.shaders[SHADER_TEXTURE]; + auto& backgroundColor = settings.previewBackgroundColor; + auto& isTransparent = settings.animationPreviewTransparent; + auto& shaderTexture = resources.shaders[SHADER_TEXTURE]; - auto previewSize = ImVec2(ImGui::GetContentRegionAvail().x, size_without_footer_get(2).y); - auto previewMin = ImGui::GetCursorScreenPos(); - auto previewMax = to_imvec2(to_vec2(previewMin) + to_vec2(previewSize)); + auto previewSize = ImVec2(ImGui::GetContentRegionAvail().x, size_without_footer_get(2).y); + auto previewMin = ImGui::GetCursorScreenPos(); + auto previewMax = to_imvec2(to_vec2(previewMin) + to_vec2(previewSize)); - size_set(to_vec2(previewSize)); - bind(); - viewport_set(); - clear(isTransparent ? vec4(0) : vec4(backgroundColor, 1.0f)); + size_set(to_vec2(previewSize)); + bind(); + viewport_set(); + clear(isTransparent ? vec4(0) : vec4(backgroundColor, 1.0f)); - if (!layerReferences.empty()) - { - auto layer = item_get(model.content.layers, previewReference.itemID); - auto sourceTexture = layer ? document.texture_get(layer->spritesheetId) : nullptr; - if (sourceTexture && sourceTexture->is_valid()) + if (!layerReferences.empty()) { - Track previewTrack = {}; - frames_generate_from_grid(previewTrack, startPosition, size, pivot, columns, count, delay); + auto layer = item_get(model.content.layers, previewReference.itemID); + auto sourceTexture = layer ? document.texture_get(layer->spritesheetId) : nullptr; + if (sourceTexture && sourceTexture->is_valid()) + { + Track previewTrack = {}; + frames_generate_from_grid(previewTrack, startPosition, size, pivot, columns, count, delay); - auto length = std::max(track_length_get(previewTrack), FRAME_DURATION_MIN); - auto sampleTime = std::min(time * (float)length, (float)length - 0.001f); - auto frame = frame_generate(previewTrack, sampleTime); - auto textureSize = vec2(sourceTexture->size); + auto length = std::max(track_length_get(previewTrack), FRAME_DURATION_MIN); + auto sampleTime = std::min(time * (float)length, (float)length - 0.001f); + auto frame = frame_generate(previewTrack, sampleTime); + auto textureSize = vec2(sourceTexture->size); - if (textureSize.x > 0.0f && textureSize.y > 0.0f && frame.size.x > 0.0f && frame.size.y > 0.0f) - { - auto uvMin = frame.crop / textureSize; - auto uvMax = (frame.crop + frame.size) / textureSize; - mat4 transform = - transform_get(zoom) * quad_model_get(frame.size, frame.position, frame.pivot, - percent_to_unit(frame.scale), frame.rotation, - percent_to_unit(frame.skew)); - auto vertices = uv_vertices_get(uvMin, uvMax); + if (textureSize.x > 0.0f && textureSize.y > 0.0f && frame.size.x > 0.0f && frame.size.y > 0.0f) + { + auto uvMin = frame.crop / textureSize; + auto uvMax = (frame.crop + frame.size) / textureSize; + mat4 transform = transform_get(zoom) * quad_model_get(frame.size, frame.position, frame.pivot, + percent_to_unit(frame.scale), frame.rotation, + percent_to_unit(frame.skew)); + auto vertices = uv_vertices_get(uvMin, uvMax); - texture_render(shaderTexture, texture_id_get(*sourceTexture), transform, frame.tint, - frame.colorOffset, vertices.data()); - } + texture_render(shaderTexture, texture_id_get(*sourceTexture), transform, frame.tint, + frame.colorOffset, vertices.data()); + } + } } - } - unbind(); + unbind(); - if (isTransparent) - render_checker_background(ImGui::GetWindowDrawList(), previewMin, previewMax, -to_vec2(previewSize) * 0.5f, - CHECKER_SIZE); - image_premultiplied_draw(texture, previewSize); + if (isTransparent) + render_checker_background(ImGui::GetWindowDrawList(), previewMin, previewMax, -to_vec2(previewSize) * 0.5f, + CHECKER_SIZE); + image_premultiplied_draw(texture, previewSize); - ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); - ImGui::SliderFloat("##Time", &time, 0.0f, 1.0f, ""); + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); + ImGui::SliderFloat("##Time", &time, 0.0f, 1.0f, ""); - ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); - ImGui::InputFloat("##Zoom", &zoom, 0.0f, 0.0f, "%.0f%%"); + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); + ImGui::InputFloat("##Zoom", &zoom, 0.0f, 0.0f, "%.0f%%"); } ImGui::EndChild(); @@ -134,29 +134,30 @@ using namespace glm; ImGui::BeginDisabled(layerReferences.empty()); if (ImGui::Button(localize.get(LABEL_GENERATE), widgetSize)) { - auto queuedLayerReferences = layerReferences; - auto queuedStartPosition = startPosition; - auto queuedSize = size; - auto queuedPivot = pivot; - auto queuedColumns = columns; - auto queuedCount = count; - auto queuedDelay = delay; - auto queuedIsMakeRegions = isMakeRegions; - auto queuedRegionNameFormat = regionNameFormat; + auto queuedLayerReferences = layerReferences; + auto queuedStartPosition = startPosition; + auto queuedSize = size; + auto queuedPivot = pivot; + auto queuedColumns = columns; + auto queuedCount = count; + auto queuedDelay = delay; + auto queuedIsMakeRegions = isMakeRegions; + auto queuedRegionNameFormat = regionNameFormat; - manager.command_push( - {manager.selected, [=](Manager&, Document& document) - { - GridOptions options{queuedStartPosition, queuedSize, queuedPivot, queuedColumns, - queuedCount, queuedDelay, queuedIsMakeRegions, queuedRegionNameFormat}; - document.edit_apply(EDIT_GENERATE_ANIMATION_FROM_GRID, [&](Model& model) - { return animation_grid_generate(model, queuedLayerReferences, options); }); - }}); - isEnd = true; + manager.command_push({manager.selected, [=](Manager&, Document& document) { + GridOptions options{ + queuedStartPosition, queuedSize, queuedPivot, queuedColumns, + queuedCount, queuedDelay, queuedIsMakeRegions, queuedRegionNameFormat}; + document.edit_apply(EDIT_GENERATE_ANIMATION_FROM_GRID, [&](Model& model) { + return animation_grid_generate(model, queuedLayerReferences, options); + }); + }}); + isEnd = true; } ImGui::EndDisabled(); ImGui::SameLine(); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) isEnd = true; - } + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) + isEnd = true; +} diff --git a/src/ui/generate_animation_from_grid.h b/src/ui/generate_animation_from_grid.h index e3fc728..a94bb75 100644 --- a/src/ui/generate_animation_from_grid.h +++ b/src/ui/generate_animation_from_grid.h @@ -6,13 +6,13 @@ #include "resources.h" #include "settings.h" - class GenerateAnimationFromGrid : public Canvas - { +class GenerateAnimationFromGrid : public Canvas +{ float time = 0; - public: +public: bool isEnd = false; GenerateAnimationFromGrid(); void update(Manager&, Document&, Resources&, Settings&); - }; +}; diff --git a/src/ui/input.cpp b/src/ui/input.cpp index 3cdbdb6..b00f197 100644 --- a/src/ui/input.cpp +++ b/src/ui/input.cpp @@ -11,196 +11,206 @@ using namespace glm; - int input_text_callback(ImGuiInputTextCallbackData* data) - { +int input_text_callback(ImGuiInputTextCallbackData* data) +{ if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) { - auto* string = (std::string*)(data->UserData); - string->resize(data->BufTextLen); - data->Buf = string->data(); + auto* string = (std::string*)(data->UserData); + string->resize(data->BufTextLen); + data->Buf = string->data(); } return 0; - } +} - bool input_text_string(const char* label, std::string* string, ImGuiInputTextFlags flags) - { +bool input_text_string(const char* label, std::string* string, ImGuiInputTextFlags flags) +{ flags |= ImGuiInputTextFlags_CallbackResize; return ImGui::InputText(label, string->data(), string->capacity() + 1, flags, input_text_callback, string); - } +} - bool input_text_path(const char* label, std::filesystem::path* path, ImGuiInputTextFlags flags) - { - if (!path) return false; +bool input_text_path(const char* label, std::filesystem::path* path, ImGuiInputTextFlags flags) +{ + if (!path) + return false; auto pathUtf8 = path_to_utf8(*path); auto edited = input_text_string(label, &pathUtf8, flags); - if (edited) *path = path_from_utf8(pathUtf8); + if (edited) + *path = path_from_utf8(pathUtf8); return edited; - } +} - // A combo over `values` shown as `labels`. - bool combo_string_mapped(const std::string& label, std::string* value, const std::vector& values, - const std::vector& labels) - { +// A combo over `values` shown as `labels`. +bool combo_string_mapped(const std::string& label, std::string* value, const std::vector& values, + const std::vector& labels) +{ std::vector ids(values.size()); std::iota(ids.begin(), ids.end(), 0); auto index = (int)std::distance(values.begin(), std::ranges::find(values, *value)); - if (!combo_id_mapped(label, &index, ids, labels) || index < 0) return false; + if (!combo_id_mapped(label, &index, ids, labels) || index < 0) + return false; *value = values[index]; return true; - } +} - bool combo_id_mapped(const std::string& label, int* id, const std::vector& ids, - const std::vector& labelStrings) - { +bool combo_id_mapped(const std::string& label, int* id, const std::vector& ids, + const std::vector& labelStrings) +{ std::vector labels; for (auto& labelString : labelStrings) - labels.push_back(labelString.c_str()); - if (!id) return false; + labels.push_back(labelString.c_str()); + if (!id) + return false; int index = -1; if (!ids.empty()) { - auto it = std::find(ids.begin(), ids.end(), *id); - if (it != ids.end()) index = (int)std::distance(ids.begin(), it); + auto it = std::find(ids.begin(), ids.end(), *id); + if (it != ids.end()) + index = (int)std::distance(ids.begin(), it); } bool isActivated = ImGui::Combo(label.c_str(), &index, labels.data(), (int)labels.size()); if (isActivated) { - if (index >= 0 && index < (int)ids.size()) - *id = ids[index]; - else - *id = -1; + if (index >= 0 && index < (int)ids.size()) + *id = ids[index]; + else + *id = -1; } return isActivated; - } +} - EditState drag_float_persistent(const char* label, float* value, float speed, float min, float max, - const char* format, ImGuiSliderFlags flags) - { +EditState drag_float_persistent(const char* label, float* value, float speed, float min, float max, const char* format, + ImGuiSliderFlags flags) +{ static bool isEditing = false; static float start = NAN; auto persistent = value ? *value : 0; ImGui::DragFloat(label, &persistent, speed, min, max, format, flags); - if (!value) return EDIT_STATE_NONE; + if (!value) + return EDIT_STATE_NONE; if (ImGui::IsItemActivated() && persistent != start) { - isEditing = true; - start = *value; - return EDIT_STATE_START; + isEditing = true; + start = *value; + return EDIT_STATE_START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { - isEditing = false; - *value = persistent; - start = NAN; - return EDIT_STATE_END; + isEditing = false; + *value = persistent; + start = NAN; + return EDIT_STATE_END; } else if (isEditing) { - *value = persistent; - return EDIT_STATE_DURING; + *value = persistent; + return EDIT_STATE_DURING; } return EDIT_STATE_NONE; - } +} - EditState drag_float2_persistent(const char* label, vec2* value, float speed, float min, float max, - const char* format, ImGuiSliderFlags flags) - { +EditState drag_float2_persistent(const char* label, vec2* value, float speed, float min, float max, const char* format, + ImGuiSliderFlags flags) +{ static bool isEditing = false; static vec2 start{NAN}; auto persistent = value ? *value : vec2(); ImGui::DragFloat2(label, value_ptr(persistent), speed, min, max, format, flags); - if (!value) return EDIT_STATE_NONE; + if (!value) + return EDIT_STATE_NONE; if (ImGui::IsItemActivated() && persistent != start) { - isEditing = true; - start = *value; - return EDIT_STATE_START; + isEditing = true; + start = *value; + return EDIT_STATE_START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { - isEditing = false; - *value = persistent; - start = vec2{NAN}; - return EDIT_STATE_END; + isEditing = false; + *value = persistent; + start = vec2{NAN}; + return EDIT_STATE_END; } else if (isEditing) { - *value = persistent; - return EDIT_STATE_DURING; + *value = persistent; + return EDIT_STATE_DURING; } return EDIT_STATE_NONE; - } +} - EditState color_edit4_persistent(const char* label, vec4* value, ImGuiColorEditFlags flags) - { +EditState color_edit4_persistent(const char* label, vec4* value, ImGuiColorEditFlags flags) +{ static bool isEditing = false; static vec4 start{NAN}; auto persistent = value ? *value : vec4(); ImGui::ColorEdit4(label, value_ptr(persistent), flags); - if (!value) return EDIT_STATE_NONE; + if (!value) + return EDIT_STATE_NONE; if (ImGui::IsItemActivated() && persistent != start) { - isEditing = true; - start = *value; - return EDIT_STATE_START; + isEditing = true; + start = *value; + return EDIT_STATE_START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { - isEditing = false; - *value = persistent; - start = vec4{NAN}; - return EDIT_STATE_END; + isEditing = false; + *value = persistent; + start = vec4{NAN}; + return EDIT_STATE_END; } else if (isEditing) { - *value = persistent; - return EDIT_STATE_DURING; + *value = persistent; + return EDIT_STATE_DURING; } return EDIT_STATE_NONE; - } +} - bool radio_button_icon(const char* label, int* value, int buttonValue, ImTextureID texture, ImVec2 size, ImVec4 tint) - { +bool radio_button_icon(const char* label, int* value, int buttonValue, ImTextureID texture, ImVec2 size, ImVec4 tint) +{ bool isSelected = value && *value == buttonValue; - if (isSelected) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive)); + if (isSelected) + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive)); bool isActivated = ImGui::ImageButton(label, texture, size, ImVec2(0, 0), ImVec2(1, 1), ImVec4(0, 0, 0, 0), tint); - if (isSelected) ImGui::PopStyleColor(); - if (isActivated && value) *value = buttonValue; + if (isSelected) + ImGui::PopStyleColor(); + if (isActivated && value) + *value = buttonValue; return isActivated; - } +} - bool input_int_range(const char* label, int& value, int min, int max, int step, int stepFast, - ImGuiInputTextFlags flags) - { +bool input_int_range(const char* label, int& value, int min, int max, int step, int stepFast, ImGuiInputTextFlags flags) +{ auto isActivated = ImGui::InputInt(label, &value, step, stepFast, flags); value = glm::clamp(value, min, max); return isActivated; - } +} - bool input_int2_range(const char* label, ivec2& value, ivec2 min, ivec2 max, ImGuiInputTextFlags flags) - { +bool input_int2_range(const char* label, ivec2& value, ivec2 min, ivec2 max, ImGuiInputTextFlags flags) +{ auto isActivated = ImGui::InputInt2(label, value_ptr(value), flags); value = glm::clamp(value, min, max); return isActivated; - } +} - bool input_float_range(const char* label, float& value, float min, float max, float step, float stepFast, - const char* format, ImGuiInputTextFlags flags) - { +bool input_float_range(const char* label, float& value, float min, float max, float step, float stepFast, + const char* format, ImGuiInputTextFlags flags) +{ auto isActivated = ImGui::InputFloat(label, &value, step, stepFast, format, flags); value = glm::clamp(value, min, max); return isActivated; - } +} diff --git a/src/ui/input.h b/src/ui/input.h index d042317..9aba52b 100644 --- a/src/ui/input.h +++ b/src/ui/input.h @@ -9,24 +9,24 @@ #include "types.h" - constexpr auto DRAG_SPEED = 0.25f; - constexpr auto DRAG_SPEED_FAST = 1.00f; - constexpr auto STEP = 1.0f; - constexpr auto STEP_FAST = 5.0f; +constexpr auto DRAG_SPEED = 0.25f; +constexpr auto DRAG_SPEED_FAST = 1.00f; +constexpr auto STEP = 1.0f; +constexpr auto STEP_FAST = 5.0f; - int input_text_callback(ImGuiInputTextCallbackData*); - bool input_text_string(const char*, std::string*, ImGuiInputTextFlags = 0); - bool input_text_path(const char*, std::filesystem::path*, ImGuiInputTextFlags = 0); - bool input_int_range(const char*, int&, int, int, int = STEP, int = STEP_FAST, ImGuiInputTextFlags = 0); - bool input_int2_range(const char*, glm::ivec2&, glm::ivec2, glm::ivec2, ImGuiInputTextFlags = 0); - bool input_float_range(const char*, float&, float, float, float = STEP, float = STEP_FAST, const char* = "%.3f", - ImGuiInputTextFlags = 0); - EditState drag_float_persistent(const char*, float*, float = DRAG_SPEED, float = {}, float = {}, - const char* = "%.3f", ImGuiSliderFlags = 0); - EditState drag_float2_persistent(const char*, glm::vec2*, float = DRAG_SPEED, float = {}, float = {}, - const char* = "%.3f", ImGuiSliderFlags = 0); - EditState color_edit4_persistent(const char*, glm::vec4*, ImGuiColorEditFlags = 0); - bool radio_button_icon(const char*, int*, int, ImTextureID, ImVec2, ImVec4 = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - bool combo_id_mapped(const std::string&, int*, const std::vector&, const std::vector&); - bool combo_string_mapped(const std::string&, std::string*, const std::vector&, - const std::vector&); +int input_text_callback(ImGuiInputTextCallbackData*); +bool input_text_string(const char*, std::string*, ImGuiInputTextFlags = 0); +bool input_text_path(const char*, std::filesystem::path*, ImGuiInputTextFlags = 0); +bool input_int_range(const char*, int&, int, int, int = STEP, int = STEP_FAST, ImGuiInputTextFlags = 0); +bool input_int2_range(const char*, glm::ivec2&, glm::ivec2, glm::ivec2, ImGuiInputTextFlags = 0); +bool input_float_range(const char*, float&, float, float, float = STEP, float = STEP_FAST, const char* = "%.3f", + ImGuiInputTextFlags = 0); +EditState drag_float_persistent(const char*, float*, float = DRAG_SPEED, float = {}, float = {}, const char* = "%.3f", + ImGuiSliderFlags = 0); +EditState drag_float2_persistent(const char*, glm::vec2*, float = DRAG_SPEED, float = {}, float = {}, + const char* = "%.3f", ImGuiSliderFlags = 0); +EditState color_edit4_persistent(const char*, glm::vec4*, ImGuiColorEditFlags = 0); +bool radio_button_icon(const char*, int*, int, ImTextureID, ImVec2, ImVec4 = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); +bool combo_id_mapped(const std::string&, int*, const std::vector&, const std::vector&); +bool combo_string_mapped(const std::string&, std::string*, const std::vector&, + const std::vector&); diff --git a/src/ui/item_properties.cpp b/src/ui/item_properties.cpp index 849b481..7185ea1 100644 --- a/src/ui/item_properties.cpp +++ b/src/ui/item_properties.cpp @@ -7,211 +7,201 @@ #include "ui/layout.h" #include "ui/shortcut.h" - constexpr int EXISTING_ITEMS_ROWS = 6; +constexpr int EXISTING_ITEMS_ROWS = 6; - void ItemProperties::reset() { edit = {}; } +void ItemProperties::reset() +{ + edit = {}; +} - void ItemProperties::open() - { +void ItemProperties::open() +{ reset(); popup.open(); - } +} - bool ItemProperties::update(Manager& manager, Settings& settings, Document& document, Reference& reference) - { +bool ItemProperties::update(Manager& manager, Settings& settings, Document& document, Reference& reference) +{ bool isAdded = false; auto& model = document.model; auto animation = model.animation_get(reference.animationIndex); - auto unused_items_get = [&](int type) - { - return animation - ? model.unused_get(type == LAYER ? ElementType::LAYER_ELEMENT : ElementType::NULL_ELEMENT, animation) - : std::set{}; + auto unused_items_get = [&](int type) { + return animation + ? model.unused_get(type == LAYER ? ElementType::LAYER_ELEMENT : ElementType::NULL_ELEMENT, animation) + : std::set{}; }; popup.trigger(); if (ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) { - auto close = [&]() - { - reset(); - popup.close(); - }; - - auto& type = settings.timelineAddItemType; - auto& destination = settings.timelineAddItemDestination; - auto& source = settings.timelineAddItemSource; - - if (ImGui::BeginChild("##Content", ImVec2(), ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY)) - { - auto spaced_pair = [](auto left, auto right) - { - auto startX = ImGui::GetCursorPosX(); - auto secondX = startX + ImGui::GetContentRegionAvail().x * 0.5f; - left(); - ImGui::SameLine(); - ImGui::SetCursorPosX(secondX); - right(); + auto close = [&]() { + reset(); + popup.close(); }; - ImGui::SeparatorText(localize.get(LABEL_TYPE)); + auto& type = settings.timelineAddItemType; + auto& destination = settings.timelineAddItemDestination; + auto& source = settings.timelineAddItemSource; - spaced_pair( - [&]() - { - ImGui::RadioButton(localize.get(LABEL_LAYER), &type, LAYER); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_TYPE)); - }, - [&]() - { - ImGui::RadioButton(localize.get(LABEL_NULL), &type, NULL_); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_TYPE)); - }); - - ImGui::SeparatorText(localize.get(LABEL_SOURCE)); - - auto isUnusedItems = animation && !unused_items_get(type).empty(); - spaced_pair( - [&]() - { - ImGui::RadioButton(localize.get(LABEL_NEW), &source, SOURCE_NEW); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NEW_ITEM)); - }, - [&]() - { - ImGui::BeginDisabled(!isUnusedItems); - ImGui::RadioButton(localize.get(LABEL_EXISTING), &source, SOURCE_EXISTING); - ImGui::EndDisabled(); - ImGui::SetItemTooltip("%s", isUnusedItems ? localize.get(TOOLTIP_USE_EXISTING_ITEM) - : localize.get(TOOLTIP_NO_UNUSED_ITEMS)); - }); - - ImGui::SeparatorText(localize.get(LABEL_DESTINATION)); - - spaced_pair( - [&]() - { - ImGui::RadioButton(localize.get(LABEL_ALL_ANIMATIONS), &destination, DESTINATION_ALL); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_ALL_ANIMATIONS)); - }, - [&]() - { - ImGui::RadioButton(localize.get(LABEL_THIS_ANIMATION), &destination, DESTINATION_THIS); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_THIS_ANIMATION)); - }); - - if (source == SOURCE_NEW) + if (ImGui::BeginChild("##Content", ImVec2(), ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY)) { - ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); + auto spaced_pair = [](auto left, auto right) { + auto startX = ImGui::GetCursorPosX(); + auto secondX = startX + ImGui::GetContentRegionAvail().x * 0.5f; + left(); + ImGui::SameLine(); + ImGui::SetCursorPosX(secondX); + right(); + }; - input_text_string(localize.get(BASIC_NAME), &edit.name); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); - if (type == LAYER) - layer_source_draw(document, edit); - else if (type == NULL_) - { - ImGui::Checkbox(localize.get(LABEL_RECT), &edit.isShowRect); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); - } - } - else if (animation) - { - ImGui::SeparatorText(localize.get(type == LAYER ? LABEL_LAYER : LABEL_NULL)); + ImGui::SeparatorText(localize.get(LABEL_TYPE)); - if (ImGui::BeginChild("##Existing Items", - ImVec2(0, ImGui::GetFrameHeightWithSpacing() * EXISTING_ITEMS_ROWS))) - { - auto unusedItems = unused_items_get(type); - if (edit.id != -1 && !unusedItems.contains(edit.id)) edit.id = -1; + spaced_pair( + [&]() { + ImGui::RadioButton(localize.get(LABEL_LAYER), &type, LAYER); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_TYPE)); + }, + [&]() { + ImGui::RadioButton(localize.get(LABEL_NULL), &type, NULL_); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_TYPE)); + }); - for (auto id : unusedItems) + ImGui::SeparatorText(localize.get(LABEL_SOURCE)); + + auto isUnusedItems = animation && !unused_items_get(type).empty(); + spaced_pair( + [&]() { + ImGui::RadioButton(localize.get(LABEL_NEW), &source, SOURCE_NEW); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NEW_ITEM)); + }, + [&]() { + ImGui::BeginDisabled(!isUnusedItems); + ImGui::RadioButton(localize.get(LABEL_EXISTING), &source, SOURCE_EXISTING); + ImGui::EndDisabled(); + ImGui::SetItemTooltip("%s", isUnusedItems ? localize.get(TOOLTIP_USE_EXISTING_ITEM) + : localize.get(TOOLTIP_NO_UNUSED_ITEMS)); + }); + + ImGui::SeparatorText(localize.get(LABEL_DESTINATION)); + + spaced_pair( + [&]() { + ImGui::RadioButton(localize.get(LABEL_ALL_ANIMATIONS), &destination, DESTINATION_ALL); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_ALL_ANIMATIONS)); + }, + [&]() { + ImGui::RadioButton(localize.get(LABEL_THIS_ANIMATION), &destination, DESTINATION_THIS); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_THIS_ANIMATION)); + }); + + if (source == SOURCE_NEW) { - auto isSelected = edit.id == id; + ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); - ImGui::PushID(id); - - if (type == LAYER) - { - if (auto layer = item_get(model.content.layers, id)) + input_text_string(localize.get(BASIC_NAME), &edit.name); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); + if (type == LAYER) + layer_source_draw(document, edit); + else if (type == NULL_) { - if (ImGui::Selectable(layer_label_get(*layer).c_str(), isSelected)) - { - edit.id = id; - } + ImGui::Checkbox(localize.get(LABEL_RECT), &edit.isShowRect); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); } - } - else if (type == NULL_) - { - if (auto null = item_get(model.content.nulls, id)) - { - auto label = std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); - if (ImGui::Selectable(label.c_str(), isSelected)) - { - edit.id = id; - } - } - } - - ImGui::PopID(); } - } - ImGui::EndChild(); + else if (animation) + { + ImGui::SeparatorText(localize.get(type == LAYER ? LABEL_LAYER : LABEL_NULL)); + + if (ImGui::BeginChild("##Existing Items", + ImVec2(0, ImGui::GetFrameHeightWithSpacing() * EXISTING_ITEMS_ROWS))) + { + auto unusedItems = unused_items_get(type); + if (edit.id != -1 && !unusedItems.contains(edit.id)) + edit.id = -1; + + for (auto id : unusedItems) + { + auto isSelected = edit.id == id; + + ImGui::PushID(id); + + if (type == LAYER) + { + if (auto layer = item_get(model.content.layers, id)) + { + if (ImGui::Selectable(layer_label_get(*layer).c_str(), isSelected)) + edit.id = id; + } + } + else if (type == NULL_) + { + if (auto null = item_get(model.content.nulls, id)) + { + auto label = + std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); + if (ImGui::Selectable(label.c_str(), isSelected)) + edit.id = id; + } + } + + ImGui::PopID(); + } + } + ImGui::EndChild(); + } } - } - ImGui::EndChild(); + ImGui::EndChild(); - auto widgetSize = widget_size_with_row_get(2); + auto widgetSize = widget_size_with_row_get(2); - ImGui::BeginDisabled(source == SOURCE_EXISTING && edit.id == -1); - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) - { - auto queuedType = type; - auto queuedDestination = destination; - auto queuedAnimationIndex = reference.animationIndex; - auto queuedInsertBeforeID = reference.itemType == LAYER && type == LAYER ? reference.itemID : -1; - auto queuedAddItemID = source == SOURCE_NEW ? -1 : edit.id; - auto queuedLayer = item_edit_layer_get(edit); - auto queuedNull = item_edit_null_get(edit); + ImGui::BeginDisabled(source == SOURCE_EXISTING && edit.id == -1); + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) + { + auto queuedType = type; + auto queuedDestination = destination; + auto queuedAnimationIndex = reference.animationIndex; + auto queuedInsertBeforeID = reference.itemType == LAYER && type == LAYER ? reference.itemID : -1; + auto queuedAddItemID = source == SOURCE_NEW ? -1 : edit.id; + auto queuedLayer = item_edit_layer_get(edit); + auto queuedNull = item_edit_null_get(edit); - manager.command_push({manager.selected, [=](Manager&, Document& document) - { - int addId = -1; - document.edit_apply(EDIT_ADD_ITEM, - [&](Model& model) - { - addId = item_add( - model, (ItemType)queuedType, queuedAnimationIndex, - queuedAddItemID, queuedLayer, queuedNull, - queuedInsertBeforeID, (Destination)queuedDestination); - }); + manager.command_push({manager.selected, [=](Manager&, Document& document) { + int addId = -1; + document.edit_apply(EDIT_ADD_ITEM, [&](Model& model) { + addId = item_add(model, (ItemType)queuedType, queuedAnimationIndex, + queuedAddItemID, queuedLayer, queuedNull, + queuedInsertBeforeID, (Destination)queuedDestination); + }); - if (addId != -1) - { - document.reference_set({queuedAnimationIndex, (int)queuedType, addId}); - document.selected_set(SelectionKind::TRACKS, {document.reference_get()}); - document.frame_references_clear(); - if (queuedType == LAYER) - if (auto layer = item_get(document.model.content.layers, addId)) - document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); - } - }}); + if (addId != -1) + { + document.reference_set({queuedAnimationIndex, (int)queuedType, addId}); + document.selected_set(SelectionKind::TRACKS, {document.reference_get()}); + document.frame_references_clear(); + if (queuedType == LAYER) + if (auto layer = item_get(document.model.content.layers, addId)) + document.focused_id_set(SelectionKind::SPRITESHEETS, + layer->spritesheetId); + } + }}); - isAdded = true; - close(); - } - ImGui::EndDisabled(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ADD_ITEM)); + isAdded = true; + close(); + } + ImGui::EndDisabled(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ADD_ITEM)); - ImGui::SameLine(); + ImGui::SameLine(); - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) close(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_ADD_ITEM)); + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) + close(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_ADD_ITEM)); - ImGui::EndPopup(); + ImGui::EndPopup(); } return isAdded; - } +} diff --git a/src/ui/item_properties.h b/src/ui/item_properties.h index a20eda0..f7d92e0 100644 --- a/src/ui/item_properties.h +++ b/src/ui/item_properties.h @@ -7,14 +7,14 @@ #include "settings.h" #include "localization.h" - class ItemProperties - { +class ItemProperties +{ PopupHelper popup = PopupHelper(LABEL_TIMELINE_PROPERTIES_POPUP, POPUP_SMALL_NO_HEIGHT); Manager::ItemEdit edit = {}; void reset(); - public: +public: void open(); bool update(Manager&, Settings&, Document&, Reference&); - }; +}; diff --git a/src/ui/items.cpp b/src/ui/items.cpp index b3a178b..da4739f 100644 --- a/src/ui/items.cpp +++ b/src/ui/items.cpp @@ -6,35 +6,46 @@ #include "ui/input.h" #include "ui/layout.h" - constexpr int NULL_PROPERTIES_ROWS = 2; - constexpr int LAYER_PROPERTIES_ROWS = 6; +constexpr int NULL_PROPERTIES_ROWS = 2; +constexpr int LAYER_PROPERTIES_ROWS = 6; - static auto& layers_get(Model& model) { return model.content.layers; } - static auto& nulls_get(Model& model) { return model.content.nulls; } - static auto& events_get(Model& model) { return model.content.events; } +static auto& layers_get(Model& model) +{ + return model.content.layers; +} - static void item_tooltip_draw(Resources& resources, const std::string& name, int id) - { +static auto& nulls_get(Model& model) +{ + return model.content.nulls; +} + +static auto& events_get(Model& model) +{ + return model.content.events; +} + +static void item_tooltip_draw(Resources& resources, const std::string& name, int id) +{ tooltip_name_draw(resources, name); ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); - } +} - // "#id name", then what the layer shows: its spritesheet or its animation. - std::string layer_label_get(const Layer& layer) - { +// "#id name", then what the layer shows: its spritesheet or its animation. +std::string layer_label_get(const Layer& layer) +{ if (layer.is_animation()) - return std::vformat(localize.get(FORMAT_LAYER_ANIMATION), - std::make_format_args(layer.id, layer.name, layer.animation)); + return std::vformat(localize.get(FORMAT_LAYER_ANIMATION), + std::make_format_args(layer.id, layer.name, layer.animation)); return std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(layer.id, layer.name, layer.spritesheetId)); - } +} - // Tooltip lines for what a layer shows: its spritesheet, or its animation and the library it's from. - void layer_source_tooltip_draw(const Document& document, const Layer& layer) - { +// Tooltip lines for what a layer shows: its spritesheet, or its animation and the library it's from. +void layer_source_tooltip_draw(const Document& document, const Layer& layer) +{ if (!layer.is_animation()) { - ImGui::TextUnformatted(localize_format(FORMAT_SPRITESHEET_ID, layer.spritesheetId).c_str()); - return; + ImGui::TextUnformatted(localize_format(FORMAT_SPRITESHEET_ID, layer.spritesheetId).c_str()); + return; } auto library = item_get(document.model.content.libraries, layer.libraryId); auto libraryLabel = library ? std::format("#{} {}", library->id, path_to_utf8(library->path)) @@ -42,41 +53,43 @@ ImGui::TextUnformatted(localize_format(FORMAT_LAYER_ANIMATION_NAME, layer.animation).c_str()); ImGui::TextUnformatted(localize_format(FORMAT_LAYER_LIBRARY, libraryLabel).c_str()); if (document.is_layer_animation_missing(layer)) - ImGui::TextUnformatted(localize.get(TOOLTIP_LAYER_ANIMATION_MISSING)); - } + ImGui::TextUnformatted(localize.get(TOOLTIP_LAYER_ANIMATION_MISSING)); +} - Layer item_edit_layer_get(const Manager::ItemEdit& edit) - { +Layer item_edit_layer_get(const Manager::ItemEdit& edit) +{ return {.name = edit.name, .spritesheetId = edit.spritesheetId, .libraryId = edit.isAnimation ? edit.libraryId : -1, .animation = edit.isAnimation ? edit.animation : std::string{}}; - } +} - Null item_edit_null_get(const Manager::ItemEdit& edit) - { +Null item_edit_null_get(const Manager::ItemEdit& edit) +{ return {.name = edit.name, .isShowRect = edit.isShowRect}; - } +} - // A layer's source: a spritesheet, or an animation of this file ("Self") or a library. - void layer_source_draw(Document& document, Manager::ItemEdit& layer) - { +// A layer's source: a spritesheet, or an animation of this file ("Self") or a library. +void layer_source_draw(Document& document, Manager::ItemEdit& layer) +{ ImGui::PushID("##Source"); for (auto [label, isAnimation] : {std::pair{LABEL_SPRITESHEET, false}, std::pair{LABEL_ANIMATION, true}}) { - if (isAnimation) ImGui::SameLine(); - if (ImGui::RadioButton(localize.get(label), layer.isAnimation == isAnimation)) layer.isAnimation = isAnimation; - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SOURCE)); + if (isAnimation) + ImGui::SameLine(); + if (ImGui::RadioButton(localize.get(label), layer.isAnimation == isAnimation)) + layer.isAnimation = isAnimation; + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SOURCE)); } ImGui::PopID(); ImGui::Separator(); if (!layer.isAnimation) { - auto spritesheets = document.choices_get(SelectionKind::SPRITESHEETS); - combo_id_mapped(localize.get(LABEL_SPRITESHEET), &layer.spritesheetId, spritesheets.ids, spritesheets.labels); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); - return; + auto spritesheets = document.choices_get(SelectionKind::SPRITESHEETS); + combo_id_mapped(localize.get(LABEL_SPRITESHEET), &layer.spritesheetId, spritesheets.ids, spritesheets.labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); + return; } auto libraries = document.choices_get(SelectionKind::LIBRARIES); @@ -84,17 +97,17 @@ combo_id_mapped(localize.get(LABEL_LIBRARY), &layer.libraryId, libraries.ids, libraries.labels); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_LIBRARY)); auto names = document.animation_names_get(layer.libraryId); - if (layer.animation.empty() && !names.empty()) layer.animation = names.front(); + if (layer.animation.empty() && !names.empty()) + layer.animation = names.front(); combo_string_mapped(localize.get(LABEL_ANIMATION), &layer.animation, names, names); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_ANIMATION)); - } +} - // The layer/null properties popup: adds a new item (id -1) or replaces the edited one, then selects it. - template - void item_properties_update(Panel& panel, int popupIndex, int rows, SelectionKind kind, StringType nameTooltip, - StringType addEdit, StringType propertiesEdit, ItemsGet items_get, - FieldsDraw&& fields_draw) - { +// The layer/null properties popup: adds a new item (id -1) or replaces the edited one, then selects it. +template +void item_properties_update(Panel& panel, int popupIndex, int rows, SelectionKind kind, StringType nameTooltip, + StringType addEdit, StringType propertiesEdit, ItemsGet items_get, FieldsDraw&& fields_draw) +{ auto& manager = panel.manager; auto& popup = manager.itemPropertiesPopups[popupIndex]; auto& edit = manager.itemEdit; @@ -102,62 +115,61 @@ popup.trigger(); if (ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) { - if (ImGui::BeginChild("##Child", child_size_get(rows), ImGuiChildFlags_Borders)) - { - if (popup.isJustOpened) ImGui::SetKeyboardFocusHere(); - input_text_string(localize.get(BASIC_NAME), &edit.name); - ImGui::SetItemTooltip("%s", localize.get(nameTooltip)); - fields_draw(edit); - } - ImGui::EndChild(); + if (ImGui::BeginChild("##Child", child_size_get(rows), ImGuiChildFlags_Borders)) + { + if (popup.isJustOpened) + ImGui::SetKeyboardFocusHere(); + input_text_string(localize.get(BASIC_NAME), &edit.name); + ImGui::SetItemTooltip("%s", localize.get(nameTooltip)); + fields_draw(edit); + } + ImGui::EndChild(); - auto result = popup_buttons_draw(manager, localize.get(edit.id == -1 ? BASIC_ADD : BASIC_CONFIRM)); - if (result == PopupButton::CONFIRM) - { - Item item = {}; - if constexpr (std::is_same_v) - item = item_edit_layer_get(edit); - else - item = item_edit_null_get(edit); - auto& state = panel.state; - command_push(panel, - [&state, item, id = edit.id, kind, addEdit, propertiesEdit, items_get](Document& document) - { - auto changedId = id; - document.edit_apply(id == -1 ? addEdit : propertiesEdit, - [&](Model& model) - { - auto& items = items_get(model); - if (auto target = item_get(items, id)) - { - auto uid = target->uid; - *target = item; - target->uid = uid; - target->id = id; - return; - } - if (id != -1) return; - changedId = item_next_id_get(items); - items.push_back(item); - items.back().id = changedId; - state.newId = changedId; - }); - document.selected_ids_set(kind, {changedId}); - document.focused_id_set(kind, changedId); - }); - } - if (result != PopupButton::NONE) popup.close(); - ImGui::EndPopup(); + auto result = popup_buttons_draw(manager, localize.get(edit.id == -1 ? BASIC_ADD : BASIC_CONFIRM)); + if (result == PopupButton::CONFIRM) + { + Item item = {}; + if constexpr (std::is_same_v) + item = item_edit_layer_get(edit); + else + item = item_edit_null_get(edit); + auto& state = panel.state; + command_push(panel, + [&state, item, id = edit.id, kind, addEdit, propertiesEdit, items_get](Document& document) { + auto changedId = id; + document.edit_apply(id == -1 ? addEdit : propertiesEdit, [&](Model& model) { + auto& items = items_get(model); + if (auto target = item_get(items, id)) + { + auto uid = target->uid; + *target = item; + target->uid = uid; + target->id = id; + return; + } + if (id != -1) + return; + changedId = item_next_id_get(items); + items.push_back(item); + items.back().id = changedId; + state.newId = changedId; + }); + document.selected_ids_set(kind, {changedId}); + document.focused_id_set(kind, changedId); + }); + } + if (result != PopupButton::NONE) + popup.close(); + ImGui::EndPopup(); } popup.end(); - } +} - // Layers and nulls: properties popup, add, remove unused, copy and paste. - template - void track_items_actions_add(Actions& actions, Panel& panel, SelectionKind kind, ElementType type, - StringType addTooltip, StringType pasteEdit, StringType pasteFailToast, - ItemsGet items_get) - { +// Layers and nulls: properties popup, add, remove unused, copy and paste. +template +void track_items_actions_add(Actions& actions, Panel& panel, SelectionKind kind, ElementType type, + StringType addTooltip, StringType pasteEdit, StringType pasteFailToast, ItemsGet items_get) +{ auto selection = panel.document.selected_ids_get(kind); auto& manager = panel.manager; actions.add( @@ -166,132 +178,113 @@ actions.add(ACTION_ADD, {}, [&manager, type]() { manager.item_properties_open(type, -1); }, addTooltip); content_remove_action_add(actions, panel, type, kind); items_clipboard_actions_add(actions, panel, kind, pasteEdit, pasteFailToast, items_get); - } +} - void layers_update(Panel& panel) - { +void layers_update(Panel& panel) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& layers = document.model.content.layers; if (ImGui::Begin(localize.get(LABEL_LAYERS_WINDOW), &settings.windowIsLayers)) { - Actions actions = {}; - track_items_actions_add(actions, panel, SelectionKind::LAYERS, ElementType::LAYER_ELEMENT, - TOOLTIP_ADD_LAYER, EDIT_PASTE_LAYERS, TOAST_DESERIALIZE_LAYERS_FAILED, - layers_get); - ListRows rows{.label_get = [&](int id) { return layer_label_get(*item_get(layers, id)); }, - .is_invalid = [&](int id) - { return document.is_layer_animation_missing(*item_get(layers, id)); }, - .tooltip_draw = - [&](int id) - { - auto layer = item_get(layers, id); - item_tooltip_draw(resources, layer->name, id); - layer_source_tooltip_draw(document, *layer); - }, - .activate = [&](int id) { manager.item_properties_open(ElementType::LAYER_ELEMENT, id); }}; - list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}}, - [&]() { content_list_draw(panel, SelectionKind::LAYERS, item_ids_get(layers), rows); }); + Actions actions = {}; + track_items_actions_add(actions, panel, SelectionKind::LAYERS, ElementType::LAYER_ELEMENT, + TOOLTIP_ADD_LAYER, EDIT_PASTE_LAYERS, TOAST_DESERIALIZE_LAYERS_FAILED, + layers_get); + ListRows rows{.label_get = [&](int id) { return layer_label_get(*item_get(layers, id)); }, + .is_invalid = [&](int id) { return document.is_layer_animation_missing(*item_get(layers, id)); }, + .tooltip_draw = + [&](int id) { + auto layer = item_get(layers, id); + item_tooltip_draw(resources, layer->name, id); + layer_source_tooltip_draw(document, *layer); + }, + .activate = [&](int id) { manager.item_properties_open(ElementType::LAYER_ELEMENT, id); }}; + list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}}, + [&]() { content_list_draw(panel, SelectionKind::LAYERS, item_ids_get(layers), rows); }); } ImGui::End(); item_properties_update(panel, 0, LAYER_PROPERTIES_ROWS, SelectionKind::LAYERS, TOOLTIP_ITEM_NAME, - EDIT_ADD_LAYER, EDIT_SET_LAYER_PROPERTIES, layers_get, - [&](Manager::ItemEdit& layer) - { - ImGui::SeparatorText(localize.get(LABEL_LAYER_SOURCE)); - layer_source_draw(document, layer); - }); - } + EDIT_ADD_LAYER, EDIT_SET_LAYER_PROPERTIES, layers_get, [&](Manager::ItemEdit& layer) { + ImGui::SeparatorText(localize.get(LABEL_LAYER_SOURCE)); + layer_source_draw(document, layer); + }); +} - void nulls_update(Panel& panel) - { +void nulls_update(Panel& panel) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& nulls = document.model.content.nulls; if (ImGui::Begin(localize.get(LABEL_NULLS_WINDOW), &settings.windowIsNulls)) { - Actions actions = {}; - track_items_actions_add(actions, panel, SelectionKind::NULLS, ElementType::NULL_ELEMENT, - TOOLTIP_ADD_NULL, EDIT_PASTE_NULLS, TOAST_DESERIALIZE_NULLS_FAILED, - nulls_get); - ListRows rows{.label_get = - [&](int id) - { - auto name = item_get(nulls, id)->name; - return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, name)); - }, - .tooltip_draw = [&](int id) { item_tooltip_draw(resources, item_get(nulls, id)->name, id); }, - .activate = [&](int id) { manager.item_properties_open(ElementType::NULL_ELEMENT, id); }, - .isFocusItalic = true}; - list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}}, - [&]() { content_list_draw(panel, SelectionKind::NULLS, item_ids_get(nulls), rows); }); + Actions actions = {}; + track_items_actions_add(actions, panel, SelectionKind::NULLS, ElementType::NULL_ELEMENT, TOOLTIP_ADD_NULL, + EDIT_PASTE_NULLS, TOAST_DESERIALIZE_NULLS_FAILED, nulls_get); + ListRows rows{.label_get = + [&](int id) { + auto name = item_get(nulls, id)->name; + return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, name)); + }, + .tooltip_draw = [&](int id) { item_tooltip_draw(resources, item_get(nulls, id)->name, id); }, + .activate = [&](int id) { manager.item_properties_open(ElementType::NULL_ELEMENT, id); }, + .isFocusItalic = true}; + list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}}, + [&]() { content_list_draw(panel, SelectionKind::NULLS, item_ids_get(nulls), rows); }); } ImGui::End(); - item_properties_update(panel, 1, NULL_PROPERTIES_ROWS, SelectionKind::NULLS, TOOLTIP_NULL_NAME, - EDIT_ADD_NULL, EDIT_SET_NULL_PROPERTIES, nulls_get, - [](Manager::ItemEdit& null) - { - ImGui::Checkbox(localize.get(LABEL_RECT), &null.isShowRect); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); - }); - } + item_properties_update(panel, 1, NULL_PROPERTIES_ROWS, SelectionKind::NULLS, TOOLTIP_NULL_NAME, EDIT_ADD_NULL, + EDIT_SET_NULL_PROPERTIES, nulls_get, [](Manager::ItemEdit& null) { + ImGui::Checkbox(localize.get(LABEL_RECT), &null.isShowRect); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); + }); +} - void events_update(Panel& panel) - { +void events_update(Panel& panel) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& events = document.model.content.events; if (ImGui::Begin(localize.get(LABEL_EVENTS_WINDOW), &settings.windowIsEvents)) { - auto selection = document.selected_ids_get(SelectionKind::EVENTS); - Actions actions = {}; - actions.add( - ACTION_RENAME, [selection]() { return selection.size() == 1; }, - [&state, selection]() { state.newId = *selection.begin(); }); - actions.add( - ACTION_ADD, {}, - [&panel]() - { - auto& state = panel.state; - command_push(panel, - [&state](Document& document) - { - int id = 0; - document.edit_apply(EDIT_ADD_EVENT, - [&](Model& model) - { - auto& events = model.content.events; - id = item_next_id_get(events); - events.push_back({.id = id, .name = localize.get(TEXT_NEW_EVENT)}); - }); - document.selected_ids_set(SelectionKind::EVENTS, {id}); - document.focused_id_set(SelectionKind::EVENTS, id); - state.newId = id; - }); - }, - TOOLTIP_ADD_EVENT); - content_remove_action_add(actions, panel, ElementType::EVENT_ELEMENT, SelectionKind::EVENTS); - items_clipboard_actions_add(actions, panel, SelectionKind::EVENTS, EDIT_PASTE_EVENTS, - TOAST_DESERIALIZE_EVENTS_FAILED, events_get); - ListRows rows{.label_get = [&](int id) { return item_get(events, id)->name; }, - .name_get = [&](int id) { return item_get(events, id)->name; }, - .rename = - [&](int id, const std::string& name) - { - command_push(panel, - [id, name](Document& document) - { - document.edit_apply(EDIT_RENAME_EVENT, - [&](Model& model) - { - if (auto event = item_get(model.content.events, id)) - event->name = name; - }); - }); - }, - .tooltip_draw = [&](int id) - { item_tooltip_draw(resources, item_get(events, id)->name, id); }}; - list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}}, - [&]() { content_list_draw(panel, SelectionKind::EVENTS, item_ids_get(events), rows); }); + auto selection = document.selected_ids_get(SelectionKind::EVENTS); + Actions actions = {}; + actions.add( + ACTION_RENAME, [selection]() { return selection.size() == 1; }, + [&state, selection]() { state.newId = *selection.begin(); }); + actions.add( + ACTION_ADD, {}, + [&panel]() { + auto& state = panel.state; + command_push(panel, [&state](Document& document) { + int id = 0; + document.edit_apply(EDIT_ADD_EVENT, [&](Model& model) { + auto& events = model.content.events; + id = item_next_id_get(events); + events.push_back({.id = id, .name = localize.get(TEXT_NEW_EVENT)}); + }); + document.selected_ids_set(SelectionKind::EVENTS, {id}); + document.focused_id_set(SelectionKind::EVENTS, id); + state.newId = id; + }); + }, + TOOLTIP_ADD_EVENT); + content_remove_action_add(actions, panel, ElementType::EVENT_ELEMENT, SelectionKind::EVENTS); + items_clipboard_actions_add(actions, panel, SelectionKind::EVENTS, EDIT_PASTE_EVENTS, + TOAST_DESERIALIZE_EVENTS_FAILED, events_get); + ListRows rows{.label_get = [&](int id) { return item_get(events, id)->name; }, + .name_get = [&](int id) { return item_get(events, id)->name; }, + .rename = + [&](int id, const std::string& name) { + command_push(panel, [id, name](Document& document) { + document.edit_apply(EDIT_RENAME_EVENT, [&](Model& model) { + if (auto event = item_get(model.content.events, id)) + event->name = name; + }); + }); + }, + .tooltip_draw = [&](int id) { item_tooltip_draw(resources, item_get(events, id)->name, id); }}; + list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}}, + [&]() { content_list_draw(panel, SelectionKind::EVENTS, item_ids_get(events), rows); }); } ImGui::End(); - } +} diff --git a/src/ui/layout.cpp b/src/ui/layout.cpp index 312bd61..50c5ac3 100644 --- a/src/ui/layout.cpp +++ b/src/ui/layout.cpp @@ -2,41 +2,44 @@ #include "localization.h" - float row_widget_width_get(int count, float width) - { +float row_widget_width_get(int count, float width) +{ return (width - (ImGui::GetStyle().ItemSpacing.x * (float)(count - 1))) / (float)count; - } +} - ImVec2 widget_size_with_row_get(int count, float width) { return ImVec2(row_widget_width_get(count, width), 0); } +ImVec2 widget_size_with_row_get(int count, float width) +{ + return ImVec2(row_widget_width_get(count, width), 0); +} - float footer_height_get(int itemCount) - { +float footer_height_get(int itemCount) +{ return ImGui::GetTextLineHeightWithSpacing() * itemCount + ImGui::GetStyle().WindowPadding.y + ImGui::GetStyle().ItemSpacing.y * (itemCount); - } +} - ImVec2 footer_size_get(int itemCount) - { +ImVec2 footer_size_get(int itemCount) +{ return ImVec2(ImGui::GetContentRegionAvail().x, footer_height_get(itemCount)); - } +} - ImVec2 size_without_footer_get(int rowCount) - { +ImVec2 size_without_footer_get(int rowCount) +{ return ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y - footer_height_get(rowCount)); - } +} - ImVec2 child_size_get(int rowCount) - { +ImVec2 child_size_get(int rowCount) +{ return ImVec2(ImGui::GetContentRegionAvail().x, (ImGui::GetFrameHeightWithSpacing() * rowCount) + (ImGui::GetStyle().WindowPadding.y * 2.0f)); - } +} - ImVec2 icon_size_get() - { +ImVec2 icon_size_get() +{ return ImVec2(ImGui::GetTextLineHeightWithSpacing(), ImGui::GetTextLineHeightWithSpacing()); - } +} - void set_item_tooltip_shortcut(const char* tooltip, const std::string& shortcut) - { +void set_item_tooltip_shortcut(const char* tooltip, const std::string& shortcut) +{ ImGui::SetItemTooltip("%s", localize_format(FORMAT_TOOLTIP_SHORTCUT, tooltip, shortcut).c_str()); - } +} diff --git a/src/ui/layout.h b/src/ui/layout.h index 47b8822..086df57 100644 --- a/src/ui/layout.h +++ b/src/ui/layout.h @@ -5,29 +5,48 @@ #include #include - constexpr ImVec2 to_imvec2(const glm::vec2& v) noexcept { return {v.x, v.y}; } - constexpr glm::vec2 to_vec2(const ImVec2& v) noexcept { return {v.x, v.y}; } - constexpr glm::ivec2 to_ivec2(const ImVec2& v) noexcept { return {v.x, v.y}; } - constexpr ImVec4 to_imvec4(const glm::vec4& v) noexcept { return {v.x, v.y, v.z, v.w}; } - constexpr glm::vec4 to_vec4(const ImVec4& v) noexcept { return {v.x, v.y, v.z, v.w}; } +constexpr ImVec2 to_imvec2(const glm::vec2& v) noexcept +{ + return {v.x, v.y}; +} - template constexpr T& dummy_value() - { +constexpr glm::vec2 to_vec2(const ImVec2& v) noexcept +{ + return {v.x, v.y}; +} + +constexpr glm::ivec2 to_ivec2(const ImVec2& v) noexcept +{ + return {v.x, v.y}; +} + +constexpr ImVec4 to_imvec4(const glm::vec4& v) noexcept +{ + return {v.x, v.y, v.z, v.w}; +} + +constexpr glm::vec4 to_vec4(const ImVec4& v) noexcept +{ + return {v.x, v.y, v.z, v.w}; +} + +template constexpr T& dummy_value() +{ static T value = {}; return value; - } +} - template constexpr T& dummy_value_negative() - { +template constexpr T& dummy_value_negative() +{ static T value = -1; return value; - } +} - float row_widget_width_get(int, float = ImGui::GetContentRegionAvail().x); - ImVec2 widget_size_with_row_get(int, float = ImGui::GetContentRegionAvail().x); - float footer_height_get(int = 1); - ImVec2 footer_size_get(int = 1); - ImVec2 size_without_footer_get(int = 1); - ImVec2 child_size_get(int = 1); - ImVec2 icon_size_get(); - void set_item_tooltip_shortcut(const char*, const std::string& = {}); +float row_widget_width_get(int, float = ImGui::GetContentRegionAvail().x); +ImVec2 widget_size_with_row_get(int, float = ImGui::GetContentRegionAvail().x); +float footer_height_get(int = 1); +ImVec2 footer_size_get(int = 1); +ImVec2 size_without_footer_get(int = 1); +ImVec2 child_size_get(int = 1); +ImVec2 icon_size_get(); +void set_item_tooltip_shortcut(const char*, const std::string& = {}); diff --git a/src/ui/libraries.cpp b/src/ui/libraries.cpp index 0450e85..0f48cbc 100644 --- a/src/ui/libraries.cpp +++ b/src/ui/libraries.cpp @@ -4,110 +4,108 @@ #include "path.h" - constexpr int LIBRARY_CARD_LINES = 2; +constexpr int LIBRARY_CARD_LINES = 2; - static auto& libraries_get(Model& model) { return model.content.libraries; } +static auto& libraries_get(Model& model) +{ + return model.content.libraries; +} - void libraries_update(Panel& panel) - { +void libraries_update(Panel& panel) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& libraries = document.model.content.libraries; auto selection = document.selected_ids_get(SelectionKind::LIBRARIES); if (dialog.is_selected(Dialog::LIBRARY_OPEN)) { - command_push(panel, - [&state, paths = dialog.paths](Document& document) - { - document.libraries_add(paths); - state.newId = document.focused_id_get(SelectionKind::LIBRARIES); - }); - dialog.reset(); + command_push(panel, [&state, paths = dialog.paths](Document& document) { + document.libraries_add(paths); + state.newId = document.focused_id_get(SelectionKind::LIBRARIES); + }); + dialog.reset(); } if (ImGui::Begin(localize.get(LABEL_LIBRARIES_WINDOW), &settings.windowIsLibraries)) { - auto isOne = [selection]() { return selection.size() == 1; }; - auto loaded_get = [&](int id) { return document.library_get(document.model, id); }; - // Opens the library as its own tab, or switches to it when it already is one. - auto open = [&](int id) - { - manager.command_push({.runManager = [path = document.library_path_get(id)](Manager& manager) - { - if (auto index = manager.path_index_get(path); index != -1) - return manager.tab_select(index); - manager.open(path); - }}); - }; + auto isOne = [selection]() { + return selection.size() == 1; + }; + auto loaded_get = [&](int id) { + return document.library_get(document.model, id); + }; + // Opens the library as its own tab, or switches to it when it already is one. + auto open = [&](int id) { + manager.command_push({.runManager = [path = document.library_path_get(id)](Manager& manager) { + if (auto index = manager.path_index_get(path); index != -1) + return manager.tab_select(index); + manager.open(path); + }}); + }; - Actions actions = {}; - actions.add(ACTION_OPEN, isOne, [&]() { open(*selection.begin()); }, TOOLTIP_LIBRARY_OPEN); - actions.add(ACTION_OPEN_DIRECTORY, isOne, - [&]() { directory_open(dialog, document, item_get(libraries, *selection.begin())->path); }); - actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::LIBRARY_OPEN, true); }, TOOLTIP_LIBRARY_ADD); - content_remove_action_add(actions, panel, ElementType::LIBRARY, SelectionKind::LIBRARIES); - actions.add( - ACTION_RELOAD, [selection]() { return !selection.empty(); }, - [&]() - { - command_push(panel, - [selection](Document& document) - { - for (auto id : selection) - if (auto library = item_get(document.model.content.libraries, id)) - { - document.library_reload(id); - toast_log(Level::INFO, TOAST_RELOAD_LIBRARY, id, path_to_utf8(library->path)); - } - }); - }, - TOOLTIP_RELOAD_LIBRARIES); - items_clipboard_actions_add(actions, panel, SelectionKind::LIBRARIES, EDIT_PASTE_LIBRARIES, - TOAST_DESERIALIZE_LIBRARIES_FAILED, libraries_get); + Actions actions = {}; + actions.add(ACTION_OPEN, isOne, [&]() { open(*selection.begin()); }, TOOLTIP_LIBRARY_OPEN); + actions.add(ACTION_OPEN_DIRECTORY, isOne, + [&]() { directory_open(dialog, document, item_get(libraries, *selection.begin())->path); }); + actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::LIBRARY_OPEN, true); }, TOOLTIP_LIBRARY_ADD); + content_remove_action_add(actions, panel, ElementType::LIBRARY, SelectionKind::LIBRARIES); + actions.add( + ACTION_RELOAD, [selection]() { return !selection.empty(); }, + [&]() { + command_push(panel, [selection](Document& document) { + for (auto id : selection) + if (auto library = item_get(document.model.content.libraries, id)) + { + document.library_reload(id); + toast_log(Level::INFO, TOAST_RELOAD_LIBRARY, id, path_to_utf8(library->path)); + } + }); + }, + TOOLTIP_RELOAD_LIBRARIES); + items_clipboard_actions_add(actions, panel, SelectionKind::LIBRARIES, EDIT_PASTE_LIBRARIES, + TOAST_DESERIALIZE_LIBRARIES_FAILED, libraries_get); - ListRows rows{ - .label_get = - [&](int id) - { - auto pathString = path_to_utf8(item_get(libraries, id)->path); - return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); - }, - .tooltip_draw = - [&](int id) - { - auto loaded = loaded_get(id); - tooltip_name_draw(resources, path_to_utf8(item_get(libraries, id)->path)); - ImGui::Text("%s: %d", localize.get(BASIC_ID), id); - if (loaded && loaded->model.isValid) - { - auto animations = loaded->model.animations_get(); - auto count = animations.size(); - ImGui::SeparatorText( - std::vformat(localize.get(FORMAT_LIBRARY_ANIMATIONS), std::make_format_args(count)).c_str()); - for (auto [index, animation] : animations) - ImGui::BulletText("%s", animation->name.c_str()); - ImGui::Separator(); - ImGui::TextUnformatted(localize.get(TOOLTIP_LIBRARY_OPEN)); - } - else - { - ImGui::Spacing(); - ImGui::TextWrapped("%s", localize.get(TOOLTIP_LIBRARY_INVALID)); - } - }, - .image_get = - [&](int id) - { - auto loaded = loaded_get(id); - auto isValid = loaded && loaded->model.isValid; - auto& texture = resources.icons[isValid ? ICON_ANIMATION : ICON_NONE]; - return CardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; - }, - .activate = open, - .cardLines = LIBRARY_CARD_LINES}; - list_panel_draw( - panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD, ACTION_OPEN}}, - [&]() { content_list_draw(panel, SelectionKind::LIBRARIES, item_ids_get(libraries), rows); }, true); + ListRows rows{ + .label_get = + [&](int id) { + auto pathString = path_to_utf8(item_get(libraries, id)->path); + return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); + }, + .tooltip_draw = + [&](int id) { + auto loaded = loaded_get(id); + tooltip_name_draw(resources, path_to_utf8(item_get(libraries, id)->path)); + ImGui::Text("%s: %d", localize.get(BASIC_ID), id); + if (loaded && loaded->model.isValid) + { + auto animations = loaded->model.animations_get(); + auto count = animations.size(); + ImGui::SeparatorText( + std::vformat(localize.get(FORMAT_LIBRARY_ANIMATIONS), std::make_format_args(count)) + .c_str()); + for (auto [index, animation] : animations) + ImGui::BulletText("%s", animation->name.c_str()); + ImGui::Separator(); + ImGui::TextUnformatted(localize.get(TOOLTIP_LIBRARY_OPEN)); + } + else + { + ImGui::Spacing(); + ImGui::TextWrapped("%s", localize.get(TOOLTIP_LIBRARY_INVALID)); + } + }, + .image_get = + [&](int id) { + auto loaded = loaded_get(id); + auto isValid = loaded && loaded->model.isValid; + auto& texture = resources.icons[isValid ? ICON_ANIMATION : ICON_NONE]; + return CardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; + }, + .activate = open, + .cardLines = LIBRARY_CARD_LINES}; + list_panel_draw( + panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD, ACTION_OPEN}}, + [&]() { content_list_draw(panel, SelectionKind::LIBRARIES, item_ids_get(libraries), rows); }, true); } ImGui::End(); - } +} diff --git a/src/ui/multiselect.cpp b/src/ui/multiselect.cpp index 2da562e..3fd5336 100644 --- a/src/ui/multiselect.cpp +++ b/src/ui/multiselect.cpp @@ -1,38 +1,49 @@ #include "ui/multiselect.h" - void external_storage_set(ImGuiSelectionExternalStorage* self, int id, bool isSelected) - { +void external_storage_set(ImGuiSelectionExternalStorage* self, int id, bool isSelected) +{ auto* storage = static_cast(self->UserData); auto value = storage ? storage->resolve_index(id) : id; if (isSelected) - storage->insert(value); + storage->insert(value); else - storage->erase(value); - }; + storage->erase(value); +}; - MultiSelectStorage::MultiSelectStorage() { internal.AdapterSetItemSelected = external_storage_set; } +MultiSelectStorage::MultiSelectStorage() +{ + internal.AdapterSetItemSelected = external_storage_set; +} - void MultiSelectStorage::start(size_t size, ImGuiMultiSelectFlags flags) - { +void MultiSelectStorage::start(size_t size, ImGuiMultiSelectFlags flags) +{ internal.UserData = this; io = ImGui::BeginMultiSelect(flags, this->size(), size); apply(); - } +} - void MultiSelectStorage::apply() { internal.ApplyRequests(io); } +void MultiSelectStorage::apply() +{ + internal.ApplyRequests(io); +} - void MultiSelectStorage::finish() - { +void MultiSelectStorage::finish() +{ io = ImGui::EndMultiSelect(); apply(); - } +} - void MultiSelectStorage::set_index_map(std::vector* map) { indexMap = map; } +void MultiSelectStorage::set_index_map(std::vector* map) +{ + indexMap = map; +} - int MultiSelectStorage::resolve_index(int index) const - { - if (!indexMap) return index; - if (index < 0 || index >= (int)indexMap->size()) return index; +int MultiSelectStorage::resolve_index(int index) const +{ + if (!indexMap) + return index; + if (index < 0 || index >= (int)indexMap->size()) + return index; return (*indexMap)[index]; - } +} diff --git a/src/ui/multiselect.h b/src/ui/multiselect.h index bc5fa9e..1f76bba 100644 --- a/src/ui/multiselect.h +++ b/src/ui/multiselect.h @@ -5,9 +5,9 @@ #include - class MultiSelectStorage : public std::set - { - public: +class MultiSelectStorage : public std::set +{ +public: ImGuiSelectionExternalStorage internal = {}; ImGuiMultiSelectIO* io = nullptr; std::vector* indexMap = nullptr; @@ -28,6 +28,6 @@ void finish(); void set_index_map(std::vector*); int resolve_index(int) const; - }; +}; - void external_storage_set(ImGuiSelectionExternalStorage*, int, bool); +void external_storage_set(ImGuiSelectionExternalStorage*, int, bool); diff --git a/src/ui/onionskin.cpp b/src/ui/onionskin.cpp index 418ac95..52ff2e4 100644 --- a/src/ui/onionskin.cpp +++ b/src/ui/onionskin.cpp @@ -9,10 +9,10 @@ using namespace glm; - constexpr auto FRAMES_MAX = 100; +constexpr auto FRAMES_MAX = 100; - void onionskin_update(Manager& manager, Settings& settings) - { +void onionskin_update(Manager& manager, Settings& settings) +{ auto& isEnabled = settings.onionskinIsEnabled; auto& beforeCount = settings.onionskinBeforeCount; auto& beforeColor = settings.onionskinBeforeColor; @@ -22,38 +22,37 @@ using namespace glm; if (ImGui::Begin(localize.get(LABEL_ONIONSKIN_WINDOW), &settings.windowIsOnionskin)) { - auto configure_widgets = [&](const char* separator, int& frames, vec3& color) - { - ImGui::PushID(separator); - ImGui::SeparatorText(separator); - input_int_range(localize.get(BASIC_FRAMES), frames, 0, FRAMES_MAX); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_FRAMES)); - ImGui::ColorEdit3(localize.get(BASIC_COLOR), value_ptr(color)); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_COLOR)); - ImGui::PopID(); - }; + auto configure_widgets = [&](const char* separator, int& frames, vec3& color) { + ImGui::PushID(separator); + ImGui::SeparatorText(separator); + input_int_range(localize.get(BASIC_FRAMES), frames, 0, FRAMES_MAX); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_FRAMES)); + ImGui::ColorEdit3(localize.get(BASIC_COLOR), value_ptr(color)); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_COLOR)); + ImGui::PopID(); + }; - ImGui::Checkbox(localize.get(BASIC_ENABLED), &isEnabled); - set_item_tooltip_shortcut(localize.get(TOOLTIP_ONIONSKIN_ENABLED), settings.shortcutOnionskin); + ImGui::Checkbox(localize.get(BASIC_ENABLED), &isEnabled); + set_item_tooltip_shortcut(localize.get(TOOLTIP_ONIONSKIN_ENABLED), settings.shortcutOnionskin); - configure_widgets(localize.get(BASIC_BEFORE), beforeCount, beforeColor); - configure_widgets(localize.get(BASIC_AFTER), afterCount, afterColor); - ImGui::SeparatorText(localize.get(BASIC_MODE)); - ImGui::RadioButton(localize.get(BASIC_TIME), &mode, (int)OnionskinMode::TIME); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_TIME)); - ImGui::SameLine(); - ImGui::RadioButton(localize.get(BASIC_INDEX), &mode, (int)OnionskinMode::INDEX); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_INDEX)); + configure_widgets(localize.get(BASIC_BEFORE), beforeCount, beforeColor); + configure_widgets(localize.get(BASIC_AFTER), afterCount, afterColor); + ImGui::SeparatorText(localize.get(BASIC_MODE)); + ImGui::RadioButton(localize.get(BASIC_TIME), &mode, (int)OnionskinMode::TIME); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_TIME)); + ImGui::SameLine(); + ImGui::RadioButton(localize.get(BASIC_INDEX), &mode, (int)OnionskinMode::INDEX); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_INDEX)); - ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); - ImGui::Checkbox(localize.get(LABEL_PIVOT_PATH), &settings.onionskinIsPivotPath); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PIVOT_PATH)); - ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_ONLY_SELECTED_ITEM), &settings.onionskinIsOnlySelected); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONLY_SELECTED_ITEM)); + ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); + ImGui::Checkbox(localize.get(LABEL_PIVOT_PATH), &settings.onionskinIsPivotPath); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PIVOT_PATH)); + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_ONLY_SELECTED_ITEM), &settings.onionskinIsOnlySelected); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONLY_SELECTED_ITEM)); } ImGui::End(); - if (shortcut(manager.chords[SHORTCUT_ONIONSKIN], SCOPE_GLOBAL)) isEnabled = !isEnabled; - } - + if (shortcut(manager.chords[SHORTCUT_ONIONSKIN], SCOPE_GLOBAL)) + isEnabled = !isEnabled; +} diff --git a/src/ui/panel.cpp b/src/ui/panel.cpp index e946965..81ef257 100644 --- a/src/ui/panel.cpp +++ b/src/ui/panel.cpp @@ -11,107 +11,115 @@ using namespace glm; - constexpr float SCROLL_CENTER = 0.5f; - constexpr std::size_t REMOVE_LINES_MAX = 10; - constexpr float TOOLTIP_PADDING_MULTIPLIER = 4.0f; - constexpr float PREVIEW_VIEWPORT_FRACTION = 0.5f; - constexpr const char* CONTEXT_MENU_LABEL = "##Context Menu"; +constexpr float SCROLL_CENTER = 0.5f; +constexpr std::size_t REMOVE_LINES_MAX = 10; +constexpr float TOOLTIP_PADDING_MULTIPLIER = 4.0f; +constexpr float PREVIEW_VIEWPORT_FRACTION = 0.5f; +constexpr const char* CONTEXT_MENU_LABEL = "##Context Menu"; - bool is_drag_drop_active() { return ImGui::GetDragDropPayload() != nullptr; } +bool is_drag_drop_active() +{ + return ImGui::GetDragDropPayload() != nullptr; +} - void command_push(const Panel& panel, std::function run) - { +void command_push(const Panel& panel, std::function run) +{ panel.manager.command_push( {panel.manager.selected, [run = std::move(run)](Manager&, Document& document) { run(document); }}); - } +} - static void row_select(std::set&, int& focus, const ListRows& rows, int key) - { +static void row_select(std::set&, int& focus, const ListRows& rows, int key) +{ focus = key; - if (rows.select) rows.select(key); - } + if (rows.select) + rows.select(key); +} - static void row_scroll_update(PanelState& state, int key, int arrowKey) - { - if ((state.newId != key && state.scrollId != key && arrowKey != key) || is_drag_drop_active()) return; +static void row_scroll_update(PanelState& state, int key, int arrowKey) +{ + if ((state.newId != key && state.scrollId != key && arrowKey != key) || is_drag_drop_active()) + return; ImGui::SetScrollHereY(SCROLL_CENTER); - if (state.scrollId == key) state.scrollId = -1; - } + if (state.scrollId == key) + state.scrollId = -1; +} - // Tooltips keep the window's padding and spacing, which card lists zero out for themselves. - bool tooltip_begin(const PanelState& state, bool isItem) - { +// Tooltips keep the window's padding and spacing, which card lists zero out for themselves. +bool tooltip_begin(const PanelState& state, bool isItem) +{ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, state.tooltipPadding); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, state.tooltipSpacing); - if (isItem ? ImGui::BeginItemTooltip() : ImGui::BeginTooltip()) return true; + if (isItem ? ImGui::BeginItemTooltip() : ImGui::BeginTooltip()) + return true; ImGui::PopStyleVar(2); return false; - } +} - void tooltip_end() - { +void tooltip_end() +{ ImGui::EndTooltip(); ImGui::PopStyleVar(2); - } +} - static void row_tooltip_update(const PanelState& state, const ListRows& rows, int key) - { - if (!rows.tooltip_draw || !tooltip_begin(state)) return; +static void row_tooltip_update(const PanelState& state, const ListRows& rows, int key) +{ + if (!rows.tooltip_draw || !tooltip_begin(state)) + return; rows.tooltip_draw(key); tooltip_end(); - } +} - // Arrow keys move a single selection through the keys. - static int arrow_key_get(const std::vector& keys, const std::set& selection, int focus) - { +// Arrow keys move a single selection through the keys. +static int arrow_key_get(const std::vector& keys, const std::set& selection, int focus) +{ if (keys.empty() || !ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) || !(ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) - return -1; + return -1; auto current = focus == -1 && !selection.empty() ? *selection.begin() : focus; auto it = std::ranges::find(keys, current); auto index = it == keys.end() ? 0 : (int)std::distance(keys.begin(), it); auto delta = ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) ? -1 : 1; return keys[std::clamp(index + delta, 0, (int)keys.size() - 1)]; - } +} - // Multi-select over `keys` (row index -> key); returns the key the arrow keys moved to, or -1. - int list_select_begin(Panel& panel, std::set& selection, int& focus, const ListRows& rows, - const std::vector& arrowKeys) - { +// Multi-select over `keys` (row index -> key). Returns the key the arrow keys moved to, or -1. +int list_select_begin(Panel& panel, std::set& selection, int& focus, const ListRows& rows, + const std::vector& arrowKeys) +{ auto& storage = panel.state.selection; storage = selection; storage.set_index_map(&panel.state.keys); storage.start(panel.state.keys.size()); selection = storage; if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) - selection = storage = std::set(panel.state.keys.begin(), panel.state.keys.end()); + selection = storage = std::set(panel.state.keys.begin(), panel.state.keys.end()); if (ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) { - storage.clear(); - selection.clear(); - row_select(selection, focus, rows, -1); + storage.clear(); + selection.clear(); + row_select(selection, focus, rows, -1); } return arrow_key_get(arrowKeys, selection, focus); - } +} - void list_select_end(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int arrowKey) - { +void list_select_end(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int arrowKey) +{ auto& storage = panel.state.selection; storage.finish(); storage.set_index_map(nullptr); selection = storage; if (arrowKey != -1) { - selection = {arrowKey}; - row_select(selection, focus, rows, arrowKey); + selection = {arrowKey}; + row_select(selection, focus, rows, arrowKey); } if (shortcut(panel.manager.chords[SHORTCUT_CONFIRM], SCOPE_FOCUSED) && selection.size() == 1 && rows.activate) - rows.activate(*selection.begin()); - } + rows.activate(*selection.begin()); +} - bool row_draw(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int key, int index, - int arrowKey) - { +bool row_draw(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int key, int index, + int arrowKey) +{ auto& state = panel.state; auto isSelected = selection.contains(key) || arrowKey == key; auto isFocused = rows.isFocusItalic && (focus == key || arrowKey == key); @@ -121,317 +129,333 @@ using namespace glm; auto isInvalid = rows.is_invalid && rows.is_invalid(key); ImGui::PushID(key); ImGui::SetNextItemSelectionUserData(index); - if (font != FONT_REGULAR) ImGui::PushFont(panel.resources.fonts[font].get(), FONT_SIZE); - if (isInvalid) ImGui::PushStyleColor(ImGuiCol_Text, CARD_TINT_INVALID); - if (arrowKey == key) ImGui::SetKeyboardFocusHere(); + if (font != FONT_REGULAR) + ImGui::PushFont(panel.resources.fonts[font].get(), FONT_SIZE); + if (isInvalid) + ImGui::PushStyleColor(ImGuiCol_Text, CARD_TINT_INVALID); + if (arrowKey == key) + ImGui::SetKeyboardFocusHere(); bool isActivated = false; if (rows.rename) { - if (state.newId == key) - { - state.renameState = RENAME_FORCE_EDIT; - state.newId = -1; - } - auto isRenaming = state.renameId == key; - auto name = rows.name_get(key); - auto renameLabel = std::format("###Document #{} Row #{}", panel.manager.selected, key); - isActivated = selectable_input_text(label, renameLabel, isRenaming ? state.renameText : name, isSelected, - ImGuiSelectableFlags_None, state.renameState); - if (isActivated && state.renameState == RENAME_BEGIN) - { - state.renameId = key; - state.renameText = name; - } - else if (isActivated && state.renameState == RENAME_FINISHED) - { - if (isRenaming && state.renameText != name) rows.rename(key, state.renameText); - state.renameId = -1; - state.renameText.clear(); - } + if (state.newId == key) + { + state.renameState = RENAME_FORCE_EDIT; + state.newId = -1; + } + auto isRenaming = state.renameId == key; + auto name = rows.name_get(key); + auto renameLabel = std::format("###Document #{} Row #{}", panel.manager.selected, key); + isActivated = selectable_input_text(label, renameLabel, isRenaming ? state.renameText : name, isSelected, + ImGuiSelectableFlags_None, state.renameState); + if (isActivated && state.renameState == RENAME_BEGIN) + { + state.renameId = key; + state.renameText = name; + } + else if (isActivated && state.renameState == RENAME_FINISHED) + { + if (isRenaming && state.renameText != name) + rows.rename(key, state.renameText); + state.renameId = -1; + state.renameText.clear(); + } } else - isActivated = ImGui::Selectable(label.c_str(), isSelected); + isActivated = ImGui::Selectable(label.c_str(), isSelected); if (isActivated || ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right)) - row_select(selection, focus, rows, key); - if (isInvalid) ImGui::PopStyleColor(); - if (font != FONT_REGULAR) ImGui::PopFont(); + row_select(selection, focus, rows, key); + if (isInvalid) + ImGui::PopStyleColor(); + if (font != FONT_REGULAR) + ImGui::PopFont(); row_scroll_update(state, key, arrowKey); - if (state.newId == key) state.newId = -1; + if (state.newId == key) + state.newId = -1; if (rows.activate && ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) - rows.activate(key); + rows.activate(key); auto isBreak = rows.drag_drop_update && rows.drag_drop_update(key, index); row_tooltip_update(panel.state, rows, key); ImGui::PopID(); return isBreak; - } +} - static void card_draw(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int key, int index, - int arrowKey, bool& isBreak) - { +static void card_draw(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int key, int index, + int arrowKey, bool& isBreak) +{ auto cardSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * rows.cardLines); auto style = ImGui::GetStyle(); ImGui::PushID(key); if (arrowKey == key) { - auto targetTop = ImGui::GetCursorPosY(); - if (targetTop < ImGui::GetScrollY()) - ImGui::SetScrollY(targetTop); - else if (targetTop + cardSize.y > ImGui::GetScrollY() + ImGui::GetWindowHeight()) - ImGui::SetScrollY(targetTop + cardSize.y - ImGui::GetWindowHeight()); - ImGui::SetNextWindowFocus(); + auto targetTop = ImGui::GetCursorPosY(); + if (targetTop < ImGui::GetScrollY()) + ImGui::SetScrollY(targetTop); + else if (targetTop + cardSize.y > ImGui::GetScrollY() + ImGui::GetWindowHeight()) + ImGui::SetScrollY(targetTop + cardSize.y - ImGui::GetWindowHeight()); + ImGui::SetNextWindowFocus(); } if (ImGui::BeginChild("##Card Child", cardSize, ImGuiChildFlags_Borders)) { - auto cursorPos = ImGui::GetCursorPos(); - auto isSelected = selection.contains(key) || arrowKey == key; - auto isFocused = key == focus || arrowKey == key; - auto image = rows.image_get(key); - auto label = rows.label_get(key); + auto cursorPos = ImGui::GetCursorPos(); + auto isSelected = selection.contains(key) || arrowKey == key; + auto isFocused = key == focus || arrowKey == key; + auto image = rows.image_get(key); + auto label = rows.label_get(key); - ImGui::SetNextItemSelectionUserData(index); - ImGui::SetNextItemStorageID(key); - if (arrowKey == key) ImGui::SetKeyboardFocusHere(); - if (ImGui::Selectable("##Card Selectable", isSelected, 0, cardSize) || - ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right)) - row_select(selection, focus, rows, key); - if (rows.activate && ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) - rows.activate(key); + ImGui::SetNextItemSelectionUserData(index); + ImGui::SetNextItemStorageID(key); + if (arrowKey == key) + ImGui::SetKeyboardFocusHere(); + if (ImGui::Selectable("##Card Selectable", isSelected, 0, cardSize) || + ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right)) + row_select(selection, focus, rows, key); + if (rows.activate && ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + rows.activate(key); - if (rows.tooltip_draw && ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip) && - !ImGui::IsMouseDragging(ImGuiMouseButton_Left)) - { - ImGui::SetNextWindowSize(ImVec2(ImGui::CalcTextSize(label.c_str()).x + panel.state.tooltipSpacing.x + - panel.state.tooltipPadding.x * TOOLTIP_PADDING_MULTIPLIER, - 0), - ImGuiCond_Appearing); - row_tooltip_update(panel.state, rows, key); - } + if (rows.tooltip_draw && ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip) && + !ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + ImGui::SetNextWindowSize(ImVec2(ImGui::CalcTextSize(label.c_str()).x + panel.state.tooltipSpacing.x + + panel.state.tooltipPadding.x * TOOLTIP_PADDING_MULTIPLIER, + 0), + ImGuiCond_Appearing); + row_tooltip_update(panel.state, rows, key); + } - isBreak = rows.drag_drop_update && rows.drag_drop_update(key, index); + isBreak = rows.drag_drop_update && rows.drag_drop_update(key, index); - auto aspectRatio = image.size.y != 0.0f ? image.size.x / image.size.y : 1.0f; - auto imageSize = ImVec2(cardSize.y, cardSize.y); - if (imageSize.x / imageSize.y > aspectRatio) - imageSize.x = imageSize.y * aspectRatio; - else - imageSize.y = imageSize.x / aspectRatio; - ImGui::SetCursorPos(cursorPos); - ImGui::ImageWithBg(texture_id_get(*image.texture), imageSize, to_imvec2(image.uvMin), - to_imvec2(image.uvMax), ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); + auto aspectRatio = image.size.y != 0.0f ? image.size.x / image.size.y : 1.0f; + auto imageSize = ImVec2(cardSize.y, cardSize.y); + if (imageSize.x / imageSize.y > aspectRatio) + imageSize.x = imageSize.y * aspectRatio; + else + imageSize.y = imageSize.x / aspectRatio; + ImGui::SetCursorPos(cursorPos); + ImGui::ImageWithBg(texture_id_get(*image.texture), imageSize, to_imvec2(image.uvMin), to_imvec2(image.uvMax), + ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); - ImGui::SetCursorPos( - ImVec2(cardSize.y + style.ItemSpacing.x, cardSize.y - cardSize.y / 2 - ImGui::GetTextLineHeight() / 2)); - if (isFocused) ImGui::PushFont(panel.resources.fonts[FONT_ITALICS].get(), FONT_SIZE); - ImGui::TextUnformatted(label.c_str()); - if (isFocused) ImGui::PopFont(); + ImGui::SetCursorPos( + ImVec2(cardSize.y + style.ItemSpacing.x, cardSize.y - cardSize.y / 2 - ImGui::GetTextLineHeight() / 2)); + if (isFocused) + ImGui::PushFont(panel.resources.fonts[FONT_ITALICS].get(), FONT_SIZE); + ImGui::TextUnformatted(label.c_str()); + if (isFocused) + ImGui::PopFont(); } ImGui::EndChild(); row_scroll_update(panel.state, key, -1); - if (panel.state.newId == key) panel.state.newId = -1; + if (panel.state.newId == key) + panel.state.newId = -1; ImGui::PopID(); - } +} - // A selectable list (or cards) of keys; `selection` and `focus` are read and written. - void list_draw(Panel& panel, const std::vector& keys, std::set& selection, int& focus, const ListRows& rows) - { +// A selectable list (or cards) of keys. `selection` and `focus` are read and written. +void list_draw(Panel& panel, const std::vector& keys, std::set& selection, int& focus, const ListRows& rows) +{ panel.state.keys = keys; auto isCards = rows.image_get != nullptr; - if (isCards) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + if (isCards) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); auto arrowKey = list_select_begin(panel, selection, focus, rows, keys); for (int i = 0; i < (int)keys.size(); ++i) { - bool isBreak = false; - if (isCards) - card_draw(panel, selection, focus, rows, keys[i], i, arrowKey, isBreak); - else - isBreak = row_draw(panel, selection, focus, rows, keys[i], i, arrowKey); - if (isBreak) break; + bool isBreak = false; + if (isCards) + card_draw(panel, selection, focus, rows, keys[i], i, arrowKey, isBreak); + else + isBreak = row_draw(panel, selection, focus, rows, keys[i], i, arrowKey); + if (isBreak) + break; } - if (isCards) ImGui::PopStyleVar(); + if (isCards) + ImGui::PopStyleVar(); list_select_end(panel, selection, focus, rows, arrowKey); - } +} - void content_list_draw(Panel& panel, SelectionKind kind, const std::vector& keys, const ListRows& rows) - { +void content_list_draw(Panel& panel, SelectionKind kind, const std::vector& keys, const ListRows& rows) +{ auto& document = panel.document; auto selection = document.selected_ids_get(kind); auto focus = document.focused_id_get(kind); list_draw(panel, keys, selection, focus, rows); document.selected_ids_set(kind, selection); document.focused_id_set(kind, focus); - } +} - // The list in a bordered child with its context menu and shortcuts, then the footer buttons. - // The confirmation's lines: the items by name, then what goes with them. - static std::vector remove_lines_get(const Model& model, ElementType type, const std::set& ids, - int spritesheetId) - { +// The list in a bordered child with its context menu and shortcuts, then the footer buttons. +// The confirmation's lines: the items by name, then what goes with them. +static std::vector remove_lines_get(const Model& model, ElementType type, const std::set& ids, + int spritesheetId) +{ auto& content = model.content; std::vector lines; - auto names_add = [&](const auto& items, auto&& name_get) - { - for (auto id : ids) - if (auto item = item_get(items, id)) lines.push_back(std::format("\"{}\"", name_get(*item))); + auto names_add = [&](const auto& items, auto&& name_get) { + for (auto id : ids) + if (auto item = item_get(items, id)) + lines.push_back(std::format("\"{}\"", name_get(*item))); }; - auto name_get = [](const auto& item) { return item.name; }; - auto path_get = [](const auto& item) { return path_to_utf8(item.path); }; - auto count_add = [&](StringType format, int count) - { - if (count > 0) lines.push_back(localize_format(format, count)); + auto name_get = [](const auto& item) { + return item.name; }; - auto layers_add = [&](StringType format, auto&& is_removed) - { - std::set layerIds; - for (auto& layer : content.layers) - if (is_removed(layer)) - { - layerIds.insert(layer.id); - lines.push_back(localize_format(format, layer.name)); - } - return layerIds; + auto path_get = [](const auto& item) { + return path_to_utf8(item.path); + }; + auto count_add = [&](StringType format, int count) { + if (count > 0) + lines.push_back(localize_format(format, count)); + }; + auto layers_add = [&](StringType format, auto&& is_removed) { + std::set layerIds; + for (auto& layer : content.layers) + if (is_removed(layer)) + { + layerIds.insert(layer.id); + lines.push_back(localize_format(format, layer.name)); + } + return layerIds; }; auto uses = model.uses_count(type, ids, spritesheetId); switch (type) { - case ElementType::LAYER_ELEMENT: - names_add(content.layers, name_get); - count_add(FORMAT_REMOVE_TRACKS, uses); - break; - case ElementType::NULL_ELEMENT: - names_add(content.nulls, name_get); - count_add(FORMAT_REMOVE_TRACKS, uses); - break; - case ElementType::EVENT_ELEMENT: - case ElementType::SOUND_ELEMENT: - { - auto isEvent = type == ElementType::EVENT_ELEMENT; - if (isEvent) - names_add(content.events, name_get); - else - names_add(content.sounds, path_get); - count_add(FORMAT_REMOVE_TRIGGER_USES, uses); - // Triggers whose every event and sound goes. - int emptied = 0; - for (auto [index, animation] : model.animations_get()) - for (auto& trigger : animation->triggers.frames) - { - auto& own = isEvent ? trigger.eventIds : trigger.soundIds; - auto& other = isEvent ? trigger.soundIds : trigger.eventIds; - emptied += - other.empty() && !own.empty() && std::ranges::all_of(own, [&](int id) { return ids.contains(id); }); - } - count_add(FORMAT_REMOVE_TRIGGERS_EMPTY, emptied); - break; - } - case ElementType::SHADER: - names_add(content.shaders, name_get); - count_add(FORMAT_REMOVE_SHADER_USES, uses); - break; - case ElementType::REGION: - if (auto spritesheet = item_get(content.spritesheets, spritesheetId)) - names_add(spritesheet->regions, name_get); - count_add(FORMAT_REMOVE_REGION_USES, uses); - break; - case ElementType::SPRITESHEET: - { - names_add(content.spritesheets, path_get); - auto layerIds = layers_add(FORMAT_REMOVE_LAYER, [&](const Layer& layer) - { return !layer.is_animation() && ids.contains(layer.spritesheetId); }); - count_add(FORMAT_REMOVE_TRACKS, model.uses_count(ElementType::LAYER_ELEMENT, layerIds)); - break; - } - default: - names_add(content.libraries, path_get); - layers_add(FORMAT_REMOVE_FLATTENED_LAYER, - [&](const Layer& layer) { return ids.contains(layer.libraryId); }); - break; + case ElementType::LAYER_ELEMENT: + names_add(content.layers, name_get); + count_add(FORMAT_REMOVE_TRACKS, uses); + break; + case ElementType::NULL_ELEMENT: + names_add(content.nulls, name_get); + count_add(FORMAT_REMOVE_TRACKS, uses); + break; + case ElementType::EVENT_ELEMENT: + case ElementType::SOUND_ELEMENT: + { + auto isEvent = type == ElementType::EVENT_ELEMENT; + if (isEvent) + names_add(content.events, name_get); + else + names_add(content.sounds, path_get); + count_add(FORMAT_REMOVE_TRIGGER_USES, uses); + // Triggers whose every event and sound goes. + int emptied = 0; + for (auto [index, animation] : model.animations_get()) + for (auto& trigger : animation->triggers.frames) + { + auto& own = isEvent ? trigger.eventIds : trigger.soundIds; + auto& other = isEvent ? trigger.soundIds : trigger.eventIds; + emptied += other.empty() && !own.empty() && + std::ranges::all_of(own, [&](int id) { return ids.contains(id); }); + } + count_add(FORMAT_REMOVE_TRIGGERS_EMPTY, emptied); + break; + } + case ElementType::SHADER: + names_add(content.shaders, name_get); + count_add(FORMAT_REMOVE_SHADER_USES, uses); + break; + case ElementType::REGION: + if (auto spritesheet = item_get(content.spritesheets, spritesheetId)) + names_add(spritesheet->regions, name_get); + count_add(FORMAT_REMOVE_REGION_USES, uses); + break; + case ElementType::SPRITESHEET: + { + names_add(content.spritesheets, path_get); + auto layerIds = layers_add(FORMAT_REMOVE_LAYER, [&](const Layer& layer) { + return !layer.is_animation() && ids.contains(layer.spritesheetId); + }); + count_add(FORMAT_REMOVE_TRACKS, model.uses_count(ElementType::LAYER_ELEMENT, layerIds)); + break; + } + default: + names_add(content.libraries, path_get); + layers_add(FORMAT_REMOVE_FLATTENED_LAYER, + [&](const Layer& layer) { return ids.contains(layer.libraryId); }); + break; } return lines; - } +} - static void content_remove_apply(Panel& panel) - { - command_push(panel, - [removal = panel.state.removal](Document& document) - { - document.edit_apply(EDIT_REMOVE_ITEMS, - [&](Model& model) - { - return content_remove( - model, removal.type, removal.ids, removal.spritesheetId, - document.library_resolver_get(), document.spritesheet_path_resolver_get()); - }); - document.selected_clear(removal.kind); - }); - } +static void content_remove_apply(Panel& panel) +{ + command_push(panel, [removal = panel.state.removal](Document& document) { + document.edit_apply(EDIT_REMOVE_ITEMS, [&](Model& model) { + return content_remove(model, removal.type, removal.ids, removal.spritesheetId, + document.library_resolver_get(), document.spritesheet_path_resolver_get()); + }); + document.selected_clear(removal.kind); + }); +} - // Removes the selected content items; when anything uses them, it asks first, saying what goes with them. - void content_remove_action_add(Actions& actions, Panel& panel, ElementType type, SelectionKind kind, - int spritesheetId) - { +// Removes the selected content items. When anything uses them, it asks first, saying what goes with them. +void content_remove_action_add(Actions& actions, Panel& panel, ElementType type, SelectionKind kind, int spritesheetId) +{ auto selection = panel.document.selected_ids_get(kind); actions.add( ACTION_REMOVE, [selection]() { return !selection.empty(); }, - [&panel, type, kind, selection, spritesheetId]() - { - auto& model = panel.document.model; - panel.state.removal = {type, kind, selection, spritesheetId, - remove_lines_get(model, type, selection, spritesheetId)}; - if (model.uses_count(type, selection, spritesheetId) > 0) - panel.state.removePopup.open(); - else - content_remove_apply(panel); + [&panel, type, kind, selection, spritesheetId]() { + auto& model = panel.document.model; + panel.state.removal = {type, kind, selection, spritesheetId, + remove_lines_get(model, type, selection, spritesheetId)}; + if (model.uses_count(type, selection, spritesheetId) > 0) + panel.state.removePopup.open(); + else + content_remove_apply(panel); }, TOOLTIP_REMOVE_CONTENT); - } +} - static void content_remove_popup_draw(Panel& panel) - { +static void content_remove_popup_draw(Panel& panel) +{ auto& popup = panel.state.removePopup; popup.trigger(); - if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) + return popup.end(); auto& removal = panel.state.removal; ImGui::TextUnformatted(localize.get(TEXT_REMOVE_LIST)); auto& lines = removal.lines; for (std::size_t i = 0; i < std::min(lines.size(), REMOVE_LINES_MAX); ++i) - ImGui::BulletText("%s", lines[i].c_str()); + ImGui::BulletText("%s", lines[i].c_str()); if (lines.size() > REMOVE_LINES_MAX) - ImGui::BulletText("%s", localize_format(FORMAT_REMOVE_MORE, (int)(lines.size() - REMOVE_LINES_MAX)).c_str()); + ImGui::BulletText("%s", localize_format(FORMAT_REMOVE_MORE, (int)(lines.size() - REMOVE_LINES_MAX)).c_str()); ImGui::Spacing(); ImGui::TextUnformatted(localize.get(TEXT_REMOVE_CONFIRM)); auto result = popup_buttons_draw(panel.manager, localize.get(BASIC_REMOVE)); - if (result == PopupButton::CONFIRM) content_remove_apply(panel); - if (result != PopupButton::NONE) popup.close(); + if (result == PopupButton::CONFIRM) + content_remove_apply(panel); + if (result != PopupButton::NONE) + popup.close(); ImGui::EndPopup(); popup.end(); - } +} - void list_panel_draw(Panel& panel, Actions& actions, const Footer& footer, const std::function& list, - bool isCards, Actions* footerActions) - { +void list_panel_draw(Panel& panel, Actions& actions, const Footer& footer, const std::function& list, + bool isCards, Actions* footerActions) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; state.tooltipPadding = ImGui::GetStyle().WindowPadding; state.tooltipSpacing = ImGui::GetStyle().ItemSpacing; - if (isCards) ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + if (isCards) + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); if (ImGui::BeginChild("##List Child", size_without_footer_get((int)footer.size()), ImGuiChildFlags_Borders)) { - list(); - actions_shortcuts_update(actions, manager); + list(); + actions_shortcuts_update(actions, manager); } ImGui::EndChild(); - if (isCards) ImGui::PopStyleVar(); + if (isCards) + ImGui::PopStyleVar(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && ImGui::IsMouseReleased(ImGuiMouseButton_Right)) - ImGui::OpenPopup(CONTEXT_MENU_LABEL); + ImGui::OpenPopup(CONTEXT_MENU_LABEL); Actions menu = {}; actions_undo_redo_add(menu, manager, document); menu.separator(); @@ -441,24 +465,24 @@ using namespace glm; auto& buttons = footerActions ? *footerActions : actions; for (auto& row : footer) { - auto widgetSize = widget_size_with_row_get((int)row.size()); - bool isSameLine = false; - for (auto type : row) - if (auto action = std::ranges::find(buttons.items, type, &Action::type); action != buttons.items.end()) - action_button_draw(*action, manager, settings, widgetSize, isSameLine); + auto widgetSize = widget_size_with_row_get((int)row.size()); + bool isSameLine = false; + for (auto type : row) + if (auto action = std::ranges::find(buttons.items, type, &Action::type); action != buttons.items.end()) + action_button_draw(*action, manager, settings, widgetSize, isSameLine); } content_remove_popup_draw(panel); - } +} - void tooltip_name_draw(Resources& resources, const std::string& name) - { +void tooltip_name_draw(Resources& resources, const std::string& name) +{ ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::TextUnformatted(name.c_str()); ImGui::PopFont(); - } +} - void tooltip_image_draw(const CardImage& image, const std::function& info_draw) - { +void tooltip_image_draw(const CardImage& image, const std::function& info_draw) +{ auto maxPreviewSize = to_vec2(ImGui::GetMainViewport()->Size) * PREVIEW_VIEWPORT_FRACTION; auto previewSize = glm::max(image.size, vec2(1.0f)); previewSize *= glm::min(1.0f, glm::min(maxPreviewSize.x / previewSize.x, maxPreviewSize.y / previewSize.y)); @@ -467,50 +491,54 @@ using namespace glm; auto noScrollFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); if (ImGui::BeginChild("##Tooltip Image Child", to_imvec2(previewSize), childFlags, noScrollFlags)) - ImGui::ImageWithBg(texture_id_get(*image.texture), to_imvec2(previewSize), to_imvec2(image.uvMin), - to_imvec2(image.uvMax), ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); + ImGui::ImageWithBg(texture_id_get(*image.texture), to_imvec2(previewSize), to_imvec2(image.uvMin), + to_imvec2(image.uvMax), ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::SameLine(); if (ImGui::BeginChild("##Tooltip Info Child", ImVec2(), ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY, noScrollFlags)) - info_draw(); + info_draw(); ImGui::EndChild(); - } +} - std::filesystem::path asset_path_get(Document& document, const std::filesystem::path& path) - { +std::filesystem::path asset_path_get(Document& document, const std::filesystem::path& path) +{ return path_backslash_replace(path_make_relative(path_backslash_handle(path), document.directory_get())); - } +} - // Shows a resource's file selected in the file manager (or the nearest folder there is, when it's missing). - void directory_open(Dialog& dialog, Document& document, const std::filesystem::path& path) - { - if (path.empty()) return; +// Shows a resource's file selected in the file manager (or the nearest folder there is, when it's missing). +void directory_open(Dialog& dialog, Document& document, const std::filesystem::path& path) +{ + if (path.empty()) + return; std::error_code ec; auto absolutePath = std::filesystem::weakly_canonical(document.directory_get() / path, ec); - if (ec) absolutePath = document.directory_get() / path; + if (ec) + absolutePath = document.directory_get() / path; auto target = std::filesystem::is_regular_file(absolutePath, ec) || std::filesystem::is_directory(absolutePath, ec) ? absolutePath : std::filesystem::is_directory(absolutePath.parent_path()) ? absolutePath.parent_path() : document.directory_get(); dialog.file_explorer_open(target); - } +} - PopupButton popup_buttons_draw(Manager& manager, const char* confirmLabel, bool isConfirmEnabled, - StringType cancelLabel) - { +PopupButton popup_buttons_draw(Manager& manager, const char* confirmLabel, bool isConfirmEnabled, + StringType cancelLabel) +{ auto widgetSize = widget_size_with_row_get(2); auto result = PopupButton::NONE; ImGui::BeginDisabled(!isConfirmEnabled); shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(confirmLabel, widgetSize)) result = PopupButton::CONFIRM; + if (ImGui::Button(confirmLabel, widgetSize)) + result = PopupButton::CONFIRM; ImGui::EndDisabled(); ImGui::SameLine(); shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(cancelLabel), widgetSize)) result = PopupButton::CANCEL; + if (ImGui::Button(localize.get(cancelLabel), widgetSize)) + result = PopupButton::CANCEL; return result; - } +} diff --git a/src/ui/panel.h b/src/ui/panel.h index 5253b60..931068c 100644 --- a/src/ui/panel.h +++ b/src/ui/panel.h @@ -19,25 +19,25 @@ #include "ui/change_all_frame_properties.h" // Panels are plain functions: each draws from the document and its selection, and queues edits as commands. - inline constexpr auto DRAG_DROP_SOURCE_FLAGS = - ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers; - inline constexpr ImVec4 CARD_TINT_INVALID = ImVec4(1.0f, 0.25f, 0.25f, 1.0f); - inline constexpr ImVec4 CARD_TINT_VALID = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); +inline constexpr auto DRAG_DROP_SOURCE_FLAGS = + ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers; +inline constexpr ImVec4 CARD_TINT_INVALID = ImVec4(1.0f, 0.25f, 0.25f, 1.0f); +inline constexpr ImVec4 CARD_TINT_VALID = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - using Footer = std::vector>; +using Footer = std::vector>; - struct CardImage - { +struct CardImage +{ const Image* texture = nullptr; glm::vec2 size{}; glm::vec2 uvMin{}; glm::vec2 uvMax{1.0f}; bool isValid = false; - }; +}; - // What a list panel remembers between frames. - struct PanelState - { +// What a list panel remembers between frames. +struct PanelState +{ int newId = -1; int scrollId = -1; int renameId = -1; @@ -52,17 +52,17 @@ // A removal waiting on its confirmation, since what it removes is in use. struct Removal { - ElementType type = {}; - SelectionKind kind = {}; - std::set ids; - int spritesheetId = -1; - std::vector lines; + ElementType type = {}; + SelectionKind kind = {}; + std::set ids; + int spritesheetId = -1; + std::vector lines; } removal{}; - }; +}; - // Everything a panel draws with, for one frame. Commands get the document again when they run. - struct Panel - { +// Everything a panel draws with, for one frame. Commands get the document again when they run. +struct Panel +{ Manager& manager; Settings& settings; Resources& resources; @@ -70,12 +70,12 @@ Clipboard& clipboard; Document& document; PanelState& state; - }; +}; - // How a list shows its keys; only `label_get` is required. With `image_get` the rows are cards; `children_draw` draws - // under a key. - struct ListRows - { +// How a list shows its keys. Only `label_get` is required. With `image_get` the rows are cards. `children_draw` draws +// under a key. +struct ListRows +{ std::function label_get{}; std::function name_get{}; std::function rename{}; @@ -88,34 +88,34 @@ std::function drag_drop_update{}; int cardLines = 0; bool isFocusItalic = false; - }; +}; - enum class PopupButton - { +enum class PopupButton +{ NONE, CONFIRM, CANCEL - }; +}; - bool is_drag_drop_active(); - void command_push(const Panel&, std::function); - bool row_draw(Panel&, std::set&, int&, const ListRows&, int, int, int); - void list_draw(Panel&, const std::vector&, std::set&, int&, const ListRows&); - void content_list_draw(Panel&, SelectionKind, const std::vector&, const ListRows&); - int list_select_begin(Panel&, std::set&, int&, const ListRows&, const std::vector&); - void list_select_end(Panel&, std::set&, int&, const ListRows&, int); - void list_panel_draw(Panel&, Actions&, const Footer&, const std::function&, bool = false, Actions* = nullptr); - bool tooltip_begin(const PanelState&, bool = true); - void tooltip_end(); - void tooltip_name_draw(Resources&, const std::string&); - void tooltip_image_draw(const CardImage&, const std::function&); - void directory_open(Dialog&, Document&, const std::filesystem::path&); - std::filesystem::path asset_path_get(Document&, const std::filesystem::path&); - PopupButton popup_buttons_draw(Manager&, const char*, bool = true, StringType = BASIC_CANCEL); - void content_remove_action_add(Actions&, Panel&, ElementType, SelectionKind, int = -1); +bool is_drag_drop_active(); +void command_push(const Panel&, std::function); +bool row_draw(Panel&, std::set&, int&, const ListRows&, int, int, int); +void list_draw(Panel&, const std::vector&, std::set&, int&, const ListRows&); +void content_list_draw(Panel&, SelectionKind, const std::vector&, const ListRows&); +int list_select_begin(Panel&, std::set&, int&, const ListRows&, const std::vector&); +void list_select_end(Panel&, std::set&, int&, const ListRows&, int); +void list_panel_draw(Panel&, Actions&, const Footer&, const std::function&, bool = false, Actions* = nullptr); +bool tooltip_begin(const PanelState&, bool = true); +void tooltip_end(); +void tooltip_name_draw(Resources&, const std::string&); +void tooltip_image_draw(const CardImage&, const std::function&); +void directory_open(Dialog&, Document&, const std::filesystem::path&); +std::filesystem::path asset_path_get(Document&, const std::filesystem::path&); +PopupButton popup_buttons_draw(Manager&, const char*, bool = true, StringType = BASIC_CANCEL); +void content_remove_action_add(Actions&, Panel&, ElementType, SelectionKind, int = -1); - struct SpritesheetsPanel - { +struct SpritesheetsPanel +{ PanelState state = {}; PopupHelper mergePopup = PopupHelper(LABEL_SPRITESHEETS_MERGE_POPUP, POPUP_SMALL_NO_HEIGHT); PopupHelper packPopup = PopupHelper(LABEL_SPRITESHEETS_PACK_POPUP, POPUP_SMALL_NO_HEIGHT); @@ -123,105 +123,104 @@ std::set mergeIds; std::set saveIds; int packId = -1; - }; +}; - struct RegionsPanel - { +struct RegionsPanel +{ PanelState state = {}; PopupHelper propertiesPopup = PopupHelper(LABEL_REGION_PROPERTIES, POPUP_SMALL_NO_HEIGHT); PopupHelper exportPopup = PopupHelper(LABEL_EXPORT_REGION, POPUP_SMALL_NO_HEIGHT); Region editRegion = {}; int editId = -1; int exportId = -1; - }; +}; - struct AnimationsPanel - { +struct AnimationsPanel +{ PanelState state = {}; PopupHelper mergePopup = PopupHelper(LABEL_ANIMATIONS_MERGE_POPUP); MultiSelectStorage mergeSelection = {}; std::vector mergeKeys; int mergeReference = -1; - }; +}; - struct FramePropertiesPanel - { +struct FramePropertiesPanel +{ ChangeAllFrameProperties changeAllFrameProperties = {}; bool isBatchMode = false; - }; +}; - class Taskbar; - class Documents; +class Taskbar; +class Documents; - void animations_update(Panel&, AnimationsPanel&); - void layers_update(Panel&); - void nulls_update(Panel&); - void events_update(Panel&); - void sounds_update(Panel&); - std::string layer_label_get(const Layer&); - void layer_source_tooltip_draw(const Document&, const Layer&); - void layer_source_tooltip_draw(const Document&, const Layer&); - Layer item_edit_layer_get(const Manager::ItemEdit&); - Null item_edit_null_get(const Manager::ItemEdit&); - void layer_source_draw(Document&, Manager::ItemEdit&); - void libraries_update(Panel&); - void spritesheets_update(Panel&, SpritesheetsPanel&); - void regions_update(Panel&, RegionsPanel&); - void frame_properties_update(Manager&, Settings&, FramePropertiesPanel&); - void onionskin_update(Manager&, Settings&); - void tools_update(Manager&, Settings&, Resources&, PopupHelper&); - void welcome_update(Manager&, Resources&, Dialog&, Taskbar&, Documents&); +void animations_update(Panel&, AnimationsPanel&); +void layers_update(Panel&); +void nulls_update(Panel&); +void events_update(Panel&); +void sounds_update(Panel&); +std::string layer_label_get(const Layer&); +void layer_source_tooltip_draw(const Document&, const Layer&); +void layer_source_tooltip_draw(const Document&, const Layer&); +Layer item_edit_layer_get(const Manager::ItemEdit&); +Null item_edit_null_get(const Manager::ItemEdit&); +void layer_source_draw(Document&, Manager::ItemEdit&); +void libraries_update(Panel&); +void spritesheets_update(Panel&, SpritesheetsPanel&); +void regions_update(Panel&, RegionsPanel&); +void frame_properties_update(Manager&, Settings&, FramePropertiesPanel&); +void onionskin_update(Manager&, Settings&); +void tools_update(Manager&, Settings&, Resources&, PopupHelper&); +void welcome_update(Manager&, Resources&, Dialog&, Taskbar&, Documents&); - template std::vector item_ids_get(const Items& items) - { +template std::vector item_ids_get(const Items& items) +{ std::vector ids; for (auto& item : items) - ids.push_back(item.id); + ids.push_back(item.id); return ids; - } +} - template void items_copy(Clipboard& clipboard, const Items& items, const std::set& ids) - { +template void items_copy(Clipboard& clipboard, const Items& items, const std::set& ids) +{ std::string text; for (auto id : ids) - if (auto item = item_get(items, id)) text += item_to_string(*item); - if (!text.empty()) clipboard.set(text); - } + if (auto item = item_get(items, id)) + text += item_to_string(*item); + if (!text.empty()) + clipboard.set(text); +} - // Pastes clipboard items into a content list with fresh ids and selects the last one. - template - void items_paste(const Panel& panel, SelectionKind kind, StringType edit, StringType failToast, ItemsGet items_get) - { +// Pastes clipboard items into a content list with fresh ids and selects the last one. +template +void items_paste(const Panel& panel, SelectionKind kind, StringType edit, StringType failToast, ItemsGet items_get) +{ auto text = panel.clipboard.get(); auto& state = panel.state; - command_push(panel, - [&state, kind, edit, failToast, text, items_get](Document& document) - { - std::string errorString; - auto pasted = items_from_string(text, &errorString); - if (pasted.empty()) return toast_log(Level::ERROR, failToast, errorString); - document.edit_apply(edit, - [&](Model& model) - { - auto& items = items_get(model); - for (auto& item : pasted) - { - item.id = item_next_id_get(items); - items.push_back(std::move(item)); - } - }); - auto id = items_get(document.model).back().id; - document.selected_ids_set(kind, {id}); - document.focused_id_set(kind, id); - state.newId = id; - }); - } + command_push(panel, [&state, kind, edit, failToast, text, items_get](Document& document) { + std::string errorString; + auto pasted = items_from_string(text, &errorString); + if (pasted.empty()) + return toast_log(Level::ERROR, failToast, errorString); + document.edit_apply(edit, [&](Model& model) { + auto& items = items_get(model); + for (auto& item : pasted) + { + item.id = item_next_id_get(items); + items.push_back(std::move(item)); + } + }); + auto id = items_get(document.model).back().id; + document.selected_ids_set(kind, {id}); + document.focused_id_set(kind, id); + state.newId = id; + }); +} - // Copy and paste for a content list, after a separator. - template - void items_clipboard_actions_add(Actions& actions, Panel& panel, SelectionKind kind, StringType pasteEdit, - StringType failToast, ItemsGet items_get) - { +// Copy and paste for a content list, after a separator. +template +void items_clipboard_actions_add(Actions& actions, Panel& panel, SelectionKind kind, StringType pasteEdit, + StringType failToast, ItemsGet items_get) +{ auto selection = panel.document.selected_ids_get(kind); actions.separator(); actions.add( @@ -229,6 +228,7 @@ [&panel, selection, items_get]() { items_copy(panel.clipboard, items_get(panel.document.model), selection); }); actions.add( ACTION_PASTE, [&panel]() { return !panel.clipboard.is_empty(); }, - [&panel, kind, pasteEdit, failToast, items_get]() - { items_paste(panel, kind, pasteEdit, failToast, items_get); }); - } + [&panel, kind, pasteEdit, failToast, items_get]() { + items_paste(panel, kind, pasteEdit, failToast, items_get); + }); +} diff --git a/src/ui/popup.cpp b/src/ui/popup.cpp index 56e176f..66ccc53 100644 --- a/src/ui/popup.cpp +++ b/src/ui/popup.cpp @@ -6,78 +6,88 @@ #include "types.h" - int PopupHelper::nextId = 1; +int PopupHelper::nextId = 1; #define POPUP_LIST \ - X(POPUP_SMALL, 0.25f, true) \ - X(POPUP_NORMAL, 0.5f, true) \ - X(POPUP_TO_CONTENT, 0.0f, true) \ - X(POPUP_SMALL_NO_HEIGHT, 0.25f, false) \ - X(POPUP_NORMAL_NO_HEIGHT, 0.5f, false) + X(POPUP_SMALL, 0.25f, true) \ + X(POPUP_NORMAL, 0.5f, true) \ + X(POPUP_TO_CONTENT, 0.0f, true) \ + X(POPUP_SMALL_NO_HEIGHT, 0.25f, false) \ + X(POPUP_NORMAL_NO_HEIGHT, 0.5f, false) - constexpr float POPUP_MULTIPLIERS[] = { +constexpr float POPUP_MULTIPLIERS[] = { #define X(name, multiplier, isHeightSet) multiplier, - POPUP_LIST + POPUP_LIST #undef X - }; +}; - constexpr bool POPUP_IS_HEIGHT_SET[] = { +constexpr bool POPUP_IS_HEIGHT_SET[] = { #define X(name, multiplier, isHeightSet) isHeightSet, - POPUP_LIST + POPUP_LIST #undef X - }; +}; #undef POPUP_LIST - PopupHelper::PopupHelper(StringType labelId, PopupType type, PopupPosition position) - { +PopupHelper::PopupHelper(StringType labelId, PopupType type, PopupPosition position) +{ this->labelId = labelId; this->type = type; this->position = position; id = nextId++; - } +} - const char* PopupHelper::label() const - { +const char* PopupHelper::label() const +{ labelText = localize.get(labelId); labelText += "##Popup"; labelText += std::to_string(id); return labelText.c_str(); - } +} - void PopupHelper::open() - { +void PopupHelper::open() +{ isOpen = true; isTriggered = true; isJustOpened = true; - } +} - bool PopupHelper::is_open() { return isOpen; } +bool PopupHelper::is_open() +{ + return isOpen; +} - void PopupHelper::trigger() - { - if (isTriggered) ImGui::OpenPopup(label()); +void PopupHelper::trigger() +{ + if (isTriggered) + ImGui::OpenPopup(label()); isTriggered = false; auto viewport = ImGui::GetMainViewport(); switch (position) { - case POPUP_CENTER: - ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_None, to_imvec2(glm::vec2(0.5f))); - if (POPUP_IS_HEIGHT_SET[type]) - ImGui::SetNextWindowSize(to_imvec2(to_vec2(viewport->Size) * POPUP_MULTIPLIERS[type])); - else - ImGui::SetNextWindowSize(ImVec2(viewport->Size.x * POPUP_MULTIPLIERS[type], 0)); - break; - case POPUP_BY_ITEM: - ImGui::SetNextWindowPos(ImGui::GetItemRectMin(), ImGuiCond_None); - case POPUP_BY_CURSOR: - default: - break; + case POPUP_CENTER: + ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_None, to_imvec2(glm::vec2(0.5f))); + if (POPUP_IS_HEIGHT_SET[type]) + ImGui::SetNextWindowSize(to_imvec2(to_vec2(viewport->Size) * POPUP_MULTIPLIERS[type])); + else + ImGui::SetNextWindowSize(ImVec2(viewport->Size.x * POPUP_MULTIPLIERS[type], 0)); + break; + case POPUP_BY_ITEM: + ImGui::SetNextWindowPos(ImGui::GetItemRectMin(), ImGuiCond_None); + case POPUP_BY_CURSOR: + default: + break; } - } +} - void PopupHelper::end() { isJustOpened = false; } +void PopupHelper::end() +{ + isJustOpened = false; +} - void PopupHelper::close() { isOpen = false; } +void PopupHelper::close() +{ + isOpen = false; +} diff --git a/src/ui/popup.h b/src/ui/popup.h index 923e04a..fa53714 100644 --- a/src/ui/popup.h +++ b/src/ui/popup.h @@ -5,29 +5,29 @@ #include "localization.h" #define POPUP_LIST \ - X(POPUP_SMALL, 0.25f, true) \ - X(POPUP_NORMAL, 0.5f, true) \ - X(POPUP_TO_CONTENT, 0.0f, true) \ - X(POPUP_SMALL_NO_HEIGHT, 0.25f, false) \ - X(POPUP_NORMAL_NO_HEIGHT, 0.5f, false) + X(POPUP_SMALL, 0.25f, true) \ + X(POPUP_NORMAL, 0.5f, true) \ + X(POPUP_TO_CONTENT, 0.0f, true) \ + X(POPUP_SMALL_NO_HEIGHT, 0.25f, false) \ + X(POPUP_NORMAL_NO_HEIGHT, 0.5f, false) - enum PopupType - { +enum PopupType +{ #define X(name, multiplier, isHeightSet) name, POPUP_LIST #undef X - }; +}; - enum PopupPosition - { +enum PopupPosition +{ POPUP_CENTER, POPUP_BY_ITEM, POPUP_BY_CURSOR - }; +}; - class PopupHelper - { - public: +class PopupHelper +{ +public: StringType labelId = {}; PopupType type = {}; PopupPosition position = {}; @@ -45,6 +45,6 @@ void trigger(); void end(); void close(); - }; +}; #undef POPUP_LIST diff --git a/src/ui/regions.cpp b/src/ui/regions.cpp index 1058092..a52c88c 100644 --- a/src/ui/regions.cpp +++ b/src/ui/regions.cpp @@ -15,80 +15,85 @@ using namespace glm; - constexpr int REGION_CARD_LINES = 2; - constexpr int REGION_POPUP_ROWS = 5; - constexpr const char* REGION_DRAG_DROP = "Region Drag Drop"; - constexpr const char* REGION_EXPORT_NAME_DEFAULT = "region"; - constexpr const char* REGION_EXPORT_EXTENSION = ".png"; - constexpr ImVec2 DRAG_TOOLTIP_OFFSET = ImVec2(16.0f, 16.0f); +constexpr int REGION_CARD_LINES = 2; +constexpr int REGION_POPUP_ROWS = 5; +constexpr const char* REGION_DRAG_DROP = "Region Drag Drop"; +constexpr const char* REGION_EXPORT_NAME_DEFAULT = "region"; +constexpr const char* REGION_EXPORT_EXTENSION = ".png"; +constexpr ImVec2 DRAG_TOOLTIP_OFFSET = ImVec2(16.0f, 16.0f); - constexpr StringType ORIGIN_LABELS[] = {LABEL_REGION_ORIGIN_CUSTOM, LABEL_REGION_ORIGIN_TOP_LEFT, - LABEL_REGION_ORIGIN_CENTER}; - constexpr Origin ORIGIN_COMBO_ORDER[] = {Origin::TOP_LEFT, Origin::CENTER, Origin::CUSTOM}; +constexpr StringType ORIGIN_LABELS[] = {LABEL_REGION_ORIGIN_CUSTOM, LABEL_REGION_ORIGIN_TOP_LEFT, + LABEL_REGION_ORIGIN_CENTER}; +constexpr Origin ORIGIN_COMBO_ORDER[] = {Origin::TOP_LEFT, Origin::CENTER, Origin::CUSTOM}; - struct RegionExportOptions - { +struct RegionExportOptions +{ int spritesheetId = -1; int regionId = -1; std::filesystem::path path; bool isMakeSpritesheet = false; bool isRemoveCurrent = false; - }; +}; - static void region_pivot_apply(Region& region) - { - if (region.origin == Origin::TOP_LEFT) region.pivot = {}; - if (region.origin == Origin::CENTER) region.pivot = region.size * 0.5f; - } +static void region_pivot_apply(Region& region) +{ + if (region.origin == Origin::TOP_LEFT) + region.pivot = {}; + if (region.origin == Origin::CENTER) + region.pivot = region.size * 0.5f; +} - static const Spritesheet* region_spritesheet_get(Document& document) - { +static const Spritesheet* region_spritesheet_get(Document& document) +{ return item_get(document.model.content.spritesheets, document.focused_id_get(SelectionKind::SPRITESHEETS)); - } +} - // New regions go after the last selected (or focused) one. - static int region_insert_index_get(Document& document) - { +// New regions go after the last selected (or focused) one. +static int region_insert_index_get(Document& document) +{ auto spritesheet = region_spritesheet_get(document); - if (!spritesheet) return 0; + if (!spritesheet) + return 0; auto selection = document.selected_ids_get(SelectionKind::REGIONS); auto focus = document.focused_id_get(SelectionKind::REGIONS); int index = (int)spritesheet->regions.size(); for (int i = 0; i < (int)spritesheet->regions.size(); i++) { - auto id = spritesheet->regions[i].id; - if (selection.contains(id) || (selection.empty() && focus == id)) index = i + 1; + auto id = spritesheet->regions[i].id; + if (selection.contains(id) || (selection.empty() && focus == id)) + index = i + 1; } return index; - } +} - static void region_select(Document& document, int id) - { +static void region_select(Document& document, int id) +{ document.editTarget = Document::EditTarget::REGION; document.selected_ids_set(SelectionKind::REGIONS, {id}); document.focused_id_set(SelectionKind::REGIONS, id); document.reference_set({document.reference_get().animationIndex}); document.frame_references_clear(); - } +} - static CardImage region_image_get(Document& document, Resources& resources, const Region& region) - { +static CardImage region_image_get(Document& document, Resources& resources, const Region& region) +{ auto texture = document.texture_get(document.focused_id_get(SelectionKind::SPRITESHEETS)); - if (!texture || !texture->is_valid()) return {.texture = &resources.icons[ICON_NONE], .size = region.size}; + if (!texture || !texture->is_valid()) + return {.texture = &resources.icons[ICON_NONE], .size = region.size}; return {.texture = texture, .size = region.size, .uvMin = region.crop / vec2(texture->size), .uvMax = (region.crop + region.size) / vec2(texture->size), .isValid = true}; - } +} - static bool region_export(Document& document, const RegionExportOptions& options) - { +static bool region_export(Document& document, const RegionExportOptions& options) +{ auto pathString = options.path.empty() ? std::string("in memory") : path_to_utf8(options.path); if (options.path.empty() && !options.isMakeSpritesheet) { - toast_log(Level::ERROR, TOAST_EXPORT_REGION_PATH_EMPTY); - return false; + toast_log(Level::ERROR, TOAST_EXPORT_REGION_PATH_EMPTY); + return false; } auto spritesheet = item_get(document.model.content.spritesheets, options.spritesheetId); @@ -98,8 +103,8 @@ using namespace glm; auto exportSize = region ? ivec2(glm::max(region->crop, region->crop + region->size)) - minPoint : ivec2(); if (!region || !texture || !texture->is_valid() || exportSize.x <= 0 || exportSize.y <= 0) { - toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, region ? region->name : std::string(), pathString); - return false; + toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, region ? region->name : std::string(), pathString); + return false; } auto exportedImage = texture->region_get(minPoint, exportSize); @@ -107,254 +112,259 @@ using namespace glm; auto outputPath = options.path; if (!outputPath.empty()) { - outputPath = asset_path_get(document, outputPath.replace_extension(REGION_EXPORT_EXTENSION)); - pathString = path_to_utf8(outputPath); - WorkingDirectory workingDirectory(document.directory_get()); - path_ensure_directory(outputPath.parent_path()); - if (!exportedImage.write_png(outputPath)) - { - toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, sourceRegion.name, pathString); - return false; - } + outputPath = asset_path_get(document, outputPath.replace_extension(REGION_EXPORT_EXTENSION)); + pathString = path_to_utf8(outputPath); + WorkingDirectory workingDirectory(document.directory_get()); + path_ensure_directory(outputPath.parent_path()); + if (!exportedImage.write_png(outputPath)) + { + toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, sourceRegion.name, pathString); + return false; + } } if (options.isMakeSpritesheet || options.isRemoveCurrent) { - document.edit_begin(EDIT_EXPORT_REGION); + document.edit_begin(EDIT_EXPORT_REGION); - if (options.isRemoveCurrent) - { - if (auto source = item_get(document.model.content.spritesheets, options.spritesheetId)) - std::erase_if(source->regions, [&](const Region& region) { return region.id == options.regionId; }); - region_frames_sync(document.model); - document.selected_clear(SelectionKind::REGIONS); - } + if (options.isRemoveCurrent) + { + if (auto source = item_get(document.model.content.spritesheets, options.spritesheetId)) + std::erase_if(source->regions, [&](const Region& region) { return region.id == options.regionId; }); + region_frames_sync(document.model); + document.selected_clear(SelectionKind::REGIONS); + } - if (options.isMakeSpritesheet) - { - auto& spritesheets = document.model.content.spritesheets; - Spritesheet exported = {.id = item_next_id_get(spritesheets), .path = outputPath}; + if (options.isMakeSpritesheet) + { + auto& spritesheets = document.model.content.spritesheets; + Spritesheet exported = {.id = item_next_id_get(spritesheets), .path = outputPath}; - auto exportedRegion = sourceRegion; - exportedRegion.uid = uid_next(); - exportedRegion.id = 0; - exportedRegion.crop = {}; - exportedRegion.size = vec2(exportSize); - region_pivot_apply(exportedRegion); - exported.regions.push_back(exportedRegion); - spritesheets.push_back(exported); + auto exportedRegion = sourceRegion; + exportedRegion.uid = uid_next(); + exportedRegion.id = 0; + exportedRegion.crop = {}; + exportedRegion.size = vec2(exportSize); + region_pivot_apply(exportedRegion); + exported.regions.push_back(exportedRegion); + spritesheets.push_back(exported); - document.texture_set(exported.id, exportedImage); - document.texturePaths[exported.id] = exported.path; - document.selected_ids_set(SelectionKind::SPRITESHEETS, {exported.id}); - document.focused_id_set(SelectionKind::SPRITESHEETS, exported.id); - document.selected_ids_set(SelectionKind::REGIONS, {exportedRegion.id}); - document.focused_id_set(SelectionKind::REGIONS, exportedRegion.id); - if (!outputPath.empty()) - document.spritesheet_hash_set_saved(exported.id); - else - document.spritesheetSaveHashes[exported.id] = 0; - } - document.change(); + document.texture_set(exported.id, exportedImage); + document.texturePaths[exported.id] = exported.path; + document.selected_ids_set(SelectionKind::SPRITESHEETS, {exported.id}); + document.focused_id_set(SelectionKind::SPRITESHEETS, exported.id); + document.selected_ids_set(SelectionKind::REGIONS, {exportedRegion.id}); + document.focused_id_set(SelectionKind::REGIONS, exportedRegion.id); + if (!outputPath.empty()) + document.spritesheet_hash_set_saved(exported.id); + else + document.spritesheetSaveHashes[exported.id] = 0; + } + document.change(); } toast_log(Level::INFO, TOAST_EXPORT_REGION, sourceRegion.name, pathString); return true; - } +} - static bool region_drag_drop_update(Panel& panel, int id, int index) - { +static bool region_drag_drop_update(Panel& panel, int id, int index) +{ auto& state = panel.state; auto selection = panel.document.selected_ids_get(SelectionKind::REGIONS); if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) { - state.dragIds = - selection.contains(id) ? std::vector(selection.begin(), selection.end()) : std::vector{id}; - ImGui::SetDragDropPayload(REGION_DRAG_DROP, state.dragIds.data(), state.dragIds.size() * sizeof(int)); - ImGui::EndDragDropSource(); + state.dragIds = + selection.contains(id) ? std::vector(selection.begin(), selection.end()) : std::vector{id}; + ImGui::SetDragDropPayload(REGION_DRAG_DROP, state.dragIds.data(), state.dragIds.size() * sizeof(int)); + ImGui::EndDragDropSource(); } - if (!ImGui::BeginDragDropTarget()) return false; + if (!ImGui::BeginDragDropTarget()) + return false; auto isMoved = false; if (auto payload = ImGui::AcceptDragDropPayload(REGION_DRAG_DROP, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { - auto cardMin = ImGui::GetWindowPos(); - auto cardMax = ImVec2(cardMin.x + ImGui::GetWindowSize().x, cardMin.y + ImGui::GetWindowSize().y); - auto isAfter = is_drop_after(cardMin, cardMax); - drop_line_draw(ImGui::GetForegroundDrawList(), cardMin, cardMax, isAfter); + auto cardMin = ImGui::GetWindowPos(); + auto cardMax = ImVec2(cardMin.x + ImGui::GetWindowSize().x, cardMin.y + ImGui::GetWindowSize().y); + auto isAfter = is_drop_after(cardMin, cardMax); + drop_line_draw(ImGui::GetForegroundDrawList(), cardMin, cardMax, isAfter); - std::vector indices; - auto payloadIds = (const int*)payload->Data; - for (int i = 0; i < payload->DataSize / (int)sizeof(int); i++) - if (auto keyIndex = vector_index_find(state.keys, payloadIds[i]); keyIndex != -1) indices.push_back(keyIndex); + std::vector indices; + auto payloadIds = (const int*)payload->Data; + for (int i = 0; i < payload->DataSize / (int)sizeof(int); i++) + if (auto keyIndex = vector_index_find(state.keys, payloadIds[i]); keyIndex != -1) + indices.push_back(keyIndex); - if (!indices.empty() && payload->IsDelivery()) - { - std::sort(indices.begin(), indices.end()); - command_push(panel, - [indices, movedIds = state.dragIds, targetIndex = index + (isAfter ? 1 : 0), - spritesheetId = panel.document.focused_id_get(SelectionKind::SPRITESHEETS)](Document& document) - { - if (!item_get(document.model.content.spritesheets, spritesheetId)) return; - document.edit_apply( - EDIT_MOVE_REGIONS, - [&](Model& model) - { - auto spritesheet = item_get(model.content.spritesheets, spritesheetId); - vector_indices_move(spritesheet->regions, indices, targetIndex); - }); - document.selected_ids_set(SelectionKind::REGIONS, {movedIds.begin(), movedIds.end()}); - }); - isMoved = true; - } + if (!indices.empty() && payload->IsDelivery()) + { + std::sort(indices.begin(), indices.end()); + command_push(panel, [indices, movedIds = state.dragIds, targetIndex = index + (isAfter ? 1 : 0), + spritesheetId = + panel.document.focused_id_get(SelectionKind::SPRITESHEETS)](Document& document) { + if (!item_get(document.model.content.spritesheets, spritesheetId)) + return; + document.edit_apply(EDIT_MOVE_REGIONS, [&](Model& model) { + auto spritesheet = item_get(model.content.spritesheets, spritesheetId); + vector_indices_move(spritesheet->regions, indices, targetIndex); + }); + document.selected_ids_set(SelectionKind::REGIONS, {movedIds.begin(), movedIds.end()}); + }); + isMoved = true; + } } ImGui::EndDragDropTarget(); return isMoved; - } +} - static void region_drag_tooltip_update(Panel& panel) - { +static void region_drag_tooltip_update(Panel& panel) +{ auto& state = panel.state; auto payload = ImGui::GetDragDropPayload(); auto spritesheet = region_spritesheet_get(panel.document); if (!spritesheet || !payload || !payload->IsDataType(REGION_DRAG_DROP) || payload->IsDelivery() || state.dragIds.empty()) - return; + return; if (payload->DataFrameCount != ImGui::GetFrameCount() && ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceExtern | DRAG_DROP_SOURCE_FLAGS)) { - ImGui::SetDragDropPayload(REGION_DRAG_DROP, state.dragIds.data(), state.dragIds.size() * sizeof(int)); - ImGui::EndDragDropSource(); + ImGui::SetDragDropPayload(REGION_DRAG_DROP, state.dragIds.data(), state.dragIds.size() * sizeof(int)); + ImGui::EndDragDropSource(); } auto mousePos = ImGui::GetIO().MousePos; ImGui::SetNextWindowPos(ImVec2(mousePos.x + DRAG_TOOLTIP_OFFSET.x, mousePos.y + DRAG_TOOLTIP_OFFSET.y)); - if (!tooltip_begin(state, false)) return; + if (!tooltip_begin(state, false)) + return; for (auto regionId : state.dragIds) - if (auto region = item_get(spritesheet->regions, regionId)) ImGui::TextUnformatted(region->name.c_str()); + if (auto region = item_get(spritesheet->regions, regionId)) + ImGui::TextUnformatted(region->name.c_str()); tooltip_end(); - } +} - static void region_properties_open(RegionsPanel& regions, Document& document, int id) - { +static void region_properties_open(RegionsPanel& regions, Document& document, int id) +{ auto spritesheet = region_spritesheet_get(document); auto region = spritesheet ? item_get(spritesheet->regions, id) : nullptr; - if (id != -1 && !region) return; + if (id != -1 && !region) + return; regions.editId = id; regions.editRegion = region ? *region : Region{}; regions.propertiesPopup.open(); - } +} - static void region_properties_popup_update(Panel& panel, RegionsPanel& regions) - { +static void region_properties_popup_update(Panel& panel, RegionsPanel& regions) +{ auto& popup = regions.propertiesPopup; popup.trigger(); - if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) + return popup.end(); auto& region = regions.editRegion; if (ImGui::BeginChild("##Child", child_size_get(REGION_POPUP_ROWS), ImGuiChildFlags_Borders)) { - if (popup.isJustOpened) ImGui::SetKeyboardFocusHere(); - input_text_string(localize.get(BASIC_NAME), ®ion.name); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); - ImGui::DragFloat2(localize.get(BASIC_CROP), value_ptr(region.crop), DRAG_SPEED, 0.0f, 0.0f, - vec2_format_get(region.crop)); - ImGui::DragFloat2(localize.get(BASIC_SIZE), value_ptr(region.size), DRAG_SPEED, 0.0f, 0.0f, - vec2_format_get(region.size)); - ImGui::BeginDisabled(region.origin != Origin::CUSTOM); - ImGui::DragFloat2(localize.get(BASIC_PIVOT), value_ptr(region.pivot), DRAG_SPEED, 0.0f, 0.0f, - vec2_format_get(region.pivot)); - ImGui::EndDisabled(); + if (popup.isJustOpened) + ImGui::SetKeyboardFocusHere(); + input_text_string(localize.get(BASIC_NAME), ®ion.name); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); + ImGui::DragFloat2(localize.get(BASIC_CROP), value_ptr(region.crop), DRAG_SPEED, 0.0f, 0.0f, + vec2_format_get(region.crop)); + ImGui::DragFloat2(localize.get(BASIC_SIZE), value_ptr(region.size), DRAG_SPEED, 0.0f, 0.0f, + vec2_format_get(region.size)); + ImGui::BeginDisabled(region.origin != Origin::CUSTOM); + ImGui::DragFloat2(localize.get(BASIC_PIVOT), value_ptr(region.pivot), DRAG_SPEED, 0.0f, 0.0f, + vec2_format_get(region.pivot)); + ImGui::EndDisabled(); - const char* originOptions[std::size(ORIGIN_COMBO_ORDER)]{}; - for (int i = 0; i < (int)std::size(ORIGIN_COMBO_ORDER); ++i) - originOptions[i] = localize.get(ORIGIN_LABELS[(int)ORIGIN_COMBO_ORDER[i]]); - auto originIndex = (int)(std::ranges::find(ORIGIN_COMBO_ORDER, region.origin) - std::begin(ORIGIN_COMBO_ORDER)); - if (ImGui::Combo(localize.get(LABEL_REGION_PROPERTIES_ORIGIN), &originIndex, originOptions, - (int)std::size(originOptions))) - region.origin = ORIGIN_COMBO_ORDER[originIndex]; - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REGION_PROPERTIES_ORIGIN)); - region_pivot_apply(region); + const char* originOptions[std::size(ORIGIN_COMBO_ORDER)]{}; + for (int i = 0; i < (int)std::size(ORIGIN_COMBO_ORDER); ++i) + originOptions[i] = localize.get(ORIGIN_LABELS[(int)ORIGIN_COMBO_ORDER[i]]); + auto originIndex = (int)(std::ranges::find(ORIGIN_COMBO_ORDER, region.origin) - std::begin(ORIGIN_COMBO_ORDER)); + if (ImGui::Combo(localize.get(LABEL_REGION_PROPERTIES_ORIGIN), &originIndex, originOptions, + (int)std::size(originOptions))) + region.origin = ORIGIN_COMBO_ORDER[originIndex]; + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REGION_PROPERTIES_ORIGIN)); + region_pivot_apply(region); } ImGui::EndChild(); auto result = popup_buttons_draw(panel.manager, localize.get(regions.editId == -1 ? BASIC_ADD : BASIC_CONFIRM)); if (result == PopupButton::CONFIRM) { - auto& state = panel.state; - command_push(panel, - [&state, edited = region, id = regions.editId, insertIndex = region_insert_index_get(panel.document), - spritesheetId = panel.document.focused_id_get(SelectionKind::SPRITESHEETS)](Document& document) - { - auto changedId = id; - document.edit_apply(id == -1 ? EDIT_ADD_REGION : EDIT_SET_REGION_PROPERTIES, - [&](Model& model) - { - auto spritesheet = - item_get(model.content.spritesheets, spritesheetId); - if (!spritesheet) return; - auto& items = spritesheet->regions; - if (auto target = item_get(items, id)) - { - auto uid = target->uid; - *target = edited; - target->uid = uid; - target->id = id; - return; - } - if (id != -1) return; - changedId = item_next_id_get(items); - auto& added = *items.insert( - items.begin() + std::min(insertIndex, (int)items.size()), edited); - added.uid = uid_next(); - added.id = changedId; - state.newId = changedId; - }); - if (changedId != -1) region_select(document, changedId); - }); + auto& state = panel.state; + command_push( + panel, [&state, edited = region, id = regions.editId, insertIndex = region_insert_index_get(panel.document), + spritesheetId = panel.document.focused_id_get(SelectionKind::SPRITESHEETS)](Document& document) { + auto changedId = id; + document.edit_apply(id == -1 ? EDIT_ADD_REGION : EDIT_SET_REGION_PROPERTIES, [&](Model& model) { + auto spritesheet = item_get(model.content.spritesheets, spritesheetId); + if (!spritesheet) + return; + auto& items = spritesheet->regions; + if (auto target = item_get(items, id)) + { + auto uid = target->uid; + *target = edited; + target->uid = uid; + target->id = id; + return; + } + if (id != -1) + return; + changedId = item_next_id_get(items); + auto& added = *items.insert(items.begin() + std::min(insertIndex, (int)items.size()), edited); + added.uid = uid_next(); + added.id = changedId; + state.newId = changedId; + }); + if (changedId != -1) + region_select(document, changedId); + }); } - if (result != PopupButton::NONE) popup.close(); + if (result != PopupButton::NONE) + popup.close(); ImGui::EndPopup(); popup.end(); - } +} - static void region_export_popup_update(Panel& panel, RegionsPanel& regions) - { +static void region_export_popup_update(Panel& panel, RegionsPanel& regions) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto spritesheet = region_spritesheet_get(document); auto region = spritesheet ? item_get(spritesheet->regions, regions.exportId) : nullptr; auto& popup = regions.exportPopup; popup.trigger(); - if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) + return popup.end(); - if (!region) popup.close(); + if (!region) + popup.close(); if (region && popup.isJustOpened) { - auto filename = path_from_utf8(region->name).filename(); - settings.exportRegionPath = - settings.exportRegionPath.parent_path() / - (filename.empty() ? std::filesystem::path(REGION_EXPORT_NAME_DEFAULT) : filename).concat(REGION_EXPORT_EXTENSION); + auto filename = path_from_utf8(region->name).filename(); + settings.exportRegionPath = settings.exportRegionPath.parent_path() / + (filename.empty() ? std::filesystem::path(REGION_EXPORT_NAME_DEFAULT) : filename) + .concat(REGION_EXPORT_EXTENSION); } if (dialog.is_selected(Dialog::REGION_EXPORT_PATH_SET)) { - settings.exportRegionPath = dialog.path; - dialog.reset(); + settings.exportRegionPath = dialog.path; + dialog.reset(); } if (ImGui::BeginChild("##Export Region Child", child_size_get(REGION_POPUP_ROWS), ImGuiChildFlags_Borders)) { - if (ImGui::ImageButton("##Export Region Path Set", resources.icon_id_get(ICON_FOLDER), icon_size_get())) - dialog.file_save(Dialog::REGION_EXPORT_PATH_SET, settings.exportRegionPath); - ImGui::SameLine(); - input_text_path(localize.get(LABEL_OUTPUT_PATH), &settings.exportRegionPath); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OUTPUT_PATH)); - ImGui::Checkbox(localize.get(LABEL_EXPORT_MAKE_SPRITESHEET), &settings.isExportRegionMakeSpritesheet); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EXPORT_MAKE_SPRITESHEET)); - ImGui::Checkbox(localize.get(LABEL_EXPORT_REMOVE_CURRENT_REGION), &settings.isExportRegionRemoveCurrent); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EXPORT_REMOVE_CURRENT_REGION)); + if (ImGui::ImageButton("##Export Region Path Set", resources.icon_id_get(ICON_FOLDER), icon_size_get())) + dialog.file_save(Dialog::REGION_EXPORT_PATH_SET, settings.exportRegionPath); + ImGui::SameLine(); + input_text_path(localize.get(LABEL_OUTPUT_PATH), &settings.exportRegionPath); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OUTPUT_PATH)); + ImGui::Checkbox(localize.get(LABEL_EXPORT_MAKE_SPRITESHEET), &settings.isExportRegionMakeSpritesheet); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EXPORT_MAKE_SPRITESHEET)); + ImGui::Checkbox(localize.get(LABEL_EXPORT_REMOVE_CURRENT_REGION), &settings.isExportRegionRemoveCurrent); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EXPORT_REMOVE_CURRENT_REGION)); } ImGui::EndChild(); @@ -365,155 +375,145 @@ using namespace glm; auto result = popup_buttons_draw(manager, localize.get(BASIC_CONFIRM), isValid); if (result == PopupButton::CONFIRM) { - if (!settings.exportRegionPath.empty()) settings.exportRegionPath.replace_extension(REGION_EXPORT_EXTENSION); - RegionExportOptions options{.spritesheetId = spritesheetId, - .regionId = regions.exportId, - .path = settings.exportRegionPath, - .isMakeSpritesheet = settings.isExportRegionMakeSpritesheet, - .isRemoveCurrent = settings.isExportRegionRemoveCurrent}; - command_push(panel, - [&state, options](Document& document) - { - if (region_export(document, options) && options.isMakeSpritesheet) - state.newId = document.focused_id_get(SelectionKind::REGIONS); - }); + if (!settings.exportRegionPath.empty()) + settings.exportRegionPath.replace_extension(REGION_EXPORT_EXTENSION); + RegionExportOptions options{.spritesheetId = spritesheetId, + .regionId = regions.exportId, + .path = settings.exportRegionPath, + .isMakeSpritesheet = settings.isExportRegionMakeSpritesheet, + .isRemoveCurrent = settings.isExportRegionRemoveCurrent}; + command_push(panel, [&state, options](Document& document) { + if (region_export(document, options) && options.isMakeSpritesheet) + state.newId = document.focused_id_get(SelectionKind::REGIONS); + }); } - if (result != PopupButton::NONE) popup.close(); + if (result != PopupButton::NONE) + popup.close(); ImGui::EndPopup(); popup.end(); - } +} - void regions_update(Panel& panel, RegionsPanel& regions) - { +void regions_update(Panel& panel, RegionsPanel& regions) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; if (manager.isMakeRegionRequested) { - document.focused_id_set(SelectionKind::SPRITESHEETS, manager.makeRegionSpritesheetId); - regions.editId = -1; - regions.editRegion = manager.makeRegion; - regions.propertiesPopup.open(); - manager.isMakeRegionRequested = false; + document.focused_id_set(SelectionKind::SPRITESHEETS, manager.makeRegionSpritesheetId); + regions.editId = -1; + regions.editRegion = manager.makeRegion; + regions.propertiesPopup.open(); + manager.isMakeRegionRequested = false; } if (ImGui::Begin(localize.get(LABEL_REGIONS_WINDOW), &settings.windowIsRegions)) { - auto spritesheet = region_spritesheet_get(document); - if (!spritesheet) - ImGui::TextUnformatted(localize.get(TEXT_SELECT_SPRITESHEET)); - else - { - auto spritesheetId = spritesheet->id; - auto selection = document.selected_ids_get(SelectionKind::REGIONS); - auto isOne = [selection]() { return selection.size() == 1; }; + auto spritesheet = region_spritesheet_get(document); + if (!spritesheet) + ImGui::TextUnformatted(localize.get(TEXT_SELECT_SPRITESHEET)); + else + { + auto spritesheetId = spritesheet->id; + auto selection = document.selected_ids_get(SelectionKind::REGIONS); + auto isOne = [selection]() { + return selection.size() == 1; + }; - Actions actions = {}; - actions.add(ACTION_PROPERTIES, isOne, [&]() { region_properties_open(regions, document, *selection.begin()); }); - actions.add(ACTION_ADD, {}, [&]() { region_properties_open(regions, document, -1); }, TOOLTIP_ADD_REGION); - content_remove_action_add(actions, panel, ElementType::REGION, SelectionKind::REGIONS, spritesheetId); - actions.add( - ACTION_TRIM, [selection]() { return !selection.empty(); }, - [&]() - { - command_push(panel, - [spritesheetId, selection](Document& document) - { - document.edit_apply(EDIT_TRIM_REGIONS, - [&](Model&) - { - if (!document.regions_trim(spritesheetId, selection)) return; - document.reference_set({document.reference_get().animationIndex}); - document.frame_references_clear(); - }); - }); - }, - TOOLTIP_TRIM_REGIONS); - actions.add(ACTION_EXPORT, isOne, - [&]() - { - regions.exportId = *selection.begin(); - regions.exportPopup.open(); + Actions actions = {}; + actions.add(ACTION_PROPERTIES, isOne, + [&]() { region_properties_open(regions, document, *selection.begin()); }); + actions.add(ACTION_ADD, {}, [&]() { region_properties_open(regions, document, -1); }, TOOLTIP_ADD_REGION); + content_remove_action_add(actions, panel, ElementType::REGION, SelectionKind::REGIONS, spritesheetId); + actions.add( + ACTION_TRIM, [selection]() { return !selection.empty(); }, + [&]() { + command_push(panel, [spritesheetId, selection](Document& document) { + document.edit_apply(EDIT_TRIM_REGIONS, [&](Model&) { + if (!document.regions_trim(spritesheetId, selection)) + return; + document.reference_set({document.reference_get().animationIndex}); + document.frame_references_clear(); + }); }); - actions.separator(); - actions.add( - ACTION_COPY, [selection]() { return !selection.empty(); }, - [&]() { items_copy(clipboard, spritesheet->regions, selection); }); - actions.add( - ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, - [&]() - { - command_push( - panel, - [&state, spritesheetId, text = clipboard.get(), - insertIndex = region_insert_index_get(document)](Document& document) - { - auto spritesheet_regions_get = [&]() -> const std::vector* - { - auto spritesheet = item_get(document.model.content.spritesheets, spritesheetId); - return spritesheet ? &spritesheet->regions : nullptr; - }; - if (!spritesheet_regions_get()) return; - auto nextId = item_next_id_get(*spritesheet_regions_get()); - std::string errorString; - document.edit_apply( - EDIT_PASTE_REGIONS, [&](Model& model) - { return regions_paste(model, spritesheetId, text, insertIndex, &errorString); }); - if (!errorString.empty()) toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); - auto lastId = item_next_id_get(*spritesheet_regions_get()) - 1; - if (lastId < nextId) return; - state.newId = lastId; - region_select(document, lastId); - }); + }, + TOOLTIP_TRIM_REGIONS); + actions.add(ACTION_EXPORT, isOne, [&]() { + regions.exportId = *selection.begin(); + regions.exportPopup.open(); }); + actions.separator(); + actions.add( + ACTION_COPY, [selection]() { return !selection.empty(); }, + [&]() { items_copy(clipboard, spritesheet->regions, selection); }); + actions.add( + ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, + [&]() { + command_push(panel, [&state, spritesheetId, text = clipboard.get(), + insertIndex = region_insert_index_get(document)](Document& document) { + auto spritesheet_regions_get = [&]() -> const std::vector* { + auto spritesheet = item_get(document.model.content.spritesheets, spritesheetId); + return spritesheet ? &spritesheet->regions : nullptr; + }; + if (!spritesheet_regions_get()) + return; + auto nextId = item_next_id_get(*spritesheet_regions_get()); + std::string errorString; + document.edit_apply(EDIT_PASTE_REGIONS, [&](Model& model) { + return regions_paste(model, spritesheetId, text, insertIndex, &errorString); + }); + if (!errorString.empty()) + toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); + auto lastId = item_next_id_get(*spritesheet_regions_get()) - 1; + if (lastId < nextId) + return; + state.newId = lastId; + region_select(document, lastId); + }); + }); - ListRows rows{.label_get = [&](int id) { return item_get(spritesheet->regions, id)->name; }, - .tooltip_draw = - [&](int id) - { + ListRows rows{ + .label_get = [&](int id) { return item_get(spritesheet->regions, id)->name; }, + .tooltip_draw = + [&](int id) { auto& region = *item_get(spritesheet->regions, id); - tooltip_image_draw( - region_image_get(document, resources, region), - [&]() - { - tooltip_name_draw(resources, region.name); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_CROP), - std::make_format_args(region.crop.x, region.crop.y)) - .c_str()); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_SIZE), - std::make_format_args(region.size.x, region.size.y)) - .c_str()); - auto originLabel = localize.get(ORIGIN_LABELS[(int)region.origin]); - ImGui::TextUnformatted( - (region.origin == Origin::CUSTOM - ? std::vformat(localize.get(FORMAT_PIVOT), - std::make_format_args(region.pivot.x, region.pivot.y)) - : std::vformat(localize.get(FORMAT_ORIGIN), std::make_format_args(originLabel))) - .c_str()); - }); - }, - .image_get = [&](int id) - { return region_image_get(document, resources, *item_get(spritesheet->regions, id)); }, - .select = - [&](int) - { + tooltip_image_draw(region_image_get(document, resources, region), [&]() { + tooltip_name_draw(resources, region.name); + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_CROP), + std::make_format_args(region.crop.x, region.crop.y)) + .c_str()); + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_SIZE), + std::make_format_args(region.size.x, region.size.y)) + .c_str()); + auto originLabel = localize.get(ORIGIN_LABELS[(int)region.origin]); + ImGui::TextUnformatted( + (region.origin == Origin::CUSTOM + ? std::vformat(localize.get(FORMAT_PIVOT), + std::make_format_args(region.pivot.x, region.pivot.y)) + : std::vformat(localize.get(FORMAT_ORIGIN), std::make_format_args(originLabel))) + .c_str()); + }); + }, + .image_get = + [&](int id) { return region_image_get(document, resources, *item_get(spritesheet->regions, id)); }, + .select = + [&](int) { document.editTarget = Document::EditTarget::REGION; document.reference_set({document.reference_get().animationIndex}); document.frame_references_clear(); - }, - .activate = [&](int id) { region_properties_open(regions, document, id); }, - .drag_drop_update = [&](int id, int index) { return region_drag_drop_update(panel, id, index); }, - .cardLines = REGION_CARD_LINES}; - list_panel_draw( - panel, actions, {{ACTION_ADD, ACTION_EXPORT, ACTION_REMOVE}}, - [&]() - { - content_list_draw(panel, SelectionKind::REGIONS, item_ids_get(spritesheet->regions), rows); - region_drag_tooltip_update(panel); - }, - true); - } + }, + .activate = [&](int id) { region_properties_open(regions, document, id); }, + .drag_drop_update = [&](int id, int index) { return region_drag_drop_update(panel, id, index); }, + .cardLines = REGION_CARD_LINES}; + list_panel_draw( + panel, actions, {{ACTION_ADD, ACTION_EXPORT, ACTION_REMOVE}}, + [&]() { + content_list_draw(panel, SelectionKind::REGIONS, item_ids_get(spritesheet->regions), rows); + region_drag_tooltip_update(panel); + }, + true); + } } ImGui::End(); region_properties_popup_update(panel, regions); region_export_popup_update(panel, regions); - } +} diff --git a/src/ui/render_animation.cpp b/src/ui/render_animation.cpp index 8a14658..71fab4c 100644 --- a/src/ui/render_animation.cpp +++ b/src/ui/render_animation.cpp @@ -14,58 +14,59 @@ #include "ui/layout.h" #include "ui/shortcut.h" - void RenderAnimation::range_to_animation_set(Manager& manager, Document& document) - { +void RenderAnimation::range_to_animation_set(Manager& manager, Document& document) +{ if (auto animation = document.model.animation_get(document.reference_get().animationIndex)) { - manager.recordingStart = 0; - manager.recordingEnd = animation->frameNum - 1; + manager.recordingStart = 0; + manager.recordingEnd = animation->frameNum - 1; } - } +} - void RenderAnimation::range_to_frames_set(Manager& manager, Document& document) - { +void RenderAnimation::range_to_frames_set(Manager& manager, Document& document) +{ auto frameReferences = document.frame_references_get(Document::FrameReferenceFallback::NONE); auto reference = document.reference_get(); - std::erase_if(frameReferences, - [&](const Reference& frameReference) - { - return frameReference.animationIndex != reference.animationIndex || - frameReference.itemType != reference.itemType || frameReference.itemID != reference.itemID || - frameReference.groupType != reference.groupType || - frameReference.groupId != reference.groupId; - }); + std::erase_if(frameReferences, [&](const Reference& frameReference) { + return frameReference.animationIndex != reference.animationIndex || + frameReference.itemType != reference.itemType || frameReference.itemID != reference.itemID || + frameReference.groupType != reference.groupType || frameReference.groupId != reference.groupId; + }); if (!frameReferences.empty()) { - if (auto item = document.model.track_get(reference)) - { - int duration = 0; - int frameIndex = 0; - for (auto& frame : item->frames) + if (auto item = document.model.track_get(reference)) { - if (frameIndex == frameReferences.begin()->frameIndex) manager.recordingStart = duration; - if (frameIndex == frameReferences.rbegin()->frameIndex) manager.recordingEnd = duration + frame.duration - 1; + int duration = 0; + int frameIndex = 0; + for (auto& frame : item->frames) + { + if (frameIndex == frameReferences.begin()->frameIndex) + manager.recordingStart = duration; + if (frameIndex == frameReferences.rbegin()->frameIndex) + manager.recordingEnd = duration + frame.duration - 1; - duration += frame.duration; - ++frameIndex; + duration += frame.duration; + ++frameIndex; + } } - } } - } +} - void RenderAnimation::reset(Manager& manager, Document& document, Settings& settings) - { - if (!manager.isRecordingRange) range_to_animation_set(manager, document); +void RenderAnimation::reset(Manager& manager, Document& document, Settings& settings) +{ + if (!manager.isRecordingRange) + range_to_animation_set(manager, document); settings.renderPath.replace_extension(RENDER_EXTENSIONS[settings.renderType]); - } +} - void RenderAnimation::update(Manager& manager, Document& document, Resources& resources, Settings& settings, - Dialog& dialog) - { +void RenderAnimation::update(Manager& manager, Document& document, Resources& resources, Settings& settings, + Dialog& dialog) +{ isEnd = false; auto animation = document.model.animation_get(document.reference_get().animationIndex); - if (!animation) return; + if (!animation) + return; auto& ffmpegPath = settings.renderFFmpegPath; auto& path = settings.renderPath; @@ -88,12 +89,12 @@ end = std::clamp(end, start, frameMax); auto animationFps = std::max(document.model.info.fps, 1); if (renderFpsMode < FPS_ANIMATION || renderFpsMode >= FPS_COUNT) - renderFpsMode = FPS_ANIMATION; + renderFpsMode = FPS_ANIMATION; auto renderFps = fps_get(renderFpsMode, animationFps, settings.playbackTickRate); - auto render_frame_count_get = [&]() - { - if (isRange) return frame_count_get(start, end, animationFps, renderFps); - return frame_count_get(0, frameMax, animationFps, renderFps); + auto render_frame_count_get = [&]() { + if (isRange) + return frame_count_get(start, end, animationFps, renderFps); + return frame_count_get(0, frameMax, animationFps, renderFps); }; auto renderFrameNum = render_frame_count_get(); @@ -102,47 +103,47 @@ Dialog::Type dialogType = Dialog::NONE; switch (type) { - case RENDER_PNGS: - dialogType = Dialog::PNG_DIRECTORY_SET; - break; - case RENDER_SPRITESHEET: - dialogType = Dialog::PNG_PATH_SET; - break; - case RENDER_GIF: - dialogType = Dialog::GIF_PATH_SET; - break; - case RENDER_WEBM: - dialogType = Dialog::WEBM_PATH_SET; - break; - case RENDER_OGV: - dialogType = Dialog::OGV_PATH_SET; - break; - case RENDER_MP4: - dialogType = Dialog::MP4_PATH_SET; - break; - default: - dialogType = Dialog::NONE; - break; + case RENDER_PNGS: + dialogType = Dialog::PNG_DIRECTORY_SET; + break; + case RENDER_SPRITESHEET: + dialogType = Dialog::PNG_PATH_SET; + break; + case RENDER_GIF: + dialogType = Dialog::GIF_PATH_SET; + break; + case RENDER_WEBM: + dialogType = Dialog::WEBM_PATH_SET; + break; + case RENDER_OGV: + dialogType = Dialog::OGV_PATH_SET; + break; + case RENDER_MP4: + dialogType = Dialog::MP4_PATH_SET; + break; + default: + dialogType = Dialog::NONE; + break; } if (ImGui::ImageButton("##FFmpeg Path Set", resources.icon_id_get(ICON_FOLDER), icon_size_get())) - dialog.file_open(Dialog::FFMPEG_PATH_SET); + dialog.file_open(Dialog::FFMPEG_PATH_SET); ImGui::SameLine(); input_text_path(localize.get(LABEL_FFMPEG_PATH), &ffmpegPath); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FFMPEG_PATH)); if (dialog.is_selected(Dialog::FFMPEG_PATH_SET)) { - ffmpegPath = dialog.path; - dialog.reset(); + ffmpegPath = dialog.path; + dialog.reset(); } if (ImGui::ImageButton("##Path Set", resources.icon_id_get(ICON_FOLDER), icon_size_get())) { - if (dialogType == Dialog::PNG_DIRECTORY_SET) - dialog.folder_open(dialogType); - else - dialog.file_save(dialogType); + if (dialogType == Dialog::PNG_DIRECTORY_SET) + dialog.folder_open(dialogType); + else + dialog.file_save(dialogType); } ImGui::SameLine(); @@ -152,29 +153,30 @@ if (dialog.is_selected(dialogType)) { - path = dialog.path; - dialog.reset(); + path = dialog.path; + dialog.reset(); } if (ImGui::Combo(localize.get(LABEL_TYPE), &type, RENDER_STRINGS, RENDER_COUNT)) - path.replace_extension(RENDER_EXTENSIONS[type]); + path.replace_extension(RENDER_EXTENSIONS[type]); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RENDER_TYPE)); - if (type == RENDER_PNGS || type == RENDER_SPRITESHEET) ImGui::Separator(); + if (type == RENDER_PNGS || type == RENDER_SPRITESHEET) + ImGui::Separator(); if (type == RENDER_PNGS) { - input_text_path(localize.get(LABEL_FORMAT), &format); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FORMAT)); + input_text_path(localize.get(LABEL_FORMAT), &format); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FORMAT)); } else if (type == RENDER_SPRITESHEET) { - input_int_range(localize.get(LABEL_GENERATE_ROWS), rows, 1, renderFrameNum); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROWS)); + input_int_range(localize.get(LABEL_GENERATE_ROWS), rows, 1, renderFrameNum); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROWS)); - input_int_range(localize.get(LABEL_GENERATE_COLUMNS), columns, 1, renderFrameNum); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_COLUMNS)); + input_int_range(localize.get(LABEL_GENERATE_COLUMNS), columns, 1, renderFrameNum); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_COLUMNS)); } ImGui::Separator(); @@ -186,30 +188,32 @@ ImGui::BeginDisabled(document.frame_references_get(Document::FrameReferenceFallback::NONE).empty() || reference.itemType == TRIGGER); - if (ImGui::Button(localize.get(LABEL_TO_SELECTED_FRAMES))) range_to_frames_set(manager, document); + if (ImGui::Button(localize.get(LABEL_TO_SELECTED_FRAMES))) + range_to_frames_set(manager, document); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TO_SELECTED_FRAMES)); ImGui::EndDisabled(); ImGui::SameLine(); - if (ImGui::Button(localize.get(LABEL_TO_ANIMATION_RANGE))) range_to_animation_set(manager, document); + if (ImGui::Button(localize.get(LABEL_TO_ANIMATION_RANGE))) + range_to_animation_set(manager, document); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TO_ANIMATION_RANGE)); ImGui::BeginDisabled(!isRange); { - input_int_range(localize.get(LABEL_START), start, 0, frameMax); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_START)); - input_int_range(localize.get(LABEL_END), end, start, frameMax); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_END)); + input_int_range(localize.get(LABEL_START), start, 0, frameMax); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_START)); + input_int_range(localize.get(LABEL_END), end, start, frameMax); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_END)); } ImGui::EndDisabled(); renderFrameNum = render_frame_count_get(); if (type == RENDER_SPRITESHEET) { - auto layout = spritesheet_layout_get(rows, columns, renderFrameNum); - rows = layout.rows; - columns = layout.columns; + auto layout = spritesheet_layout_get(rows, columns, renderFrameNum); + rows = layout.rows; + columns = layout.columns; } ImGui::Separator(); @@ -224,9 +228,9 @@ ImGui::BeginDisabled(!isUseAnimationBounds); { - input_float_range(localize.get(BASIC_SCALE), scale, RENDER_SCALE_MIN, RENDER_SCALE_MAX, RENDER_SCALE_STEP, - RENDER_SCALE_STEP, "%.0f%%"); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SCALE_OUTPUT)); + input_float_range(localize.get(BASIC_SCALE), scale, RENDER_SCALE_MIN, RENDER_SCALE_MAX, RENDER_SCALE_STEP, + RENDER_SCALE_STEP, "%.0f%%"); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SCALE_OUTPUT)); } ImGui::EndDisabled(); @@ -240,9 +244,9 @@ renderFrameNum = render_frame_count_get(); if (type == RENDER_SPRITESHEET) { - auto layout = spritesheet_layout_get(rows, columns, renderFrameNum); - rows = layout.rows; - columns = layout.columns; + auto layout = spritesheet_layout_get(rows, columns, renderFrameNum); + rows = layout.rows; + columns = layout.columns; } ImGui::Separator(); @@ -255,107 +259,107 @@ shortcut(manager.chords[SHORTCUT_CONFIRM]); if (ImGui::Button(localize.get(LABEL_RENDER), widgetSize)) { - path.replace_extension(RENDER_EXTENSIONS[type]); + path.replace_extension(RENDER_EXTENSIONS[type]); - auto render_is_valid = [&]() - { - auto ffmpeg_is_valid = [&]() - { - if (!is_path_executable(ffmpegPath)) return false; + auto render_is_valid = [&]() { + auto ffmpeg_is_valid = [&]() { + if (!is_path_executable(ffmpegPath)) + return false; - auto testCommand = std::string("\"") + path_to_utf8(ffmpegPath) + "\" -version"; - Process process(testCommand.c_str(), "r"); - auto result = process.output_get_and_close(); + auto testCommand = std::string("\"") + path_to_utf8(ffmpegPath) + "\" -version"; + Process process(testCommand.c_str(), "r"); + auto result = process.output_get_and_close(); - if (!result.contains("ffmpeg version")) return false; + if (!result.contains("ffmpeg version")) + return false; - return true; + return true; + }; + + auto ffmpeg_valid_check = [&]() { + if (!ffmpeg_is_valid()) + { + toast_log(Level::ERROR, TOAST_INVALID_FFMPEG); + return false; + } + return true; + }; + + auto png_format_valid_check = [&]() { + auto formatString = path_to_utf8(format); + if (!formatString.contains("{}")) + { + toast_log(Level::ERROR, TOAST_PNG_FORMAT_INVALID); + return false; + } + return true; + }; + + auto path_valid_check = [&]() { + if (path.empty()) + { + toast_log(Level::ERROR, TOAST_RENDER_PATH_EMPTY); + return false; + } + return true; + }; + + auto png_directory_valid_check = [&]() { + if (!path_ensure_directory(path)) + { + toast_log(Level::ERROR, TOAST_PNG_DIRECTORY_INVALID); + return false; + } + return true; + }; + + auto spritesheet_valid_check = [&]() { + if (rows <= 0 && columns <= 0) + { + toast_log(Level::ERROR, TOAST_RENDER_PATH_EMPTY); + return false; + } + return true; + }; + + if (!path_valid_check()) + return false; + + switch (type) + { + case RENDER_PNGS: + if (!png_format_valid_check()) + return false; + if (!png_directory_valid_check()) + return false; + format.replace_extension(RENDER_EXTENSIONS[RENDER_SPRITESHEET]); + break; + case RENDER_SPRITESHEET: + if (!spritesheet_valid_check()) + return false; + break; + case RENDER_GIF: + case RENDER_WEBM: + case RENDER_OGV: + case RENDER_MP4: + if (!ffmpeg_valid_check()) + return false; + break; + default: + return false; + break; + } + + return true; }; - auto ffmpeg_valid_check = [&]() + if (render_is_valid()) { - if (!ffmpeg_is_valid()) - { - toast_log(Level::ERROR, TOAST_INVALID_FFMPEG); - return false; - } - return true; - }; - - auto png_format_valid_check = [&]() - { - auto formatString = path_to_utf8(format); - if (!formatString.contains("{}")) - { - toast_log(Level::ERROR, TOAST_PNG_FORMAT_INVALID); - return false; - } - return true; - }; - - auto path_valid_check = [&]() - { - if (path.empty()) - { - toast_log(Level::ERROR, TOAST_RENDER_PATH_EMPTY); - return false; - } - return true; - }; - - auto png_directory_valid_check = [&]() - { - if (!path_ensure_directory(path)) - { - toast_log(Level::ERROR, TOAST_PNG_DIRECTORY_INVALID); - return false; - } - return true; - }; - - auto spritesheet_valid_check = [&]() - { - if (rows <= 0 && columns <= 0) - { - toast_log(Level::ERROR, TOAST_RENDER_PATH_EMPTY); - return false; - } - return true; - }; - - if (!path_valid_check()) return false; - - switch (type) - { - case RENDER_PNGS: - if (!png_format_valid_check()) return false; - if (!png_directory_valid_check()) return false; - format.replace_extension(RENDER_EXTENSIONS[RENDER_SPRITESHEET]); - break; - case RENDER_SPRITESHEET: - if (!spritesheet_valid_check()) return false; - break; - case RENDER_GIF: - case RENDER_WEBM: - case RENDER_OGV: - case RENDER_MP4: - if (!ffmpeg_valid_check()) return false; - break; - default: - return false; - break; + manager.isRecordingStart = true; + manager.progressPopup.open(); } - return true; - }; - - if (render_is_valid()) - { - manager.isRecordingStart = true; - manager.progressPopup.open(); - } - - isEnd = true; + isEnd = true; } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RENDER_BUTTON)); @@ -363,5 +367,6 @@ ImGui::SameLine(); shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) isEnd = true; - } + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) + isEnd = true; +} diff --git a/src/ui/render_animation.h b/src/ui/render_animation.h index 7fcde96..ce82eea 100644 --- a/src/ui/render_animation.h +++ b/src/ui/render_animation.h @@ -4,14 +4,14 @@ #include "manager.h" #include "resources.h" - class RenderAnimation - { +class RenderAnimation +{ - public: +public: bool isEnd = false; void range_to_frames_set(Manager&, Document&); void range_to_animation_set(Manager&, Document&); void reset(Manager&, Document&, Settings&); void update(Manager&, Document&, Resources&, Settings&, Dialog&); - }; +}; diff --git a/src/ui/selectable.cpp b/src/ui/selectable.cpp index b290cae..786d53d 100644 --- a/src/ui/selectable.cpp +++ b/src/ui/selectable.cpp @@ -4,61 +4,63 @@ #include "ui/input.h" - bool isSelectableInputTextRenaming = false; +bool isSelectableInputTextRenaming = false; - std::string& selectable_input_text_id() - { +std::string& selectable_input_text_id() +{ static std::string editID; return editID; - } +} - bool input_text_rename_update(std::string& text, RenameState& state, float width) - { +bool input_text_rename_update(std::string& text, RenameState& state, float width) +{ bool isActivated = false; - auto finish = [&]() - { - selectable_input_text_id().clear(); - isActivated = true; - state = RENAME_FINISHED; - isSelectableInputTextRenaming = false; + auto finish = [&]() { + selectable_input_text_id().clear(); + isActivated = true; + state = RENAME_FINISHED; + isSelectableInputTextRenaming = false; }; if (state == RENAME_BEGIN) { - ImGui::SetKeyboardFocusHere(); - state = RENAME_EDITING; + ImGui::SetKeyboardFocusHere(); + state = RENAME_EDITING; } ImGui::SetNextItemWidth(width); if (input_text_string("##Edit", &text, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll)) - finish(); - if (ImGui::IsItemDeactivatedAfterEdit() || ImGui::IsKeyPressed(ImGuiKey_Escape)) finish(); + finish(); + if (ImGui::IsItemDeactivatedAfterEdit() || ImGui::IsKeyPressed(ImGuiKey_Escape)) + finish(); return isActivated; - } +} - bool selectable_input_text(const std::string& label, const std::string& id, std::string& text, bool isSelected, - ImGuiSelectableFlags flags, RenameState& state) - { +bool selectable_input_text(const std::string& label, const std::string& id, std::string& text, bool isSelected, + ImGuiSelectableFlags flags, RenameState& state) +{ auto& editID = selectable_input_text_id(); auto isRename = editID == id; bool isActivated = false; if (isRename) - isActivated = input_text_rename_update(text, state); + isActivated = input_text_rename_update(text, state); else { - if (ImGui::Selectable(label.c_str(), isSelected, flags)) isActivated = true; + if (ImGui::Selectable(label.c_str(), isSelected, flags)) + isActivated = true; - if (state == RENAME_FORCE_EDIT || (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))) - { - state = RENAME_BEGIN; - editID = id; - isActivated = true; - isSelectableInputTextRenaming = true; - } + if (state == RENAME_FORCE_EDIT || + (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))) + { + state = RENAME_BEGIN; + editID = id; + isActivated = true; + isSelectableInputTextRenaming = true; + } } return isActivated; - } +} diff --git a/src/ui/selectable.h b/src/ui/selectable.h index 6efda69..d3dd5cb 100644 --- a/src/ui/selectable.h +++ b/src/ui/selectable.h @@ -5,16 +5,16 @@ #include - enum RenameState - { +enum RenameState +{ RENAME_SELECTABLE, RENAME_BEGIN, RENAME_EDITING, RENAME_FINISHED, RENAME_FORCE_EDIT - }; +}; - std::string& selectable_input_text_id(); - bool input_text_rename_update(std::string&, RenameState&, float = -FLT_MIN); - bool selectable_input_text(const std::string&, const std::string&, std::string&, bool, ImGuiSelectableFlags, - RenameState&); +std::string& selectable_input_text_id(); +bool input_text_rename_update(std::string&, RenameState&, float = -FLT_MIN); +bool selectable_input_text(const std::string&, const std::string&, std::string&, bool, ImGuiSelectableFlags, + RenameState&); diff --git a/src/ui/shaders.cpp b/src/ui/shaders.cpp index 4704f04..c145df7 100644 --- a/src/ui/shaders.cpp +++ b/src/ui/shaders.cpp @@ -12,76 +12,79 @@ #include "ui/input.h" #include "ui/layout.h" - constexpr int SHADER_CARD_LINES = 2; +constexpr int SHADER_CARD_LINES = 2; #define SHADER_UNIFORM_BINDING_COMBO_VALUES \ - X(UNIFORM_BINDING_IGNORE) \ - X(UNIFORM_BINDING_MANUAL) \ - X(UNIFORM_BINDING_COLOR_OFFSET) \ - X(UNIFORM_BINDING_FRAME_TINT) \ - X(UNIFORM_BINDING_MAIN_TEXTURE) \ - X(UNIFORM_BINDING_COMPONENTS) \ - X(UNIFORM_BINDING_PLAYBACK_TIME) \ - X(UNIFORM_BINDING_TEXTURE_SIZE) \ - X(UNIFORM_BINDING_TRANSFORM) + X(UNIFORM_BINDING_IGNORE) \ + X(UNIFORM_BINDING_MANUAL) \ + X(UNIFORM_BINDING_COLOR_OFFSET) \ + X(UNIFORM_BINDING_FRAME_TINT) \ + X(UNIFORM_BINDING_MAIN_TEXTURE) \ + X(UNIFORM_BINDING_COMPONENTS) \ + X(UNIFORM_BINDING_PLAYBACK_TIME) \ + X(UNIFORM_BINDING_TEXTURE_SIZE) \ + X(UNIFORM_BINDING_TRANSFORM) - inline constexpr UniformBinding SHADER_UNIFORM_BINDING_COMBO_ORDER[] = { +inline constexpr UniformBinding SHADER_UNIFORM_BINDING_COMBO_ORDER[] = { #define X(binding) binding, - SHADER_UNIFORM_BINDING_COMBO_VALUES + SHADER_UNIFORM_BINDING_COMBO_VALUES #undef X - }; +}; #undef SHADER_UNIFORM_BINDING_COMBO_VALUES - static bool is_shader_reload_needed(Document& document, Shader* shader) - { - if (!shader || shader->fragment.empty()) return false; - if (!document.shader_get(shader->id)) return true; +static bool is_shader_reload_needed(Document& document, Shader* shader) +{ + if (!shader || shader->fragment.empty()) + return false; + if (!document.shader_get(shader->id)) + return true; if (!document.shaderVertexPaths.contains(shader->id) || !document.shaderFragmentPaths.contains(shader->id)) - return true; + return true; return document.shaderVertexPaths.at(shader->id) != shader->vertex || document.shaderFragmentPaths.at(shader->id) != shader->fragment; - } +} - static Shader* shader_element_get(Document& document, int id) - { +static Shader* shader_element_get(Document& document, int id) +{ return item_get(document.model.content.shaders, id); - } +} - static std::filesystem::path shader_asset_path_get(Document& document, const std::filesystem::path& path) - { +static std::filesystem::path shader_asset_path_get(Document& document, const std::filesystem::path& path) +{ auto loadPath = path_backslash_handle(path); return path_backslash_replace(path_make_relative(loadPath, document.directory_get())); - } +} - static void shader_path_edit(Document& document, int shaderId, std::filesystem::path Shader::* member, - const std::filesystem::path& value) - { +static void shader_path_edit(Document& document, int shaderId, std::filesystem::path Shader::* member, + const std::filesystem::path& value) +{ auto shader = shader_element_get(document, shaderId); if (shader) { - shader->*member = path_backslash_replace(value); - document.change(); + shader->*member = path_backslash_replace(value); + document.change(); } - } +} - static void shader_dialog_update(ShadersPanel& window, Manager& manager, Dialog& dialog, Dialog::Type type, - std::filesystem::path Shader::* member) - { - if (!dialog.is_selected(type)) return; +static void shader_dialog_update(ShadersPanel& window, Manager& manager, Dialog& dialog, Dialog::Type type, + std::filesystem::path Shader::* member) +{ + if (!dialog.is_selected(type)) + return; auto dialogPath = dialog.path; auto shaderId = window.dialogShaderId; - manager.command_push( - {manager.selected, [dialogPath, shaderId, member](Manager&, Document& document) - { shader_path_edit(document, shaderId, member, shader_asset_path_get(document, dialogPath)); }}); + manager.command_push({manager.selected, [dialogPath, shaderId, member](Manager&, Document& document) { + shader_path_edit(document, shaderId, member, shader_asset_path_get(document, dialogPath)); + }}); window.dialogShaderId = -1; dialog.reset(); - } +} - static void shader_path_row_update(ShadersPanel& window, Document& document, Resources& resources, Dialog& dialog, - Shader* shader, std::filesystem::path Shader::* member, - Dialog::Type dialogType, StringType label) - { +static void shader_path_row_update(ShadersPanel& window, Document& document, Resources& resources, Dialog& dialog, + Shader* shader, std::filesystem::path Shader::* member, Dialog::Type dialogType, + StringType label) +{ auto shaderPath = shader ? shader->*member : std::filesystem::path{}; auto isDefault = shaderPath.empty(); auto displayPath = isDefault ? path_from_utf8(localize.get(BASIC_DEFAULT)) : shaderPath; @@ -89,130 +92,140 @@ if (ImGui::ImageButton(std::format("##{} Path Set", localize.get(label)).c_str(), resources.icon_id_get(ICON_FOLDER), icon_size_get())) { - if (shader) - { - window.dialogShaderId = shader->id; - dialog.file_open(dialogType); - } + if (shader) + { + window.dialogShaderId = shader->id; + dialog.file_open(dialogType); + } } ImGui::SameLine(); auto labelWidth = ImGui::CalcTextSize(localize.get(label)).x; auto inputWidth = ImGui::GetContentRegionAvail().x - labelWidth - ImGui::GetStyle().ItemSpacing.x; - if (inputWidth < ImGui::GetFrameHeight()) inputWidth = ImGui::GetFrameHeight(); + if (inputWidth < ImGui::GetFrameHeight()) + inputWidth = ImGui::GetFrameHeight(); ImGui::SetNextItemWidth(inputWidth); ImGui::BeginDisabled(isDefault); auto isEdited = input_text_path(std::format("##{} Path", localize.get(label)).c_str(), &displayPath); ImGui::EndDisabled(); - if (isEdited && shader) shader_path_edit(document, shader->id, member, displayPath); + if (isEdited && shader) + shader_path_edit(document, shader->id, member, displayPath); ImGui::SameLine(); ImGui::TextUnformatted(localize.get(label)); - } +} - static void shader_uniform_config_save(Document& document, Shader& shaderElement, - const ShaderUniform& uniform) - { +static void shader_uniform_config_save(Document& document, Shader& shaderElement, const ShaderUniform& uniform) +{ uniform_config_save(shaderElement, uniform); document.change(); - } +} - static void shader_uniform_components_from_value_set(ShaderUniform& uniform) - { +static void shader_uniform_components_from_value_set(ShaderUniform& uniform) +{ for (int i = 0; i < (int)uniform.components.size(); ++i) - uniform.components[i].value = uniform.value[i]; - } + uniform.components[i].value = uniform.value[i]; +} - static void shader_uniform_value_from_components_set(ShaderUniform& uniform) - { +static void shader_uniform_value_from_components_set(ShaderUniform& uniform) +{ for (int i = 0; i < (int)uniform.components.size(); ++i) - uniform.value[i] = uniform.components[i].value; - } + uniform.value[i] = uniform.components[i].value; +} - static bool shader_uniform_value_update(ShaderUniform& uniform) - { +static bool shader_uniform_value_update(ShaderUniform& uniform) +{ ImGui::SetNextItemWidth(-1.0f); switch (uniform.valueType) { - case UNIFORM_VALUE_FLOAT: - return ImGui::DragFloat("##Value", &uniform.value.x, 0.01f); - case UNIFORM_VALUE_INT: - case UNIFORM_VALUE_SAMPLER2D: - return ImGui::InputInt("##Value", &uniform.intValue); - case UNIFORM_VALUE_VEC2: - return ImGui::DragFloat2("##Value", &uniform.value.x, 0.01f); - case UNIFORM_VALUE_VEC3: - return ImGui::DragFloat3("##Value", &uniform.value.x, 0.01f); - case UNIFORM_VALUE_VEC4: - return ImGui::DragFloat4("##Value", &uniform.value.x, 0.01f); - default: - ImGui::TextUnformatted(localize.get(BASIC_NONE)); - return false; + case UNIFORM_VALUE_FLOAT: + return ImGui::DragFloat("##Value", &uniform.value.x, 0.01f); + case UNIFORM_VALUE_INT: + case UNIFORM_VALUE_SAMPLER2D: + return ImGui::InputInt("##Value", &uniform.intValue); + case UNIFORM_VALUE_VEC2: + return ImGui::DragFloat2("##Value", &uniform.value.x, 0.01f); + case UNIFORM_VALUE_VEC3: + return ImGui::DragFloat3("##Value", &uniform.value.x, 0.01f); + case UNIFORM_VALUE_VEC4: + return ImGui::DragFloat4("##Value", &uniform.value.x, 0.01f); + default: + ImGui::TextUnformatted(localize.get(BASIC_NONE)); + return false; } - } +} - static bool shader_uniform_component_binding_update(ShaderUniform::Component& component) - { +static bool shader_uniform_component_binding_update(ShaderUniform::Component& component) +{ auto bindingLabel = uniform_binding_label_get(component.binding); ImGui::SetNextItemWidth(ImGui::GetFrameHeight() * 5.0f); - if (!ImGui::BeginCombo("##Component Binding", bindingLabel.data())) return false; + if (!ImGui::BeginCombo("##Component Binding", bindingLabel.data())) + return false; bool isChanged = false; - constexpr UniformBinding bindings[] = {UNIFORM_BINDING_MANUAL, - UNIFORM_BINDING_PLAYBACK_TIME}; + constexpr UniformBinding bindings[] = {UNIFORM_BINDING_MANUAL, UNIFORM_BINDING_PLAYBACK_TIME}; for (auto binding : bindings) { - auto isSelected = component.binding == binding; - auto label = uniform_binding_label_get(binding); - if (ImGui::Selectable(label.data(), isSelected)) - { - component.binding = binding; - isChanged = true; - } - if (isSelected) ImGui::SetItemDefaultFocus(); + auto isSelected = component.binding == binding; + auto label = uniform_binding_label_get(binding); + if (ImGui::Selectable(label.data(), isSelected)) + { + component.binding = binding; + isChanged = true; + } + if (isSelected) + ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); return isChanged; - } +} - static bool shader_uniform_components_update(ShaderUniform& uniform) - { +static bool shader_uniform_components_update(ShaderUniform& uniform) +{ bool isChanged = false; constexpr const char* labels[] = {"X", "Y", "Z", "W"}; auto componentCount = UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount; for (int index = 0; index < componentCount; ++index) { - auto& component = uniform.components[index]; - ImGui::PushID(index); - if (index > 0) ImGui::Spacing(); - ImGui::TextUnformatted(labels[index]); - ImGui::SameLine(); - if (shader_uniform_component_binding_update(component)) isChanged = true; - ImGui::SameLine(); - ImGui::BeginDisabled(component.binding != UNIFORM_BINDING_MANUAL); - ImGui::SetNextItemWidth(-1.0f); - if (ImGui::DragFloat("##Component Value", &component.value, 0.01f)) isChanged = true; - ImGui::EndDisabled(); - ImGui::PopID(); + auto& component = uniform.components[index]; + ImGui::PushID(index); + if (index > 0) + ImGui::Spacing(); + ImGui::TextUnformatted(labels[index]); + ImGui::SameLine(); + if (shader_uniform_component_binding_update(component)) + isChanged = true; + ImGui::SameLine(); + ImGui::BeginDisabled(component.binding != UNIFORM_BINDING_MANUAL); + ImGui::SetNextItemWidth(-1.0f); + if (ImGui::DragFloat("##Component Value", &component.value, 0.01f)) + isChanged = true; + ImGui::EndDisabled(); + ImGui::PopID(); } - if (isChanged) shader_uniform_value_from_components_set(uniform); + if (isChanged) + shader_uniform_value_from_components_set(uniform); return isChanged; - } +} - static void shader_uniforms_update(Document& document, Shader* shaderElement, ShaderProgram* runtime, - ImVec2 tableSize) - { - if (!shaderElement) return; +static void shader_uniforms_update(Document& document, Shader* shaderElement, ShaderProgram* runtime, ImVec2 tableSize) +{ + if (!shaderElement) + return; auto flags = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY; - if (tableSize.x <= 0.0f) tableSize.x = ImGui::GetContentRegionAvail().x; - if (tableSize.y <= 0.0f) tableSize.y = ImGui::GetContentRegionAvail().y; - if (tableSize.y < ImGui::GetFrameHeight()) tableSize.y = ImGui::GetFrameHeight(); - if (!ImGui::BeginTable("##Shader Uniforms", 4, flags, tableSize)) return; + if (tableSize.x <= 0.0f) + tableSize.x = ImGui::GetContentRegionAvail().x; + if (tableSize.y <= 0.0f) + tableSize.y = ImGui::GetContentRegionAvail().y; + if (tableSize.y < ImGui::GetFrameHeight()) + tableSize.y = ImGui::GetFrameHeight(); + if (!ImGui::BeginTable("##Shader Uniforms", 4, flags, tableSize)) + return; ImGui::TableSetupColumn(localize.get(BASIC_NAME)); ImGui::TableSetupColumn(localize.get(LABEL_TYPE)); @@ -222,63 +235,66 @@ ImGui::TableHeadersRow(); if (runtime) - for (auto& uniform : runtime->uniforms) - { - ImGui::PushID(uniform.name.c_str()); - ImGui::TableNextRow(); - - ImGui::TableNextColumn(); - ImGui::TextUnformatted(uniform.name.c_str()); - - ImGui::TableNextColumn(); - ImGui::TextUnformatted(uniform_value_type_label_get(uniform.valueType).data()); - - ImGui::TableNextColumn(); - auto bindingLabel = uniform_binding_label_get(uniform.binding); - ImGui::SetNextItemWidth(-1.0f); - if (ImGui::BeginCombo("##Binding", bindingLabel.data())) + for (auto& uniform : runtime->uniforms) { - for (auto binding : SHADER_UNIFORM_BINDING_COMBO_ORDER) - { - if (!is_uniform_binding_valid(binding, uniform.valueType)) continue; - auto isSelected = uniform.binding == binding; - auto label = uniform_binding_label_get(binding); - if (ImGui::Selectable(label.data(), isSelected)) + ImGui::PushID(uniform.name.c_str()); + ImGui::TableNextRow(); + + ImGui::TableNextColumn(); + ImGui::TextUnformatted(uniform.name.c_str()); + + ImGui::TableNextColumn(); + ImGui::TextUnformatted(uniform_value_type_label_get(uniform.valueType).data()); + + ImGui::TableNextColumn(); + auto bindingLabel = uniform_binding_label_get(uniform.binding); + ImGui::SetNextItemWidth(-1.0f); + if (ImGui::BeginCombo("##Binding", bindingLabel.data())) { - uniform.binding = binding; - if (uniform.binding == UNIFORM_BINDING_COMPONENTS) - shader_uniform_components_from_value_set(uniform); - shader_uniform_config_save(document, *shaderElement, uniform); + for (auto binding : SHADER_UNIFORM_BINDING_COMBO_ORDER) + { + if (!is_uniform_binding_valid(binding, uniform.valueType)) + continue; + auto isSelected = uniform.binding == binding; + auto label = uniform_binding_label_get(binding); + if (ImGui::Selectable(label.data(), isSelected)) + { + uniform.binding = binding; + if (uniform.binding == UNIFORM_BINDING_COMPONENTS) + shader_uniform_components_from_value_set(uniform); + shader_uniform_config_save(document, *shaderElement, uniform); + } + if (isSelected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); } - if (isSelected) ImGui::SetItemDefaultFocus(); - } - ImGui::EndCombo(); - } - ImGui::TableNextColumn(); - if (uniform.binding == UNIFORM_BINDING_COMPONENTS) - { - if (shader_uniform_components_update(uniform)) shader_uniform_config_save(document, *shaderElement, uniform); - } - else - { - ImGui::BeginDisabled(uniform.binding != UNIFORM_BINDING_MANUAL); - if (shader_uniform_value_update(uniform)) - { - shader_uniform_components_from_value_set(uniform); - shader_uniform_config_save(document, *shaderElement, uniform); - } - ImGui::EndDisabled(); - } + ImGui::TableNextColumn(); + if (uniform.binding == UNIFORM_BINDING_COMPONENTS) + { + if (shader_uniform_components_update(uniform)) + shader_uniform_config_save(document, *shaderElement, uniform); + } + else + { + ImGui::BeginDisabled(uniform.binding != UNIFORM_BINDING_MANUAL); + if (shader_uniform_value_update(uniform)) + { + shader_uniform_components_from_value_set(uniform); + shader_uniform_config_save(document, *shaderElement, uniform); + } + ImGui::EndDisabled(); + } - ImGui::PopID(); - } + ImGui::PopID(); + } ImGui::EndTable(); - } +} - void shaders_update(Panel& panel, ShadersPanel& shaders) - { +void shaders_update(Panel& panel, ShadersPanel& shaders) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& items = document.model.content.shaders; auto& status = shaders.status; @@ -289,146 +305,147 @@ if (ImGui::Begin(localize.get(LABEL_SHADERS_WINDOW), &settings.windowIsShaders)) { - auto selection = document.selected_ids_get(SelectionKind::SHADERS); - auto properties_open = [&](int id) - { - document.selected_ids_set(SelectionKind::SHADERS, {id}); - popupShaderId = id; - propertiesPopup.open(); - }; + auto selection = document.selected_ids_get(SelectionKind::SHADERS); + auto properties_open = [&](int id) { + document.selected_ids_set(SelectionKind::SHADERS, {id}); + popupShaderId = id; + propertiesPopup.open(); + }; - Actions actions = {}; - actions.add( - ACTION_ADD, {}, - [&]() - { - command_push(panel, - [&state](Document& document) - { - int id = 0; - document.edit_apply(EDIT_ADD_SHADER, - [&](Model& model) - { - auto& shaders = model.content.shaders; - id = item_next_id_get(shaders); - shaders.push_back({.id = id, .name = localize.get(TEXT_NEW_SHADER)}); - }); - document.selected_ids_set(SelectionKind::SHADERS, {id}); - document.focused_id_set(SelectionKind::SHADERS, id); - state.newId = id; - }); - }, - TOOLTIP_ADD_SHADER); - content_remove_action_add(actions, panel, ElementType::SHADER, SelectionKind::SHADERS); - actions.add( - ACTION_RELOAD, [selection]() { return !selection.empty(); }, - [&]() - { - status.clear(); - for (auto id : selection) - if (auto shader = shader_element_get(document, id)) - { - document.shader_reload(id, &status); - toasts.push(std::vformat(localize.get(TOAST_RELOAD_SHADER), std::make_format_args(id, shader->name))); - } - }, - TOOLTIP_RELOAD_SHADERS); - - auto image_get = [&](int id) - { - auto isValid = document.shader_get(id) != nullptr; - auto& image = resources.icons[isValid ? ICON_SHADER : ICON_NONE]; - return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; - }; - ListRows rows{.label_get = - [&](int id) + Actions actions = {}; + actions.add( + ACTION_ADD, {}, + [&]() { + command_push(panel, [&state](Document& document) { + int id = 0; + document.edit_apply(EDIT_ADD_SHADER, [&](Model& model) { + auto& shaders = model.content.shaders; + id = item_next_id_get(shaders); + shaders.push_back({.id = id, .name = localize.get(TEXT_NEW_SHADER)}); + }); + document.selected_ids_set(SelectionKind::SHADERS, {id}); + document.focused_id_set(SelectionKind::SHADERS, id); + state.newId = id; + }); + }, + TOOLTIP_ADD_SHADER); + content_remove_action_add(actions, panel, ElementType::SHADER, SelectionKind::SHADERS); + actions.add( + ACTION_RELOAD, [selection]() { return !selection.empty(); }, + [&]() { + status.clear(); + for (auto id : selection) + if (auto shader = shader_element_get(document, id)) { - auto name = shader_element_get(document, id)->name; - return std::vformat(localize.get(FORMAT_SHADER), std::make_format_args(id, name)); - }, - .tooltip_draw = - [&](int id) - { - auto& shader = *shader_element_get(document, id); - tooltip_name_draw(resources, shader.name); - ImGui::Text("%s: %d", localize.get(BASIC_ID), id); - ImGui::Text("%s: %s", localize.get(LABEL_VERTEX), path_to_utf8(shader.vertex).c_str()); - ImGui::Text("%s: %s", localize.get(LABEL_FRAGMENT), path_to_utf8(shader.fragment).c_str()); - if (image_get(id).isValid) return; - ImGui::Spacing(); - ImGui::TextWrapped("%s", localize.get(TOOLTIP_SHADER_INVALID)); - }, - .image_get = image_get, - .activate = properties_open, - .cardLines = SHADER_CARD_LINES}; - list_panel_draw( - panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD}}, - [&]() { content_list_draw(panel, SelectionKind::SHADERS, item_ids_get(items), rows); }, true); + document.shader_reload(id, &status); + toasts.push( + std::vformat(localize.get(TOAST_RELOAD_SHADER), std::make_format_args(id, shader->name))); + } + }, + TOOLTIP_RELOAD_SHADERS); - propertiesPopup.trigger(); - if (ImGui::BeginPopupModal(propertiesPopup.label(), &propertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) - { - auto shader = shader_element_get(document, popupShaderId); - if (!shader) propertiesPopup.close(); - if (!shader) + auto image_get = [&](int id) { + auto isValid = document.shader_get(id) != nullptr; + auto& image = resources.icons[isValid ? ICON_SHADER : ICON_NONE]; + return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; + }; + ListRows rows{.label_get = + [&](int id) { + auto name = shader_element_get(document, id)->name; + return std::vformat(localize.get(FORMAT_SHADER), std::make_format_args(id, name)); + }, + .tooltip_draw = + [&](int id) { + auto& shader = *shader_element_get(document, id); + tooltip_name_draw(resources, shader.name); + ImGui::Text("%s: %d", localize.get(BASIC_ID), id); + ImGui::Text("%s: %s", localize.get(LABEL_VERTEX), path_to_utf8(shader.vertex).c_str()); + ImGui::Text("%s: %s", localize.get(LABEL_FRAGMENT), + path_to_utf8(shader.fragment).c_str()); + if (image_get(id).isValid) + return; + ImGui::Spacing(); + ImGui::TextWrapped("%s", localize.get(TOOLTIP_SHADER_INVALID)); + }, + .image_get = image_get, + .activate = properties_open, + .cardLines = SHADER_CARD_LINES}; + list_panel_draw( + panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD}}, + [&]() { content_list_draw(panel, SelectionKind::SHADERS, item_ids_get(items), rows); }, true); + + propertiesPopup.trigger(); + if (ImGui::BeginPopupModal(propertiesPopup.label(), &propertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) { - ImGui::EndPopup(); - propertiesPopup.end(); - ImGui::End(); - return; + auto shader = shader_element_get(document, popupShaderId); + if (!shader) + propertiesPopup.close(); + if (!shader) + { + ImGui::EndPopup(); + propertiesPopup.end(); + ImGui::End(); + return; + } + + auto popupSize = size_without_footer_get(); + if (popupSize.y < ImGui::GetFrameHeight()) + popupSize.y = ImGui::GetFrameHeight(); + if (ImGui::BeginChild("##Shader Properties Child", popupSize)) + { + if (propertiesPopup.isJustOpened) + ImGui::SetKeyboardFocusHere(); + if (input_text_string(localize.get(BASIC_NAME), &shader->name)) + document.change(); + + ImGui::SeparatorText(localize.get(LABEL_FILES)); + + shader_path_row_update(shaders, document, resources, dialog, shader, &Shader::vertex, + Dialog::SHADER_VERTEX_PATH_SET, LABEL_VERTEX); + shader_path_row_update(shaders, document, resources, dialog, shader, &Shader::fragment, + Dialog::SHADER_FRAGMENT_PATH_SET, LABEL_FRAGMENT); + + if (is_shader_reload_needed(document, shader)) + ImGui::TextWrapped("%s", localize.get(LABEL_SHADER_RELOAD_NEEDED)); + + ImGui::SeparatorText(localize.get(LABEL_UNIFORMS)); + + auto runtime = document.shader_get(shader->id); + auto tableSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 8.0f); + auto outputReserve = ImGui::GetTextLineHeightWithSpacing() * 6.0f; + auto availableHeight = ImGui::GetContentRegionAvail().y; + if (availableHeight - outputReserve < tableSize.y) + tableSize.y = availableHeight - outputReserve; + if (tableSize.y < ImGui::GetFrameHeight()) + tableSize.y = ImGui::GetFrameHeight(); + shader_uniforms_update(document, shader, runtime, tableSize); + + ImGui::SeparatorText(localize.get(LABEL_OUTPUT)); + + auto consoleSize = ImGui::GetContentRegionAvail(); + if (consoleSize.y < ImGui::GetFrameHeight()) + consoleSize.y = ImGui::GetFrameHeight(); + if (ImGui::BeginChild("##Shaders Output", consoleSize, ImGuiChildFlags_Borders)) + ImGui::TextWrapped("%s", status.c_str()); + ImGui::EndChild(); + } + ImGui::EndChild(); + + auto popupWidgetSize = widget_size_with_row_get(2); + if (ImGui::Button(localize.get(BASIC_CONFIRM), popupWidgetSize)) + { + status.clear(); + document.shader_reload(shader->id, &status); + propertiesPopup.close(); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RELOAD_SHADERS)); + ImGui::SameLine(); + if (ImGui::Button(localize.get(BASIC_CANCEL), popupWidgetSize)) + propertiesPopup.close(); + + ImGui::EndPopup(); } - - auto popupSize = size_without_footer_get(); - if (popupSize.y < ImGui::GetFrameHeight()) popupSize.y = ImGui::GetFrameHeight(); - if (ImGui::BeginChild("##Shader Properties Child", popupSize)) - { - if (propertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); - if (input_text_string(localize.get(BASIC_NAME), &shader->name)) document.change(); - - ImGui::SeparatorText(localize.get(LABEL_FILES)); - - shader_path_row_update(shaders, document, resources, dialog, shader, &Shader::vertex, - Dialog::SHADER_VERTEX_PATH_SET, LABEL_VERTEX); - shader_path_row_update(shaders, document, resources, dialog, shader, &Shader::fragment, - Dialog::SHADER_FRAGMENT_PATH_SET, LABEL_FRAGMENT); - - if (is_shader_reload_needed(document, shader)) - ImGui::TextWrapped("%s", localize.get(LABEL_SHADER_RELOAD_NEEDED)); - - ImGui::SeparatorText(localize.get(LABEL_UNIFORMS)); - - auto runtime = document.shader_get(shader->id); - auto tableSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 8.0f); - auto outputReserve = ImGui::GetTextLineHeightWithSpacing() * 6.0f; - auto availableHeight = ImGui::GetContentRegionAvail().y; - if (availableHeight - outputReserve < tableSize.y) tableSize.y = availableHeight - outputReserve; - if (tableSize.y < ImGui::GetFrameHeight()) tableSize.y = ImGui::GetFrameHeight(); - shader_uniforms_update(document, shader, runtime, tableSize); - - ImGui::SeparatorText(localize.get(LABEL_OUTPUT)); - - auto consoleSize = ImGui::GetContentRegionAvail(); - if (consoleSize.y < ImGui::GetFrameHeight()) consoleSize.y = ImGui::GetFrameHeight(); - if (ImGui::BeginChild("##Shaders Output", consoleSize, ImGuiChildFlags_Borders)) - ImGui::TextWrapped("%s", status.c_str()); - ImGui::EndChild(); - } - ImGui::EndChild(); - - auto popupWidgetSize = widget_size_with_row_get(2); - if (ImGui::Button(localize.get(BASIC_CONFIRM), popupWidgetSize)) - { - status.clear(); - document.shader_reload(shader->id, &status); - propertiesPopup.close(); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RELOAD_SHADERS)); - ImGui::SameLine(); - if (ImGui::Button(localize.get(BASIC_CANCEL), popupWidgetSize)) propertiesPopup.close(); - - ImGui::EndPopup(); - } - propertiesPopup.end(); + propertiesPopup.end(); } ImGui::End(); - } +} diff --git a/src/ui/shaders.h b/src/ui/shaders.h index 029d542..d212aa2 100644 --- a/src/ui/shaders.h +++ b/src/ui/shaders.h @@ -2,13 +2,13 @@ #include "ui/panel.h" - struct ShadersPanel - { +struct ShadersPanel +{ PanelState state = {}; std::string status; int dialogShaderId = -1; int popupShaderId = -1; PopupHelper propertiesPopup = PopupHelper(LABEL_SHADER_PROPERTIES, POPUP_NORMAL); - }; +}; - void shaders_update(Panel&, ShadersPanel&); +void shaders_update(Panel&, ShadersPanel&); diff --git a/src/ui/shortcut.cpp b/src/ui/shortcut.cpp index 63d9abf..66b2067 100644 --- a/src/ui/shortcut.cpp +++ b/src/ui/shortcut.cpp @@ -6,131 +6,137 @@ #include - const std::vector> CANONICAL_KEY_NAMES = { - {ImGuiKey_A, "A"}, - {ImGuiKey_B, "B"}, - {ImGuiKey_C, "C"}, - {ImGuiKey_D, "D"}, - {ImGuiKey_E, "E"}, - {ImGuiKey_F, "F"}, - {ImGuiKey_G, "G"}, - {ImGuiKey_H, "H"}, - {ImGuiKey_I, "I"}, - {ImGuiKey_J, "J"}, - {ImGuiKey_K, "K"}, - {ImGuiKey_L, "L"}, - {ImGuiKey_M, "M"}, - {ImGuiKey_N, "N"}, - {ImGuiKey_O, "O"}, - {ImGuiKey_P, "P"}, - {ImGuiKey_Q, "Q"}, - {ImGuiKey_R, "R"}, - {ImGuiKey_S, "S"}, - {ImGuiKey_T, "T"}, - {ImGuiKey_U, "U"}, - {ImGuiKey_V, "V"}, - {ImGuiKey_W, "W"}, - {ImGuiKey_X, "X"}, - {ImGuiKey_Y, "Y"}, - {ImGuiKey_Z, "Z"}, - {ImGuiKey_0, "0"}, - {ImGuiKey_1, "1"}, - {ImGuiKey_2, "2"}, - {ImGuiKey_3, "3"}, - {ImGuiKey_4, "4"}, - {ImGuiKey_5, "5"}, - {ImGuiKey_6, "6"}, - {ImGuiKey_7, "7"}, - {ImGuiKey_8, "8"}, - {ImGuiKey_9, "9"}, - {ImGuiKey_Keypad0, "Num0"}, - {ImGuiKey_Keypad1, "Num1"}, - {ImGuiKey_Keypad2, "Num2"}, - {ImGuiKey_Keypad3, "Num3"}, - {ImGuiKey_Keypad4, "Num4"}, - {ImGuiKey_Keypad5, "Num5"}, - {ImGuiKey_Keypad6, "Num6"}, - {ImGuiKey_Keypad7, "Num7"}, - {ImGuiKey_Keypad8, "Num8"}, - {ImGuiKey_Keypad9, "Num9"}, - {ImGuiKey_KeypadAdd, "NumAdd"}, - {ImGuiKey_KeypadSubtract, "NumSubtract"}, - {ImGuiKey_KeypadMultiply, "NumMultiply"}, - {ImGuiKey_KeypadDivide, "NumDivide"}, - {ImGuiKey_KeypadEnter, "NumEnter"}, - {ImGuiKey_KeypadDecimal, "NumDecimal"}, - {ImGuiKey_KeypadEqual, "NumEqual"}, - {ImGuiKey_F1, "F1"}, - {ImGuiKey_F2, "F2"}, - {ImGuiKey_F3, "F3"}, - {ImGuiKey_F4, "F4"}, - {ImGuiKey_F5, "F5"}, - {ImGuiKey_F6, "F6"}, - {ImGuiKey_F7, "F7"}, - {ImGuiKey_F8, "F8"}, - {ImGuiKey_F9, "F9"}, - {ImGuiKey_F10, "F10"}, - {ImGuiKey_F11, "F11"}, - {ImGuiKey_F12, "F12"}, - {ImGuiKey_UpArrow, "Up"}, - {ImGuiKey_DownArrow, "Down"}, - {ImGuiKey_LeftArrow, "Left"}, - {ImGuiKey_RightArrow, "Right"}, - {ImGuiKey_Space, "Space"}, - {ImGuiKey_Enter, "Enter"}, - {ImGuiKey_Escape, "Escape"}, - {ImGuiKey_Tab, "Tab"}, - {ImGuiKey_Backspace, "Backspace"}, - {ImGuiKey_Delete, "Delete"}, - {ImGuiKey_Insert, "Insert"}, - {ImGuiKey_Home, "Home"}, - {ImGuiKey_End, "End"}, - {ImGuiKey_PageUp, "PageUp"}, - {ImGuiKey_PageDown, "PageDown"}, - {ImGuiKey_Minus, "Minus"}, - {ImGuiKey_Equal, "Equal"}, - {ImGuiKey_LeftBracket, "LeftBracket"}, - {ImGuiKey_RightBracket, "RightBracket"}, - {ImGuiKey_Semicolon, "Semicolon"}, - {ImGuiKey_Apostrophe, "Apostrophe"}, - {ImGuiKey_Comma, "Comma"}, - {ImGuiKey_Period, "Period"}, - {ImGuiKey_Slash, "Slash"}, - {ImGuiKey_Backslash, "Backslash"}, - {ImGuiKey_GraveAccent, "GraveAccent"}, - }; +const std::vector> CANONICAL_KEY_NAMES = { + {ImGuiKey_A, "A"}, + {ImGuiKey_B, "B"}, + {ImGuiKey_C, "C"}, + {ImGuiKey_D, "D"}, + {ImGuiKey_E, "E"}, + {ImGuiKey_F, "F"}, + {ImGuiKey_G, "G"}, + {ImGuiKey_H, "H"}, + {ImGuiKey_I, "I"}, + {ImGuiKey_J, "J"}, + {ImGuiKey_K, "K"}, + {ImGuiKey_L, "L"}, + {ImGuiKey_M, "M"}, + {ImGuiKey_N, "N"}, + {ImGuiKey_O, "O"}, + {ImGuiKey_P, "P"}, + {ImGuiKey_Q, "Q"}, + {ImGuiKey_R, "R"}, + {ImGuiKey_S, "S"}, + {ImGuiKey_T, "T"}, + {ImGuiKey_U, "U"}, + {ImGuiKey_V, "V"}, + {ImGuiKey_W, "W"}, + {ImGuiKey_X, "X"}, + {ImGuiKey_Y, "Y"}, + {ImGuiKey_Z, "Z"}, + {ImGuiKey_0, "0"}, + {ImGuiKey_1, "1"}, + {ImGuiKey_2, "2"}, + {ImGuiKey_3, "3"}, + {ImGuiKey_4, "4"}, + {ImGuiKey_5, "5"}, + {ImGuiKey_6, "6"}, + {ImGuiKey_7, "7"}, + {ImGuiKey_8, "8"}, + {ImGuiKey_9, "9"}, + {ImGuiKey_Keypad0, "Num0"}, + {ImGuiKey_Keypad1, "Num1"}, + {ImGuiKey_Keypad2, "Num2"}, + {ImGuiKey_Keypad3, "Num3"}, + {ImGuiKey_Keypad4, "Num4"}, + {ImGuiKey_Keypad5, "Num5"}, + {ImGuiKey_Keypad6, "Num6"}, + {ImGuiKey_Keypad7, "Num7"}, + {ImGuiKey_Keypad8, "Num8"}, + {ImGuiKey_Keypad9, "Num9"}, + {ImGuiKey_KeypadAdd, "NumAdd"}, + {ImGuiKey_KeypadSubtract, "NumSubtract"}, + {ImGuiKey_KeypadMultiply, "NumMultiply"}, + {ImGuiKey_KeypadDivide, "NumDivide"}, + {ImGuiKey_KeypadEnter, "NumEnter"}, + {ImGuiKey_KeypadDecimal, "NumDecimal"}, + {ImGuiKey_KeypadEqual, "NumEqual"}, + {ImGuiKey_F1, "F1"}, + {ImGuiKey_F2, "F2"}, + {ImGuiKey_F3, "F3"}, + {ImGuiKey_F4, "F4"}, + {ImGuiKey_F5, "F5"}, + {ImGuiKey_F6, "F6"}, + {ImGuiKey_F7, "F7"}, + {ImGuiKey_F8, "F8"}, + {ImGuiKey_F9, "F9"}, + {ImGuiKey_F10, "F10"}, + {ImGuiKey_F11, "F11"}, + {ImGuiKey_F12, "F12"}, + {ImGuiKey_UpArrow, "Up"}, + {ImGuiKey_DownArrow, "Down"}, + {ImGuiKey_LeftArrow, "Left"}, + {ImGuiKey_RightArrow, "Right"}, + {ImGuiKey_Space, "Space"}, + {ImGuiKey_Enter, "Enter"}, + {ImGuiKey_Escape, "Escape"}, + {ImGuiKey_Tab, "Tab"}, + {ImGuiKey_Backspace, "Backspace"}, + {ImGuiKey_Delete, "Delete"}, + {ImGuiKey_Insert, "Insert"}, + {ImGuiKey_Home, "Home"}, + {ImGuiKey_End, "End"}, + {ImGuiKey_PageUp, "PageUp"}, + {ImGuiKey_PageDown, "PageDown"}, + {ImGuiKey_Minus, "Minus"}, + {ImGuiKey_Equal, "Equal"}, + {ImGuiKey_LeftBracket, "LeftBracket"}, + {ImGuiKey_RightBracket, "RightBracket"}, + {ImGuiKey_Semicolon, "Semicolon"}, + {ImGuiKey_Apostrophe, "Apostrophe"}, + {ImGuiKey_Comma, "Comma"}, + {ImGuiKey_Period, "Period"}, + {ImGuiKey_Slash, "Slash"}, + {ImGuiKey_Backslash, "Backslash"}, + {ImGuiKey_GraveAccent, "GraveAccent"}, +}; - static const char* shortcut_canonical_key_name(ImGuiKey key) - { +static const char* shortcut_canonical_key_name(ImGuiKey key) +{ for (auto& [mappedKey, name] : CANONICAL_KEY_NAMES) - if (mappedKey == key) return name; + if (mappedKey == key) + return name; return nullptr; - } +} - std::string chord_to_string(ImGuiKeyChord chord) - { +std::string chord_to_string(ImGuiKeyChord chord) +{ std::string result; - if (chord & ImGuiMod_Ctrl) result += "Ctrl+"; - if (chord & ImGuiMod_Shift) result += "Shift+"; - if (chord & ImGuiMod_Alt) result += "Alt+"; - if (chord & ImGuiMod_Super) result += "Super+"; + if (chord & ImGuiMod_Ctrl) + result += "Ctrl+"; + if (chord & ImGuiMod_Shift) + result += "Shift+"; + if (chord & ImGuiMod_Alt) + result += "Alt+"; + if (chord & ImGuiMod_Super) + result += "Super+"; if (auto key = (ImGuiKey)(chord & ~ImGuiMod_Mask_); key != ImGuiKey_None) { - if (const char* name = shortcut_canonical_key_name(key); name && *name) - result += name; - else - result += ImGui::GetKeyName(key); + if (const char* name = shortcut_canonical_key_name(key); name && *name) + result += name; + else + result += ImGui::GetKeyName(key); } - if (!result.empty() && result.back() == '+') result.pop_back(); + if (!result.empty() && result.back() == '+') + result.pop_back(); return result; - } +} - ImGuiKeyChord string_to_chord(const std::string& string) - { +ImGuiKeyChord string_to_chord(const std::string& string) +{ ImGuiKeyChord chord = 0; ImGuiKey baseKey = ImGuiKey_None; @@ -138,39 +144,42 @@ std::string token; while (std::getline(ss, token, '+')) { - token.erase(0, token.find_first_not_of(" \t\r\n")); - token.erase(token.find_last_not_of(" \t\r\n") + 1); + token.erase(0, token.find_first_not_of(" \t\r\n")); + token.erase(token.find_last_not_of(" \t\r\n") + 1); - if (token.empty()) continue; + if (token.empty()) + continue; - if (auto it = MOD_MAP.find(token); it != MOD_MAP.end()) - chord |= it->second; - else if (baseKey == ImGuiKey_None) - if (auto it2 = KEY_MAP.find(token); it2 != KEY_MAP.end()) baseKey = it2->second; + if (auto it = MOD_MAP.find(token); it != MOD_MAP.end()) + chord |= it->second; + else if (baseKey == ImGuiKey_None) + if (auto it2 = KEY_MAP.find(token); it2 != KEY_MAP.end()) + baseKey = it2->second; } - if (baseKey != ImGuiKey_None) chord |= baseKey; + if (baseKey != ImGuiKey_None) + chord |= baseKey; return chord; - } +} - bool shortcut(ImGuiKeyChord chord, ShortcutScope type) - { - if (chord == ImGuiKey_None) return false; +bool shortcut(ImGuiKeyChord chord, ShortcutScope type) +{ + if (chord == ImGuiKey_None) + return false; - if (ImGui::GetTopMostPopupModal() != nullptr && - (type == SCOPE_GLOBAL || type == SCOPE_GLOBAL_SET)) - return false; + if (ImGui::GetTopMostPopupModal() != nullptr && (type == SCOPE_GLOBAL || type == SCOPE_GLOBAL_SET)) + return false; - int flags = type == SCOPE_GLOBAL || type == SCOPE_GLOBAL_SET ? ImGuiInputFlags_RouteGlobal - : ImGuiInputFlags_RouteFocused; + int flags = + type == SCOPE_GLOBAL || type == SCOPE_GLOBAL_SET ? ImGuiInputFlags_RouteGlobal : ImGuiInputFlags_RouteFocused; flags |= ImGuiInputFlags_Repeat; if (type == SCOPE_GLOBAL_SET || type == SCOPE_FOCUSED_SET) { - ImGui::SetNextItemShortcut(chord, flags); - return false; + ImGui::SetNextItemShortcut(chord, flags); + return false; } return ImGui::Shortcut(chord, flags); - } +} diff --git a/src/ui/shortcut.h b/src/ui/shortcut.h index bd735e9..c901420 100644 --- a/src/ui/shortcut.h +++ b/src/ui/shortcut.h @@ -7,128 +7,128 @@ #include "types.h" - inline const std::unordered_map KEY_MAP = { - {"A", ImGuiKey_A}, - {"B", ImGuiKey_B}, - {"C", ImGuiKey_C}, - {"D", ImGuiKey_D}, - {"E", ImGuiKey_E}, - {"F", ImGuiKey_F}, - {"G", ImGuiKey_G}, - {"H", ImGuiKey_H}, - {"I", ImGuiKey_I}, - {"J", ImGuiKey_J}, - {"K", ImGuiKey_K}, - {"L", ImGuiKey_L}, - {"M", ImGuiKey_M}, - {"N", ImGuiKey_N}, - {"O", ImGuiKey_O}, - {"P", ImGuiKey_P}, - {"Q", ImGuiKey_Q}, - {"R", ImGuiKey_R}, - {"S", ImGuiKey_S}, - {"T", ImGuiKey_T}, - {"U", ImGuiKey_U}, - {"V", ImGuiKey_V}, - {"W", ImGuiKey_W}, - {"X", ImGuiKey_X}, - {"Y", ImGuiKey_Y}, - {"Z", ImGuiKey_Z}, - {"0", ImGuiKey_0}, - {"1", ImGuiKey_1}, - {"2", ImGuiKey_2}, - {"3", ImGuiKey_3}, - {"4", ImGuiKey_4}, - {"5", ImGuiKey_5}, - {"6", ImGuiKey_6}, - {"7", ImGuiKey_7}, - {"8", ImGuiKey_8}, - {"9", ImGuiKey_9}, - {"Num0", ImGuiKey_Keypad0}, - {"Num1", ImGuiKey_Keypad1}, - {"Num2", ImGuiKey_Keypad2}, - {"Num3", ImGuiKey_Keypad3}, - {"Num4", ImGuiKey_Keypad4}, - {"Num5", ImGuiKey_Keypad5}, - {"Num6", ImGuiKey_Keypad6}, - {"Num7", ImGuiKey_Keypad7}, - {"Num8", ImGuiKey_Keypad8}, - {"Num9", ImGuiKey_Keypad9}, - {"NumAdd", ImGuiKey_KeypadAdd}, - {"NumSubtract", ImGuiKey_KeypadSubtract}, - {"NumMultiply", ImGuiKey_KeypadMultiply}, - {"NumDivide", ImGuiKey_KeypadDivide}, - {"NumEnter", ImGuiKey_KeypadEnter}, - {"NumDecimal", ImGuiKey_KeypadDecimal}, - {"NumEqual", ImGuiKey_KeypadEqual}, - {"F1", ImGuiKey_F1}, - {"F2", ImGuiKey_F2}, - {"F3", ImGuiKey_F3}, - {"F4", ImGuiKey_F4}, - {"F5", ImGuiKey_F5}, - {"F6", ImGuiKey_F6}, - {"F7", ImGuiKey_F7}, - {"F8", ImGuiKey_F8}, - {"F9", ImGuiKey_F9}, - {"F10", ImGuiKey_F10}, - {"F11", ImGuiKey_F11}, - {"F12", ImGuiKey_F12}, - {"Up", ImGuiKey_UpArrow}, - {"Down", ImGuiKey_DownArrow}, - {"Left", ImGuiKey_LeftArrow}, - {"Right", ImGuiKey_RightArrow}, - {"Space", ImGuiKey_Space}, - {"Enter", ImGuiKey_Enter}, - {"Escape", ImGuiKey_Escape}, - {"Tab", ImGuiKey_Tab}, - {"Backspace", ImGuiKey_Backspace}, - {"Delete", ImGuiKey_Delete}, - {"Insert", ImGuiKey_Insert}, - {"Home", ImGuiKey_Home}, - {"End", ImGuiKey_End}, - {"PageUp", ImGuiKey_PageUp}, - {"PageDown", ImGuiKey_PageDown}, - {"Minus", ImGuiKey_Minus}, - {"Equal", ImGuiKey_Equal}, - {"LeftBracket", ImGuiKey_LeftBracket}, - {"RightBracket", ImGuiKey_RightBracket}, - {"Semicolon", ImGuiKey_Semicolon}, - {"Apostrophe", ImGuiKey_Apostrophe}, - {"Comma", ImGuiKey_Comma}, - {"Period", ImGuiKey_Period}, - {"Slash", ImGuiKey_Slash}, - {"Backslash", ImGuiKey_Backslash}, - {"GraveAccent", ImGuiKey_GraveAccent}, - {"Keypad0", ImGuiKey_Keypad0}, - {"Keypad1", ImGuiKey_Keypad1}, - {"Keypad2", ImGuiKey_Keypad2}, - {"Keypad3", ImGuiKey_Keypad3}, - {"Keypad4", ImGuiKey_Keypad4}, - {"Keypad5", ImGuiKey_Keypad5}, - {"Keypad6", ImGuiKey_Keypad6}, - {"Keypad7", ImGuiKey_Keypad7}, - {"Keypad8", ImGuiKey_Keypad8}, - {"Keypad9", ImGuiKey_Keypad9}, - {"KeypadAdd", ImGuiKey_KeypadAdd}, - {"KeypadSubtract", ImGuiKey_KeypadSubtract}, - {"KeypadMultiply", ImGuiKey_KeypadMultiply}, - {"KeypadDivide", ImGuiKey_KeypadDivide}, - {"KeypadEnter", ImGuiKey_KeypadEnter}, - {"KeypadDecimal", ImGuiKey_KeypadDecimal}, - {"KeypadEqual", ImGuiKey_KeypadEqual}, - {"UpArrow", ImGuiKey_UpArrow}, - {"DownArrow", ImGuiKey_DownArrow}, - {"LeftArrow", ImGuiKey_LeftArrow}, - {"RightArrow", ImGuiKey_RightArrow}, - }; +inline const std::unordered_map KEY_MAP = { + {"A", ImGuiKey_A}, + {"B", ImGuiKey_B}, + {"C", ImGuiKey_C}, + {"D", ImGuiKey_D}, + {"E", ImGuiKey_E}, + {"F", ImGuiKey_F}, + {"G", ImGuiKey_G}, + {"H", ImGuiKey_H}, + {"I", ImGuiKey_I}, + {"J", ImGuiKey_J}, + {"K", ImGuiKey_K}, + {"L", ImGuiKey_L}, + {"M", ImGuiKey_M}, + {"N", ImGuiKey_N}, + {"O", ImGuiKey_O}, + {"P", ImGuiKey_P}, + {"Q", ImGuiKey_Q}, + {"R", ImGuiKey_R}, + {"S", ImGuiKey_S}, + {"T", ImGuiKey_T}, + {"U", ImGuiKey_U}, + {"V", ImGuiKey_V}, + {"W", ImGuiKey_W}, + {"X", ImGuiKey_X}, + {"Y", ImGuiKey_Y}, + {"Z", ImGuiKey_Z}, + {"0", ImGuiKey_0}, + {"1", ImGuiKey_1}, + {"2", ImGuiKey_2}, + {"3", ImGuiKey_3}, + {"4", ImGuiKey_4}, + {"5", ImGuiKey_5}, + {"6", ImGuiKey_6}, + {"7", ImGuiKey_7}, + {"8", ImGuiKey_8}, + {"9", ImGuiKey_9}, + {"Num0", ImGuiKey_Keypad0}, + {"Num1", ImGuiKey_Keypad1}, + {"Num2", ImGuiKey_Keypad2}, + {"Num3", ImGuiKey_Keypad3}, + {"Num4", ImGuiKey_Keypad4}, + {"Num5", ImGuiKey_Keypad5}, + {"Num6", ImGuiKey_Keypad6}, + {"Num7", ImGuiKey_Keypad7}, + {"Num8", ImGuiKey_Keypad8}, + {"Num9", ImGuiKey_Keypad9}, + {"NumAdd", ImGuiKey_KeypadAdd}, + {"NumSubtract", ImGuiKey_KeypadSubtract}, + {"NumMultiply", ImGuiKey_KeypadMultiply}, + {"NumDivide", ImGuiKey_KeypadDivide}, + {"NumEnter", ImGuiKey_KeypadEnter}, + {"NumDecimal", ImGuiKey_KeypadDecimal}, + {"NumEqual", ImGuiKey_KeypadEqual}, + {"F1", ImGuiKey_F1}, + {"F2", ImGuiKey_F2}, + {"F3", ImGuiKey_F3}, + {"F4", ImGuiKey_F4}, + {"F5", ImGuiKey_F5}, + {"F6", ImGuiKey_F6}, + {"F7", ImGuiKey_F7}, + {"F8", ImGuiKey_F8}, + {"F9", ImGuiKey_F9}, + {"F10", ImGuiKey_F10}, + {"F11", ImGuiKey_F11}, + {"F12", ImGuiKey_F12}, + {"Up", ImGuiKey_UpArrow}, + {"Down", ImGuiKey_DownArrow}, + {"Left", ImGuiKey_LeftArrow}, + {"Right", ImGuiKey_RightArrow}, + {"Space", ImGuiKey_Space}, + {"Enter", ImGuiKey_Enter}, + {"Escape", ImGuiKey_Escape}, + {"Tab", ImGuiKey_Tab}, + {"Backspace", ImGuiKey_Backspace}, + {"Delete", ImGuiKey_Delete}, + {"Insert", ImGuiKey_Insert}, + {"Home", ImGuiKey_Home}, + {"End", ImGuiKey_End}, + {"PageUp", ImGuiKey_PageUp}, + {"PageDown", ImGuiKey_PageDown}, + {"Minus", ImGuiKey_Minus}, + {"Equal", ImGuiKey_Equal}, + {"LeftBracket", ImGuiKey_LeftBracket}, + {"RightBracket", ImGuiKey_RightBracket}, + {"Semicolon", ImGuiKey_Semicolon}, + {"Apostrophe", ImGuiKey_Apostrophe}, + {"Comma", ImGuiKey_Comma}, + {"Period", ImGuiKey_Period}, + {"Slash", ImGuiKey_Slash}, + {"Backslash", ImGuiKey_Backslash}, + {"GraveAccent", ImGuiKey_GraveAccent}, + {"Keypad0", ImGuiKey_Keypad0}, + {"Keypad1", ImGuiKey_Keypad1}, + {"Keypad2", ImGuiKey_Keypad2}, + {"Keypad3", ImGuiKey_Keypad3}, + {"Keypad4", ImGuiKey_Keypad4}, + {"Keypad5", ImGuiKey_Keypad5}, + {"Keypad6", ImGuiKey_Keypad6}, + {"Keypad7", ImGuiKey_Keypad7}, + {"Keypad8", ImGuiKey_Keypad8}, + {"Keypad9", ImGuiKey_Keypad9}, + {"KeypadAdd", ImGuiKey_KeypadAdd}, + {"KeypadSubtract", ImGuiKey_KeypadSubtract}, + {"KeypadMultiply", ImGuiKey_KeypadMultiply}, + {"KeypadDivide", ImGuiKey_KeypadDivide}, + {"KeypadEnter", ImGuiKey_KeypadEnter}, + {"KeypadDecimal", ImGuiKey_KeypadDecimal}, + {"KeypadEqual", ImGuiKey_KeypadEqual}, + {"UpArrow", ImGuiKey_UpArrow}, + {"DownArrow", ImGuiKey_DownArrow}, + {"LeftArrow", ImGuiKey_LeftArrow}, + {"RightArrow", ImGuiKey_RightArrow}, +}; - inline const std::unordered_map MOD_MAP = { - {"Ctrl", ImGuiMod_Ctrl}, - {"Shift", ImGuiMod_Shift}, - {"Alt", ImGuiMod_Alt}, - {"Super", ImGuiMod_Super}, - }; +inline const std::unordered_map MOD_MAP = { + {"Ctrl", ImGuiMod_Ctrl}, + {"Shift", ImGuiMod_Shift}, + {"Alt", ImGuiMod_Alt}, + {"Super", ImGuiMod_Super}, +}; - std::string chord_to_string(ImGuiKeyChord); - ImGuiKeyChord string_to_chord(const std::string&); - bool shortcut(ImGuiKeyChord, ShortcutScope = SCOPE_FOCUSED_SET); +std::string chord_to_string(ImGuiKeyChord); +ImGuiKeyChord string_to_chord(const std::string&); +bool shortcut(ImGuiKeyChord, ShortcutScope = SCOPE_FOCUSED_SET); diff --git a/src/ui/sounds.cpp b/src/ui/sounds.cpp index 4e944a9..d57baa6 100644 --- a/src/ui/sounds.cpp +++ b/src/ui/sounds.cpp @@ -4,127 +4,118 @@ #include "path.h" - constexpr int SOUND_CARD_LINES = 2; +constexpr int SOUND_CARD_LINES = 2; - static auto& sounds_get(Model& model) { return model.content.sounds; } +static auto& sounds_get(Model& model) +{ + return model.content.sounds; +} - void sounds_update(Panel& panel) - { +void sounds_update(Panel& panel) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& sounds = document.model.content.sounds; auto selection = document.selected_ids_get(SelectionKind::SOUNDS); if (dialog.is_selected(Dialog::SOUND_OPEN)) { - command_push(panel, - [&state, paths = dialog.paths](Document& document) - { - document.sounds_add(paths); - state.newId = document.focused_id_get(SelectionKind::SOUNDS); - }); - dialog.reset(); + command_push(panel, [&state, paths = dialog.paths](Document& document) { + document.sounds_add(paths); + state.newId = document.focused_id_get(SelectionKind::SOUNDS); + }); + dialog.reset(); } if (dialog.is_selected(Dialog::SOUND_REPLACE)) { - if (selection.size() == 1 && !dialog.path.empty()) - command_push(panel, - [id = *selection.begin(), dialogPath = dialog.path](Document& document) - { - if (!item_get(document.model.content.sounds, id)) return; - document.edit_apply(EDIT_REPLACE_SOUND, - [&](Model& model) - { - auto sound = item_get(model.content.sounds, id); - sound->path = asset_path_get(document, dialogPath); - document.sound_reload(id); - toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, - path_to_utf8(sound->path)); - }); - }); - dialog.reset(); + if (selection.size() == 1 && !dialog.path.empty()) + command_push(panel, [id = *selection.begin(), dialogPath = dialog.path](Document& document) { + if (!item_get(document.model.content.sounds, id)) + return; + document.edit_apply(EDIT_REPLACE_SOUND, [&](Model& model) { + auto sound = item_get(model.content.sounds, id); + sound->path = asset_path_get(document, dialogPath); + document.sound_reload(id); + toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, path_to_utf8(sound->path)); + }); + }); + dialog.reset(); } if (ImGui::Begin(localize.get(LABEL_SOUNDS_WINDOW), &settings.windowIsSounds)) { - auto isOne = [selection]() { return selection.size() == 1; }; - auto play = [&](int id) - { - if (auto audio = document.sound_get(id)) audio_play(*audio); - }; - auto open = [&](int id) - { - if (auto sound = item_get(sounds, id)) directory_open(dialog, document, sound->path); - }; + auto isOne = [selection]() { + return selection.size() == 1; + }; + auto play = [&](int id) { + if (auto audio = document.sound_get(id)) + audio_play(*audio); + }; + auto open = [&](int id) { + if (auto sound = item_get(sounds, id)) + directory_open(dialog, document, sound->path); + }; - Actions actions = {}; - actions.add(ACTION_PLAY, isOne, [&]() { play(*selection.begin()); }, STRING_UNDEFINED, -1); - actions.add(ACTION_OPEN_DIRECTORY, isOne, [&]() { open(*selection.begin()); }); - actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::SOUND_OPEN, true); }, TOOLTIP_SOUND_ADD); - content_remove_action_add(actions, panel, ElementType::SOUND_ELEMENT, SelectionKind::SOUNDS); - actions.add( - ACTION_RELOAD, [selection]() { return !selection.empty(); }, - [&]() - { - command_push(panel, - [selection](Document& document) - { - document.edit_apply(EDIT_RELOAD_SOUNDS, - [&](Model& model) - { - for (auto id : selection) - if (auto sound = item_get(model.content.sounds, id)) - { - document.sound_reload(id); - toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, - path_to_utf8(sound->path)); - } - }); - }); - }, - TOOLTIP_RELOAD_SOUNDS); - actions.add(ACTION_REPLACE, isOne, [&]() { dialog.file_open(Dialog::SOUND_REPLACE); }, TOOLTIP_REPLACE_SOUND); - items_clipboard_actions_add(actions, panel, SelectionKind::SOUNDS, TOAST_SOUNDS_PASTE, - TOAST_SOUNDS_DESERIALIZE_ERROR, sounds_get); + Actions actions = {}; + actions.add(ACTION_PLAY, isOne, [&]() { play(*selection.begin()); }, STRING_UNDEFINED, -1); + actions.add(ACTION_OPEN_DIRECTORY, isOne, [&]() { open(*selection.begin()); }); + actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::SOUND_OPEN, true); }, TOOLTIP_SOUND_ADD); + content_remove_action_add(actions, panel, ElementType::SOUND_ELEMENT, SelectionKind::SOUNDS); + actions.add( + ACTION_RELOAD, [selection]() { return !selection.empty(); }, + [&]() { + command_push(panel, [selection](Document& document) { + document.edit_apply(EDIT_RELOAD_SOUNDS, [&](Model& model) { + for (auto id : selection) + if (auto sound = item_get(model.content.sounds, id)) + { + document.sound_reload(id); + toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, path_to_utf8(sound->path)); + } + }); + }); + }, + TOOLTIP_RELOAD_SOUNDS); + actions.add(ACTION_REPLACE, isOne, [&]() { dialog.file_open(Dialog::SOUND_REPLACE); }, TOOLTIP_REPLACE_SOUND); + items_clipboard_actions_add(actions, panel, SelectionKind::SOUNDS, TOAST_SOUNDS_PASTE, + TOAST_SOUNDS_DESERIALIZE_ERROR, sounds_get); - ListRows rows{.label_get = - [&](int id) - { - auto pathString = path_to_utf8(item_get(sounds, id)->path); - return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); - }, - .tooltip_draw = - [&](int id) - { - auto audio = document.sound_get(id); - tooltip_name_draw(resources, path_to_utf8(item_get(sounds, id)->path)); - ImGui::Text("%s: %d", localize.get(BASIC_ID), id); - if (audio && audio->is_valid()) - ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); - else - { - ImGui::Spacing(); - ImGui::TextWrapped("%s", localize.get(TOOLTIP_SOUND_INVALID)); - } - }, - .image_get = - [&](int id) - { - auto audio = document.sound_get(id); - auto isValid = audio && audio->is_valid(); - auto& texture = resources.icons[isValid ? ICON_SOUND : ICON_NONE]; - return CardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; - }, - .select = - [&](int id) - { - if (id != -1 && ImGui::IsItemClicked(ImGuiMouseButton_Left)) play(id); - }, - .activate = open, - .cardLines = SOUND_CARD_LINES}; - list_panel_draw( - panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD, ACTION_REPLACE}}, - [&]() { content_list_draw(panel, SelectionKind::SOUNDS, item_ids_get(sounds), rows); }, true); + ListRows rows{.label_get = + [&](int id) { + auto pathString = path_to_utf8(item_get(sounds, id)->path); + return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); + }, + .tooltip_draw = + [&](int id) { + auto audio = document.sound_get(id); + tooltip_name_draw(resources, path_to_utf8(item_get(sounds, id)->path)); + ImGui::Text("%s: %d", localize.get(BASIC_ID), id); + if (audio && audio->is_valid()) + ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); + else + { + ImGui::Spacing(); + ImGui::TextWrapped("%s", localize.get(TOOLTIP_SOUND_INVALID)); + } + }, + .image_get = + [&](int id) { + auto audio = document.sound_get(id); + auto isValid = audio && audio->is_valid(); + auto& texture = resources.icons[isValid ? ICON_SOUND : ICON_NONE]; + return CardImage{ + .texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; + }, + .select = + [&](int id) { + if (id != -1 && ImGui::IsItemClicked(ImGuiMouseButton_Left)) + play(id); + }, + .activate = open, + .cardLines = SOUND_CARD_LINES}; + list_panel_draw( + panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD, ACTION_REPLACE}}, + [&]() { content_list_draw(panel, SelectionKind::SOUNDS, item_ids_get(sounds), rows); }, true); } ImGui::End(); - } +} diff --git a/src/ui/spritesheet_editor.cpp b/src/ui/spritesheet_editor.cpp index f6b8312..574fca1 100644 --- a/src/ui/spritesheet_editor.cpp +++ b/src/ui/spritesheet_editor.cpp @@ -21,8 +21,8 @@ using namespace glm; - void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources& resources) - { +void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources& resources) +{ isFocused = false; auto& document = *manager.get(); @@ -51,485 +51,504 @@ using namespace glm; auto regionReference = document.focused_id_get(SelectionKind::REGIONS); auto regionSelection = document.selected_ids_get(SelectionKind::REGIONS); - auto center_view = [&]() { pan = -size * 0.5f; }; - - auto fit_view = [&]() - { - auto fitTexture = baseTexture && baseTexture->is_valid() ? baseTexture : texture; - if (fitTexture && fitTexture->is_valid()) - set_to_rect(zoom, pan, {0, 0, (float)fitTexture->size.x, (float)fitTexture->size.y}); + auto center_view = [&]() { + pan = -size * 0.5f; }; - auto region_get = [&](int id) { return spritesheet ? item_get(spritesheet->regions, id) : nullptr; }; + auto fit_view = [&]() { + auto fitTexture = baseTexture && baseTexture->is_valid() ? baseTexture : texture; + if (fitTexture && fitTexture->is_valid()) + set_to_rect(zoom, pan, {0, 0, (float)fitTexture->size.x, (float)fitTexture->size.y}); + }; + + auto region_get = [&](int id) { + return spritesheet ? item_get(spritesheet->regions, id) : nullptr; + }; if (ImGui::Begin(localize.get(LABEL_SPRITESHEET_EDITOR_WINDOW), &settings.windowIsSpritesheetEditor)) { - isFocused = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); + isFocused = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); - auto childSize = ImVec2(row_widget_width_get(3), - (ImGui::GetTextLineHeightWithSpacing() * 4) + (ImGui::GetStyle().WindowPadding.y * 2)); + auto childSize = ImVec2(row_widget_width_get(3), + (ImGui::GetTextLineHeightWithSpacing() * 4) + (ImGui::GetStyle().WindowPadding.y * 2)); - grid_child_draw(childSize, isGrid, gridColor, gridSize, gridOffset, &isGridSnap); + grid_child_draw(childSize, isGrid, gridColor, gridSize, gridOffset, &isGridSnap); - ImGui::SameLine(); + ImGui::SameLine(); - if (ImGui::BeginChild("##View Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) - { - ImGui::InputFloat(localize.get(BASIC_ZOOM), &zoom, 0.0f, 0.0f, "%.0f%%"); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EDITOR_ZOOM)); - - view_buttons_draw(manager, settings, center_view, fit_view); - - auto mousePosInt = ivec2(mousePos); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_POSITION_SPACED), std::make_format_args(mousePosInt.x, mousePosInt.y)) - .c_str()); - } - ImGui::EndChild(); - - ImGui::SameLine(); - - if (ImGui::BeginChild("##Background Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) - { - auto subChildSize = ImVec2(row_widget_width_get(2), ImGui::GetContentRegionAvail().y); - - if (ImGui::BeginChild("##Background Child 1", subChildSize)) + if (ImGui::BeginChild("##View Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) { - ImGui::BeginDisabled(isTransparent); - { - ImGui::ColorEdit3(localize.get(LABEL_BACKGROUND_COLOR), value_ptr(backgroundColor), - ImGuiColorEditFlags_NoInputs); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BACKGROUND_COLOR)); - } - ImGui::EndDisabled(); + ImGui::InputFloat(localize.get(BASIC_ZOOM), &zoom, 0.0f, 0.0f, "%.0f%%"); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EDITOR_ZOOM)); - ImGui::Checkbox(localize.get(LABEL_BORDER), &isBorder); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SPRITESHEET_BORDER)); + view_buttons_draw(manager, settings, center_view, fit_view); + + auto mousePosInt = ivec2(mousePos); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_POSITION_SPACED), std::make_format_args(mousePosInt.x, mousePosInt.y)) + .c_str()); } ImGui::EndChild(); ImGui::SameLine(); - if (ImGui::BeginChild("##Background Child 2", subChildSize)) + if (ImGui::BeginChild("##Background Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar)) { - ImGui::Checkbox(localize.get(LABEL_TRANSPARENT), &isTransparent); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRANSPARENT)); - } + auto subChildSize = ImVec2(row_widget_width_get(2), ImGui::GetContentRegionAvail().y); + if (ImGui::BeginChild("##Background Child 1", subChildSize)) + { + ImGui::BeginDisabled(isTransparent); + { + ImGui::ColorEdit3(localize.get(LABEL_BACKGROUND_COLOR), value_ptr(backgroundColor), + ImGuiColorEditFlags_NoInputs); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BACKGROUND_COLOR)); + } + ImGui::EndDisabled(); + + ImGui::Checkbox(localize.get(LABEL_BORDER), &isBorder); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SPRITESHEET_BORDER)); + } + ImGui::EndChild(); + + ImGui::SameLine(); + + if (ImGui::BeginChild("##Background Child 2", subChildSize)) + { + ImGui::Checkbox(localize.get(LABEL_TRANSPARENT), &isTransparent); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRANSPARENT)); + } + + ImGui::EndChild(); + } ImGui::EndChild(); - } - ImGui::EndChild(); - auto drawList = ImGui::GetCurrentWindow()->DrawList; - size_set(to_vec2(ImGui::GetContentRegionAvail())); + auto drawList = ImGui::GetCurrentWindow()->DrawList; + size_set(to_vec2(ImGui::GetContentRegionAvail())); - auto cursorScreenPos = ImGui::GetCursorScreenPos(); - auto min = ImGui::GetCursorScreenPos(); - auto max = to_imvec2(to_vec2(min) + size); + auto cursorScreenPos = ImGui::GetCursorScreenPos(); + auto min = ImGui::GetCursorScreenPos(); + auto max = to_imvec2(to_vec2(min) + size); - hoveredRegionId = -1; - if (is_canvas_hovered(min, max)) - { - auto input = canvas_input_get(manager, isFocused); - auto isMouseClicked = input.isLeftClicked || input.isRightClicked; - auto isMouseDown = input.isLeftDown || input.isRightDown; - auto isBegin = isMouseClicked || input.isArrowBegin; - auto isDuring = isMouseDown || input.isArrowDown; - auto isEnd = input.isLeftReleased || input.isRightReleased || input.isArrowEnd; - auto arrow = input.arrow * input.step; - auto gridArrow = isGridSnap ? arrow * vec2(gridSize) : arrow; - auto isArrow = arrow != vec2(); - - auto selectedFrameReferences = document.frame_references_get(); - std::erase_if(selectedFrameReferences, - [](const Reference& frameReference) { return frameReference.itemType != LAYER; }); - auto editReference = reference; - if (!selectedFrameReferences.contains(reference) && !selectedFrameReferences.empty()) - editReference = *selectedFrameReferences.begin(); - auto frame = model.frame_get(editReference); - auto layer = item_get(model.content.layers, editReference.itemID); - bool isReferenceLayerOnSpritesheet = - frame && editReference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; - if (selectedFrameReferences.empty() && isReferenceLayerOnSpritesheet) - selectedFrameReferences.insert(editReference); - previousMousePos = mousePos; - mousePos = position_translate(zoom, pan, to_ivec2(ImGui::GetMousePos()) - to_ivec2(cursorScreenPos)); - - auto pivot_snap = [&](vec2 value, vec2 current) - { return isGridSnap ? vec2(ivec2(value)) : glm::floor(value) + (current - glm::floor(current)); }; - // Region edits apply to the given regions of the edited spritesheet when the command runs. - auto regions_update = [&](std::set ids, std::function update) + hoveredRegionId = -1; + if (is_canvas_hovered(min, max)) { - manager.command_push( - {manager.selected, [=, spritesheetId = referenceSpritesheet](Manager&, Document& document) - { - auto spritesheet = item_get(document.model.content.spritesheets, spritesheetId); - for (auto id : ids) - if (auto region = spritesheet ? item_get(spritesheet->regions, id) : nullptr) update(*region); - }}); - }; - auto region_pivot_update = [&](std::function pivot_get) - { - regions_update({regionReference}, - [=](Region& region) - { - region.origin = Origin::CUSTOM; - region.pivot = pivot_get(region.pivot); - }); - }; + auto input = canvas_input_get(manager, isFocused); + auto isMouseClicked = input.isLeftClicked || input.isRightClicked; + auto isMouseDown = input.isLeftDown || input.isRightDown; + auto isBegin = isMouseClicked || input.isArrowBegin; + auto isDuring = isMouseDown || input.isArrowDown; + auto isEnd = input.isLeftReleased || input.isRightReleased || input.isArrowEnd; + auto arrow = input.arrow * input.step; + auto gridArrow = isGridSnap ? arrow * vec2(gridSize) : arrow; + auto isArrow = arrow != vec2(); - auto useTool = (Tool)tool; - if (input.isMiddleDown) useTool = TOOL_PAN; - if (tool == TOOL_MOVE && input.isRightDown) useTool = TOOL_CROP; - if (tool == TOOL_CROP && input.isRightDown) useTool = TOOL_MOVE; - if (tool == TOOL_DRAW && input.isRightDown) useTool = TOOL_ERASE; - if (tool == TOOL_ERASE && input.isRightDown) useTool = TOOL_DRAW; + auto selectedFrameReferences = document.frame_references_get(); + std::erase_if(selectedFrameReferences, + [](const Reference& frameReference) { return frameReference.itemType != LAYER; }); + auto editReference = reference; + if (!selectedFrameReferences.contains(reference) && !selectedFrameReferences.empty()) + editReference = *selectedFrameReferences.begin(); + auto frame = model.frame_get(editReference); + auto layer = item_get(model.content.layers, editReference.itemID); + bool isReferenceLayerOnSpritesheet = + frame && editReference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; + if (selectedFrameReferences.empty() && isReferenceLayerOnSpritesheet) + selectedFrameReferences.insert(editReference); + previousMousePos = mousePos; + mousePos = position_translate(zoom, pan, to_ivec2(ImGui::GetMousePos()) - to_ivec2(cursorScreenPos)); - if (useTool == TOOL_PAN && spritesheet && texture && texture->is_valid()) - for (auto& region : spritesheet->regions) - { - auto minPoint = glm::min(region.crop, region.crop + region.size); - auto maxPoint = glm::max(region.crop, region.crop + region.size); - if (glm::all(glm::greaterThanEqual(mousePos, minPoint)) && glm::all(glm::lessThanEqual(mousePos, maxPoint))) + auto pivot_snap = [&](vec2 value, vec2 current) { + return isGridSnap ? vec2(ivec2(value)) : glm::floor(value) + (current - glm::floor(current)); + }; + // Region edits apply to the given regions of the edited spritesheet when the command runs. + auto regions_update = [&](std::set ids, std::function update) { + manager.command_push( + {manager.selected, [=, spritesheetId = referenceSpritesheet](Manager&, Document& document) { + auto spritesheet = item_get(document.model.content.spritesheets, spritesheetId); + for (auto id : ids) + if (auto region = spritesheet ? item_get(spritesheet->regions, id) : nullptr) + update(*region); + }}); + }; + auto region_pivot_update = [&](std::function pivot_get) { + regions_update({regionReference}, [=](Region& region) { + region.origin = Origin::CUSTOM; + region.pivot = pivot_get(region.pivot); + }); + }; + + auto useTool = (Tool)tool; + if (input.isMiddleDown) + useTool = TOOL_PAN; + if (tool == TOOL_MOVE && input.isRightDown) + useTool = TOOL_CROP; + if (tool == TOOL_CROP && input.isRightDown) + useTool = TOOL_MOVE; + if (tool == TOOL_DRAW && input.isRightDown) + useTool = TOOL_ERASE; + if (tool == TOOL_ERASE && input.isRightDown) + useTool = TOOL_DRAW; + + if (useTool == TOOL_PAN && spritesheet && texture && texture->is_valid()) + for (auto& region : spritesheet->regions) + { + auto minPoint = glm::min(region.crop, region.crop + region.size); + auto maxPoint = glm::max(region.crop, region.crop + region.size); + if (glm::all(glm::greaterThanEqual(mousePos, minPoint)) && + glm::all(glm::lessThanEqual(mousePos, maxPoint))) + { + hoveredRegionId = region.id; + break; + } + } + + // Crop and pivot edit regions while a region is the edit target, or a frame's region is in use. + auto isRegionEditTarget = document.editTarget == Document::EditTarget::REGION; + auto toolFrames = isRegionEditTarget ? std::set{} : selectedFrameReferences; + bool isRegionInUse = !isRegionEditTarget && toolFrames.size() <= 1 && frame && frame->regionId != -1 && + (useTool == TOOL_CROP || useTool == TOOL_MOVE); + auto isRegionTool = isRegionEditTarget || isRegionInUse || toolFrames.empty(); + auto isFrameTool = frame && !toolFrames.empty() && !isRegionInUse; + bool isFrameAvailable = isFrameTool || (useTool == TOOL_CROP && !regionSelection.empty()) || + (useTool == TOOL_MOVE && regionReference != -1); + auto frames_change = [&](FrameChange change, ChangeType type = ChangeType::ADJUST) { + frames_change_push(manager, toolFrames, change, type); + }; + + tool_cursor_update(useTool, TOOL_AREA_SPRITESHEET_EDITOR, isFrameAvailable, texture && texture->is_valid(), + isMouseDown || input.isArrowDown, + isRegionInUse ? TEXT_REGION_IN_USE + : useTool == TOOL_CROP ? TEXT_SELECT_FRAME_OR_REGION + : TEXT_SELECT_FRAME); + + if (useTool == TOOL_PAN) { - hoveredRegionId = region.id; - break; + if (input.isLeftClicked && hoveredRegionId != -1) + { + document.editTarget = Document::EditTarget::REGION; + regionReference = hoveredRegionId; + regionSelection = {hoveredRegionId}; + document.selected_ids_set(SelectionKind::REGIONS, regionSelection); + document.focused_id_set(SelectionKind::REGIONS, hoveredRegionId); + if (auto region = region_get(hoveredRegionId); region && isReferenceLayerOnSpritesheet) + { + edit_begin_push(manager, EDIT_FRAME_REGION); + frames_change_push(manager, selectedFrameReferences, + {.regionId = hoveredRegionId, + .cropX = region->crop.x, + .cropY = region->crop.y, + .sizeX = region->size.x, + .sizeY = region->size.y, + .pivotX = region->pivot.x, + .pivotY = region->pivot.y}); + document_change_push(manager); + } + } + if (isMouseDown || input.isMiddleDown) + pan += input.mouseDelta; } - } - // Crop and pivot edit regions while a region is the edit target, or a frame's region is in use. - auto isRegionEditTarget = document.editTarget == Document::EditTarget::REGION; - auto toolFrames = isRegionEditTarget ? std::set{} : selectedFrameReferences; - bool isRegionInUse = !isRegionEditTarget && toolFrames.size() <= 1 && frame && frame->regionId != -1 && - (useTool == TOOL_CROP || useTool == TOOL_MOVE); - auto isRegionTool = isRegionEditTarget || isRegionInUse || toolFrames.empty(); - auto isFrameTool = frame && !toolFrames.empty() && !isRegionInUse; - bool isFrameAvailable = isFrameTool || (useTool == TOOL_CROP && !regionSelection.empty()) || - (useTool == TOOL_MOVE && regionReference != -1); - auto frames_change = [&](FrameChange change, ChangeType type = ChangeType::ADJUST) - { frames_change_push(manager, toolFrames, change, type); }; - - tool_cursor_update(useTool, TOOL_AREA_SPRITESHEET_EDITOR, isFrameAvailable, texture && texture->is_valid(), - isMouseDown || input.isArrowDown, - isRegionInUse ? TEXT_REGION_IN_USE - : useTool == TOOL_CROP ? TEXT_SELECT_FRAME_OR_REGION - : TEXT_SELECT_FRAME); - - if (useTool == TOOL_PAN) - { - if (input.isLeftClicked && hoveredRegionId != -1) - { - document.editTarget = Document::EditTarget::REGION; - regionReference = hoveredRegionId; - regionSelection = {hoveredRegionId}; - document.selected_ids_set(SelectionKind::REGIONS, regionSelection); - document.focused_id_set(SelectionKind::REGIONS, hoveredRegionId); - if (auto region = region_get(hoveredRegionId); region && isReferenceLayerOnSpritesheet) + auto region = isRegionTool ? region_get(regionReference) : nullptr; + if (useTool == TOOL_MOVE && region) { - edit_begin_push(manager, EDIT_FRAME_REGION); - frames_change_push(manager, selectedFrameReferences, - {.regionId = hoveredRegionId, - .cropX = region->crop.x, - .cropY = region->crop.y, - .sizeX = region->size.x, - .sizeY = region->size.y, - .pivotX = region->pivot.x, - .pivotY = region->pivot.y}); - document_change_push(manager); + if (isBegin) + edit_begin_push(manager, EDIT_REGION_MOVE); + if (isMouseDown) + region_pivot_update( + [pivot = pivot_snap(mousePos - region->crop, region->pivot)](vec2) { return pivot; }); + if (isArrow) + region_pivot_update( + [=, this](vec2 pivot) { return isGridSnap ? vec2(ivec2(pivot + arrow)) : pivot + arrow; }); + if (isDuring) + tooltip_lines_draw({localize_format(FORMAT_PIVOT, region->pivot.x, region->pivot.y)}); + if (isEnd) + document_change_push(manager); + } + else if (useTool == TOOL_MOVE && isFrameTool) + { + if (isBegin) + edit_begin_push(manager, EDIT_FRAME_PIVOT); + if (isMouseDown) + { + auto pivot = pivot_snap(mousePos - frame->crop, frame->pivot); + frames_change({.regionId = -1, .pivotX = pivot.x, .pivotY = pivot.y}); + } + if (isArrow) + frames_change({.regionId = -1, .pivotX = arrow.x, .pivotY = arrow.y}, ChangeType::ADD); + if (isDuring) + tooltip_lines_draw({localize_format(FORMAT_PIVOT, frame->pivot.x, frame->pivot.y)}); + if (isEnd) + document_change_push(manager); + } + + auto isRegionCrop = isRegionTool && !regionSelection.empty() && spritesheet; + if (useTool == TOOL_CROP && (isRegionCrop || isFrameTool)) + { + if (isBegin) + edit_begin_push(manager, isRegionCrop ? EDIT_REGION_CROP : EDIT_FRAME_CROP); + auto rect_set = [&](vec2 crop, vec2 cropSize) { + if (isRegionCrop) + regions_update(regionSelection, [=](Region& region) { + region.crop = crop; + region.size = cropSize; + }); + else + frames_change({.regionId = -1, + .cropX = crop.x, + .cropY = crop.y, + .sizeX = cropSize.x, + .sizeY = cropSize.y}); + }; + if (isMouseClicked) + { + cropAnchor = mousePos; + auto crop = vec2(ivec2(cropAnchor)); + if (isRegionCrop) + rect_set(crop, vec2()); + else + frames_change({.regionId = -1, .cropX = crop.x, .cropY = crop.y}); + } + if (isMouseDown) + { + auto [minPoint, maxPoint] = rect_snap(cropAnchor, mousePos, isGridSnap, gridSize, gridOffset); + rect_set(minPoint, maxPoint - minPoint); + } + if (isArrow && isRegionCrop) + regions_update(regionSelection, [=](Region& region) { + region.crop = vec2(ivec2(region.crop + gridArrow)); + region.size = vec2(ivec2(region.size)); + }); + else if (isArrow) + frames_change({.regionId = -1, .cropX = gridArrow.x, .cropY = gridArrow.y}, ChangeType::ADD); + + // Arrow nudges are snapped (and the rectangle normalized) when the command runs, after the nudge. + if (isDuring && !isMouseDown && isRegionCrop) + regions_update(regionSelection, [=, this](Region& region) { + auto [minPoint, maxPoint] = + rect_snap(region.crop, region.crop + region.size, isGridSnap, gridSize, gridOffset); + region.crop = minPoint; + region.size = maxPoint - minPoint; + }); + else if (isDuring && !isMouseDown) + manager.command_push({manager.selected, [=, this](Manager&, Document& document) { + auto source = document.model.frame_get(editReference); + if (!source) + return; + auto [minPoint, maxPoint] = + rect_snap(source->crop, source->crop + source->size, isGridSnap, + gridSize, gridOffset); + frames_change_apply(document.model, {.references = toolFrames}, + {.regionId = -1, + .cropX = minPoint.x, + .cropY = minPoint.y, + .sizeX = maxPoint.x - minPoint.x, + .sizeY = maxPoint.y - minPoint.y}, + ChangeType::ADJUST); + }}); + + auto shown = isRegionCrop ? region_get(*regionSelection.begin()) : nullptr; + auto crop = shown ? shown->crop : frame ? frame->crop : vec2(); + auto cropSize = shown ? shown->size : frame ? frame->size : vec2(); + if (isDuring && (shown || !isRegionCrop)) + tooltip_lines_draw({localize_format(FORMAT_CROP, crop.x, crop.y), + localize_format(FORMAT_SIZE, cropSize.x, cropSize.y)}); + if (isEnd) + document_change_push(manager); + } + + auto isDrawTool = useTool == TOOL_DRAW || useTool == TOOL_ERASE; + if (isDrawTool && texture && texture->is_vector()) + { + ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); + if (isMouseDown) + tooltip_lines_draw({localize.get(TEXT_SVG_NOT_EDITABLE)}); + } + else if (isDrawTool && texture) + { + if (isMouseClicked) + edit_begin_push(manager, useTool == TOOL_DRAW ? EDIT_DRAW : EDIT_ERASE); + if (isMouseDown) + manager.command_push( + {manager.selected, [start = ivec2(previousMousePos), end = ivec2(mousePos), + color = useTool == TOOL_DRAW ? toolColor : vec4(), + spritesheetId = referenceSpritesheet](Manager&, Document& document) { + if (auto texture = document.texture_edit(spritesheetId)) + texture->pixel_line(start, end, color); + }}); + if (input.isLeftReleased || input.isRightReleased) + manager.command_push( + {manager.selected, [spritesheetId = referenceSpritesheet](Manager&, Document& document) { + document.texture_change(spritesheetId); + }}); + } + + if (useTool == TOOL_COLOR_PICKER && texture && isDuring) + { + toolColor = texture->pixel_read(mousePos); + if (ImGui::BeginTooltip()) + { + ImGui::ColorButton("##Color Picker Button", to_imvec4(toolColor)); + ImGui::SameLine(); + auto rgba8 = glm::clamp(ivec4(toolColor * 255.0f + 0.5f), ivec4(0), ivec4(255)); + ImGui::TextUnformatted( + std::format("#{:02X}{:02X}{:02X}{:02X}", rgba8.r, rgba8.g, rgba8.b, rgba8.a).c_str()); + ImGui::SameLine(); + ImGui::Text("(%d, %d, %d, %d)", rgba8.r, rgba8.g, rgba8.b, rgba8.a); + ImGui::EndTooltip(); + } + } + + if (tool == TOOL_PAN && hoveredRegionId != -1 && spritesheet) + if (auto region = region_get(hoveredRegionId); region && ImGui::BeginTooltip()) + { + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); + ImGui::TextUnformatted(region->name.c_str()); + ImGui::PopFont(); + auto originLabel = localize.get(region->origin == Origin::TOP_LEFT ? LABEL_REGION_ORIGIN_TOP_LEFT + : LABEL_REGION_ORIGIN_CENTER); + for (auto& line : {localize_format(FORMAT_ID, hoveredRegionId), + localize_format(FORMAT_CROP, region->crop.x, region->crop.y), + localize_format(FORMAT_SIZE, region->size.x, region->size.y), + region->origin == Origin::CUSTOM + ? localize_format(FORMAT_PIVOT, region->pivot.x, region->pivot.y) + : localize_format(FORMAT_ORIGIN, originLabel)}) + ImGui::TextUnformatted(line.c_str()); + ImGui::EndTooltip(); + } + + if (input.wheel != 0 || input.isZoomIn || input.isZoomOut) + { + auto focus = input.wheel != 0 ? vec2(mousePos) : texture ? vec2(texture->size) / 2.0f : vec2(); + zoom_step(zoom, pan, focus, (input.wheel > 0 || input.isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP); } - } - if (isMouseDown || input.isMiddleDown) pan += input.mouseDelta; } - auto region = isRegionTool ? region_get(regionReference) : nullptr; - if (useTool == TOOL_MOVE && region) + bind(); + viewport_set(); + clear(isTransparent ? vec4(0) : vec4(backgroundColor, 1.0f)); + + auto frame = model.frame_get(reference); + + auto viewTexture = baseTexture && baseTexture->is_valid() ? baseTexture : texture; + + if (spritesheet && viewTexture && viewTexture->is_valid()) { - if (isBegin) edit_begin_push(manager, EDIT_REGION_MOVE); - if (isMouseDown) - region_pivot_update([pivot = pivot_snap(mousePos - region->crop, region->pivot)](vec2) { return pivot; }); - if (isArrow) - region_pivot_update([=, this](vec2 pivot) - { return isGridSnap ? vec2(ivec2(pivot + arrow)) : pivot + arrow; }); - if (isDuring) tooltip_lines_draw({localize_format(FORMAT_PIVOT, region->pivot.x, region->pivot.y)}); - if (isEnd) document_change_push(manager); - } - else if (useTool == TOOL_MOVE && isFrameTool) - { - if (isBegin) edit_begin_push(manager, EDIT_FRAME_PIVOT); - if (isMouseDown) - { - auto pivot = pivot_snap(mousePos - frame->crop, frame->pivot); - frames_change({.regionId = -1, .pivotX = pivot.x, .pivotY = pivot.y}); - } - if (isArrow) frames_change({.regionId = -1, .pivotX = arrow.x, .pivotY = arrow.y}, ChangeType::ADD); - if (isDuring) tooltip_lines_draw({localize_format(FORMAT_PIVOT, frame->pivot.x, frame->pivot.y)}); - if (isEnd) document_change_push(manager); + auto transform = transform_get(zoom, pan); + + auto spritesheetModel = quad_model_get(viewTexture->size); + auto spritesheetTransform = transform * spritesheetModel; + + if (baseTexture && baseTexture->is_valid()) + texture_render(shaderTexture, + texture_id_get(*document.vector_image_get(baseTexture, percent_to_unit(zoom))), + spritesheetTransform); + + if (isGrid) + grid_render(shaderGrid, zoom, pan, gridSize, gridOffset, gridColor); + + if (isBorder) + rect_render(dashedShader, spritesheetTransform, spritesheetModel, COLOR_WHITE, BORDER_DASH_LENGTH, + BORDER_DASH_GAP, BORDER_DASH_OFFSET); + + if (hoveredRegionId != -1) + { + if (auto region = region_get(hoveredRegionId)) + { + auto cropModel = quad_model_get(region->size, region->crop); + auto cropTransform = transform * cropModel; + rect_fill_render(shaderLine, cropTransform, cropModel, vec4(1.0f, 1.0f, 1.0f, 0.5f)); + } + } + + auto layer = item_get(model.content.layers, reference.itemID); + bool isReferenceLayerOnSpritesheet = + frame && reference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; + + int highlightedRegionId = -1; + if (document.editTarget == Document::EditTarget::REGION && regionReference != -1 && + region_get(regionReference)) + { + highlightedRegionId = regionReference; + } + else if (isReferenceLayerOnSpritesheet && frame->regionId != -1 && region_get(frame->regionId)) + { + highlightedRegionId = frame->regionId; + } + else if (regionReference != -1 && region_get(regionReference)) + { + highlightedRegionId = regionReference; + } + + auto draw_region_rect = [&](const Region& region, vec4 regionColor) { + auto cropModel = quad_model_get(region.size, region.crop); + auto cropTransform = transform * cropModel; + rect_render(dashedShader, cropTransform, cropModel, regionColor, BORDER_DASH_LENGTH, BORDER_DASH_GAP, + BORDER_DASH_OFFSET); + }; + + for (auto& region : spritesheet->regions) + { + auto id = region.id; + if (id == highlightedRegionId) + continue; + draw_region_rect(region, COLOR_WHITE); + + auto pivotTransform = + transform * quad_model_get(PIVOT_SIZE, region.crop + region.pivot, PIVOT_SIZE * 0.5f); + texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), pivotTransform, COLOR_WHITE); + } + + if (highlightedRegionId != -1) + { + if (auto region = region_get(highlightedRegionId)) + { + draw_region_rect(*region, COLOR_RED); + + auto pivotTransform = + transform * quad_model_get(PIVOT_SIZE, region->crop + region->pivot, PIVOT_SIZE * 0.5f); + texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), pivotTransform, PIVOT_COLOR); + } + } + + bool isFrameOnSpritesheet = isReferenceLayerOnSpritesheet; + if (isFrameOnSpritesheet && frame->regionId == -1) + { + auto frameModel = quad_model_get(frame->size, frame->crop); + auto frameTransform = transform * frameModel; + rect_render(shaderLine, frameTransform, frameModel, COLOR_RED); + + auto pivotTransform = + transform * quad_model_get(PIVOT_SIZE, frame->crop + frame->pivot, PIVOT_SIZE * 0.5f); + texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), pivotTransform, PIVOT_COLOR); + } } - auto isRegionCrop = isRegionTool && !regionSelection.empty() && spritesheet; - if (useTool == TOOL_CROP && (isRegionCrop || isFrameTool)) - { - if (isBegin) edit_begin_push(manager, isRegionCrop ? EDIT_REGION_CROP : EDIT_FRAME_CROP); - auto rect_set = [&](vec2 crop, vec2 cropSize) - { - if (isRegionCrop) - regions_update(regionSelection, - [=](Region& region) - { - region.crop = crop; - region.size = cropSize; - }); - else - frames_change( - {.regionId = -1, .cropX = crop.x, .cropY = crop.y, .sizeX = cropSize.x, .sizeY = cropSize.y}); - }; - if (isMouseClicked) - { - cropAnchor = mousePos; - auto crop = vec2(ivec2(cropAnchor)); - if (isRegionCrop) - rect_set(crop, vec2()); - else - frames_change({.regionId = -1, .cropX = crop.x, .cropY = crop.y}); - } - if (isMouseDown) - { - auto [minPoint, maxPoint] = rect_snap(cropAnchor, mousePos, isGridSnap, gridSize, gridOffset); - rect_set(minPoint, maxPoint - minPoint); - } - if (isArrow && isRegionCrop) - regions_update(regionSelection, - [=](Region& region) - { - region.crop = vec2(ivec2(region.crop + gridArrow)); - region.size = vec2(ivec2(region.size)); - }); - else if (isArrow) - frames_change({.regionId = -1, .cropX = gridArrow.x, .cropY = gridArrow.y}, ChangeType::ADD); + unbind(); - // Arrow nudges are snapped (and the rectangle normalized) when the command runs, after the nudge. - if (isDuring && !isMouseDown && isRegionCrop) - regions_update(regionSelection, - [=, this](Region& region) - { - auto [minPoint, maxPoint] = - rect_snap(region.crop, region.crop + region.size, isGridSnap, gridSize, gridOffset); - region.crop = minPoint; - region.size = maxPoint - minPoint; - }); - else if (isDuring && !isMouseDown) - manager.command_push({manager.selected, [=, this](Manager&, Document& document) - { - auto source = document.model.frame_get(editReference); - if (!source) return; - auto [minPoint, maxPoint] = rect_snap(source->crop, source->crop + source->size, - isGridSnap, gridSize, gridOffset); - frames_change_apply(document.model, {.references = toolFrames}, - {.regionId = -1, - .cropX = minPoint.x, - .cropY = minPoint.y, - .sizeX = maxPoint.x - minPoint.x, - .sizeY = maxPoint.y - minPoint.y}, - ChangeType::ADJUST); - }}); - - auto shown = isRegionCrop ? region_get(*regionSelection.begin()) : nullptr; - auto crop = shown ? shown->crop : frame ? frame->crop : vec2(); - auto cropSize = shown ? shown->size : frame ? frame->size : vec2(); - if (isDuring && (shown || !isRegionCrop)) - tooltip_lines_draw( - {localize_format(FORMAT_CROP, crop.x, crop.y), localize_format(FORMAT_SIZE, cropSize.x, cropSize.y)}); - if (isEnd) document_change_push(manager); - } - - auto isDrawTool = useTool == TOOL_DRAW || useTool == TOOL_ERASE; - if (isDrawTool && texture && texture->is_vector()) - { - ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); - if (isMouseDown) tooltip_lines_draw({localize.get(TEXT_SVG_NOT_EDITABLE)}); - } - else if (isDrawTool && texture) - { - if (isMouseClicked) edit_begin_push(manager, useTool == TOOL_DRAW ? EDIT_DRAW : EDIT_ERASE); - if (isMouseDown) - manager.command_push({manager.selected, [start = ivec2(previousMousePos), end = ivec2(mousePos), - color = useTool == TOOL_DRAW ? toolColor : vec4(), - spritesheetId = referenceSpritesheet](Manager&, Document& document) - { - if (auto texture = document.texture_edit(spritesheetId)) - texture->pixel_line(start, end, color); - }}); - if (input.isLeftReleased || input.isRightReleased) - manager.command_push({manager.selected, [spritesheetId = referenceSpritesheet](Manager&, Document& document) - { document.texture_change(spritesheetId); }}); - } - - if (useTool == TOOL_COLOR_PICKER && texture && isDuring) - { - toolColor = texture->pixel_read(mousePos); - if (ImGui::BeginTooltip()) - { - ImGui::ColorButton("##Color Picker Button", to_imvec4(toolColor)); - ImGui::SameLine(); - auto rgba8 = glm::clamp(ivec4(toolColor * 255.0f + 0.5f), ivec4(0), ivec4(255)); - ImGui::TextUnformatted( - std::format("#{:02X}{:02X}{:02X}{:02X}", rgba8.r, rgba8.g, rgba8.b, rgba8.a).c_str()); - ImGui::SameLine(); - ImGui::Text("(%d, %d, %d, %d)", rgba8.r, rgba8.g, rgba8.b, rgba8.a); - ImGui::EndTooltip(); - } - } - - if (tool == TOOL_PAN && hoveredRegionId != -1 && spritesheet) - if (auto region = region_get(hoveredRegionId); region && ImGui::BeginTooltip()) - { - ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); - ImGui::TextUnformatted(region->name.c_str()); - ImGui::PopFont(); - auto originLabel = localize.get(region->origin == Origin::TOP_LEFT ? LABEL_REGION_ORIGIN_TOP_LEFT - : LABEL_REGION_ORIGIN_CENTER); - for (auto& line : - {localize_format(FORMAT_ID, hoveredRegionId), - localize_format(FORMAT_CROP, region->crop.x, region->crop.y), - localize_format(FORMAT_SIZE, region->size.x, region->size.y), - region->origin == Origin::CUSTOM ? localize_format(FORMAT_PIVOT, region->pivot.x, region->pivot.y) - : localize_format(FORMAT_ORIGIN, originLabel)}) - ImGui::TextUnformatted(line.c_str()); - ImGui::EndTooltip(); - } - - if (input.wheel != 0 || input.isZoomIn || input.isZoomOut) - { - auto focus = input.wheel != 0 ? vec2(mousePos) : texture ? vec2(texture->size) / 2.0f : vec2(); - zoom_step(zoom, pan, focus, (input.wheel > 0 || input.isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP); - } - } - - bind(); - viewport_set(); - clear(isTransparent ? vec4(0) : vec4(backgroundColor, 1.0f)); - - auto frame = model.frame_get(reference); - - auto viewTexture = baseTexture && baseTexture->is_valid() ? baseTexture : texture; - - if (spritesheet && viewTexture && viewTexture->is_valid()) - { - auto transform = transform_get(zoom, pan); - - auto spritesheetModel = quad_model_get(viewTexture->size); - auto spritesheetTransform = transform * spritesheetModel; - - if (baseTexture && baseTexture->is_valid()) - texture_render( - shaderTexture, - texture_id_get(*document.vector_image_get(baseTexture, percent_to_unit(zoom))), - spritesheetTransform); - - if (isGrid) grid_render(shaderGrid, zoom, pan, gridSize, gridOffset, gridColor); - - if (isBorder) - rect_render(dashedShader, spritesheetTransform, spritesheetModel, COLOR_WHITE, BORDER_DASH_LENGTH, - BORDER_DASH_GAP, BORDER_DASH_OFFSET); - - if (hoveredRegionId != -1) - { - if (auto region = region_get(hoveredRegionId)) - { - auto cropModel = quad_model_get(region->size, region->crop); - auto cropTransform = transform * cropModel; - rect_fill_render(shaderLine, cropTransform, cropModel, vec4(1.0f, 1.0f, 1.0f, 0.5f)); - } - } - - auto layer = item_get(model.content.layers, reference.itemID); - bool isReferenceLayerOnSpritesheet = - frame && reference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; - - int highlightedRegionId = -1; - if (document.editTarget == Document::EditTarget::REGION && regionReference != -1 && region_get(regionReference)) - { - highlightedRegionId = regionReference; - } - else if (isReferenceLayerOnSpritesheet && frame->regionId != -1 && region_get(frame->regionId)) - { - highlightedRegionId = frame->regionId; - } - else if (regionReference != -1 && region_get(regionReference)) - { - highlightedRegionId = regionReference; - } - - auto draw_region_rect = [&](const Region& region, vec4 regionColor) - { - auto cropModel = quad_model_get(region.size, region.crop); - auto cropTransform = transform * cropModel; - rect_render(dashedShader, cropTransform, cropModel, regionColor, BORDER_DASH_LENGTH, BORDER_DASH_GAP, - BORDER_DASH_OFFSET); - }; - - for (auto& region : spritesheet->regions) - { - auto id = region.id; - if (id == highlightedRegionId) continue; - draw_region_rect(region, COLOR_WHITE); - - auto pivotTransform = - transform * quad_model_get(PIVOT_SIZE, region.crop + region.pivot, PIVOT_SIZE * 0.5f); - texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), pivotTransform, COLOR_WHITE); - } - - if (highlightedRegionId != -1) - { - if (auto region = region_get(highlightedRegionId)) - { - draw_region_rect(*region, COLOR_RED); - - auto pivotTransform = - transform * quad_model_get(PIVOT_SIZE, region->crop + region->pivot, PIVOT_SIZE * 0.5f); - texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), pivotTransform, PIVOT_COLOR); - } - } - - bool isFrameOnSpritesheet = isReferenceLayerOnSpritesheet; - if (isFrameOnSpritesheet && frame->regionId == -1) - { - auto frameModel = quad_model_get(frame->size, frame->crop); - auto frameTransform = transform * frameModel; - rect_render(shaderLine, frameTransform, frameModel, COLOR_RED); - - auto pivotTransform = - transform * quad_model_get(PIVOT_SIZE, frame->crop + frame->pivot, PIVOT_SIZE * 0.5f); - texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), pivotTransform, PIVOT_COLOR); - } - } - - unbind(); - - checker_pan_sync(zoom, pan); - if (isTransparent) - render_checker_background(drawList, min, max, -size * 0.5f - checkerPan, CHECKER_SIZE); - else - drawList->AddRectFilled(min, max, ImGui::GetColorU32(to_imvec4(vec4(backgroundColor, 1.0f)))); - image_premultiplied_draw(this->texture, to_imvec2(size)); + checker_pan_sync(zoom, pan); + if (isTransparent) + render_checker_background(drawList, min, max, -size * 0.5f - checkerPan, CHECKER_SIZE); + else + drawList->AddRectFilled(min, max, ImGui::GetColorU32(to_imvec4(vec4(backgroundColor, 1.0f)))); + image_premultiplied_draw(this->texture, to_imvec2(size)); } if (tool == TOOL_PAN) - view_context_menu_draw("##Spritesheet Editor Context Menu", manager, settings, document, zoom, pan, center_view, - fit_view, (baseTexture && baseTexture->is_valid()) || (texture && texture->is_valid())); + view_context_menu_draw("##Spritesheet Editor Context Menu", manager, settings, document, zoom, pan, center_view, + fit_view, (baseTexture && baseTexture->is_valid()) || (texture && texture->is_valid())); if (!document.isSpritesheetEditorSet) { - size = settings.editorSize; - zoom = settings.editorStartZoom; - set(); - center_view(); - checker_pan_reset(zoom, pan); - document.isSpritesheetEditorSet = true; + size = settings.editorSize; + zoom = settings.editorStartZoom; + set(); + center_view(); + checker_pan_reset(zoom, pan); + document.isSpritesheetEditorSet = true; } settings.editorSize = size; settings.editorStartZoom = zoom; ImGui::End(); - } - +} diff --git a/src/ui/spritesheet_editor.h b/src/ui/spritesheet_editor.h index 0ff47cf..f627b3d 100644 --- a/src/ui/spritesheet_editor.h +++ b/src/ui/spritesheet_editor.h @@ -5,12 +5,12 @@ #include "resources.h" #include "settings.h" - class SpritesheetEditor : public CanvasView - { +class SpritesheetEditor : public CanvasView +{ glm::vec2 previousMousePos{}; glm::vec2 cropAnchor{}; int hoveredRegionId = -1; - public: +public: void update(Manager&, Settings&, Resources&); - }; +}; diff --git a/src/ui/spritesheets.cpp b/src/ui/spritesheets.cpp index 4466893..1c58bbe 100644 --- a/src/ui/spritesheets.cpp +++ b/src/ui/spritesheets.cpp @@ -7,340 +7,342 @@ #include "ui/layout.h" #include "working_directory.h" - constexpr int SPRITESHEET_CARD_LINES = 4; - constexpr int MERGE_OPTIONS_ROWS = 6; - constexpr int PADDING_MAX = 100; - // The merge region origin setting indexes this (top-left or center). - constexpr Origin MERGE_REGION_ORIGINS[] = {Origin::TOP_LEFT, Origin::CENTER}; +constexpr int SPRITESHEET_CARD_LINES = 4; +constexpr int MERGE_OPTIONS_ROWS = 6; +constexpr int PADDING_MAX = 100; +// The merge region origin setting indexes this (top-left or center). +constexpr Origin MERGE_REGION_ORIGINS[] = {Origin::TOP_LEFT, Origin::CENTER}; - static auto& spritesheets_get(Model& model) { return model.content.spritesheets; } +static auto& spritesheets_get(Model& model) +{ + return model.content.spritesheets; +} - static const Spritesheet* spritesheet_get(Document& document, int id) - { +static const Spritesheet* spritesheet_get(Document& document, int id) +{ return item_get(document.model.content.spritesheets, id); - } +} - static bool is_spritesheet_regions(Document& document, int id) - { +static bool is_spritesheet_regions(Document& document, int id) +{ auto spritesheet = spritesheet_get(document, id); return spritesheet && !spritesheet->regions.empty(); - } +} - static void spritesheets_save(Document& document, const std::set& ids) - { +static void spritesheets_save(Document& document, const std::set& ids) +{ for (auto id : ids) { - auto spritesheet = spritesheet_get(document, id); - auto texture = document.texture_get(id); - if (!spritesheet || !texture) continue; - auto pathString = path_to_utf8(spritesheet->path); - WorkingDirectory workingDirectory(document.directory_get()); - path_ensure_directory(spritesheet->path.parent_path()); - auto isSaved = texture->write(spritesheet->path); - if (isSaved) document.spritesheet_hash_set_saved(id); - toast_log(isSaved ? Level::INFO : Level::ERROR, isSaved ? TOAST_SAVE_SPRITESHEET : TOAST_SAVE_SPRITESHEET_FAILED, - id, pathString); + auto spritesheet = spritesheet_get(document, id); + auto texture = document.texture_get(id); + if (!spritesheet || !texture) + continue; + auto pathString = path_to_utf8(spritesheet->path); + WorkingDirectory workingDirectory(document.directory_get()); + path_ensure_directory(spritesheet->path.parent_path()); + auto isSaved = texture->write(spritesheet->path); + if (isSaved) + document.spritesheet_hash_set_saved(id); + toast_log(isSaved ? Level::INFO : Level::ERROR, + isSaved ? TOAST_SAVE_SPRITESHEET : TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); } - } +} - // Points a spritesheet at a new file: replacing loads it, setting the path writes the current texture there. - static void spritesheet_path_change(Document& document, int id, const std::filesystem::path& dialogPath, StringType edit, - bool isWritten) - { +// Points a spritesheet at a new file: replacing loads it, setting the path writes the current texture there. +static void spritesheet_path_change(Document& document, int id, const std::filesystem::path& dialogPath, + StringType edit, bool isWritten) +{ auto texture = document.texture_get(id); - if (!spritesheet_get(document, id) || (isWritten && !texture)) return; - document.edit_apply(edit, - [&](Model& model) - { - auto spritesheet = item_get(model.content.spritesheets, id); - auto newPath = asset_path_get(document, dialogPath); - auto pathString = path_to_utf8(newPath); - if (isWritten) - { - WorkingDirectory workingDirectory(document.directory_get()); - path_ensure_directory(newPath.parent_path()); - if (!texture->write(newPath)) - return toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); - } - spritesheet->path = newPath; - if (isWritten) - document.texturePaths[id] = newPath; - else - document.texture_reload(id); - document.spritesheet_hash_set_saved(id); - toast_log(Level::INFO, isWritten ? TOAST_SAVE_SPRITESHEET : TOAST_REPLACE_SPRITESHEET, id, - pathString); - }); - } + if (!spritesheet_get(document, id) || (isWritten && !texture)) + return; + document.edit_apply(edit, [&](Model& model) { + auto spritesheet = item_get(model.content.spritesheets, id); + auto newPath = asset_path_get(document, dialogPath); + auto pathString = path_to_utf8(newPath); + if (isWritten) + { + WorkingDirectory workingDirectory(document.directory_get()); + path_ensure_directory(newPath.parent_path()); + if (!texture->write(newPath)) + return toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); + } + spritesheet->path = newPath; + if (isWritten) + document.texturePaths[id] = newPath; + else + document.texture_reload(id); + document.spritesheet_hash_set_saved(id); + toast_log(Level::INFO, isWritten ? TOAST_SAVE_SPRITESHEET : TOAST_REPLACE_SPRITESHEET, id, pathString); + }); +} - static void spritesheet_textures_edit(Document& document, StringType edit, const std::function& behavior, - StringType successToast, StringType failToast) - { +static void spritesheet_textures_edit(Document& document, StringType edit, const std::function& behavior, + StringType successToast, StringType failToast) +{ document.edit_begin(edit); auto isSuccess = behavior(); toast_log(isSuccess ? Level::INFO : Level::ERROR, isSuccess ? successToast : failToast); document.change(); - } +} - static void spritesheets_dialog_update(Panel& panel) - { +static void spritesheets_dialog_update(Panel& panel) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; if (dialog.is_selected(Dialog::SPRITESHEET_OPEN)) { - command_push(panel, - [&state, paths = dialog.paths](Document& document) - { - document.spritesheets_add(paths); - document.selected_clear(SelectionKind::REGIONS); - state.newId = document.focused_id_get(SelectionKind::SPRITESHEETS); - }); - dialog.reset(); + command_push(panel, [&state, paths = dialog.paths](Document& document) { + document.spritesheets_add(paths); + document.selected_clear(SelectionKind::REGIONS); + state.newId = document.focused_id_get(SelectionKind::SPRITESHEETS); + }); + dialog.reset(); } auto selection = document.selected_ids_get(SelectionKind::SPRITESHEETS); for (auto [type, edit] : {std::pair{Dialog::SPRITESHEET_REPLACE, EDIT_REPLACE_SPRITESHEET}, std::pair{Dialog::SPRITESHEET_PATH_SET, EDIT_SET_SPRITESHEET_FILE_PATH}}) { - if (!dialog.is_selected(type)) continue; - if (selection.size() == 1 && !dialog.path.empty()) - command_push(panel, [id = *selection.begin(), path = dialog.path, edit, - isWritten = type == Dialog::SPRITESHEET_PATH_SET](Document& document) - { spritesheet_path_change(document, id, path, edit, isWritten); }); - dialog.reset(); + if (!dialog.is_selected(type)) + continue; + if (selection.size() == 1 && !dialog.path.empty()) + command_push(panel, [id = *selection.begin(), path = dialog.path, edit, + isWritten = type == Dialog::SPRITESHEET_PATH_SET](Document& document) { + spritesheet_path_change(document, id, path, edit, isWritten); + }); + dialog.reset(); } - } +} - static void spritesheets_merge_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) - { +static void spritesheets_merge_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& popup = spritesheets.mergePopup; popup.trigger(); - if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) + return popup.end(); settings.mergeSpritesheetsRegionOrigin = glm::clamp(settings.mergeSpritesheetsRegionOrigin, 0, (int)std::size(MERGE_REGION_ORIGINS) - 1); if (ImGui::BeginChild("##Merge Spritesheets Options", child_size_get(MERGE_OPTIONS_ROWS), ImGuiChildFlags_Borders)) { - ImGui::SeparatorText(localize.get(LABEL_REGION_PROPERTIES_ORIGIN)); - ImGui::RadioButton(localize.get(LABEL_MERGE_SPRITESHEETS_APPEND_BOTTOM), &settings.mergeSpritesheetsOrigin, - APPEND_BOTTOM); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_SPRITESHEETS_BOTTOM_LEFT)); - ImGui::SameLine(); - ImGui::RadioButton(localize.get(LABEL_MERGE_SPRITESHEETS_APPEND_RIGHT), &settings.mergeSpritesheetsOrigin, - APPEND_RIGHT); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_SPRITESHEETS_TOP_RIGHT)); + ImGui::SeparatorText(localize.get(LABEL_REGION_PROPERTIES_ORIGIN)); + ImGui::RadioButton(localize.get(LABEL_MERGE_SPRITESHEETS_APPEND_BOTTOM), &settings.mergeSpritesheetsOrigin, + APPEND_BOTTOM); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_SPRITESHEETS_BOTTOM_LEFT)); + ImGui::SameLine(); + ImGui::RadioButton(localize.get(LABEL_MERGE_SPRITESHEETS_APPEND_RIGHT), &settings.mergeSpritesheetsOrigin, + APPEND_RIGHT); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_SPRITESHEETS_TOP_RIGHT)); - ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); - ImGui::Checkbox(localize.get(LABEL_MERGE_MAKE_SPRITESHEET_REGIONS), &settings.mergeSpritesheetsIsMakeRegions); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_MAKE_SPRITESHEET_REGIONS)); + ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); + ImGui::Checkbox(localize.get(LABEL_MERGE_MAKE_SPRITESHEET_REGIONS), &settings.mergeSpritesheetsIsMakeRegions); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_MAKE_SPRITESHEET_REGIONS)); - ImGui::BeginDisabled(!settings.mergeSpritesheetsIsMakeRegions); - ImGui::Checkbox(localize.get(LABEL_MERGE_MAKE_PRIMARY_SPRITESHEET_REGION), - &settings.mergeSpritesheetsIsMakePrimaryRegion); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_MAKE_PRIMARY_SPRITESHEET_REGION)); - const char* regionOriginOptions[] = {localize.get(LABEL_REGION_ORIGIN_TOP_LEFT), - localize.get(LABEL_REGION_ORIGIN_CENTER)}; - ImGui::Combo(localize.get(LABEL_REGION_PROPERTIES_ORIGIN), &settings.mergeSpritesheetsRegionOrigin, - regionOriginOptions, IM_ARRAYSIZE(regionOriginOptions)); - ImGui::EndDisabled(); + ImGui::BeginDisabled(!settings.mergeSpritesheetsIsMakeRegions); + ImGui::Checkbox(localize.get(LABEL_MERGE_MAKE_PRIMARY_SPRITESHEET_REGION), + &settings.mergeSpritesheetsIsMakePrimaryRegion); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_MAKE_PRIMARY_SPRITESHEET_REGION)); + const char* regionOriginOptions[] = {localize.get(LABEL_REGION_ORIGIN_TOP_LEFT), + localize.get(LABEL_REGION_ORIGIN_CENTER)}; + ImGui::Combo(localize.get(LABEL_REGION_PROPERTIES_ORIGIN), &settings.mergeSpritesheetsRegionOrigin, + regionOriginOptions, IM_ARRAYSIZE(regionOriginOptions)); + ImGui::EndDisabled(); } ImGui::EndChild(); auto result = popup_buttons_draw(manager, localize.get(BASIC_MERGE), spritesheets.mergeIds.size() > 1); if (result == PopupButton::CONFIRM) - command_push(panel, - [ids = spritesheets.mergeIds, isAppendRight = settings.mergeSpritesheetsOrigin == APPEND_RIGHT, - isMakeRegions = settings.mergeSpritesheetsIsMakeRegions, - isMakePrimaryRegion = settings.mergeSpritesheetsIsMakePrimaryRegion, - regionOrigin = MERGE_REGION_ORIGINS[settings.mergeSpritesheetsRegionOrigin]](Document& document) - { - spritesheet_textures_edit( - document, EDIT_MERGE_SPRITESHEETS, - [&]() - { - if (!document.spritesheets_merge(ids, isAppendRight, isMakeRegions, isMakePrimaryRegion, - regionOrigin)) - return false; - document.selected_ids_set(SelectionKind::SPRITESHEETS, {*ids.begin()}); - document.focused_id_set(SelectionKind::SPRITESHEETS, *ids.begin()); - document.selected_clear(SelectionKind::REGIONS); - return true; - }, - TOAST_MERGE_SPRITESHEETS, TOAST_MERGE_SPRITESHEETS_FAILED); - }); - if (result != PopupButton::NONE) popup.close(); + command_push(panel, + [ids = spritesheets.mergeIds, isAppendRight = settings.mergeSpritesheetsOrigin == APPEND_RIGHT, + isMakeRegions = settings.mergeSpritesheetsIsMakeRegions, + isMakePrimaryRegion = settings.mergeSpritesheetsIsMakePrimaryRegion, + regionOrigin = MERGE_REGION_ORIGINS[settings.mergeSpritesheetsRegionOrigin]](Document& document) { + spritesheet_textures_edit( + document, EDIT_MERGE_SPRITESHEETS, + [&]() { + if (!document.spritesheets_merge(ids, isAppendRight, isMakeRegions, + isMakePrimaryRegion, regionOrigin)) + return false; + document.selected_ids_set(SelectionKind::SPRITESHEETS, {*ids.begin()}); + document.focused_id_set(SelectionKind::SPRITESHEETS, *ids.begin()); + document.selected_clear(SelectionKind::REGIONS); + return true; + }, + TOAST_MERGE_SPRITESHEETS, TOAST_MERGE_SPRITESHEETS_FAILED); + }); + if (result != PopupButton::NONE) + popup.close(); ImGui::EndPopup(); popup.end(); - } +} - static void spritesheets_pack_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) - { +static void spritesheets_pack_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& popup = spritesheets.packPopup; popup.trigger(); - if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) + return popup.end(); settings.packPadding = std::max(0, settings.packPadding); if (ImGui::BeginChild("##Pack Spritesheet Options", child_size_get(), ImGuiChildFlags_Borders)) - ImGui::DragInt(localize.get(LABEL_PACK_PADDING), &settings.packPadding, DRAG_SPEED, 0, PADDING_MAX); + ImGui::DragInt(localize.get(LABEL_PACK_PADDING), &settings.packPadding, DRAG_SPEED, 0, PADDING_MAX); ImGui::EndChild(); auto result = popup_buttons_draw(manager, localize.get(BASIC_PACK), is_spritesheet_regions(document, spritesheets.packId)); if (result == PopupButton::CONFIRM) - command_push(panel, - [id = spritesheets.packId, padding = settings.packPadding](Document& document) - { - spritesheet_textures_edit( - document, EDIT_PACK_SPRITESHEET, [&]() { return document.spritesheet_pack(id, padding); }, - TOAST_PACK_SPRITESHEET, TOAST_PACK_SPRITESHEET_FAILED); - }); - if (result != PopupButton::NONE) popup.close(); + command_push(panel, [id = spritesheets.packId, padding = settings.packPadding](Document& document) { + spritesheet_textures_edit( + document, EDIT_PACK_SPRITESHEET, [&]() { return document.spritesheet_pack(id, padding); }, + TOAST_PACK_SPRITESHEET, TOAST_PACK_SPRITESHEET_FAILED); + }); + if (result != PopupButton::NONE) + popup.close(); ImGui::EndPopup(); popup.end(); - } +} - static void spritesheets_overwrite_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) - { +static void spritesheets_overwrite_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) +{ auto& popup = spritesheets.overwritePopup; popup.trigger(); - if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) + return popup.end(); ImGui::TextUnformatted(localize.get(LABEL_OVERWRITE_CONFIRMATION)); auto result = popup_buttons_draw(panel.manager, localize.get(BASIC_YES), true, BASIC_NO); if (result == PopupButton::CONFIRM) - command_push(panel, [ids = spritesheets.saveIds](Document& document) { spritesheets_save(document, ids); }); - if (result != PopupButton::NONE) popup.close(); + command_push(panel, [ids = spritesheets.saveIds](Document& document) { spritesheets_save(document, ids); }); + if (result != PopupButton::NONE) + popup.close(); ImGui::EndPopup(); popup.end(); - } +} - void spritesheets_update(Panel& panel, SpritesheetsPanel& spritesheets) - { +void spritesheets_update(Panel& panel, SpritesheetsPanel& spritesheets) +{ auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& items = document.model.content.spritesheets; spritesheets_dialog_update(panel); if (ImGui::Begin(localize.get(LABEL_SPRITESHEETS_WINDOW), &settings.windowIsSpritesheets)) { - auto selection = document.selected_ids_get(SelectionKind::SPRITESHEETS); - auto isOne = [selection]() { return selection.size() == 1; }; - auto isAny = [selection]() { return !selection.empty(); }; - auto open = [&](int id) - { - if (auto spritesheet = spritesheet_get(document, id)) directory_open(dialog, document, spritesheet->path); - }; + auto selection = document.selected_ids_get(SelectionKind::SPRITESHEETS); + auto isOne = [selection]() { + return selection.size() == 1; + }; + auto isAny = [selection]() { + return !selection.empty(); + }; + auto open = [&](int id) { + if (auto spritesheet = spritesheet_get(document, id)) + directory_open(dialog, document, spritesheet->path); + }; - Actions actions = {}; - actions.add(ACTION_OPEN_DIRECTORY, isOne, [&]() { open(*selection.begin()); }); - actions.add(ACTION_SET_FILE_PATH, isOne, [&]() { dialog.file_save(Dialog::SPRITESHEET_PATH_SET); }); - actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::SPRITESHEET_OPEN, true); }, TOOLTIP_ADD_SPRITESHEET); - content_remove_action_add(actions, panel, ElementType::SPRITESHEET, SelectionKind::SPRITESHEETS); - actions.add( - ACTION_RELOAD, isAny, - [&]() { command_push(panel, [selection](Document& document) { document.spritesheets_reload(selection); }); }, - TOOLTIP_RELOAD_SPRITESHEETS); - actions.add( - ACTION_REPLACE, isOne, [&]() { dialog.file_open(Dialog::SPRITESHEET_REPLACE); }, TOOLTIP_REPLACE_SPRITESHEET); - actions.add( - ACTION_MERGE, [selection]() { return selection.size() > 1; }, - [&]() - { - spritesheets.mergeIds = selection; - spritesheets.mergePopup.open(); - }); - actions.add( - ACTION_PACK, [&]() { return selection.size() == 1 && is_spritesheet_regions(document, *selection.begin()); }, - [&]() - { - spritesheets.packId = *selection.begin(); - spritesheets.packPopup.open(); - }, - TOOLTIP_PACK_SPRITESHEET); - // SVG sheets become PNGs beside them; greyed when none of the selection is an SVG. - actions.add( - ACTION_RASTERIZE, - [&]() - { - return std::ranges::any_of(selection, - [&](int id) - { - auto texture = document.texture_get(id); - return texture && texture->is_vector(); - }); - }, - [&]() - { - command_push(panel, [selection](Document& document) { document.spritesheets_vector_convert(selection); }); - }, - TOOLTIP_RASTERIZE_SPRITESHEETS); - actions.add( - ACTION_SAVE, isAny, - [&]() - { - if (!settings.fileIsWarnOverwrite) - return command_push(panel, [selection](Document& document) { spritesheets_save(document, selection); }); - spritesheets.saveIds = selection; - spritesheets.overwritePopup.open(); - }, - TOOLTIP_SAVE_SPRITESHEETS); - items_clipboard_actions_add(actions, panel, SelectionKind::SPRITESHEETS, - EDIT_PASTE_SPRITESHEETS, TOAST_DESERIALIZE_SPRITESHEETS_FAILED, - spritesheets_get); + Actions actions = {}; + actions.add(ACTION_OPEN_DIRECTORY, isOne, [&]() { open(*selection.begin()); }); + actions.add(ACTION_SET_FILE_PATH, isOne, [&]() { dialog.file_save(Dialog::SPRITESHEET_PATH_SET); }); + actions.add( + ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::SPRITESHEET_OPEN, true); }, TOOLTIP_ADD_SPRITESHEET); + content_remove_action_add(actions, panel, ElementType::SPRITESHEET, SelectionKind::SPRITESHEETS); + actions.add( + ACTION_RELOAD, isAny, + [&]() { + command_push(panel, [selection](Document& document) { document.spritesheets_reload(selection); }); + }, + TOOLTIP_RELOAD_SPRITESHEETS); + actions.add( + ACTION_REPLACE, isOne, [&]() { dialog.file_open(Dialog::SPRITESHEET_REPLACE); }, + TOOLTIP_REPLACE_SPRITESHEET); + actions.add( + ACTION_MERGE, [selection]() { return selection.size() > 1; }, + [&]() { + spritesheets.mergeIds = selection; + spritesheets.mergePopup.open(); + }); + actions.add( + ACTION_PACK, + [&]() { return selection.size() == 1 && is_spritesheet_regions(document, *selection.begin()); }, + [&]() { + spritesheets.packId = *selection.begin(); + spritesheets.packPopup.open(); + }, + TOOLTIP_PACK_SPRITESHEET); + // SVG sheets become PNGs beside them. Greyed when none of the selection is an SVG. + actions.add( + ACTION_RASTERIZE, + [&]() { + return std::ranges::any_of(selection, [&](int id) { + auto texture = document.texture_get(id); + return texture && texture->is_vector(); + }); + }, + [&]() { + command_push(panel, + [selection](Document& document) { document.spritesheets_vector_convert(selection); }); + }, + TOOLTIP_RASTERIZE_SPRITESHEETS); + actions.add( + ACTION_SAVE, isAny, + [&]() { + if (!settings.fileIsWarnOverwrite) + return command_push(panel, + [selection](Document& document) { spritesheets_save(document, selection); }); + spritesheets.saveIds = selection; + spritesheets.overwritePopup.open(); + }, + TOOLTIP_SAVE_SPRITESHEETS); + items_clipboard_actions_add(actions, panel, SelectionKind::SPRITESHEETS, EDIT_PASTE_SPRITESHEETS, + TOAST_DESERIALIZE_SPRITESHEETS_FAILED, spritesheets_get); - auto image_get = [&](int id) - { - auto texture = document.texture_get(id); - auto isValid = texture && texture->is_valid(); - auto& image = isValid ? *texture : resources.icons[ICON_NONE]; - return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; - }; - ListRows rows{ - .label_get = - [&](int id) - { - auto pathString = path_to_utf8(spritesheet_get(document, id)->path); - auto label = std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(id, pathString)); - return document.spritesheet_is_dirty(id) - ? std::vformat(localize.get(FORMAT_SPRITESHEET_NOT_SAVED), std::make_format_args(label)) - : label; - }, - .tooltip_draw = - [&](int id) - { - auto image = image_get(id); - tooltip_image_draw(image, - [&]() - { - tooltip_name_draw(resources, path_to_utf8(spritesheet_get(document, id)->path)); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); - if (image.isValid) - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_TEXTURE_SIZE), - std::make_format_args(image.texture->size.x, image.texture->size.y)) - .c_str()); - else - ImGui::TextUnformatted(localize.get(TOOLTIP_SPRITESHEET_INVALID)); - ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); - }); - }, - .image_get = image_get, - .select = - [&](int) - { - document.editTarget = Document::EditTarget::SPRITESHEET; - document.selected_clear(SelectionKind::REGIONS); - }, - .activate = open, - .cardLines = SPRITESHEET_CARD_LINES}; - list_panel_draw( - panel, actions, {{ACTION_ADD, ACTION_RELOAD, ACTION_REPLACE}, {ACTION_REMOVE, ACTION_SAVE}}, - [&]() { content_list_draw(panel, SelectionKind::SPRITESHEETS, item_ids_get(items), rows); }, true); + auto image_get = [&](int id) { + auto texture = document.texture_get(id); + auto isValid = texture && texture->is_valid(); + auto& image = isValid ? *texture : resources.icons[ICON_NONE]; + return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; + }; + ListRows rows{ + .label_get = + [&](int id) { + auto pathString = path_to_utf8(spritesheet_get(document, id)->path); + auto label = std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(id, pathString)); + return document.spritesheet_is_dirty(id) + ? std::vformat(localize.get(FORMAT_SPRITESHEET_NOT_SAVED), std::make_format_args(label)) + : label; + }, + .tooltip_draw = + [&](int id) { + auto image = image_get(id); + tooltip_image_draw(image, [&]() { + tooltip_name_draw(resources, path_to_utf8(spritesheet_get(document, id)->path)); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); + if (image.isValid) + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_TEXTURE_SIZE), + std::make_format_args(image.texture->size.x, image.texture->size.y)) + .c_str()); + else + ImGui::TextUnformatted(localize.get(TOOLTIP_SPRITESHEET_INVALID)); + ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); + }); + }, + .image_get = image_get, + .select = + [&](int) { + document.editTarget = Document::EditTarget::SPRITESHEET; + document.selected_clear(SelectionKind::REGIONS); + }, + .activate = open, + .cardLines = SPRITESHEET_CARD_LINES}; + list_panel_draw( + panel, actions, {{ACTION_ADD, ACTION_RELOAD, ACTION_REPLACE}, {ACTION_REMOVE, ACTION_SAVE}}, + [&]() { content_list_draw(panel, SelectionKind::SPRITESHEETS, item_ids_get(items), rows); }, true); } ImGui::End(); spritesheets_merge_popup_update(panel, spritesheets); spritesheets_pack_popup_update(panel, spritesheets); spritesheets_overwrite_popup_update(panel, spritesheets); - } +} diff --git a/src/ui/taskbar.cpp b/src/ui/taskbar.cpp index 83d3ee4..d8a9fa7 100644 --- a/src/ui/taskbar.cpp +++ b/src/ui/taskbar.cpp @@ -20,281 +20,284 @@ using namespace glm; - constexpr auto GENERATE_REGIONS_TARGET_SELECTION = 0; - constexpr auto GENERATE_REGIONS_TARGET_ALL = 1; +constexpr auto GENERATE_REGIONS_TARGET_SELECTION = 0; +constexpr auto GENERATE_REGIONS_TARGET_ALL = 1; - bool Taskbar::save_execute(Manager& manager, const PendingSave& request) - { +bool Taskbar::save_execute(Manager& manager, const PendingSave& request) +{ return manager.save(request.index, request.path); - } +} - void Taskbar::save_enqueue(Manager& manager, const PendingSave& request) - { +void Taskbar::save_enqueue(Manager& manager, const PendingSave& request) +{ auto index = request.index; auto path = request.path; manager.command_push({.runManager = [=](Manager& manager) { manager.save(index, path); }}); - } +} - bool Taskbar::save_request(Manager& manager, Settings& settings, int index, const std::filesystem::path& path, - bool isQueued) - { +bool Taskbar::save_request(Manager& manager, Settings& settings, int index, const std::filesystem::path& path, + bool isQueued) +{ auto* document = manager.get(index); - if (!document) return false; + if (!document) + return false; PendingSave request = {.index = index, .path = path}; if (isQueued) { - // Rebirth can't load SVG spritesheets: offer to convert them (the request waits in isaacSave either way). - if (!settings.fileIsJson && !document->isVectorKept && - !spritesheets_vector_used_get(document->model).empty()) - { - isaacSave = request; - vectorPopup.open(); - return false; - } - // The game can't read JSON, or its copy would differ from the document: ask first. - if (settings.fileIsWarnIsaac && - (settings.fileIsJson || isaac_issues_get(document->model) != IsaacIssues{})) - { - isaacSave = request; - isaacPopup.open(); - return false; - } - save_enqueue(manager, request); - return true; + // Rebirth can't load SVG spritesheets: offer to convert them (the request waits in isaacSave either way). + if (!settings.fileIsJson && !document->isVectorKept && !spritesheets_vector_used_get(document->model).empty()) + { + isaacSave = request; + vectorPopup.open(); + return false; + } + // The game can't read JSON, or its copy would differ from the document: ask first. + if (settings.fileIsWarnIsaac && (settings.fileIsJson || isaac_issues_get(document->model) != IsaacIssues{})) + { + isaacSave = request; + isaacPopup.open(); + return false; + } + save_enqueue(manager, request); + return true; } return save_execute(manager, request); - } +} - bool Taskbar::save_manual(Manager& manager, Settings& settings, int index, const std::filesystem::path& path) - { +bool Taskbar::save_manual(Manager& manager, Settings& settings, int index, const std::filesystem::path& path) +{ return save_request(manager, settings, index, path); - } +} - void Taskbar::update(Manager& manager, Settings& settings, Resources& resources, Dialog& dialog, bool& isQuitting) - { +void Taskbar::update(Manager& manager, Settings& settings, Resources& resources, Dialog& dialog, bool& isQuitting) +{ auto document = manager.get(); auto itemType = document ? (ItemType)document->reference_get().itemType : ItemType::NONE; auto animation = document ? document->model.animation_get(document->reference_get().animationIndex) : nullptr; auto layerReferences = document ? document->layer_references_get() : std::vector{}; bool isGenerateAnimationFromGridAvailable = !layerReferences.empty(); - bool hasRegions = document && std::ranges::any_of(document->model.content.spritesheets, [](const auto& spritesheet) - { return !spritesheet.regions.empty(); }); + bool hasRegions = + document && std::ranges::any_of(document->model.content.spritesheets, + [](const auto& spritesheet) { return !spritesheet.regions.empty(); }); if (ImGui::BeginMainMenuBar()) { - height = ImGui::GetWindowSize().y; + height = ImGui::GetWindowSize().y; - if (ImGui::BeginMenu(localize.get(LABEL_FILE_MENU))) - { - if (ImGui::MenuItem(localize.get(BASIC_NEW), settings.shortcutNew.c_str())) - dialog.file_save(Dialog::ANM2_CREATE); - if (ImGui::MenuItem(localize.get(BASIC_OPEN), settings.shortcutOpen.c_str())) - dialog.file_open(Dialog::ANM2_OPEN, true); - - auto recentFiles = manager.recent_files_ordered(); - if (ImGui::BeginMenu(localize.get(LABEL_OPEN_RECENT), !recentFiles.empty())) + if (ImGui::BeginMenu(localize.get(LABEL_FILE_MENU))) { - for (auto [i, file] : std::views::enumerate(recentFiles)) - { - ImGui::PushID((int)i); - auto fileNameUtf8 = path_to_utf8(file.filename()); - auto filePathUtf8 = path_to_utf8(file); - auto label = std::format(FILE_LABEL_FORMAT, fileNameUtf8, filePathUtf8); - if (ImGui::MenuItem(label.c_str())) - manager.command_push({.runManager = [file](Manager& manager) { manager.open(file); }}); - ImGui::PopID(); - } + if (ImGui::MenuItem(localize.get(BASIC_NEW), settings.shortcutNew.c_str())) + dialog.file_save(Dialog::ANM2_CREATE); + if (ImGui::MenuItem(localize.get(BASIC_OPEN), settings.shortcutOpen.c_str())) + dialog.file_open(Dialog::ANM2_OPEN, true); - if (!recentFiles.empty()) - if (ImGui::MenuItem(localize.get(LABEL_CLEAR_LIST))) manager.recent_files_clear(); + auto recentFiles = manager.recent_files_ordered(); + if (ImGui::BeginMenu(localize.get(LABEL_OPEN_RECENT), !recentFiles.empty())) + { + for (auto [i, file] : std::views::enumerate(recentFiles)) + { + ImGui::PushID((int)i); + auto fileNameUtf8 = path_to_utf8(file.filename()); + auto filePathUtf8 = path_to_utf8(file); + auto label = std::format(FILE_LABEL_FORMAT, fileNameUtf8, filePathUtf8); + if (ImGui::MenuItem(label.c_str())) + manager.command_push({.runManager = [file](Manager& manager) { manager.open(file); }}); + ImGui::PopID(); + } - ImGui::EndMenu(); + if (!recentFiles.empty()) + if (ImGui::MenuItem(localize.get(LABEL_CLEAR_LIST))) + manager.recent_files_clear(); + + ImGui::EndMenu(); + } + + if (ImGui::MenuItem(localize.get(BASIC_SAVE), settings.shortcutSave.c_str(), false, document)) + { + if (settings.fileIsWarnOverwrite) + overwritePopup.open(); + else + save_request(manager, settings, manager.selected, document->path, true); + } + + if (ImGui::MenuItem(localize.get(LABEL_SAVE_AS), settings.shortcutSaveAs.c_str(), false, document)) + dialog.file_save(Dialog::ANM2_SAVE); + if (ImGui::MenuItem(localize.get(LABEL_EXPLORE_XML_LOCATION), nullptr, false, document)) + dialog.file_explorer_open(document->path); + + ImGui::Separator(); + if (ImGui::MenuItem(localize.get(LABEL_EXIT), settings.shortcutExit.c_str())) + isQuitting = true; + ImGui::EndMenu(); + } + if (dialog.is_selected(Dialog::ANM2_CREATE)) + { + auto path = dialog.path; + manager.command_push({.runManager = [path](Manager& manager) { manager.new_(path); }}); + dialog.reset(); } - if (ImGui::MenuItem(localize.get(BASIC_SAVE), settings.shortcutSave.c_str(), false, document)) + if (dialog.is_selected(Dialog::ANM2_OPEN)) { - if (settings.fileIsWarnOverwrite) - overwritePopup.open(); - else - save_request(manager, settings, manager.selected, document->path, true); + auto paths = dialog.paths; + manager.command_push({.runManager = [paths](Manager& manager) { + for (auto& path : paths) + manager.open(path); + }}); + dialog.reset(); } - if (ImGui::MenuItem(localize.get(LABEL_SAVE_AS), settings.shortcutSaveAs.c_str(), false, document)) - dialog.file_save(Dialog::ANM2_SAVE); - if (ImGui::MenuItem(localize.get(LABEL_EXPLORE_XML_LOCATION), nullptr, false, document)) - dialog.file_explorer_open(document->path); - - ImGui::Separator(); - if (ImGui::MenuItem(localize.get(LABEL_EXIT), settings.shortcutExit.c_str())) isQuitting = true; - ImGui::EndMenu(); - } - if (dialog.is_selected(Dialog::ANM2_CREATE)) - { - auto path = dialog.path; - manager.command_push({.runManager = [path](Manager& manager) { manager.new_(path); }}); - dialog.reset(); - } - - if (dialog.is_selected(Dialog::ANM2_OPEN)) - { - auto paths = dialog.paths; - manager.command_push({.runManager = [paths](Manager& manager) - { - for (auto& path : paths) - manager.open(path); - }}); - dialog.reset(); - } - - if (dialog.is_selected(Dialog::ANM2_SAVE)) - { - save_request(manager, settings, manager.selected, dialog.path, true); - dialog.reset(); - } - - if (ImGui::BeginMenu(localize.get(LABEL_WIZARD_MENU))) - { - if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_GENERATE_ANIMATION_FROM_GRID), nullptr, false, - isGenerateAnimationFromGridAvailable)) - generatePopup.open(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_GENERATE_ANIMATION_FROM_GRID)); - - if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_GENERATE_REGIONS_FROM_ANIMATIONS), nullptr, false, document)) - generateRegionsPopup.open(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_GENERATE_REGIONS_FROM_ANIMATIONS)); - - if (ImGui::MenuItem(localize.get(LABEL_SCAN_AND_SET_REGIONS), nullptr, false, document && hasRegions)) + if (dialog.is_selected(Dialog::ANM2_SAVE)) { - manager.command_push({manager.selected, [](Manager&, Document& document) - { - document.edit_apply(EDIT_SCAN_AND_SET_REGIONS, - [](Model& model) { return regions_scan(model); }); - }}); - toast_log(Level::INFO, TOAST_SCAN_AND_SET_REGIONS); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_SCAN_AND_SET_REGIONS)); - - ImGui::Separator(); - - bool isChangeAllFramesAvailable = - document && !document->frame_references_get().empty() && itemType != ItemType::TRIGGER; - bool isChangeAllAnimationsAvailable = document && !document->animations_selected_get().empty(); - if (ImGui::MenuItem(localize.get(LABEL_CHANGE_ALL_FRAME_PROPERTIES), nullptr, false, - isChangeAllFramesAvailable || isChangeAllAnimationsAvailable)) - changePopup.open(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_CHANGE_ALL_FRAME_PROPERTIES)); - - ImGui::Separator(); - - if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_RENDER_ANIMATION), nullptr, false, - animation && manager.isAbleToRecord)) - renderPopup.open(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_RENDER_ANIMATION)); - - ImGui::EndMenu(); - } - - if (ImGui::BeginMenu(localize.get(LABEL_PLAYBACK_MENU))) - { - ImGui::MenuItem(localize.get(LABEL_PLAYBACK_ALWAYS_LOOP), nullptr, &settings.playbackIsLoop); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PLAYBACK_ALWAYS_LOOP)); - - ImGui::MenuItem(localize.get(LABEL_CLAMP), nullptr, &settings.playbackIsClamp); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PLAYBACK_CLAMP)); - - ImGui::EndMenu(); - } - - if (ImGui::BeginMenu(localize.get(LABEL_WINDOW_MENU))) - { - for (int i = 0; i < WINDOW_COUNT; i++) - { - auto member = WINDOW_MEMBERS[i]; - ImGui::MenuItem(localize.get(WINDOW_STRING_TYPES[i]), nullptr, &(settings.*member)); + save_request(manager, settings, manager.selected, dialog.path, true); + dialog.reset(); } - ImGui::EndMenu(); - } + if (ImGui::BeginMenu(localize.get(LABEL_WIZARD_MENU))) + { + if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_GENERATE_ANIMATION_FROM_GRID), nullptr, false, + isGenerateAnimationFromGridAvailable)) + generatePopup.open(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_GENERATE_ANIMATION_FROM_GRID)); - if (ImGui::BeginMenu(localize.get(LABEL_SETTINGS_MENU))) - { - if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_CONFIGURE))) configurePopup.open(); - ImGui::EndMenu(); - } + if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_GENERATE_REGIONS_FROM_ANIMATIONS), nullptr, false, document)) + generateRegionsPopup.open(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_GENERATE_REGIONS_FROM_ANIMATIONS)); - if (ImGui::BeginMenu(localize.get(LABEL_HELP_MENU))) - { - if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_ABOUT))) aboutPopup.open(); - ImGui::EndMenu(); - } + if (ImGui::MenuItem(localize.get(LABEL_SCAN_AND_SET_REGIONS), nullptr, false, document && hasRegions)) + { + manager.command_push({manager.selected, [](Manager&, Document& document) { + document.edit_apply(EDIT_SCAN_AND_SET_REGIONS, + [](Model& model) { return regions_scan(model); }); + }}); + toast_log(Level::INFO, TOAST_SCAN_AND_SET_REGIONS); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_SCAN_AND_SET_REGIONS)); - ImGui::EndMainMenuBar(); + ImGui::Separator(); + + bool isChangeAllFramesAvailable = + document && !document->frame_references_get().empty() && itemType != ItemType::TRIGGER; + bool isChangeAllAnimationsAvailable = document && !document->animations_selected_get().empty(); + if (ImGui::MenuItem(localize.get(LABEL_CHANGE_ALL_FRAME_PROPERTIES), nullptr, false, + isChangeAllFramesAvailable || isChangeAllAnimationsAvailable)) + changePopup.open(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_CHANGE_ALL_FRAME_PROPERTIES)); + + ImGui::Separator(); + + if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_RENDER_ANIMATION), nullptr, false, + animation && manager.isAbleToRecord)) + renderPopup.open(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_RENDER_ANIMATION)); + + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu(localize.get(LABEL_PLAYBACK_MENU))) + { + ImGui::MenuItem(localize.get(LABEL_PLAYBACK_ALWAYS_LOOP), nullptr, &settings.playbackIsLoop); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PLAYBACK_ALWAYS_LOOP)); + + ImGui::MenuItem(localize.get(LABEL_CLAMP), nullptr, &settings.playbackIsClamp); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PLAYBACK_CLAMP)); + + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu(localize.get(LABEL_WINDOW_MENU))) + { + for (int i = 0; i < WINDOW_COUNT; i++) + { + auto member = WINDOW_MEMBERS[i]; + ImGui::MenuItem(localize.get(WINDOW_STRING_TYPES[i]), nullptr, &(settings.*member)); + } + + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu(localize.get(LABEL_SETTINGS_MENU))) + { + if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_CONFIGURE))) + configurePopup.open(); + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu(localize.get(LABEL_HELP_MENU))) + { + if (ImGui::MenuItem(localize.get(LABEL_TASKBAR_ABOUT))) + aboutPopup.open(); + ImGui::EndMenu(); + } + + ImGui::EndMainMenuBar(); } generatePopup.trigger(); if (ImGui::BeginPopupModal(generatePopup.label(), &generatePopup.isOpen, ImGuiWindowFlags_NoResize)) { - if (document) - { - generateAnimationFromGrid.update(manager, *document, resources, settings); - if (generateAnimationFromGrid.isEnd) generatePopup.close(); - } - ImGui::EndPopup(); + if (document) + { + generateAnimationFromGrid.update(manager, *document, resources, settings); + if (generateAnimationFromGrid.isEnd) + generatePopup.close(); + } + ImGui::EndPopup(); } generateRegionsPopup.trigger(); if (ImGui::BeginPopupModal(generateRegionsPopup.label(), &generateRegionsPopup.isOpen, ImGuiWindowFlags_NoResize)) { - if (document) - { - ImGui::RadioButton(localize.get(LABEL_CURRENT_SELECTION), &generateRegionsTarget, - GENERATE_REGIONS_TARGET_SELECTION); - ImGui::SameLine(); - ImGui::RadioButton(localize.get(LABEL_ALL), &generateRegionsTarget, GENERATE_REGIONS_TARGET_ALL); - - input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); - ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isGenerateRegionsMapFrames); - - auto widgetSize = widget_size_with_row_get(2); - if (ImGui::Button(localize.get(LABEL_GENERATE), widgetSize)) + if (document) { - std::set animationIndices; - if (generateRegionsTarget == GENERATE_REGIONS_TARGET_ALL) - { - for (int i = 0; i < document->model.animations_count_get(); ++i) - animationIndices.insert(i); - } - else - { - animationIndices = document->animations_selected_get(); - if (animationIndices.empty() && document->reference_get().animationIndex >= 0) - animationIndices.insert(document->reference_get().animationIndex); - } + ImGui::RadioButton(localize.get(LABEL_CURRENT_SELECTION), &generateRegionsTarget, + GENERATE_REGIONS_TARGET_SELECTION); + ImGui::SameLine(); + ImGui::RadioButton(localize.get(LABEL_ALL), &generateRegionsTarget, GENERATE_REGIONS_TARGET_ALL); - auto queuedAnimationIndices = animationIndices; - auto queuedFormat = settings.generateRegionNameFormat; - auto queuedMapping = isGenerateRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE; - manager.command_push({manager.selected, [=](Manager&, Document& document) - { - if (queuedAnimationIndices.empty()) return; - document.edit_apply(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, - [&](Model& model) - { - return regions_generate(model, queuedAnimationIndices, {}, - queuedFormat, queuedMapping); - }); - }}); - generateRegionsPopup.close(); + input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); + ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isGenerateRegionsMapFrames); + + auto widgetSize = widget_size_with_row_get(2); + if (ImGui::Button(localize.get(LABEL_GENERATE), widgetSize)) + { + std::set animationIndices; + if (generateRegionsTarget == GENERATE_REGIONS_TARGET_ALL) + { + for (int i = 0; i < document->model.animations_count_get(); ++i) + animationIndices.insert(i); + } + else + { + animationIndices = document->animations_selected_get(); + if (animationIndices.empty() && document->reference_get().animationIndex >= 0) + animationIndices.insert(document->reference_get().animationIndex); + } + + auto queuedAnimationIndices = animationIndices; + auto queuedFormat = settings.generateRegionNameFormat; + auto queuedMapping = + isGenerateRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE; + manager.command_push({manager.selected, [=](Manager&, Document& document) { + if (queuedAnimationIndices.empty()) + return; + document.edit_apply(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, [&](Model& model) { + return regions_generate(model, queuedAnimationIndices, {}, queuedFormat, + queuedMapping); + }); + }}); + generateRegionsPopup.close(); + } + + ImGui::SameLine(); + + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) + generateRegionsPopup.close(); } - - ImGui::SameLine(); - - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) generateRegionsPopup.close(); - } - ImGui::EndPopup(); + ImGui::EndPopup(); } generateRegionsPopup.end(); @@ -302,67 +305,75 @@ using namespace glm; if (ImGui::BeginPopupModal(changePopup.label(), &changePopup.isOpen, ImGuiWindowFlags_NoResize)) { - if (document) - { - changeAllFrameProperties.update(manager, *document, settings, true); - if (changeAllFrameProperties.isChanged) changePopup.close(); - } - ImGui::EndPopup(); + if (document) + { + changeAllFrameProperties.update(manager, *document, settings, true); + if (changeAllFrameProperties.isChanged) + changePopup.close(); + } + ImGui::EndPopup(); } configurePopup.trigger(); if (ImGui::BeginPopupModal(configurePopup.label(), &configurePopup.isOpen, ImGuiWindowFlags_NoResize)) { - if (configurePopup.isJustOpened) configure.reset(settings); - configure.update(manager, settings); - if (configure.isSet) configurePopup.close(); - ImGui::EndPopup(); + if (configurePopup.isJustOpened) + configure.reset(settings); + configure.update(manager, settings); + if (configure.isSet) + configurePopup.close(); + ImGui::EndPopup(); } configurePopup.end(); renderPopup.trigger(); if (ImGui::BeginPopupModal(renderPopup.label(), &renderPopup.isOpen, ImGuiWindowFlags_NoResize)) { - if (document) - { - if (renderPopup.isJustOpened) renderAnimation.reset(manager, *document, settings); - renderAnimation.update(manager, *document, resources, settings, dialog); - } - if (renderAnimation.isEnd) renderPopup.close(); - ImGui::EndPopup(); + if (document) + { + if (renderPopup.isJustOpened) + renderAnimation.reset(manager, *document, settings); + renderAnimation.update(manager, *document, resources, settings, dialog); + } + if (renderAnimation.isEnd) + renderPopup.close(); + ImGui::EndPopup(); } renderPopup.end(); aboutPopup.trigger(); if (ImGui::BeginPopupModal(aboutPopup.label(), &aboutPopup.isOpen, ImGuiWindowFlags_NoResize)) { - if (aboutPopup.isJustOpened) about.reset(resources); - about.update(resources); - ImGui::EndPopup(); + if (aboutPopup.isJustOpened) + about.reset(resources); + about.update(resources); + ImGui::EndPopup(); } if (auto* music = resources.music_track_if_loaded()) - if (is_audio_playing(*music) && !aboutPopup.isOpen) audio_stop(*music); + if (is_audio_playing(*music) && !aboutPopup.isOpen) + audio_stop(*music); overwritePopup.trigger(); if (ImGui::BeginPopupModal(overwritePopup.label(), &overwritePopup.isOpen, ImGuiWindowFlags_NoResize)) { - ImGui::TextUnformatted(localize.get(LABEL_OVERWRITE_CONFIRMATION)); + ImGui::TextUnformatted(localize.get(LABEL_OVERWRITE_CONFIRMATION)); - auto widgetSize = widget_size_with_row_get(2); + auto widgetSize = widget_size_with_row_get(2); - if (ImGui::Button(localize.get(BASIC_YES), widgetSize)) - { - save_request(manager, settings, manager.selected, {}, true); - overwritePopup.close(); - } + if (ImGui::Button(localize.get(BASIC_YES), widgetSize)) + { + save_request(manager, settings, manager.selected, {}, true); + overwritePopup.close(); + } - ImGui::SameLine(); + ImGui::SameLine(); - if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) overwritePopup.close(); + if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) + overwritePopup.close(); - ImGui::EndPopup(); + ImGui::EndPopup(); } aboutPopup.end(); @@ -370,89 +381,98 @@ using namespace glm; vectorPopup.trigger(); if (ImGui::BeginPopupModal(vectorPopup.label(), &vectorPopup.isOpen, ImGuiWindowFlags_NoResize)) { - ImGui::TextWrapped("%s", localize.get(TEXT_CONVERT_SVG)); - auto widgetSize = widget_size_with_row_get(2); - auto document = manager.get(isaacSave.index); - for (auto [label, isConverted] : {std::pair{LABEL_CONVERT, true}, std::pair{LABEL_KEEP_SVG, false}}) - { - if (!isConverted) ImGui::SameLine(); - shortcut(manager.chords[isConverted ? SHORTCUT_CONFIRM : SHORTCUT_CANCEL]); - if (!ImGui::Button(localize.get(label), widgetSize) || !document) continue; - if (isConverted) - document->spritesheets_vector_convert(spritesheets_vector_used_get(document->model)); - else - document->isVectorKept = true; - vectorPopup.close(); - save_request(manager, settings, isaacSave.index, isaacSave.path, true); - } - ImGui::EndPopup(); + ImGui::TextWrapped("%s", localize.get(TEXT_CONVERT_SVG)); + auto widgetSize = widget_size_with_row_get(2); + auto document = manager.get(isaacSave.index); + for (auto [label, isConverted] : {std::pair{LABEL_CONVERT, true}, std::pair{LABEL_KEEP_SVG, false}}) + { + if (!isConverted) + ImGui::SameLine(); + shortcut(manager.chords[isConverted ? SHORTCUT_CONFIRM : SHORTCUT_CANCEL]); + if (!ImGui::Button(localize.get(label), widgetSize) || !document) + continue; + if (isConverted) + document->spritesheets_vector_convert(spritesheets_vector_used_get(document->model)); + else + document->isVectorKept = true; + vectorPopup.close(); + save_request(manager, settings, isaacSave.index, isaacSave.path, true); + } + ImGui::EndPopup(); } vectorPopup.end(); isaacPopup.trigger(); if (ImGui::BeginPopupModal(isaacPopup.label(), &isaacPopup.isOpen, ImGuiWindowFlags_NoResize)) { - if (settings.fileIsJson) - ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_JSON)); - else if (auto document = manager.get(isaacSave.index)) - { - ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_ISSUES)); - auto issues = isaac_issues_get(document->model); - for (auto [count, format] : {std::pair{issues.easedFrames, FORMAT_ISAAC_EASED_FRAMES}, - {issues.groupTransforms, FORMAT_ISAAC_GROUP_TRANSFORMS}, - {issues.animationLayers, FORMAT_ISAAC_ANIMATION_LAYERS}, - {issues.depthFrames, FORMAT_ISAAC_DEPTH_FRAMES}, - {issues.alphaOffsetFrames, FORMAT_ISAAC_ALPHA_OFFSET_FRAMES}, - {issues.skewFrames, FORMAT_ISAAC_SKEW_FRAMES}, - {issues.blurFrames, FORMAT_ISAAC_BLUR_FRAMES}, - {issues.shaderFrames, FORMAT_ISAAC_SHADER_FRAMES}, - {issues.extraEvents, FORMAT_ISAAC_EXTRA_EVENTS}, - {issues.triggerSounds, FORMAT_ISAAC_TRIGGER_SOUNDS}, - {issues.vectorSpritesheets, FORMAT_ISAAC_VECTOR_SPRITESHEETS}}) - if (count > 0) ImGui::BulletText("%s", localize_format(format, count).c_str()); - ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_CONVERT)); - ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_EDITOR_COPY)); - } + if (settings.fileIsJson) + ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_JSON)); + else if (auto document = manager.get(isaacSave.index)) + { + ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_ISSUES)); + auto issues = isaac_issues_get(document->model); + for (auto [count, format] : {std::pair{issues.easedFrames, FORMAT_ISAAC_EASED_FRAMES}, + {issues.groupTransforms, FORMAT_ISAAC_GROUP_TRANSFORMS}, + {issues.animationLayers, FORMAT_ISAAC_ANIMATION_LAYERS}, + {issues.depthFrames, FORMAT_ISAAC_DEPTH_FRAMES}, + {issues.alphaOffsetFrames, FORMAT_ISAAC_ALPHA_OFFSET_FRAMES}, + {issues.skewFrames, FORMAT_ISAAC_SKEW_FRAMES}, + {issues.blurFrames, FORMAT_ISAAC_BLUR_FRAMES}, + {issues.shaderFrames, FORMAT_ISAAC_SHADER_FRAMES}, + {issues.extraEvents, FORMAT_ISAAC_EXTRA_EVENTS}, + {issues.triggerSounds, FORMAT_ISAAC_TRIGGER_SOUNDS}, + {issues.vectorSpritesheets, FORMAT_ISAAC_VECTOR_SPRITESHEETS}}) + if (count > 0) + ImGui::BulletText("%s", localize_format(format, count).c_str()); + ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_CONVERT)); + ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_EDITOR_COPY)); + } - // Converting works around what the game can't show; the document remembers which, for saves that don't ask. - auto isConvertible = !settings.fileIsJson; - auto widgetSize = widget_size_with_row_get(isConvertible ? 3 : 2); - auto save = [&](std::optional isIgnored) - { - if (isIgnored) - manager.command_push({isaacSave.index, [isIgnored = *isIgnored](Manager&, Document& document) - { - if (document.model.info.isIsaacIgnored == isIgnored) return; - document.edit_apply(EDIT_ISAAC_COMPATIBILITY, [&](Model& model) - { model.info.isIsaacIgnored = isIgnored; }); - }}); - save_enqueue(manager, isaacSave); - isaacPopup.close(); - }; - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(localize.get(isConvertible ? LABEL_CONVERT_AND_SAVE : LABEL_SAVE_ANYWAY), widgetSize)) - save(isConvertible ? std::optional(false) : std::nullopt); - if (isConvertible) - { + // Converting works around what the game can't show. The document remembers which, for saves that don't ask. + auto isConvertible = !settings.fileIsJson; + auto widgetSize = widget_size_with_row_get(isConvertible ? 3 : 2); + auto save = [&](std::optional isIgnored) { + if (isIgnored) + manager.command_push({isaacSave.index, [isIgnored = *isIgnored](Manager&, Document& document) { + if (document.model.info.isIsaacIgnored == isIgnored) + return; + document.edit_apply(EDIT_ISAAC_COMPATIBILITY, [&](Model& model) { + model.info.isIsaacIgnored = isIgnored; + }); + }}); + save_enqueue(manager, isaacSave); + isaacPopup.close(); + }; + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(localize.get(isConvertible ? LABEL_CONVERT_AND_SAVE : LABEL_SAVE_ANYWAY), widgetSize)) + save(isConvertible ? std::optional(false) : std::nullopt); + if (isConvertible) + { + ImGui::SameLine(); + if (ImGui::Button(localize.get(LABEL_IGNORE_AND_SAVE), widgetSize)) + save(true); + } ImGui::SameLine(); - if (ImGui::Button(localize.get(LABEL_IGNORE_AND_SAVE), widgetSize)) save(true); - } - ImGui::SameLine(); - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) isaacPopup.close(); - ImGui::EndPopup(); + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) + isaacPopup.close(); + ImGui::EndPopup(); } isaacPopup.end(); - if (shortcut(manager.chords[SHORTCUT_NEW], SCOPE_GLOBAL)) dialog.file_save(Dialog::ANM2_CREATE); - if (shortcut(manager.chords[SHORTCUT_OPEN], SCOPE_GLOBAL)) dialog.file_open(Dialog::ANM2_OPEN, true); + if (shortcut(manager.chords[SHORTCUT_NEW], SCOPE_GLOBAL)) + dialog.file_save(Dialog::ANM2_CREATE); + if (shortcut(manager.chords[SHORTCUT_OPEN], SCOPE_GLOBAL)) + dialog.file_open(Dialog::ANM2_OPEN, true); if (shortcut(manager.chords[SHORTCUT_SAVE], SCOPE_GLOBAL)) { - if (settings.fileIsWarnOverwrite) - overwritePopup.open(); - else - save_request(manager, settings, manager.selected, {}, true); + if (settings.fileIsWarnOverwrite) + overwritePopup.open(); + else + save_request(manager, settings, manager.selected, {}, true); } - if (shortcut(manager.chords[SHORTCUT_SAVE_AS], SCOPE_GLOBAL)) dialog.file_save(Dialog::ANM2_SAVE); - if (shortcut(manager.chords[SHORTCUT_EXIT], SCOPE_GLOBAL)) isQuitting = true; - } + if (shortcut(manager.chords[SHORTCUT_SAVE_AS], SCOPE_GLOBAL)) + dialog.file_save(Dialog::ANM2_SAVE); + if (shortcut(manager.chords[SHORTCUT_EXIT], SCOPE_GLOBAL)) + isQuitting = true; +} diff --git a/src/ui/taskbar.h b/src/ui/taskbar.h index f00264e..c67e35f 100644 --- a/src/ui/taskbar.h +++ b/src/ui/taskbar.h @@ -16,13 +16,13 @@ #include "ui/generate_animation_from_grid.h" #include "ui/render_animation.h" - class Taskbar - { +class Taskbar +{ struct PendingSave { - int index = -1; - std::filesystem::path path; - bool isQueued = false; + int index = -1; + std::filesystem::path path; + bool isQueued = false; }; ChangeAllFrameProperties changeAllFrameProperties = {}; @@ -52,9 +52,9 @@ void save_enqueue(Manager&, const PendingSave&); bool save_request(Manager&, Settings&, int = -1, const std::filesystem::path& = {}, bool = false); - public: +public: float height = 0; void update(Manager&, Settings&, Resources&, Dialog&, bool&); bool save_manual(Manager&, Settings&, int = -1, const std::filesystem::path& = {}); - }; +}; diff --git a/src/ui/theme.cpp b/src/ui/theme.cpp index fafc2f4..33a6b2a 100644 --- a/src/ui/theme.cpp +++ b/src/ui/theme.cpp @@ -2,35 +2,35 @@ #include - constexpr ImVec4 COLOR_LIGHT_BUTTON = {0.98f, 0.98f, 0.98f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TITLE_BG = {0.78f, 0.78f, 0.78f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TITLE_BG_ACTIVE = {0.64f, 0.64f, 0.64f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TITLE_BG_COLLAPSED = {0.74f, 0.74f, 0.74f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TABLE_HEADER = {0.78f, 0.78f, 0.78f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TAB = {0.74f, 0.74f, 0.74f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TAB_HOVERED = {0.82f, 0.82f, 0.82f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TAB_SELECTED = {0.92f, 0.92f, 0.92f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TAB_DIMMED = {0.70f, 0.70f, 0.70f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TAB_DIMMED_SELECTED = {0.86f, 0.86f, 0.86f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TAB_OVERLINE = {0.55f, 0.55f, 0.55f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_TAB_DIMMED_OVERLINE = {0.50f, 0.50f, 0.50f, 1.0f}; - constexpr ImVec4 COLOR_LIGHT_CHECK_MARK = {0.0f, 0.0f, 0.0f, 1.0f}; - constexpr auto FRAME_BORDER_SIZE = 1.0f; +constexpr ImVec4 COLOR_LIGHT_BUTTON = {0.98f, 0.98f, 0.98f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TITLE_BG = {0.78f, 0.78f, 0.78f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TITLE_BG_ACTIVE = {0.64f, 0.64f, 0.64f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TITLE_BG_COLLAPSED = {0.74f, 0.74f, 0.74f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TABLE_HEADER = {0.78f, 0.78f, 0.78f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TAB = {0.74f, 0.74f, 0.74f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TAB_HOVERED = {0.82f, 0.82f, 0.82f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TAB_SELECTED = {0.92f, 0.92f, 0.92f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TAB_DIMMED = {0.70f, 0.70f, 0.70f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TAB_DIMMED_SELECTED = {0.86f, 0.86f, 0.86f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TAB_OVERLINE = {0.55f, 0.55f, 0.55f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_TAB_DIMMED_OVERLINE = {0.50f, 0.50f, 0.50f, 1.0f}; +constexpr ImVec4 COLOR_LIGHT_CHECK_MARK = {0.0f, 0.0f, 0.0f, 1.0f}; +constexpr auto FRAME_BORDER_SIZE = 1.0f; - void theme_set(Theme theme) - { +void theme_set(Theme theme) +{ switch (theme) { - case THEME_LIGHT: - ImGui::StyleColorsLight(); - break; - case THEME_DARK: - default: - ImGui::StyleColorsDark(); - break; - case THEME_CLASSIC: - ImGui::StyleColorsClassic(); - break; + case THEME_LIGHT: + ImGui::StyleColorsLight(); + break; + case THEME_DARK: + default: + ImGui::StyleColorsDark(); + break; + case THEME_CLASSIC: + ImGui::StyleColorsClassic(); + break; } auto& style = ImGui::GetStyle(); style.FrameBorderSize = FRAME_BORDER_SIZE; @@ -38,19 +38,19 @@ if (theme == THEME_LIGHT) { - auto& colors = style.Colors; - colors[ImGuiCol_Button] = COLOR_LIGHT_BUTTON; - colors[ImGuiCol_TitleBg] = COLOR_LIGHT_TITLE_BG; - colors[ImGuiCol_TitleBgActive] = COLOR_LIGHT_TITLE_BG_ACTIVE; - colors[ImGuiCol_TitleBgCollapsed] = COLOR_LIGHT_TITLE_BG_COLLAPSED; - colors[ImGuiCol_TableHeaderBg] = COLOR_LIGHT_TABLE_HEADER; - colors[ImGuiCol_Tab] = COLOR_LIGHT_TAB; - colors[ImGuiCol_TabHovered] = COLOR_LIGHT_TAB_HOVERED; - colors[ImGuiCol_TabSelected] = COLOR_LIGHT_TAB_SELECTED; - colors[ImGuiCol_TabSelectedOverline] = COLOR_LIGHT_TAB_OVERLINE; - colors[ImGuiCol_TabDimmed] = COLOR_LIGHT_TAB_DIMMED; - colors[ImGuiCol_TabDimmedSelected] = COLOR_LIGHT_TAB_DIMMED_SELECTED; - colors[ImGuiCol_TabDimmedSelectedOverline] = COLOR_LIGHT_TAB_DIMMED_OVERLINE; - colors[ImGuiCol_CheckMark] = COLOR_LIGHT_CHECK_MARK; + auto& colors = style.Colors; + colors[ImGuiCol_Button] = COLOR_LIGHT_BUTTON; + colors[ImGuiCol_TitleBg] = COLOR_LIGHT_TITLE_BG; + colors[ImGuiCol_TitleBgActive] = COLOR_LIGHT_TITLE_BG_ACTIVE; + colors[ImGuiCol_TitleBgCollapsed] = COLOR_LIGHT_TITLE_BG_COLLAPSED; + colors[ImGuiCol_TableHeaderBg] = COLOR_LIGHT_TABLE_HEADER; + colors[ImGuiCol_Tab] = COLOR_LIGHT_TAB; + colors[ImGuiCol_TabHovered] = COLOR_LIGHT_TAB_HOVERED; + colors[ImGuiCol_TabSelected] = COLOR_LIGHT_TAB_SELECTED; + colors[ImGuiCol_TabSelectedOverline] = COLOR_LIGHT_TAB_OVERLINE; + colors[ImGuiCol_TabDimmed] = COLOR_LIGHT_TAB_DIMMED; + colors[ImGuiCol_TabDimmedSelected] = COLOR_LIGHT_TAB_DIMMED_SELECTED; + colors[ImGuiCol_TabDimmedSelectedOverline] = COLOR_LIGHT_TAB_DIMMED_OVERLINE; + colors[ImGuiCol_CheckMark] = COLOR_LIGHT_CHECK_MARK; } - } +} diff --git a/src/ui/theme.h b/src/ui/theme.h index ea8d4a1..a0f9516 100644 --- a/src/ui/theme.h +++ b/src/ui/theme.h @@ -3,24 +3,24 @@ #include "localization.h" #define THEMES \ - X(THEME_LIGHT, LABEL_THEME_LIGHT) \ - X(THEME_DARK, LABEL_THEME_DARK) \ - X(THEME_CLASSIC, LABEL_THEME_CLASSIC) + X(THEME_LIGHT, LABEL_THEME_LIGHT) \ + X(THEME_DARK, LABEL_THEME_DARK) \ + X(THEME_CLASSIC, LABEL_THEME_CLASSIC) - enum Theme - { +enum Theme +{ #define X(symbol, string) symbol, THEMES #undef X THEME_COUNT - }; +}; - constexpr StringType THEME_STRINGS[] = { +constexpr StringType THEME_STRINGS[] = { #define X(symbol, string) string, - THEMES + THEMES #undef X - }; +}; #undef THEMES - void theme_set(Theme); +void theme_set(Theme); diff --git a/src/ui/timeline.cpp b/src/ui/timeline.cpp index b011831..be05d13 100644 --- a/src/ui/timeline.cpp +++ b/src/ui/timeline.cpp @@ -1,18 +1,16 @@ #include "ui/timeline_context.h" - Timeline::Timeline() = default; - Timeline::~Timeline() = default; +Timeline::Timeline() = default; +Timeline::~Timeline() = default; - TimelineContext::TimelineContext(TimelineState&& state, Manager& manager, Settings& settings, Resources& resources, - Clipboard& clipboard) - : TimelineState(std::move(state)), manager(manager), settings(settings), resources(resources), - clipboard(clipboard), document(*manager.get()), model(document.model), playback(document.playback), - reference(document.reference_get()) - { - } +TimelineContext::TimelineContext(TimelineState&& state, Manager& manager, Settings& settings, Resources& resources, + Clipboard& clipboard) + : TimelineState(std::move(state)), manager(manager), settings(settings), resources(resources), clipboard(clipboard), + document(*manager.get()), model(document.model), playback(document.playback), reference(document.reference_get()) +{} - void TimelineContext::update() - { +void TimelineContext::update() +{ animation = model.animation_get(reference.animationIndex); rowFrameChildHeight = ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y * 1.5f; @@ -21,64 +19,67 @@ isTextPushed = false; if (isLightTheme) { - ImGui::PushStyleColor(ImGuiCol_Text, TIMELINE_TEXT_COLOR_LIGHT); - isTextPushed = true; + ImGui::PushStyleColor(ImGuiCol_Text, TIMELINE_TEXT_COLOR_LIGHT); + isTextPushed = true; } frame_begin(); draw(); - } +} - void Timeline::update(Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard) - { - if (!manager.get()) return; +void Timeline::update(Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard) +{ + if (!manager.get()) + return; context = std::make_unique(context ? std::move(static_cast(*context)) : TimelineState{}, manager, settings, resources, clipboard); context->update(); - } +} - void TimelineContext::draw() - { +void TimelineContext::draw() +{ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); if (ImGui::Begin(localize.get(LABEL_TIMELINE_WINDOW), &settings.windowIsTimeline)) { - isWindowHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | - ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); - breadcrumb_draw(); - frames_child(); - items_child(); + isWindowHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); + breadcrumb_draw(); + frames_child(); + items_child(); } ImGui::PopStyleVar(); ImGui::End(); - if (itemProperties.update(manager, settings, document, reference)) group_selection_reset_for(document); + if (itemProperties.update(manager, settings, document, reference)) + group_selection_reset_for(document); group_properties_update(); popups_update(); shortcuts_update(); - if (isTextPushed) ImGui::PopStyleColor(); - } + if (isTextPushed) + ImGui::PopStyleColor(); +} - void TimelineContext::popups_update() - { +void TimelineContext::popups_update() +{ makeManyRegionsPopup.trigger(); if (ImGui::BeginPopupModal(makeManyRegionsPopup.label(), &makeManyRegionsPopup.isOpen, ImGuiWindowFlags_NoResize)) { - input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); - ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isMakeManyRegionsMapFrames); + input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); + ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isMakeManyRegionsMapFrames); - auto result = popup_buttons_draw(manager, localize.get(LABEL_MAKE_MANY_REGIONS)); - if (result == PopupButton::CONFIRM) - edit_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, - [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, - mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET - : RegionFrameMapping::PRESERVE](Model& model) - { return regions_generate(model, {}, targetFrames, format, mapping); }); - if (result != PopupButton::NONE) makeManyRegionsPopup.close(); + auto result = popup_buttons_draw(manager, localize.get(LABEL_MAKE_MANY_REGIONS)); + if (result == PopupButton::CONFIRM) + edit_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, + [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, + mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE]( + Model& model) { return regions_generate(model, {}, targetFrames, format, mapping); }); + if (result != PopupButton::NONE) + makeManyRegionsPopup.close(); - ImGui::EndPopup(); + ImGui::EndPopup(); } makeManyRegionsPopup.end(); @@ -86,39 +87,40 @@ if (ImGui::BeginPopupModal(bakePopup.label(), &bakePopup.isOpen, ImGuiWindowFlags_NoResize)) { - auto& interval = settings.bakeInterval; - auto& isRoundRotation = settings.bakeIsRoundRotation; - auto& isRoundScale = settings.bakeIsRoundScale; + auto& interval = settings.bakeInterval; + auto& isRoundRotation = settings.bakeIsRoundRotation; + auto& isRoundScale = settings.bakeIsRoundScale; - auto frame = frame_get(); + auto frame = frame_get(); - input_int_range(localize.get(LABEL_INTERVAL), interval, FRAME_DURATION_MIN, - frame ? frame->duration : FRAME_DURATION_MIN); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_INTERVAL)); + input_int_range(localize.get(LABEL_INTERVAL), interval, FRAME_DURATION_MIN, + frame ? frame->duration : FRAME_DURATION_MIN); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_INTERVAL)); - ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); + ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); - ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); + ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); - auto widgetSize = widget_size_with_row_get(2); + auto widgetSize = widget_size_with_row_get(2); - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) - { - frames_bake(); - bakePopup.close(); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_FRAMES_OPTIONS)); + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) + { + frames_bake(); + bakePopup.close(); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_FRAMES_OPTIONS)); - ImGui::SameLine(); + ImGui::SameLine(); - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakePopup.close(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) + bakePopup.close(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); - ImGui::EndPopup(); + ImGui::EndPopup(); } bakeIntoOtherFramesPopup.trigger(); @@ -126,110 +128,115 @@ if (ImGui::BeginPopupModal(bakeIntoOtherFramesPopup.label(), &bakeIntoOtherFramesPopup.isOpen, ImGuiWindowFlags_NoResize)) { - auto& isRoundRotation = settings.bakeIsRoundRotation; - auto& isRoundScale = settings.bakeIsRoundScale; - auto& isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; - auto& isUseRootPivot = settings.bakeIsUseRootPivot; - int target = (int)bakeIntoOtherFramesTarget; - ImGui::RadioButton(localize.get(LABEL_CURRENT_SELECTION), &target, - (int)BakeIntoOtherFramesTarget::CURRENT_SELECTION); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_CURRENT_SELECTION)); - ImGui::SameLine(); - ImGui::RadioButton(localize.get(LABEL_ALL), &target, (int)BakeIntoOtherFramesTarget::ALL); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_ALL)); - bakeIntoOtherFramesTarget = (BakeIntoOtherFramesTarget)target; + auto& isRoundRotation = settings.bakeIsRoundRotation; + auto& isRoundScale = settings.bakeIsRoundScale; + auto& isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; + auto& isUseRootPivot = settings.bakeIsUseRootPivot; + int target = (int)bakeIntoOtherFramesTarget; + ImGui::RadioButton(localize.get(LABEL_CURRENT_SELECTION), &target, + (int)BakeIntoOtherFramesTarget::CURRENT_SELECTION); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_CURRENT_SELECTION)); + ImGui::SameLine(); + ImGui::RadioButton(localize.get(LABEL_ALL), &target, (int)BakeIntoOtherFramesTarget::ALL); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_ALL)); + bakeIntoOtherFramesTarget = (BakeIntoOtherFramesTarget)target; - auto isCurrentSelection = bakeIntoOtherFramesTarget == BakeIntoOtherFramesTarget::CURRENT_SELECTION; - ImGui::BeginDisabled(isCurrentSelection); - ImGui::Checkbox(localize.get(LABEL_LAYERS), &isBakeIntoOtherFramesLayers); - ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_NULLS), &isBakeIntoOtherFramesNulls); - ImGui::EndDisabled(); + auto isCurrentSelection = bakeIntoOtherFramesTarget == BakeIntoOtherFramesTarget::CURRENT_SELECTION; + ImGui::BeginDisabled(isCurrentSelection); + ImGui::Checkbox(localize.get(LABEL_LAYERS), &isBakeIntoOtherFramesLayers); + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_NULLS), &isBakeIntoOtherFramesNulls); + ImGui::EndDisabled(); - ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); + ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); - ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); + ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); - ImGui::Checkbox(localize.get(LABEL_BAKE_MATCH_ROOT_INTERPOLATION), &isMatchRootInterpolation); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_MATCH_ROOT_INTERPOLATION)); + ImGui::Checkbox(localize.get(LABEL_BAKE_MATCH_ROOT_INTERPOLATION), &isMatchRootInterpolation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_MATCH_ROOT_INTERPOLATION)); - ImGui::Checkbox(localize.get(LABEL_BAKE_USE_ROOT_PIVOT), &isUseRootPivot); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_USE_ROOT_PIVOT)); + ImGui::Checkbox(localize.get(LABEL_BAKE_USE_ROOT_PIVOT), &isUseRootPivot); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_USE_ROOT_PIVOT)); - auto widgetSize = widget_size_with_row_get(2); + auto widgetSize = widget_size_with_row_get(2); - shortcut(manager.chords[SHORTCUT_CONFIRM]); - ImGui::BeginDisabled(!is_bake_into_other_frames_ready()); - if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) - { - bake_into_other_frames(); - bakeIntoOtherFramesPopup.close(); - } - ImGui::EndDisabled(); + shortcut(manager.chords[SHORTCUT_CONFIRM]); + ImGui::BeginDisabled(!is_bake_into_other_frames_ready()); + if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) + { + bake_into_other_frames(); + bakeIntoOtherFramesPopup.close(); + } + ImGui::EndDisabled(); - ImGui::SameLine(); + ImGui::SameLine(); - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakeIntoOtherFramesPopup.close(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) + bakeIntoOtherFramesPopup.close(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); - ImGui::EndPopup(); + ImGui::EndPopup(); } - } +} - // Global timeline shortcuts: playback, playhead, frame resizing and frame/item navigation. - void TimelineContext::shortcuts_update() - { - if (!animation) return; +// Global timeline shortcuts: playback, playhead, frame resizing and frame/item navigation. +void TimelineContext::shortcuts_update() +{ + if (!animation) + return; - if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], SCOPE_GLOBAL)) playback.toggle(); - if (shortcut(manager.chords[SHORTCUT_START_MARKER], SCOPE_GLOBAL)) marker_set(true, (int)playback.time); - if (shortcut(manager.chords[SHORTCUT_END_MARKER], SCOPE_GLOBAL)) marker_set(false, (int)playback.time); + if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], SCOPE_GLOBAL)) + playback.toggle(); + if (shortcut(manager.chords[SHORTCUT_START_MARKER], SCOPE_GLOBAL)) + marker_set(true, (int)playback.time); + if (shortcut(manager.chords[SHORTCUT_END_MARKER], SCOPE_GLOBAL)) + marker_set(false, (int)playback.time); if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_BACK], SCOPE_GLOBAL)) { - playback_stop(); - playback.decrement(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); - document.frameTime = playback.time; + playback_stop(); + playback.decrement(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); + document.frameTime = playback.time; } if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_FORWARD], SCOPE_GLOBAL)) { - playback_stop(); - playback.increment(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); - document.frameTime = playback.time; + playback_stop(); + playback.increment(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); + document.frameTime = playback.time; } struct FrameResize { - int shortcut; - StringType edit; - int delta; + int shortcut; + StringType edit; + int delta; }; constexpr FrameResize FRAME_RESIZES[] = {{SHORTCUT_SHORTEN_FRAME, EDIT_SHORTEN_FRAME, -1}, {SHORTCUT_EXTEND_FRAME, EDIT_EXTEND_FRAME, 1}}; for (int i = 0; i < (int)std::size(FRAME_RESIZES); ++i) { - auto resize = FRAME_RESIZES[i]; - auto isPressed = shortcut(manager.chords[resize.shortcut], SCOPE_GLOBAL); - auto selectedFrames = - isPressed ? document.frame_references_get(Document::FrameReferenceFallback::NONE) : std::set{}; - std::erase_if(selectedFrames, is_trigger_reference); - if (!selectedFrames.empty()) - { - if (resizeChordTabIds[i] != document.tabId) edit_begin_push(resize.edit); - command_push( - [=, this](Manager&, Document& document) - { - for (auto frameReference : selectedFrames) - if (auto frame = document.model.frame_edit(frameReference)) - frame->duration = std::clamp(frame->duration + resize.delta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); - document.change(); + auto resize = FRAME_RESIZES[i]; + auto isPressed = shortcut(manager.chords[resize.shortcut], SCOPE_GLOBAL); + auto selectedFrames = + isPressed ? document.frame_references_get(Document::FrameReferenceFallback::NONE) : std::set{}; + std::erase_if(selectedFrames, is_trigger_reference); + if (!selectedFrames.empty()) + { + if (resizeChordTabIds[i] != document.tabId) + edit_begin_push(resize.edit); + command_push([=, this](Manager&, Document& document) { + for (auto frameReference : selectedFrames) + if (auto frame = document.model.frame_edit(frameReference)) + frame->duration = + std::clamp(frame->duration + resize.delta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); + document.change(); }); - } - resizeChordTabIds[i] = isPressed ? document.tabId : 0; + } + resizeChordTabIds[i] = isPressed ? document.tabId : 0; } auto isPreviousFrame = shortcut(manager.chords[SHORTCUT_PREVIOUS_FRAME], SCOPE_GLOBAL); @@ -238,16 +245,18 @@ auto isNextItem = shortcut(manager.chords[SHORTCUT_NEXT_ITEM], SCOPE_GLOBAL); if (isPreviousFrame || isNextFrame) - if (auto item = selected_item_get(); item && !item->frames.empty()) - { - auto frameReference = reference; - frameReference.frameIndex = - glm::clamp(reference.frameIndex + (int)isNextFrame - (int)isPreviousFrame, 0, (int)item->frames.size() - 1); - reference_set(frameReference); - document.frame_focus_select(); - document.frameTime = frame_time_from_index_get(*item, reference.frameIndex); - } + if (auto item = selected_item_get(); item && !item->frames.empty()) + { + auto frameReference = reference; + frameReference.frameIndex = glm::clamp(reference.frameIndex + (int)isNextFrame - (int)isPreviousFrame, 0, + (int)item->frames.size() - 1); + reference_set(frameReference); + document.frame_focus_select(); + document.frameTime = frame_time_from_index_get(*item, reference.frameIndex); + } - if (isPreviousItem) reference_set_adjacent_item(-1); - if (isNextItem) reference_set_adjacent_item(1); - } + if (isPreviousItem) + reference_set_adjacent_item(-1); + if (isNextItem) + reference_set_adjacent_item(1); +} diff --git a/src/ui/timeline.h b/src/ui/timeline.h index 030bcad..e8285ce 100644 --- a/src/ui/timeline.h +++ b/src/ui/timeline.h @@ -15,65 +15,65 @@ #include "localization.h" #include "ui/popup.h" - inline const glm::vec4 ROOT_COLOR = glm::vec4(0.140f, 0.310f, 0.560f, 1.000f); - inline const glm::vec4 ROOT_COLOR_ACTIVE = glm::vec4(0.240f, 0.520f, 0.880f, 1.000f); - inline const glm::vec4 ROOT_COLOR_HOVERED = glm::vec4(0.320f, 0.640f, 1.000f, 1.000f); +inline const glm::vec4 ROOT_COLOR = glm::vec4(0.140f, 0.310f, 0.560f, 1.000f); +inline const glm::vec4 ROOT_COLOR_ACTIVE = glm::vec4(0.240f, 0.520f, 0.880f, 1.000f); +inline const glm::vec4 ROOT_COLOR_HOVERED = glm::vec4(0.320f, 0.640f, 1.000f, 1.000f); - inline const glm::vec4 LAYER_COLOR = glm::vec4(0.640f, 0.320f, 0.110f, 1.000f); - inline const glm::vec4 LAYER_COLOR_ACTIVE = glm::vec4(0.840f, 0.450f, 0.170f, 1.000f); - inline const glm::vec4 LAYER_COLOR_HOVERED = glm::vec4(0.960f, 0.560f, 0.240f, 1.000f); +inline const glm::vec4 LAYER_COLOR = glm::vec4(0.640f, 0.320f, 0.110f, 1.000f); +inline const glm::vec4 LAYER_COLOR_ACTIVE = glm::vec4(0.840f, 0.450f, 0.170f, 1.000f); +inline const glm::vec4 LAYER_COLOR_HOVERED = glm::vec4(0.960f, 0.560f, 0.240f, 1.000f); - inline const glm::vec4 NULL_COLOR = glm::vec4(0.140f, 0.430f, 0.200f, 1.000f); - inline const glm::vec4 NULL_COLOR_ACTIVE = glm::vec4(0.250f, 0.650f, 0.350f, 1.000f); - inline const glm::vec4 NULL_COLOR_HOVERED = glm::vec4(0.350f, 0.800f, 0.480f, 1.000f); +inline const glm::vec4 NULL_COLOR = glm::vec4(0.140f, 0.430f, 0.200f, 1.000f); +inline const glm::vec4 NULL_COLOR_ACTIVE = glm::vec4(0.250f, 0.650f, 0.350f, 1.000f); +inline const glm::vec4 NULL_COLOR_HOVERED = glm::vec4(0.350f, 0.800f, 0.480f, 1.000f); - inline const glm::vec4 TRIGGER_COLOR = glm::vec4(0.620f, 0.150f, 0.260f, 1.000f); - inline const glm::vec4 TRIGGER_COLOR_ACTIVE = glm::vec4(0.820f, 0.250f, 0.380f, 1.000f); - inline const glm::vec4 TRIGGER_COLOR_HOVERED = glm::vec4(0.950f, 0.330f, 0.490f, 1.000f); +inline const glm::vec4 TRIGGER_COLOR = glm::vec4(0.620f, 0.150f, 0.260f, 1.000f); +inline const glm::vec4 TRIGGER_COLOR_ACTIVE = glm::vec4(0.820f, 0.250f, 0.380f, 1.000f); +inline const glm::vec4 TRIGGER_COLOR_HOVERED = glm::vec4(0.950f, 0.330f, 0.490f, 1.000f); #define ANM2_ITEM_TYPES \ - X(NONE, STRING_UNDEFINED, ICON_NONE, glm::vec4(), glm::vec4(), glm::vec4()) \ - X(ROOT, BASIC_ROOT, ICON_ROOT, ROOT_COLOR, ROOT_COLOR_ACTIVE, ROOT_COLOR_HOVERED) \ - X(LAYER, BASIC_LAYER_ANIMATION, ICON_LAYER, LAYER_COLOR, LAYER_COLOR_ACTIVE, LAYER_COLOR_HOVERED) \ - X(NULL_, BASIC_NULL_ANIMATION, ICON_NULL, NULL_COLOR, NULL_COLOR_ACTIVE, NULL_COLOR_HOVERED) \ - X(TRIGGER, BASIC_TRIGGERS, ICON_TRIGGERS, TRIGGER_COLOR, TRIGGER_COLOR_ACTIVE, TRIGGER_COLOR_HOVERED) + X(NONE, STRING_UNDEFINED, ICON_NONE, glm::vec4(), glm::vec4(), glm::vec4()) \ + X(ROOT, BASIC_ROOT, ICON_ROOT, ROOT_COLOR, ROOT_COLOR_ACTIVE, ROOT_COLOR_HOVERED) \ + X(LAYER, BASIC_LAYER_ANIMATION, ICON_LAYER, LAYER_COLOR, LAYER_COLOR_ACTIVE, LAYER_COLOR_HOVERED) \ + X(NULL_, BASIC_NULL_ANIMATION, ICON_NULL, NULL_COLOR, NULL_COLOR_ACTIVE, NULL_COLOR_HOVERED) \ + X(TRIGGER, BASIC_TRIGGERS, ICON_TRIGGERS, TRIGGER_COLOR, TRIGGER_COLOR_ACTIVE, TRIGGER_COLOR_HOVERED) - constexpr StringType TYPE_STRINGS[] = { +constexpr StringType TYPE_STRINGS[] = { #define X(symbol, string, icon, color, colorActive, colorHovered) string, - ANM2_ITEM_TYPES + ANM2_ITEM_TYPES #undef X - }; +}; - constexpr Icon TYPE_ICONS[] = { +constexpr Icon TYPE_ICONS[] = { #define X(symbol, string, icon, color, colorActive, colorHovered) icon, - ANM2_ITEM_TYPES + ANM2_ITEM_TYPES #undef X - }; +}; - inline const glm::vec4 TYPE_COLOR[] = { +inline const glm::vec4 TYPE_COLOR[] = { #define X(symbol, string, icon, color, colorActive, colorHovered) color, - ANM2_ITEM_TYPES + ANM2_ITEM_TYPES #undef X - }; +}; - inline const glm::vec4 TYPE_COLOR_ACTIVE[] = { +inline const glm::vec4 TYPE_COLOR_ACTIVE[] = { #define X(symbol, string, icon, color, colorActive, colorHovered) colorActive, - ANM2_ITEM_TYPES + ANM2_ITEM_TYPES #undef X - }; +}; - inline const glm::vec4 TYPE_COLOR_HOVERED[] = { +inline const glm::vec4 TYPE_COLOR_HOVERED[] = { #define X(symbol, string, icon, color, colorActive, colorHovered) colorHovered, - ANM2_ITEM_TYPES + ANM2_ITEM_TYPES #undef X - }; +}; - struct TimelineContext; +struct TimelineContext; - // A timeline row: a track (in a group or not), a group, or a group's root. groupType/groupId name the group a - // track or group root belongs to. - struct TimelineRow - { +// A timeline row: a track (in a group or not), a group, or a group's root. groupType/groupId name the group a +// track or group root belongs to. +struct TimelineRow +{ int documentIndex = -1; int animationIndex = -1; int type = NONE; @@ -85,38 +85,38 @@ bool isGroup = false; auto operator<=>(const TimelineRow&) const = default; - }; +}; - struct FrameMoveDrag - { +struct FrameMoveDrag +{ int animationIndex = -1; int duration = 1; std::vector references; bool isActive = false; - }; +}; - // What the timeline last put on the clipboard: frames of a type, or one property of a frame. - struct FrameClipboard - { +// What the timeline last put on the clipboard: frames of a type, or one property of a frame. +struct FrameClipboard +{ std::string text; int itemType = NONE; int property = -1; - }; +}; - struct FrameDurationDrag - { +struct FrameDurationDrag +{ Reference reference = {}; int duration = 1; - }; +}; - enum class BakeIntoOtherFramesTarget - { +enum class BakeIntoOtherFramesTarget +{ CURRENT_SELECTION, ALL - }; +}; - struct TimelineState - { +struct TimelineState +{ bool isDragging = false; bool isRulerHovered = false; FrameClipboard frameClipboard = {}; @@ -155,7 +155,8 @@ float draggedFrameWidth = 0; bool isDraggedFrameSnapshot = false; FrameMoveDrag frameMoveDrag = {}; - // The tab a held shorten/extend chord is editing (0 when released), so a held chord starts one undo entry per document. + // The tab a held shorten/extend chord is editing (0 when released), so a held chord starts one undo entry per + // document. std::uint64_t resizeChordTabIds[2]{}; std::optional frameSelectionAnchor; int animationLengthEditIndex = -1; @@ -163,14 +164,14 @@ std::set expandedLayerTracks; // animation layer tracks (by uid) showing their child's tracks glm::vec2 scroll{}; ImGuiStyle style = {}; - }; +}; - class Timeline - { +class Timeline +{ std::unique_ptr context; - public: +public: Timeline(); ~Timeline(); void update(Manager&, Settings&, Resources&, Clipboard&); - }; +}; diff --git a/src/ui/timeline_children.cpp b/src/ui/timeline_children.cpp index ddb507d..c455d24 100644 --- a/src/ui/timeline_children.cpp +++ b/src/ui/timeline_children.cpp @@ -2,47 +2,52 @@ // Animation layers in the timeline: their child's tracks under them (read only, timed as the parent plays them), // stepping into the child, and the breadcrumb back out. - constexpr auto BREADCRUMB_SEPARATOR = ">"; +constexpr auto BREADCRUMB_SEPARATOR = ">"; - // The child animation's tracks (root, layers top-down, nulls, triggers) when an animation layer row is expanded. - std::vector TimelineContext::peek_rows_get(const TimelineRow& row) - { +// The child animation's tracks (root, layers top-down, nulls, triggers) when an animation layer row is expanded. +std::vector TimelineContext::peek_rows_get(const TimelineRow& row) +{ std::vector rows; - if (row.isGroup || row.type != LAYER) return rows; + if (row.isGroup || row.type != LAYER) + return rows; auto track = item_get(LAYER, row.id, row.groupType, row.groupId); auto layer = ::item_get(model.content.layers, row.id); - if (!track || !layer || !layer->is_animation() || !expandedLayerTracks.contains(track->uid)) return rows; + if (!track || !layer || !layer->is_animation() || !expandedLayerTracks.contains(track->uid)) + return rows; auto [source, child] = child_get(model, *layer, {}, document.library_resolver_get()); - if (!child) return rows; + if (!child) + return rows; - auto row_add = [&](const Track& childTrack) - { - if (settings.timelineIsShowUnused || !childTrack.frames.empty()) rows.push_back({source, child, &childTrack}); + auto row_add = [&](const Track& childTrack) { + if (settings.timelineIsShowUnused || !childTrack.frames.empty()) + rows.push_back({source, child, &childTrack}); }; row_add(child->root); std::vector layers; tracks_each(child->layers, [&](const Track& childTrack, auto*) { layers.push_back(&childTrack); }); for (auto it = layers.rbegin(); it != layers.rend(); ++it) - row_add(**it); + row_add(**it); tracks_each(child->nulls, [&](const Track& childTrack, auto*) { row_add(childTrack); }); row_add(child->triggers); return rows; - } +} - void TimelineContext::child_step_in(const TimelineRow& row) - { +void TimelineContext::child_step_in(const TimelineRow& row) +{ manager.command_push({.runManager = [index = manager.selected, layer = row_item_reference_get(row)]( Manager& manager) { manager.child_step_in(index, layer); }}); - } +} - void TimelineContext::peek_item_child(const TimelineRow& row, const PeekRow& peek, int index) - { +void TimelineContext::peek_item_child(const TimelineRow& row, const PeekRow& peek, int index) +{ auto type = (int)peek.track->type; auto label = std::string(localize.get(TYPE_STRINGS[type])); if (type == LAYER) - if (auto layer = ::item_get(peek.source->content.layers, peek.track->id)) label = layer_label_get(*layer); + if (auto layer = ::item_get(peek.source->content.layers, peek.track->id)) + label = layer_label_get(*layer); if (type == NULL_) - if (auto null = ::item_get(peek.source->content.nulls, peek.track->id)) label = null->name; + if (auto null = ::item_get(peek.source->content.nulls, peek.track->id)) + label = null->name; ImGui::PushID(index); ImGui::PushStyleColor(ImGuiCol_ChildBg, to_imvec4(color_get(COLOR_ITEM_BASE, type) * COLOR_HIDDEN_MULTIPLIER)); @@ -51,106 +56,112 @@ if (ImGui::BeginChild("##Peek Item Child", ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) { - ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)(row.depth + 1) * ImGui::GetTextLineHeightWithSpacing()); - ImGui::BeginDisabled(); - ImGui::Image(resources.icon_id_get(TYPE_ICONS[type]), icon_size_get()); - ImGui::SameLine(); - ImGui::TextUnformatted(label.c_str()); - ImGui::EndDisabled(); - if (ImGui::IsWindowHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) child_step_in(row); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_TRACK)); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)(row.depth + 1) * ImGui::GetTextLineHeightWithSpacing()); + ImGui::BeginDisabled(); + ImGui::Image(resources.icon_id_get(TYPE_ICONS[type]), icon_size_get()); + ImGui::SameLine(); + ImGui::TextUnformatted(label.c_str()); + ImGui::EndDisabled(); + if (ImGui::IsWindowHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + child_step_in(row); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_TRACK)); } ImGui::EndChild(); ImGui::PopStyleVar(2); ImGui::PopStyleColor(); ImGui::PopID(); - } +} - // The child track's keyframes where the parent reaches them: a run of parent frames showing the same keyframe is one - // cell (a trigger, one cell on the frame it fires). - void TimelineContext::peek_frame_child(const TimelineRow& row, const PeekRow& peek, int& index, float width) - { +// The child track's keyframes where the parent reaches them: a run of parent frames showing the same keyframe is one +// cell (a trigger, one cell on the frame it fires). +void TimelineContext::peek_frame_child(const TimelineRow& row, const PeekRow& peek, int& index, float width) +{ ImGui::PushID(index++); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); if (ImGui::BeginChild("##Peek Frames Child", ImVec2(width, rowFrameChildHeight), ImGuiChildFlags_Borders) && animation) { - auto drawList = ImGui::GetWindowDrawList(); - auto origin = ImGui::GetCursorScreenPos(); - auto frameSize = ImVec2(ImGui::GetTextLineHeight(), ImGui::GetContentRegionAvail().y); - auto track = item_get(LAYER, row.id, row.groupType, row.groupId); - auto layer = ::item_get(model.content.layers, row.id); - auto type = (int)peek.track->type; - auto isTrigger = type == TRIGGER; - auto color = ImGui::GetColorU32(to_imvec4(color_get(COLOR_FRAME_BASE, type) * COLOR_HIDDEN_MULTIPLIER)); - auto libraryGet = document.library_resolver_get(); + auto drawList = ImGui::GetWindowDrawList(); + auto origin = ImGui::GetCursorScreenPos(); + auto frameSize = ImVec2(ImGui::GetTextLineHeight(), ImGui::GetContentRegionAvail().y); + auto track = item_get(LAYER, row.id, row.groupType, row.groupId); + auto layer = ::item_get(model.content.layers, row.id); + auto type = (int)peek.track->type; + auto isTrigger = type == TRIGGER; + auto color = ImGui::GetColorU32(to_imvec4(color_get(COLOR_FRAME_BASE, type) * COLOR_HIDDEN_MULTIPLIER)); + auto libraryGet = document.library_resolver_get(); - auto key_get = [&](int time) - { - auto frame = frame_generate(*track, (float)time); - if (!frame.isVisible || child_get(model, *layer, frame, libraryGet).second != peek.child) return -1; - auto childTime = child_time_get(*track, (float)time, peek.child->frameNum, layer->id); - return isTrigger ? frame_index_from_at_frame_get(*peek.track, (int)childTime) - : frame_index_from_time_get(*peek.track, childTime); - }; - auto cell_draw = [&](int start, int end, int key) - { - auto min = ImVec2(origin.x + frameSize.x * (float)start, origin.y); - auto max = ImVec2(origin.x + frameSize.x * (float)end, origin.y + frameSize.y); - drawList->AddRectFilled(min, max, color, FRAME_ROUNDING); - drawList->AddRect(min, max, ImGui::GetColorU32(frameBorderColor), FRAME_ROUNDING); - auto icon = isTrigger ? ICON_TRIGGER : INTERPOLATION_ICONS[(int)peek.track->frames[key].interpolation]; - auto iconSize = icon_size_get(); - auto iconMin = ImVec2(min.x, origin.y + (frameSize.y - iconSize.y) / 2); - drawList->AddImage((ImTextureID)(intptr_t)resources.icon_id_get(icon), iconMin, - ImVec2(iconMin.x + iconSize.x, iconMin.y + iconSize.y), ImVec2(0, 0), ImVec2(1, 1), - ImGui::GetColorU32(iconTintDefault)); - }; + auto key_get = [&](int time) { + auto frame = frame_generate(*track, (float)time); + if (!frame.isVisible || child_get(model, *layer, frame, libraryGet).second != peek.child) + return -1; + auto childTime = child_time_get(*track, (float)time, peek.child->frameNum, layer->id); + return isTrigger ? frame_index_from_at_frame_get(*peek.track, (int)childTime) + : frame_index_from_time_get(*peek.track, childTime); + }; + auto cell_draw = [&](int start, int end, int key) { + auto min = ImVec2(origin.x + frameSize.x * (float)start, origin.y); + auto max = ImVec2(origin.x + frameSize.x * (float)end, origin.y + frameSize.y); + drawList->AddRectFilled(min, max, color, FRAME_ROUNDING); + drawList->AddRect(min, max, ImGui::GetColorU32(frameBorderColor), FRAME_ROUNDING); + auto icon = isTrigger ? ICON_TRIGGER : INTERPOLATION_ICONS[(int)peek.track->frames[key].interpolation]; + auto iconSize = icon_size_get(); + auto iconMin = ImVec2(min.x, origin.y + (frameSize.y - iconSize.y) / 2); + drawList->AddImage((ImTextureID)(intptr_t)resources.icon_id_get(icon), iconMin, + ImVec2(iconMin.x + iconSize.x, iconMin.y + iconSize.y), ImVec2(0, 0), ImVec2(1, 1), + ImGui::GetColorU32(iconTintDefault)); + }; - int runStart = 0; - int runKey = -1; - for (int time = 0; time <= animation->frameNum; ++time) - { - auto key = time < animation->frameNum && track && layer ? key_get(time) : -1; - if (key == runKey) continue; - if (runKey != -1 && !isTrigger) cell_draw(runStart, time, runKey); - if (key != -1 && isTrigger) cell_draw(time, time + 1, key); - runStart = time; - runKey = key; - } + int runStart = 0; + int runKey = -1; + for (int time = 0; time <= animation->frameNum; ++time) + { + auto key = time < animation->frameNum && track && layer ? key_get(time) : -1; + if (key == runKey) + continue; + if (runKey != -1 && !isTrigger) + cell_draw(runStart, time, runKey); + if (key != -1 && isTrigger) + cell_draw(time, time + 1, key); + runStart = time; + runKey = key; + } - if (ImGui::IsWindowHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) child_step_in(row); + if (ImGui::IsWindowHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + child_step_in(row); } ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::PopID(); - } +} - // Where the animation being edited was stepped into from: each step leads back. - void TimelineContext::breadcrumb_draw() - { +// Where the animation being edited was stepped into from: each step leads back. +void TimelineContext::breadcrumb_draw() +{ auto& steps = document.childSteps; - if (!steps.empty() && steps.back().childAnimationIndex != reference.animationIndex) steps.clear(); - if (steps.empty()) return; + if (!steps.empty() && steps.back().childAnimationIndex != reference.animationIndex) + steps.clear(); + if (steps.empty()) + return; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); ImGui::SetCursorPos(ImVec2(style.WindowPadding.x, ImGui::GetCursorPosY() + style.ItemSpacing.y)); - auto crumb_draw = [&](const std::string& label, int stepIndex) - { - ImGui::PushID(stepIndex); - if (ImGui::SmallButton(label.c_str())) - manager.command_push({.runManager = [index = manager.selected, stepIndex](Manager& manager) - { manager.child_step_out(index, stepIndex); }}); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_STEP_OUT)); - ImGui::PopID(); - ImGui::SameLine(); - ImGui::TextUnformatted(BREADCRUMB_SEPARATOR); - ImGui::SameLine(); + auto crumb_draw = [&](const std::string& label, int stepIndex) { + ImGui::PushID(stepIndex); + if (ImGui::SmallButton(label.c_str())) + manager.command_push({.runManager = [index = manager.selected, stepIndex](Manager& manager) { + manager.child_step_out(index, stepIndex); + }}); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_STEP_OUT)); + ImGui::PopID(); + ImGui::SameLine(); + ImGui::TextUnformatted(BREADCRUMB_SEPARATOR); + ImGui::SameLine(); }; crumb_draw(steps.front().animationName, 0); for (int i = 0; i + 1 < (int)steps.size(); ++i) - crumb_draw(steps[i].layerName, i + 1); + crumb_draw(steps[i].layerName, i + 1); ImGui::TextUnformatted(steps.back().layerName.c_str()); ImGui::PopStyleVar(2); - } +} diff --git a/src/ui/timeline_context.h b/src/ui/timeline_context.h index cd7e8ed..8e808ad 100644 --- a/src/ui/timeline_context.h +++ b/src/ui/timeline_context.h @@ -28,122 +28,124 @@ using namespace glm; - constexpr auto WIDTH_MULTIPLIER = 1.25f; +constexpr auto WIDTH_MULTIPLIER = 1.25f; - constexpr auto COLOR_HIDDEN_MULTIPLIER = vec4(0.5f, 0.5f, 0.5f, 1.000f); - constexpr auto FRAME_BORDER_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.15f); - constexpr auto FRAME_BORDER_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.25f); - constexpr auto FRAME_BORDER_COLOR_REFERENCED_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.50f); - constexpr auto FRAME_BORDER_COLOR_REFERENCED_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.60f); - constexpr auto FRAME_BORDER_THICKNESS = 1.0f; - constexpr auto FRAME_BORDER_THICKNESS_REFERENCED = 2.0f; - constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.05f); - constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.1f); - constexpr auto FRAME_ROUNDING = 3.0f; - constexpr auto ICON_TINT_DEFAULT_DARK = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - constexpr auto ICON_TINT_DEFAULT_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - constexpr auto ITEM_TEXT_COLOR_DARK = to_imvec4(COLOR_WHITE); - constexpr auto ITEM_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - constexpr auto PLAYHEAD_ICON_TINT_LIGHT = ImVec4(0.3922f, 0.7843f, 0.5882f, 1.0f); - constexpr auto PLAYHEAD_LINE_COLOR_DARK = to_imvec4(COLOR_WHITE); - constexpr auto PLAYHEAD_LINE_COLOR_LIGHT = ImVec4(0.1961f, 0.5882f, 0.3922f, 1.0f); - constexpr auto PLAYHEAD_LINE_THICKNESS = 4.0f; - constexpr auto TEXT_MULTIPLE_COLOR_DARK = to_imvec4(COLOR_WHITE); - constexpr auto TEXT_MULTIPLE_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - constexpr auto TIMELINE_BACKGROUND_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f); - constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_DARK = ImVec4(0.60f, 0.45f, 0.30f, 1.0f); - constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT = ImVec4(0.8353f, 0.8353f, 0.7294f, 1.0f); - constexpr auto TIMELINE_TICK_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - constexpr auto TIMELINE_CHILD_BG_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f); - constexpr auto TIMELINE_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); +constexpr auto COLOR_HIDDEN_MULTIPLIER = vec4(0.5f, 0.5f, 0.5f, 1.000f); +constexpr auto FRAME_BORDER_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.15f); +constexpr auto FRAME_BORDER_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.25f); +constexpr auto FRAME_BORDER_COLOR_REFERENCED_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.50f); +constexpr auto FRAME_BORDER_COLOR_REFERENCED_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.60f); +constexpr auto FRAME_BORDER_THICKNESS = 1.0f; +constexpr auto FRAME_BORDER_THICKNESS_REFERENCED = 2.0f; +constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.05f); +constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.1f); +constexpr auto FRAME_ROUNDING = 3.0f; +constexpr auto ICON_TINT_DEFAULT_DARK = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); +constexpr auto ICON_TINT_DEFAULT_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); +constexpr auto ITEM_TEXT_COLOR_DARK = to_imvec4(COLOR_WHITE); +constexpr auto ITEM_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); +constexpr auto PLAYHEAD_ICON_TINT_LIGHT = ImVec4(0.3922f, 0.7843f, 0.5882f, 1.0f); +constexpr auto PLAYHEAD_LINE_COLOR_DARK = to_imvec4(COLOR_WHITE); +constexpr auto PLAYHEAD_LINE_COLOR_LIGHT = ImVec4(0.1961f, 0.5882f, 0.3922f, 1.0f); +constexpr auto PLAYHEAD_LINE_THICKNESS = 4.0f; +constexpr auto TEXT_MULTIPLE_COLOR_DARK = to_imvec4(COLOR_WHITE); +constexpr auto TEXT_MULTIPLE_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); +constexpr auto TIMELINE_BACKGROUND_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f); +constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_DARK = ImVec4(0.60f, 0.45f, 0.30f, 1.0f); +constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT = ImVec4(0.8353f, 0.8353f, 0.7294f, 1.0f); +constexpr auto TIMELINE_TICK_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); +constexpr auto TIMELINE_CHILD_BG_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f); +constexpr auto TIMELINE_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - enum class DropZone - { +enum class DropZone +{ BEFORE, INSIDE, AFTER - }; +}; - constexpr glm::vec4 FRAME_COLOR_LIGHT_BASE[] = {{0.80f, 0.80f, 0.80f, 1.0f}, - {0.5216f, 0.7333f, 1.0f, 1.0f}, - {1.0f, 0.9961f, 0.5882f, 1.0f}, - {0.6157f, 1.0f, 0.5882f, 1.0f}, - {1.0f, 0.5882f, 0.8314f, 1.0f}}; - constexpr glm::vec4 FRAME_COLOR_LIGHT_ACTIVE[] = {{0.74f, 0.74f, 0.74f, 1.0f}, - {0.0980f, 0.3765f, 0.6431f, 1.0f}, - {1.0f, 0.5255f, 0.3333f, 1.0f}, - {0.3686f, 0.5765f, 0.2353f, 1.0f}, - {0.6118f, 0.2039f, 0.2745f, 1.0f}}; - constexpr glm::vec4 FRAME_COLOR_LIGHT_HOVERED[] = {{0.84f, 0.84f, 0.84f, 1.0f}, - {0.0752f, 0.2887f, 0.4931f, 1.0f}, - {0.85f, 0.4467f, 0.2833f, 1.0f}, - {0.2727f, 0.4265f, 0.1741f, 1.0f}, - {0.4618f, 0.1539f, 0.2072f, 1.0f}}; - constexpr glm::vec4 ITEM_COLOR_LIGHT_BASE[] = {{0.3059f, 0.3255f, 0.5412f, 1.0f}, - {0.3333f, 0.5725f, 0.8392f, 1.0f}, - {1.0f, 0.5412f, 0.3412f, 1.0f}, - {0.5255f, 0.8471f, 0.4588f, 1.0f}, - {0.7961f, 0.3882f, 0.5412f, 1.0f}}; - constexpr glm::vec4 ITEM_COLOR_LIGHT_ACTIVE[] = {{0.3459f, 0.3655f, 0.5812f, 1.0f}, - {0.3733f, 0.6125f, 0.8792f, 1.0f}, - {0.9106f, 0.4949f, 0.2753f, 1.0f}, - {0.5655f, 0.8871f, 0.4988f, 1.0f}, - {0.8361f, 0.4282f, 0.5812f, 1.0f}}; - constexpr glm::vec4 ITEM_COLOR_LIGHT_SELECTED[] = {{0.74f, 0.74f, 0.74f, 1.0f}, - {0.2039f, 0.4549f, 0.7176f, 1.0f}, - {0.8745f, 0.4392f, 0.2275f, 1.0f}, - {0.3765f, 0.6784f, 0.2980f, 1.0f}, - {0.6353f, 0.2235f, 0.3647f, 1.0f}}; +constexpr glm::vec4 FRAME_COLOR_LIGHT_BASE[] = {{0.80f, 0.80f, 0.80f, 1.0f}, + {0.5216f, 0.7333f, 1.0f, 1.0f}, + {1.0f, 0.9961f, 0.5882f, 1.0f}, + {0.6157f, 1.0f, 0.5882f, 1.0f}, + {1.0f, 0.5882f, 0.8314f, 1.0f}}; +constexpr glm::vec4 FRAME_COLOR_LIGHT_ACTIVE[] = {{0.74f, 0.74f, 0.74f, 1.0f}, + {0.0980f, 0.3765f, 0.6431f, 1.0f}, + {1.0f, 0.5255f, 0.3333f, 1.0f}, + {0.3686f, 0.5765f, 0.2353f, 1.0f}, + {0.6118f, 0.2039f, 0.2745f, 1.0f}}; +constexpr glm::vec4 FRAME_COLOR_LIGHT_HOVERED[] = {{0.84f, 0.84f, 0.84f, 1.0f}, + {0.0752f, 0.2887f, 0.4931f, 1.0f}, + {0.85f, 0.4467f, 0.2833f, 1.0f}, + {0.2727f, 0.4265f, 0.1741f, 1.0f}, + {0.4618f, 0.1539f, 0.2072f, 1.0f}}; +constexpr glm::vec4 ITEM_COLOR_LIGHT_BASE[] = {{0.3059f, 0.3255f, 0.5412f, 1.0f}, + {0.3333f, 0.5725f, 0.8392f, 1.0f}, + {1.0f, 0.5412f, 0.3412f, 1.0f}, + {0.5255f, 0.8471f, 0.4588f, 1.0f}, + {0.7961f, 0.3882f, 0.5412f, 1.0f}}; +constexpr glm::vec4 ITEM_COLOR_LIGHT_ACTIVE[] = {{0.3459f, 0.3655f, 0.5812f, 1.0f}, + {0.3733f, 0.6125f, 0.8792f, 1.0f}, + {0.9106f, 0.4949f, 0.2753f, 1.0f}, + {0.5655f, 0.8871f, 0.4988f, 1.0f}, + {0.8361f, 0.4282f, 0.5812f, 1.0f}}; +constexpr glm::vec4 ITEM_COLOR_LIGHT_SELECTED[] = {{0.74f, 0.74f, 0.74f, 1.0f}, + {0.2039f, 0.4549f, 0.7176f, 1.0f}, + {0.8745f, 0.4392f, 0.2275f, 1.0f}, + {0.3765f, 0.6784f, 0.2980f, 1.0f}, + {0.6353f, 0.2235f, 0.3647f, 1.0f}}; - constexpr auto MARKER_ALPHA = 0.5f; - constexpr auto MARKER_OUTSIDE_COLOR = IM_COL32(0, 0, 0, 96); - constexpr auto FRAME_MULTIPLE = 5; - constexpr auto FRAME_TOOLTIP_HOVER_DELAY = 0.75f; +constexpr auto MARKER_ALPHA = 0.5f; +constexpr auto MARKER_OUTSIDE_COLOR = IM_COL32(0, 0, 0, 96); +constexpr auto FRAME_MULTIPLE = 5; +constexpr auto FRAME_TOOLTIP_HOVER_DELAY = 0.75f; #define ITEM_CHILD_WIDTH ImGui::GetTextLineHeightWithSpacing() * 12.5 - enum TimelineColor - { +enum TimelineColor +{ COLOR_FRAME_BASE, COLOR_FRAME_ACTIVE, COLOR_FRAME_HOVERED, COLOR_ITEM_BASE, COLOR_ITEM_ACTIVE, COLOR_ITEM_SELECTED - }; +}; - struct TimelineColorSet - { +struct TimelineColorSet +{ const glm::vec4* light; const glm::vec4* dark; - }; +}; - inline const TimelineColorSet TIMELINE_COLORS[] = {{FRAME_COLOR_LIGHT_BASE, TYPE_COLOR}, - {FRAME_COLOR_LIGHT_ACTIVE, TYPE_COLOR_ACTIVE}, - {FRAME_COLOR_LIGHT_HOVERED, TYPE_COLOR_HOVERED}, - {ITEM_COLOR_LIGHT_BASE, TYPE_COLOR}, - {ITEM_COLOR_LIGHT_ACTIVE, TYPE_COLOR_ACTIVE}, - {ITEM_COLOR_LIGHT_SELECTED, TYPE_COLOR_ACTIVE}}; +inline const TimelineColorSet TIMELINE_COLORS[] = {{FRAME_COLOR_LIGHT_BASE, TYPE_COLOR}, + {FRAME_COLOR_LIGHT_ACTIVE, TYPE_COLOR_ACTIVE}, + {FRAME_COLOR_LIGHT_HOVERED, TYPE_COLOR_HOVERED}, + {ITEM_COLOR_LIGHT_BASE, TYPE_COLOR}, + {ITEM_COLOR_LIGHT_ACTIVE, TYPE_COLOR_ACTIVE}, + {ITEM_COLOR_LIGHT_SELECTED, TYPE_COLOR_ACTIVE}}; - inline bool is_trigger_reference(const Reference& reference) { return reference.itemType == TRIGGER; } +inline bool is_trigger_reference(const Reference& reference) +{ + return reference.itemType == TRIGGER; +} - constexpr Icon INTERPOLATION_ICONS[] = {ICON_UNINTERPOLATED, ICON_INTERPOLATED, - ICON_EASE_IN, ICON_EASE_OUT, - ICON_EASE_IN_OUT}; +constexpr Icon INTERPOLATION_ICONS[] = {ICON_UNINTERPOLATED, ICON_INTERPOLATED, ICON_EASE_IN, ICON_EASE_OUT, + ICON_EASE_IN_OUT}; - // A read-only row under an expanded animation layer: one track of the child animation it plays. - struct PeekRow - { +// A read-only row under an expanded animation layer: one track of the child animation it plays. +struct PeekRow +{ const Model* source = nullptr; const Animation* child = nullptr; const Track* track = nullptr; - }; +}; - Reference row_item_reference_get(const TimelineRow&); - Reference row_selection_reference_get(const TimelineRow&); +Reference row_item_reference_get(const TimelineRow&); +Reference row_selection_reference_get(const TimelineRow&); - struct TimelineContext : TimelineState - { +struct TimelineContext : TimelineState +{ Manager& manager; Settings& settings; Resources& resources; @@ -187,16 +189,14 @@ using namespace glm; const TrackGroup* row_group_get(const TimelineRow& row); glm::vec4 color_get(TimelineColor, int); std::set drag_frame_references_get(const Reference&); - // Queues an edit on the document; its result is selected (frames by default). + // Queues an edit on the document. Its result is selected (frames by default). template void edit_push(StringType label, Operation operation, std::function select = {}) { - command_push( - [=, this](Manager&, Document& document) mutable - { + command_push([=, this](Manager&, Document& document) mutable { auto uids = document.edit_apply(label, operation); select ? select(document, uids) : document.frames_select(uids); - }); + }); } void edit_begin_push(StringType); void reference_set(Reference); @@ -277,4 +277,4 @@ using namespace glm; void popups_update(); void shortcuts_update(); void draw(); - }; +}; diff --git a/src/ui/timeline_edit.cpp b/src/ui/timeline_edit.cpp index 838020f..2092c10 100644 --- a/src/ui/timeline_edit.cpp +++ b/src/ui/timeline_edit.cpp @@ -1,281 +1,312 @@ #include "ui/timeline_context.h" - void TimelineContext::frame_insert() - { +void TimelineContext::frame_insert() +{ auto targetReference = reference; auto time = (int)document.frameTime; - if (!animation || !document.model.track_get(targetReference)) return; + if (!animation || !document.model.track_get(targetReference)) + return; edit_push(EDIT_INSERT_FRAME, [=](Model& model) { return ::frame_insert(model, targetReference, time); }); - } +} - void TimelineContext::frames_delete_action() - { +void TimelineContext::frames_delete_action() +{ auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - if (selectedFrames.empty()) return; + if (selectedFrames.empty()) + return; edit_push( EDIT_DELETE_FRAMES, [=](Model& model) { return frames_delete(model, selectedFrames); }, [this](Document& document, const Uids&) { document.frame_focus_select(); }); - } +} - void TimelineContext::frames_duplicate() - { +void TimelineContext::frames_duplicate() +{ auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); - if (selectedFrames.empty()) return; - edit_push(EDIT_DUPLICATE_FRAMES, [=, focus = reference](Model& model) - { return ::frames_duplicate(model, selectedFrames, focus); }); - } + if (selectedFrames.empty()) + return; + edit_push(EDIT_DUPLICATE_FRAMES, + [=, focus = reference](Model& model) { return ::frames_duplicate(model, selectedFrames, focus); }); +} - bool TimelineContext::is_frames_reverse_available(std::set selectedFrames) - { +bool TimelineContext::is_frames_reverse_available(std::set selectedFrames) +{ std::map counts; std::erase_if(selectedFrames, is_trigger_reference); for (auto frameReference : selectedFrames) { - auto itemReference = item_reference_from_frame_get(frameReference); - ++counts[itemReference]; + auto itemReference = item_reference_from_frame_get(frameReference); + ++counts[itemReference]; } return std::ranges::any_of(counts, [](const auto& item) { return item.second >= 2; }); - } +} - void TimelineContext::frames_reverse() - { +void TimelineContext::frames_reverse() +{ auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); - if (!is_frames_reverse_available(selectedFrames)) return; + if (!is_frames_reverse_available(selectedFrames)) + return; edit_push(EDIT_REVERSE_FRAMES, [=](Model& model) { return ::frames_reverse(model, selectedFrames); }); - } +} - void TimelineContext::frames_bake() - { +void TimelineContext::frames_bake() +{ auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); - if (selectedFrames.empty()) return; + if (selectedFrames.empty()) + return; edit_push(EDIT_BAKE_FRAMES, [=, interval = settings.bakeInterval, isRoundScale = settings.bakeIsRoundScale, - isRoundRotation = settings.bakeIsRoundRotation](Model& model) - { return ::frames_bake(model, selectedFrames, interval, isRoundScale, isRoundRotation); }); - } + isRoundRotation = settings.bakeIsRoundRotation](Model& model) { + return ::frames_bake(model, selectedFrames, interval, isRoundScale, isRoundRotation); + }); +} - std::set TimelineContext::selected_root_frame_references_get() - { +std::set TimelineContext::selected_root_frame_references_get() +{ auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType != ROOT; }); return selectedFrames; - } +} - std::set TimelineContext::item_references_for_bake_into_other_frames_get( - const Document& targetDocument, const Animation& targetAnimation, BakeIntoOtherFramesTarget target, - bool isLayers, bool isNulls) - { +std::set TimelineContext::item_references_for_bake_into_other_frames_get(const Document& targetDocument, + const Animation& targetAnimation, + BakeIntoOtherFramesTarget target, + bool isLayers, bool isNulls) +{ std::set result; auto animationIndex = targetDocument.reference_get().animationIndex; if (target == BakeIntoOtherFramesTarget::CURRENT_SELECTION) { - for (auto itemReference : targetDocument.selected_get(SelectionKind::TRACKS)) - if (itemReference.itemType == LAYER || itemReference.itemType == NULL_) result.insert(itemReference); - return result; + for (auto itemReference : targetDocument.selected_get(SelectionKind::TRACKS)) + if (itemReference.itemType == LAYER || itemReference.itemType == NULL_) + result.insert(itemReference); + return result; } for (auto itemType : {LAYER, NULL_}) { - if (!(itemType == LAYER ? isLayers : isNulls)) continue; - tracks_each(animation_entries_get(targetAnimation, itemType), - [&](const Track& track, const TrackGroup* group) - { - result.insert(Reference{animationIndex, itemType, track.id, -1, group ? itemType : NONE, - group ? group->id : -1}); - }); + if (!(itemType == LAYER ? isLayers : isNulls)) + continue; + tracks_each(animation_entries_get(targetAnimation, itemType), [&](const Track& track, const TrackGroup* group) { + result.insert( + Reference{animationIndex, itemType, track.id, -1, group ? itemType : NONE, group ? group->id : -1}); + }); } return result; - } +} - bool TimelineContext::is_bake_into_other_frames_ready() - { +bool TimelineContext::is_bake_into_other_frames_ready() +{ auto selectedRootFrames = selected_root_frame_references_get(); - if (selectedRootFrames.empty() || !animation) return false; + if (selectedRootFrames.empty() || !animation) + return false; auto targetItems = item_references_for_bake_into_other_frames_get( document, *animation, bakeIntoOtherFramesTarget, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); return !targetItems.empty(); - } +} - void TimelineContext::bake_into_other_frames() - { +void TimelineContext::bake_into_other_frames() +{ auto selectedRootFrames = selected_root_frame_references_get(); - if (selectedRootFrames.empty() || !animation) return; + if (selectedRootFrames.empty() || !animation) + return; auto targetItems = item_references_for_bake_into_other_frames_get( document, *animation, bakeIntoOtherFramesTarget, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); RootBakeOptions options{settings.bakeIsRoundScale, settings.bakeIsRoundRotation, - settings.bakeIsMatchRootInterpolation, settings.bakeIsUseRootPivot}; - edit_push(EDIT_BAKE_INTO_OTHER_FRAMES, [=](Model& model) - { return root_bake_into(model, selectedRootFrames, targetItems, options); }); - } + settings.bakeIsMatchRootInterpolation, settings.bakeIsUseRootPivot}; + edit_push(EDIT_BAKE_INTO_OTHER_FRAMES, + [=](Model& model) { return root_bake_into(model, selectedRootFrames, targetItems, options); }); +} - void TimelineContext::frame_split() - { +void TimelineContext::frame_split() +{ auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); - if (selectedFrames.empty()) return; + if (selectedFrames.empty()) + return; auto time = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); edit_push(EDIT_SPLIT_FRAME, [=](Model& model) { return frames_split(model, selectedFrames, time); }); - } +} - void TimelineContext::item_remove() - { +void TimelineContext::item_remove() +{ std::map> ids; std::map> groupIds; for (auto row : selected_row_references_get()) - if (row.type == LAYER || row.type == NULL_) (row.isGroup ? groupIds : ids)[row.type].insert(row.id); - if (!animation || (ids.empty() && groupIds.empty())) return; + if (row.type == LAYER || row.type == NULL_) + (row.isGroup ? groupIds : ids)[row.type].insert(row.id); + if (!animation || (ids.empty() && groupIds.empty())) + return; edit_push( - EDIT_REMOVE_ITEMS, [=, animationIndex = reference.animationIndex](Model& model) - { return items_remove(model, animationIndex, ids, groupIds); }, - [this](Document& document, const Uids&) - { - document.focus_clear(); - group_selection_reset_for(document); + EDIT_REMOVE_ITEMS, + [=, animationIndex = reference.animationIndex](Model& model) { + return items_remove(model, animationIndex, ids, groupIds); + }, + [this](Document& document, const Uids&) { + document.focus_clear(); + group_selection_reset_for(document); }); - } +} - std::vector TimelineContext::item_references_groupable_get() - { - if (!document.selection.uids[SelectionKind::GROUPS].empty()) return std::vector{}; +std::vector TimelineContext::item_references_groupable_get() +{ + if (!document.selection.uids[SelectionKind::GROUPS].empty()) + return std::vector{}; auto selectedItems = item_references_for_current_get(); - std::erase_if(selectedItems, [](const Reference& itemReference) - { return itemReference.itemType != LAYER && itemReference.itemType != NULL_; }); - if (selectedItems.empty()) return std::vector{}; + std::erase_if(selectedItems, [](const Reference& itemReference) { + return itemReference.itemType != LAYER && itemReference.itemType != NULL_; + }); + if (selectedItems.empty()) + return std::vector{}; auto itemType = selectedItems.begin()->itemType; for (auto& itemReference : selectedItems) - if (itemReference.itemType != itemType) return std::vector{}; + if (itemReference.itemType != itemType) + return std::vector{}; std::vector result; for (auto& row : timeline_item_rows_get()) { - if (row.isGroup || row.type != itemType) continue; - auto itemReference = item_reference_get(row.type, row.id, NONE, -1); - if (!selectedItems.contains(itemReference)) continue; - if (row.groupId != -1) return std::vector{}; - result.push_back(itemReference); + if (row.isGroup || row.type != itemType) + continue; + auto itemReference = item_reference_get(row.type, row.id, NONE, -1); + if (!selectedItems.contains(itemReference)) + continue; + if (row.groupId != -1) + return std::vector{}; + result.push_back(itemReference); } return result; - } +} - void TimelineContext::item_group() - { +void TimelineContext::item_group() +{ auto targetReferences = item_references_groupable_get(); - if (targetReferences.empty()) return; + if (targetReferences.empty()) + return; std::set ids; for (auto itemReference : targetReferences) - ids.insert(itemReference.itemID); + ids.insert(itemReference.itemID); edit_push( EDIT_GROUP_ITEMS, [=, animationIndex = reference.animationIndex, type = targetReferences.front().itemType, - name = std::string(localize.get(TEXT_NEW_GROUP))](Model& model) - { return items_group(model, animationIndex, type, ids, name); }, - [=, this](Document& document, const Uids& uids) - { - if (uids.empty()) return; - document.selected_set(SelectionKind::TRACKS, {targetReferences.begin(), targetReferences.end()}); - document.reference_set(targetReferences.front()); - document.frame_references_clear(); + name = std::string(localize.get(TEXT_NEW_GROUP))](Model& model) { + return items_group(model, animationIndex, type, ids, name); + }, + [=, this](Document& document, const Uids& uids) { + if (uids.empty()) + return; + document.selected_set(SelectionKind::TRACKS, {targetReferences.begin(), targetReferences.end()}); + document.reference_set(targetReferences.front()); + document.frame_references_clear(); }); - } +} - void TimelineContext::rows_move_to_row(std::vector draggedRows, TimelineRow targetRow, bool isDropAfter, - bool isDropIntoGroup) - { - if (draggedRows.empty()) return; +void TimelineContext::rows_move_to_row(std::vector draggedRows, TimelineRow targetRow, bool isDropAfter, + bool isDropIntoGroup) +{ + if (draggedRows.empty()) + return; auto targetType = draggedRows.front().type; - if (targetType != LAYER && targetType != NULL_) return; - if (std::ranges::any_of(draggedRows, [&](const auto& row) { return row.type != targetType; })) return; - if (targetRow.isGroup && targetRow.type != targetType) return; + if (targetType != LAYER && targetType != NULL_) + return; + if (std::ranges::any_of(draggedRows, [&](const auto& row) { return row.type != targetType; })) + return; + if (targetRow.isGroup && targetRow.type != targetType) + return; if (!targetRow.isGroup && targetRow.type != targetType && targetRow.type != NONE && targetRow.type != ROOT && targetRow.type != TRIGGER) - return; + return; std::set ids; std::set groupIds; for (auto& row : draggedRows) - (row.isGroup ? groupIds : ids).insert(row.id); - RowTarget target{targetRow.isGroup, targetRow.type, targetRow.id, - targetRow.type == ROOT ? -1 : targetRow.groupId}; + (row.isGroup ? groupIds : ids).insert(row.id); + RowTarget target{targetRow.isGroup, targetRow.type, targetRow.id, targetRow.type == ROOT ? -1 : targetRow.groupId}; auto animationIndex = reference.animationIndex; std::set tracks; std::set groups; for (auto& row : draggedRows) - (row.isGroup ? groups : tracks).insert(row_selection_reference_get(row)); + (row.isGroup ? groups : tracks).insert(row_selection_reference_get(row)); Selection moved = {}; selection_references_set(moved, model, SelectionKind::TRACKS, tracks); selection_references_set(moved, model, SelectionKind::GROUPS, groups); - if (!tracks.empty()) selection_focus_set(moved, model, *tracks.begin()); + if (!tracks.empty()) + selection_focus_set(moved, model, *tracks.begin()); edit_push( EDIT_MOVE_ITEMS, - [=](Model& model) - { - return items_move(model, animationIndex, targetType, ids, groupIds, target, isDropAfter, - isDropIntoGroup); + [=](Model& model) { + return items_move(model, animationIndex, targetType, ids, groupIds, target, isDropAfter, isDropIntoGroup); }, - [=, this](Document& document, const Uids&) - { - document.selection.uids[SelectionKind::TRACKS] = moved.uids.at(SelectionKind::TRACKS); - document.selection.uids[SelectionKind::GROUPS] = moved.uids.at(SelectionKind::GROUPS); - if (tracks.empty()) - document.reference_set({document.reference_get().animationIndex}); - else - document.selection.focus = moved.focus; - document.frame_references_clear(); + [=, this](Document& document, const Uids&) { + document.selection.uids[SelectionKind::TRACKS] = moved.uids.at(SelectionKind::TRACKS); + document.selection.uids[SelectionKind::GROUPS] = moved.uids.at(SelectionKind::GROUPS); + if (tracks.empty()) + document.reference_set({document.reference_get().animationIndex}); + else + document.selection.focus = moved.focus; + document.frame_references_clear(); }); - } +} - void TimelineContext::fit_animation_length() - { - if (!animation) return; - edit_push(EDIT_FIT_ANIMATION_LENGTH, [animationIndex = reference.animationIndex](Model& model) - { return animation_length_fit(model, animationIndex); }); - } +void TimelineContext::fit_animation_length() +{ + if (!animation) + return; + edit_push(EDIT_FIT_ANIMATION_LENGTH, [animationIndex = reference.animationIndex](Model& model) { + return animation_length_fit(model, animationIndex); + }); +} - void TimelineContext::frame_references_copy(const std::set& selectedFrames) - { - if (!animation || selectedFrames.empty()) return; +void TimelineContext::frame_references_copy(const std::set& selectedFrames) +{ + if (!animation || selectedFrames.empty()) + return; std::string clipboardString; for (auto frameReference : selectedFrames) { - auto frame = model.frame_get(frameReference); - if (!frame) continue; - clipboardString += frame_to_string(*frame, (ItemType)frameReference.itemType); + auto frame = model.frame_get(frameReference); + if (!frame) + continue; + clipboardString += frame_to_string(*frame, (ItemType)frameReference.itemType); } - if (clipboardString.empty()) return; + if (clipboardString.empty()) + return; clipboard.set(clipboardString); frameClipboard = {.text = clipboardString, .itemType = selectedFrames.begin()->itemType}; - } +} - void TimelineContext::copy() - { +void TimelineContext::copy() +{ auto selectedFrames = copy_frame_references_get(); - if (selectedFrames.empty()) return; + if (selectedFrames.empty()) + return; frame_references_copy(selectedFrames); - } +} - void TimelineContext::cut() - { +void TimelineContext::cut() +{ auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - if (selectedFrames.empty()) return; + if (selectedFrames.empty()) + return; frame_references_copy(selectedFrames); edit_push( EDIT_CUT_FRAMES, [=](Model& model) { return frames_delete(model, selectedFrames); }, [this](Document& document, const Uids&) { document.frame_focus_select(); }); - } +} - void TimelineContext::paste() - { +void TimelineContext::paste() +{ auto text = clipboard.get(); - if (text.empty()) return; + if (text.empty()) + return; if (!document.model.track_get(reference)) { - toast_log(Level::WARNING, TOAST_DESERIALIZE_FRAMES_NO_SELECTION); - return; + toast_log(Level::WARNING, TOAST_DESERIALIZE_FRAMES_NO_SELECTION); + return; } auto errorString = std::make_shared(); @@ -283,123 +314,137 @@ EDIT_PASTE_FRAMES, [=, targetReference = reference, selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE), - time = hoveredTime](Model& model) - { return frames_paste(model, targetReference, selectedFrames, text, time, errorString.get()); }, - [=, this](Document& document, const Uids& uids) - { - if (errorString->empty()) return document.frames_select(uids); - toasts.push(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), *errorString)); - logger.error( - std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, ENGLISH), *errorString)); + time = hoveredTime](Model& model) { + return frames_paste(model, targetReference, selectedFrames, text, time, errorString.get()); + }, + [=, this](Document& document, const Uids& uids) { + if (errorString->empty()) + return document.frames_select(uids); + toasts.push(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), *errorString)); + logger.error(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, ENGLISH), *errorString)); }); - } +} - // Sets the animation's start or end marker at a time, moving the other one if it would end up on the wrong side. - void TimelineContext::marker_set(bool isStart, int time) - { - if (!animation) return; +// Sets the animation's start or end marker at a time, moving the other one if it would end up on the wrong side. +void TimelineContext::marker_set(bool isStart, int time) +{ + if (!animation) + return; edit_push(isStart ? EDIT_START_MARKER : EDIT_END_MARKER, - [=, animationIndex = reference.animationIndex](Model& model) - { - auto animation = model.animation_edit(animationIndex); - if (!animation) return; - auto marker = std::clamp(time, 0, std::max(animation->frameNum - 1, 0)); - (isStart ? animation->startMarker : animation->endMarker) = marker; - auto& other = isStart ? animation->endMarker : animation->startMarker; - if (other != -1 && (isStart ? other < marker : other > marker)) other = marker; + [=, animationIndex = reference.animationIndex](Model& model) { + auto animation = model.animation_edit(animationIndex); + if (!animation) + return; + auto marker = std::clamp(time, 0, std::max(animation->frameNum - 1, 0)); + (isStart ? animation->startMarker : animation->endMarker) = marker; + auto& other = isStart ? animation->endMarker : animation->startMarker; + if (other != -1 && (isStart ? other < marker : other > marker)) + other = marker; }); - } +} - void TimelineContext::markers_remove() - { - edit_push(EDIT_REMOVE_MARKERS, - [animationIndex = reference.animationIndex](Model& model) - { - if (auto animation = model.animation_edit(animationIndex)) - animation->startMarker = animation->endMarker = -1; - }); - } +void TimelineContext::markers_remove() +{ + edit_push(EDIT_REMOVE_MARKERS, [animationIndex = reference.animationIndex](Model& model) { + if (auto animation = model.animation_edit(animationIndex)) + animation->startMarker = animation->endMarker = -1; + }); +} - // The frame a property is copied from: the focused frame, or else the first selected one. - std::optional TimelineContext::property_source_get() - { - if (reference.frameIndex >= 0 && model.frame_get(reference)) return reference; - auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - if (selectedFrames.empty()) return {}; - return *selectedFrames.begin(); - } - - // The frames a property is cut from or pasted into: the selected ones, or else the focused one. - std::set TimelineContext::property_targets_get() - { +// The frame a property is copied from: the focused frame, or else the first selected one. +std::optional TimelineContext::property_source_get() +{ + if (reference.frameIndex >= 0 && model.frame_get(reference)) + return reference; auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); if (selectedFrames.empty()) - if (auto source = property_source_get()) selectedFrames.insert(*source); + return {}; + return *selectedFrames.begin(); +} + +// The frames a property is cut from or pasted into: the selected ones, or else the focused one. +std::set TimelineContext::property_targets_get() +{ + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + if (selectedFrames.empty()) + if (auto source = property_source_get()) + selectedFrames.insert(*source); return selectedFrames; - } +} - // The frame this timeline put on the clipboard, while it is still there. - std::optional TimelineContext::property_clipboard_frame_get() - { - if (frameClipboard.text.empty() || clipboard.get() != frameClipboard.text) return {}; +// The frame this timeline put on the clipboard, while it is still there. +std::optional TimelineContext::property_clipboard_frame_get() +{ + if (frameClipboard.text.empty() || clipboard.get() != frameClipboard.text) + return {}; auto frames = frames_from_string(frameClipboard.text, (ItemType)frameClipboard.itemType); - if (frames.empty()) return {}; + if (frames.empty()) + return {}; return frames.front(); - } +} - // Every target frame has the property, and what it refers to (a region, shader, event, sound) exists for it. - bool TimelineContext::is_property_pasteable(FrameProperty property) - { - if (frameClipboard.property != -1 && frameClipboard.property != (int)property) return false; - if (!is_frame_property_valid(property, (ItemType)frameClipboard.itemType)) return false; +// Every target frame has the property, and what it refers to (a region, shader, event, sound) exists for it. +bool TimelineContext::is_property_pasteable(FrameProperty property) +{ + if (frameClipboard.property != -1 && frameClipboard.property != (int)property) + return false; + if (!is_frame_property_valid(property, (ItemType)frameClipboard.itemType)) + return false; auto source = property_clipboard_frame_get(); auto targets = property_targets_get(); - if (!source || targets.empty()) return false; + if (!source || targets.empty()) + return false; auto& content = model.content; for (auto target : targets) { - if (!is_frame_property_valid(property, (ItemType)target.itemType)) return false; - if (property == FrameProperty::REGION && source->regionId != -1) - { - auto layer = ::item_get(content.layers, target.itemID); - auto spritesheet = layer ? ::item_get(content.spritesheets, layer->spritesheetId) : nullptr; - if (!spritesheet || !::item_get(spritesheet->regions, source->regionId)) return false; - } + if (!is_frame_property_valid(property, (ItemType)target.itemType)) + return false; + if (property == FrameProperty::REGION && source->regionId != -1) + { + auto layer = ::item_get(content.layers, target.itemID); + auto spritesheet = layer ? ::item_get(content.spritesheets, layer->spritesheetId) : nullptr; + if (!spritesheet || !::item_get(spritesheet->regions, source->regionId)) + return false; + } } - if (property == FrameProperty::SHADER && source->shaderId != -1 && - !::item_get(content.shaders, source->shaderId)) - return false; + if (property == FrameProperty::SHADER && source->shaderId != -1 && !::item_get(content.shaders, source->shaderId)) + return false; if (property == FrameProperty::EVENT) - for (auto eventId : source->eventIds) - if (eventId != -1 && !::item_get(content.events, eventId)) return false; + for (auto eventId : source->eventIds) + if (eventId != -1 && !::item_get(content.events, eventId)) + return false; if (property == FrameProperty::SOUNDS) - for (auto soundId : source->soundIds) - if (soundId != -1 && !::item_get(content.sounds, soundId)) return false; + for (auto soundId : source->soundIds) + if (soundId != -1 && !::item_get(content.sounds, soundId)) + return false; return true; - } +} - void TimelineContext::property_copy(FrameProperty property) - { +void TimelineContext::property_copy(FrameProperty property) +{ auto source = property_source_get(); - if (!source) return; + if (!source) + return; frame_references_copy({*source}); frameClipboard.property = (int)property; - } +} - // Copies the property, then sets it back to its default on the targets. - void TimelineContext::property_cut(FrameProperty property) - { +// Copies the property, then sets it back to its default on the targets. +void TimelineContext::property_cut(FrameProperty property) +{ auto targets = property_targets_get(); property_copy(property); edit_push(EDIT_CUT_FRAME_PROPERTY, [=](Model& model) { return frames_property_set(model, targets, property, Frame{}); }); - } +} - void TimelineContext::property_paste(FrameProperty property) - { +void TimelineContext::property_paste(FrameProperty property) +{ auto source = property_clipboard_frame_get(); - if (!source || !is_property_pasteable(property)) return; - edit_push(EDIT_PASTE_FRAME_PROPERTY, [=, targets = property_targets_get(), source = *source](Model& model) - { return frames_property_set(model, targets, property, source); }); - } + if (!source || !is_property_pasteable(property)) + return; + edit_push(EDIT_PASTE_FRAME_PROPERTY, [=, targets = property_targets_get(), source = *source](Model& model) { + return frames_property_set(model, targets, property, source); + }); +} diff --git a/src/ui/timeline_frames.cpp b/src/ui/timeline_frames.cpp index e25979c..042e44e 100644 --- a/src/ui/timeline_frames.cpp +++ b/src/ui/timeline_frames.cpp @@ -1,99 +1,106 @@ #include "ui/timeline_context.h" - // Moves the dragged frames to `target`'s track, before its frame index. - void TimelineContext::frames_move_to(Reference target) - { - if (!frameMoveDrag.isActive || !animation || frameMoveDrag.animationIndex != reference.animationIndex) return; - if (target.itemType == TRIGGER) return; +// Moves the dragged frames to `target`'s track, before its frame index. +void TimelineContext::frames_move_to(Reference target) +{ + if (!frameMoveDrag.isActive || !animation || frameMoveDrag.animationIndex != reference.animationIndex) + return; + if (target.itemType == TRIGGER) + return; auto frames = std::set(frameMoveDrag.references.begin(), frameMoveDrag.references.end()); std::erase_if(frames, [](const Reference& frame) { return frame.itemType == TRIGGER || frame.frameIndex < 0; }); - if (frames.empty()) return; + if (frames.empty()) + return; auto insertIndex = std::exchange(target.frameIndex, -1); edit_push( - EDIT_MOVE_FRAMES, [frames, target, insertIndex](Model& model) - { return frames_move(model, frames, target, insertIndex); }, - [=, this](Document& document, const Uids& uids) - { - document.frames_select(uids); - if (target.itemType == LAYER) - if (auto layer = ::item_get(document.model.content.layers, target.itemID)) - document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); + EDIT_MOVE_FRAMES, + [frames, target, insertIndex](Model& model) { return frames_move(model, frames, target, insertIndex); }, + [=, this](Document& document, const Uids& uids) { + document.frames_select(uids); + if (target.itemType == LAYER) + if (auto layer = ::item_get(document.model.content.layers, target.itemID)) + document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); }); - } +} - ImVec2 TimelineContext::frame_box_content_point_get() - { +ImVec2 TimelineContext::frame_box_content_point_get() +{ auto mousePos = ImGui::GetIO().MousePos; return ImVec2(mousePos.x + scroll.x - frameBoxClipMin.x, mousePos.y + scroll.y - frameBoxClipMin.y); - } +} - ImVec2 TimelineContext::frame_box_screen_point_get(ImVec2 point) - { +ImVec2 TimelineContext::frame_box_screen_point_get(ImVec2 point) +{ return ImVec2(point.x - scroll.x + frameBoxClipMin.x, point.y - scroll.y + frameBoxClipMin.y); - } +} - void TimelineContext::frame_overlay_draw(ImDrawList* drawList, ImVec2 clipMin, ImVec2 clipMax) - { +void TimelineContext::frame_overlay_draw(ImDrawList* drawList, ImVec2 clipMin, ImVec2 clipMax) +{ if (isFrameBoxSelecting && isFrameBoxClipSet) { - auto boxContentMin = ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); - auto boxContentMax = ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); - auto boxMin = frame_box_screen_point_get(boxContentMin); - auto boxMax = frame_box_screen_point_get(boxContentMax); - auto boxClipMin = clipMin; - if (isPlayheadLineSet) boxClipMin.y = std::max(boxClipMin.y, playheadLineTopY); - drawList->PushClipRect(boxClipMin, clipMax, true); - drawList->AddRectFilled(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTargetBg)); - drawList->AddRect(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget)); - drawList->PopClipRect(); + auto boxContentMin = ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); + auto boxContentMax = ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); + auto boxMin = frame_box_screen_point_get(boxContentMin); + auto boxMax = frame_box_screen_point_get(boxContentMax); + auto boxClipMin = clipMin; + if (isPlayheadLineSet) + boxClipMin.y = std::max(boxClipMin.y, playheadLineTopY); + drawList->PushClipRect(boxClipMin, clipMax, true); + drawList->AddRectFilled(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTargetBg)); + drawList->AddRect(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget)); + drawList->PopClipRect(); } if (isPlayheadLineSet) { - auto lineTopY = std::max(clipMin.y, playheadLineTopY); - if (clipMax.y > lineTopY) - { - auto linePos = ImVec2(playheadLineCenterX - (PLAYHEAD_LINE_THICKNESS * 0.5f), lineTopY); - auto lineSize = ImVec2(PLAYHEAD_LINE_THICKNESS * 0.5f, clipMax.y - lineTopY); - drawList->PushClipRect(clipMin, clipMax, true); - drawList->AddRectFilled(linePos, ImVec2(linePos.x + lineSize.x, linePos.y + lineSize.y), - ImGui::GetColorU32(playheadLineColor)); - drawList->PopClipRect(); - } + auto lineTopY = std::max(clipMin.y, playheadLineTopY); + if (clipMax.y > lineTopY) + { + auto linePos = ImVec2(playheadLineCenterX - (PLAYHEAD_LINE_THICKNESS * 0.5f), lineTopY); + auto lineSize = ImVec2(PLAYHEAD_LINE_THICKNESS * 0.5f, clipMax.y - lineTopY); + drawList->PushClipRect(clipMin, clipMax, true); + drawList->AddRectFilled(linePos, ImVec2(linePos.x + lineSize.x, linePos.y + lineSize.y), + ImGui::GetColorU32(playheadLineColor)); + drawList->PopClipRect(); + } } - } +} - void TimelineContext::frame_child(const TimelineRow& row, int& index, float width) - { +void TimelineContext::frame_child(const TimelineRow& row, int& index, float width) +{ auto type = row.type; auto id = row.id; - auto row_reference_make = [&](int frameIndex = -1) - { return Reference{reference.animationIndex, type, id, frameIndex, row.groupType, row.groupId}; }; + auto row_reference_make = [&](int frameIndex = -1) { + return Reference{reference.animationIndex, type, id, frameIndex, row.groupType, row.groupId}; + }; auto childSize = ImVec2(width, rowFrameChildHeight); if (row.isGroup) { - auto group = row_group_get(row); - if (!group) return; + auto group = row_group_get(row); + if (!group) + return; - ImGui::PushID(index); - ImGui::BeginChild("##Frames Group Child", childSize, ImGuiChildFlags_None, - ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar); - ImGui::EndChild(); - index++; - ImGui::PopID(); - return; + ImGui::PushID(index); + ImGui::BeginChild("##Frames Group Child", childSize, ImGuiChildFlags_None, + ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar); + ImGui::EndChild(); + index++; + ImGui::PopID(); + return; } auto item = item_get(type, id, row.groupType, row.groupId); - if (type != NONE && !item) return; + if (type != NONE && !item) + return; auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; if (item && type == ROOT && row.groupId != -1) - isVisible = item->isVisible && is_track_group_visible(row.groupType, row.groupId); + isVisible = item->isVisible && is_track_group_visible(row.groupType, row.groupId); auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; - if (isOnlyShowLayers && type != LAYER) isVisible = false; + if (isOnlyShowLayers && type != LAYER) + isVisible = false; auto colorVec = color_get(COLOR_FRAME_BASE, type); auto colorActiveVec = color_get(COLOR_FRAME_ACTIVE, type); @@ -109,7 +116,8 @@ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); bool isDefaultChild = type == NONE; - if (isLightTheme && isDefaultChild) ImGui::PushStyleColor(ImGuiCol_ChildBg, TIMELINE_CHILD_BG_COLOR_LIGHT); + if (isLightTheme && isDefaultChild) + ImGui::PushStyleColor(ImGuiCol_ChildBg, TIMELINE_CHILD_BG_COLOR_LIGHT); bool isFramesChildVisible = ImGui::BeginChild("##Frames Child", childSize, ImGuiChildFlags_Borders); auto drawList = ImGui::GetWindowDrawList(); @@ -121,8 +129,8 @@ auto cursorScreenPos = ImGui::GetCursorScreenPos(); if (frameSize.x > 0.0f && ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { - auto mouseX = ImGui::GetIO().MousePos.x - cursorScreenPos.x; - frameSplitTimeAtCursor = glm::max(0, (int)std::floor(mouseX / frameSize.x)); + auto mouseX = ImGui::GetIO().MousePos.x - cursorScreenPos.x; + frameSplitTimeAtCursor = glm::max(0, (int)std::floor(mouseX / frameSize.x)); } auto border = glm::max(0.5f, ImGui::GetStyle().FrameBorderSize * 0.5f); auto borderLineLength = frameSize.y / 5; @@ -131,419 +139,444 @@ if (isFrameBoxSelecting && isFrameBoxClipSet && type != NONE && animation && item) { - auto boxMin = ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); - auto boxMax = ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); - auto rowMinY = cursorScreenPos.y + scroll.y - frameBoxClipMin.y; - auto rowMaxY = rowMinY + childSize.y; - float selectionFrameTime = 0; - int frameIndex = 0; - for (auto& frame : item->frames) - { - auto frameReference = row_reference_make(frameIndex); - auto frameStart = type == TRIGGER ? frame.atFrame : selectionFrameTime; - auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; - auto frameContentMin = ImVec2(frameStart * frameSize.x, rowMinY); - auto frameContentMax = ImVec2(frameEnd * frameSize.x, rowMaxY); - if (frameContentMin.x <= boxMax.x && frameContentMax.x >= boxMin.x && frameContentMin.y <= boxMax.y && - frameContentMax.y >= boxMin.y) - frameBoxSelection.insert(frameReference); - if (type != TRIGGER) selectionFrameTime += frame.duration; - ++frameIndex; - } + auto boxMin = ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); + auto boxMax = ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); + auto rowMinY = cursorScreenPos.y + scroll.y - frameBoxClipMin.y; + auto rowMaxY = rowMinY + childSize.y; + float selectionFrameTime = 0; + int frameIndex = 0; + for (auto& frame : item->frames) + { + auto frameReference = row_reference_make(frameIndex); + auto frameStart = type == TRIGGER ? frame.atFrame : selectionFrameTime; + auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; + auto frameContentMin = ImVec2(frameStart * frameSize.x, rowMinY); + auto frameContentMax = ImVec2(frameEnd * frameSize.x, rowMaxY); + if (frameContentMin.x <= boxMax.x && frameContentMax.x >= boxMin.x && frameContentMin.y <= boxMax.y && + frameContentMax.y >= boxMin.y) + frameBoxSelection.insert(frameReference); + if (type != TRIGGER) + selectionFrameTime += frame.duration; + ++frameIndex; + } } if (isFramesChildVisible) { - if (type == NONE) - { - if (length > 0) + if (type == NONE) { - if (isLightTheme) - { - auto totalMax = ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y); - drawList->AddRectFilled(cursorScreenPos, totalMax, ImGui::GetColorU32(timelineBackgroundColor)); - float animationWidth = std::min(framesSize.x, frameSize.x * (float)length); - drawList->AddRectFilled(cursorScreenPos, - ImVec2(cursorScreenPos.x + animationWidth, cursorScreenPos.y + framesSize.y), - ImGui::GetColorU32(timelinePlayheadRectColor)); - } - else - { - drawList->AddRectFilled(cursorScreenPos, - ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y), - ImGui::GetColorU32(ImGui::GetStyleColorVec4(ImGuiCol_Header))); - } + if (length > 0) + { + if (isLightTheme) + { + auto totalMax = ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y); + drawList->AddRectFilled(cursorScreenPos, totalMax, ImGui::GetColorU32(timelineBackgroundColor)); + float animationWidth = std::min(framesSize.x, frameSize.x * (float)length); + drawList->AddRectFilled( + cursorScreenPos, ImVec2(cursorScreenPos.x + animationWidth, cursorScreenPos.y + framesSize.y), + ImGui::GetColorU32(timelinePlayheadRectColor)); + } + else + { + drawList->AddRectFilled(cursorScreenPos, + ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y), + ImGui::GetColorU32(ImGui::GetStyleColorVec4(ImGuiCol_Header))); + } + } + + for (int i = frameMin; i < frameMax; i++) + { + auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); + + drawList->AddRect(frameScreenPos, + ImVec2(frameScreenPos.x + border, frameScreenPos.y + borderLineLength), + ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5f); + + drawList->AddRect(ImVec2(frameScreenPos.x, frameScreenPos.y + frameSize.y - borderLineLength), + ImVec2(frameScreenPos.x + border, frameScreenPos.y + frameSize.y), + ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5); + + if (i % FRAME_MULTIPLE == 0) + { + auto string = std::to_string(i); + auto textSize = ImGui::CalcTextSize(string.c_str()); + auto textPos = ImVec2(frameScreenPos.x + (frameSize.x - textSize.x) / 2, + frameScreenPos.y + (frameSize.y - textSize.y) / 2); + + drawList->AddRectFilled(frameScreenPos, + ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y), + ImGui::GetColorU32(frameMultipleOverlayColor)); + + drawList->AddText(textPos, ImGui::GetColorU32(textMultipleColor), string.c_str()); + } + } + + if (ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && + ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + playback_stop(); + isDragging = true; + } + + auto childPos = ImGui::GetWindowPos(); + auto mousePos = ImGui::GetIO().MousePos; + auto localMousePos = ImVec2(mousePos.x - childPos.x, mousePos.y - childPos.y); + hoveredTime = floorf(localMousePos.x / frameSize.x); + + if (isDragging) + { + playback.time = hoveredTime; + playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); + document.frameTime = playback.time; + } + + if (!playback.isPlaying) + playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); + + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + isDragging = false; + + // Markers show as faded playheads, with the numbers outside the range they set darkened. + if (length > 0 && animation) + { + auto x_get = [&](int time) { + return cursorScreenPos.x + frameSize.x * (float)time; + }; + auto range = animation_play_range_get(*animation); + auto bottom = cursorScreenPos.y + frameSize.y; + if (animation->startMarker != -1) + drawList->AddRectFilled(cursorScreenPos, ImVec2(x_get(range.x), bottom), MARKER_OUTSIDE_COLOR); + if (animation->endMarker != -1) + drawList->AddRectFilled(ImVec2(x_get(range.y), cursorScreenPos.y), + ImVec2(cursorScreenPos.x + framesSize.x, bottom), MARKER_OUTSIDE_COLOR); + auto markerTint = playheadIconTint; + markerTint.w *= MARKER_ALPHA; + for (auto marker : {animation->startMarker, animation->endMarker}) + if (marker != -1) + drawList->AddImage((ImTextureID)(intptr_t)resources.icon_id_get(ICON_PLAYHEAD), + ImVec2(x_get(marker), cursorScreenPos.y), + ImVec2(x_get(marker) + frameSize.x, bottom), ImVec2(0, 0), ImVec2(1, 1), + ImGui::GetColorU32(markerTint)); + } + + isRulerHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); + if (isRulerHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Right)) + markerTime = hoveredTime; + Actions markerActions = {}; + auto isAnimation = [&]() { + return animation != nullptr; + }; + markerActions.add({.label = LABEL_ADD_START_MARKER, + .shortcut = SHORTCUT_START_MARKER, + .isEnabled = isAnimation, + .run = [&]() { marker_set(true, markerTime); }}); + markerActions.add({.label = LABEL_ADD_END_MARKER, + .shortcut = SHORTCUT_END_MARKER, + .isEnabled = isAnimation, + .run = [&]() { marker_set(false, markerTime); }}); + markerActions.separator(); + markerActions.add( + {.label = LABEL_REMOVE_MARKERS, + .shortcut = -1, + .isEnabled = + [&]() { return animation && (animation->startMarker != -1 || animation->endMarker != -1); }, + .run = [&]() { markers_remove(); }}); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + actions_context_window_draw("##Marker Menu", markerActions, settings); + ImGui::PopStyleVar(2); + + if (length > 0) + { + ImGui::SetCursorPos(ImVec2(cursorPos.x + frameSize.x * floorf(playback.time), cursorPos.y)); + ImGui::Image(resources.icon_id_get(ICON_PLAYHEAD), frameSize); + auto playheadMin = ImGui::GetItemRectMin(); + auto playheadMax = ImGui::GetItemRectMax(); + playheadLineCenterX = (playheadMin.x + playheadMax.x) * 0.5f; + playheadLineTopY = playheadMax.y; + isPlayheadLineSet = true; + overlay_icon(resources.icon_id_get(ICON_PLAYHEAD), playheadIconTint, true); + } } - - for (int i = frameMin; i < frameMax; i++) + else if (animation) { - auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); - - drawList->AddRect(frameScreenPos, ImVec2(frameScreenPos.x + border, frameScreenPos.y + borderLineLength), - ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5f); - - drawList->AddRect(ImVec2(frameScreenPos.x, frameScreenPos.y + frameSize.y - borderLineLength), - ImVec2(frameScreenPos.x + border, frameScreenPos.y + frameSize.y), - ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5); - - if (i % FRAME_MULTIPLE == 0) - { - auto string = std::to_string(i); - auto textSize = ImGui::CalcTextSize(string.c_str()); - auto textPos = ImVec2(frameScreenPos.x + (frameSize.x - textSize.x) / 2, - frameScreenPos.y + (frameSize.y - textSize.y) / 2); - - drawList->AddRectFilled(frameScreenPos, - ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y), - ImGui::GetColorU32(frameMultipleOverlayColor)); - - drawList->AddText(textPos, ImGui::GetColorU32(textMultipleColor), string.c_str()); - } - } - - if (ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && - ImGui::IsMouseClicked(ImGuiMouseButton_Left)) - { - playback_stop(); - isDragging = true; - } - - auto childPos = ImGui::GetWindowPos(); - auto mousePos = ImGui::GetIO().MousePos; - auto localMousePos = ImVec2(mousePos.x - childPos.x, mousePos.y - childPos.y); - hoveredTime = floorf(localMousePos.x / frameSize.x); - - if (isDragging) - { - playback.time = hoveredTime; - playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); - document.frameTime = playback.time; - } - - if (!playback.isPlaying) playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); - - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) isDragging = false; - - // Markers show as faded playheads, with the numbers outside the range they set darkened. - if (length > 0 && animation) - { - auto x_get = [&](int time) { return cursorScreenPos.x + frameSize.x * (float)time; }; - auto range = animation_play_range_get(*animation); - auto bottom = cursorScreenPos.y + frameSize.y; - if (animation->startMarker != -1) - drawList->AddRectFilled(cursorScreenPos, ImVec2(x_get(range.x), bottom), MARKER_OUTSIDE_COLOR); - if (animation->endMarker != -1) - drawList->AddRectFilled(ImVec2(x_get(range.y), cursorScreenPos.y), - ImVec2(cursorScreenPos.x + framesSize.x, bottom), MARKER_OUTSIDE_COLOR); - auto markerTint = playheadIconTint; - markerTint.w *= MARKER_ALPHA; - for (auto marker : {animation->startMarker, animation->endMarker}) - if (marker != -1) - drawList->AddImage((ImTextureID)(intptr_t)resources.icon_id_get(ICON_PLAYHEAD), - ImVec2(x_get(marker), cursorScreenPos.y), ImVec2(x_get(marker) + frameSize.x, bottom), - ImVec2(0, 0), ImVec2(1, 1), ImGui::GetColorU32(markerTint)); - } - - isRulerHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); - if (isRulerHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Right)) markerTime = hoveredTime; - Actions markerActions = {}; - auto isAnimation = [&]() { return animation != nullptr; }; - markerActions.add({.label = LABEL_ADD_START_MARKER, - .shortcut = SHORTCUT_START_MARKER, - .isEnabled = isAnimation, - .run = [&]() { marker_set(true, markerTime); }}); - markerActions.add({.label = LABEL_ADD_END_MARKER, - .shortcut = SHORTCUT_END_MARKER, - .isEnabled = isAnimation, - .run = [&]() { marker_set(false, markerTime); }}); - markerActions.separator(); - markerActions.add( - {.label = LABEL_REMOVE_MARKERS, - .shortcut = -1, - .isEnabled = [&]() { return animation && (animation->startMarker != -1 || animation->endMarker != -1); }, - .run = [&]() { markers_remove(); }}); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - actions_context_window_draw("##Marker Menu", markerActions, settings); - ImGui::PopStyleVar(2); - - if (length > 0) - { - ImGui::SetCursorPos(ImVec2(cursorPos.x + frameSize.x * floorf(playback.time), cursorPos.y)); - ImGui::Image(resources.icon_id_get(ICON_PLAYHEAD), frameSize); - auto playheadMin = ImGui::GetItemRectMin(); - auto playheadMax = ImGui::GetItemRectMax(); - playheadLineCenterX = (playheadMin.x + playheadMax.x) * 0.5f; - playheadLineTopY = playheadMax.y; - isPlayheadLineSet = true; - overlay_icon(resources.icon_id_get(ICON_PLAYHEAD), playheadIconTint, true); - } - } - else if (animation) - { - float frameTime = 0; - - for (int i = frameMin; i < frameMax; i++) - { - auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); - auto frameRectMax = ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y); - - drawList->AddRect(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameBorderColor)); - - if (i % FRAME_MULTIPLE == 0) - drawList->AddRectFilled(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameMultipleOverlayColor)); - } - - if (!frameMoveDrag.isActive && !ImGui::IsKeyDown(ImGuiMod_Shift) && - ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && - ImGui::IsMouseClicked(ImGuiMouseButton_Left) && !ImGui::IsAnyItemHovered()) - { - isFrameBoxPending = true; - isFrameBoxAdditive = ImGui::IsKeyDown(ImGuiMod_Ctrl); - frameBoxStart = frame_box_content_point_get(); - frameBoxEnd = frameBoxStart; - frameBoxSelection.clear(); - } - - bool isFrameMovePreview = false; - ImVec2 frameMovePreviewMin; - ImVec2 frameMovePreviewMax; - bool isFrameMoveHoveredFrame = false; - ImVec2 frameMoveHoveredFrameMin; - ImVec2 frameMoveHoveredFrameMax; - - if (frameMoveDrag.isActive && type != TRIGGER) - { - auto mousePos = ImGui::GetIO().MousePos; - auto rowMin = cursorScreenPos; - auto rowMax = ImVec2(cursorScreenPos.x + width, cursorScreenPos.y + frameSize.y); - if (mousePos.x >= rowMin.x && mousePos.x < rowMax.x && mousePos.y >= rowMin.y && mousePos.y < rowMax.y) - { - auto mouseX = mousePos.x - cursorScreenPos.x; - auto targetTime = glm::max(0.0f, mouseX / frameSize.x); - int dropIndex = (int)item->frames.size(); - float dropFrameTime = 0; float frameTime = 0; - int frameIndex = 0; - for (auto& frame : item->frames) + for (int i = frameMin; i < frameMax; i++) { - auto frameStart = frameTime; - auto frameEnd = frameStart + frame.duration; - if (!isFrameMoveHoveredFrame && targetTime >= frameStart && targetTime < frameEnd) - { - isFrameMoveHoveredFrame = true; - frameMoveHoveredFrameMin = ImVec2(cursorScreenPos.x + frameStart * frameSize.x, cursorScreenPos.y); - frameMoveHoveredFrameMax = - ImVec2(cursorScreenPos.x + frameEnd * frameSize.x, cursorScreenPos.y + frameSize.y); - } + auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); + auto frameRectMax = ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y); - auto midpoint = frameStart + ((float)frame.duration * 0.5f); - if (targetTime < midpoint) - { - dropIndex = frameIndex; - dropFrameTime = frameStart; - break; - } + drawList->AddRect(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameBorderColor)); - frameTime = frameEnd; - dropFrameTime = frameTime; - ++frameIndex; + if (i % FRAME_MULTIPLE == 0) + drawList->AddRectFilled(frameScreenPos, frameRectMax, + ImGui::GetColorU32(frameMultipleOverlayColor)); } - frameMoveDropTarget = Reference{reference.animationIndex, type, id, dropIndex, row.groupType, row.groupId}; - - auto dropX = cursorScreenPos.x + dropFrameTime * frameSize.x; - auto previewWidth = glm::max(frameSize.x, (float)frameMoveDrag.duration * frameSize.x); - frameMovePreviewMin = ImVec2(dropX, cursorScreenPos.y); - frameMovePreviewMax = ImVec2(dropX + previewWidth, cursorScreenPos.y + frameSize.y); - isFrameMovePreview = true; - } - } - - auto& selectedFrames = document.selection.uids[SelectionKind::FRAMES]; - for (int frameIndex = 0; frameIndex < (int)item->frames.size(); ++frameIndex) - { - auto& frame = item->frames[frameIndex]; - ImGui::PushID(frameIndex); - - auto frameReference = row_reference_make(frameIndex); - auto isFrameVisible = isVisible && frame.isVisible; - auto isReferenced = reference == frameReference; - auto isSelected = selectedFrames.contains(frame.uid); - - if (type == TRIGGER) frameTime = frame.atFrame; - - auto buttonSize = type == TRIGGER ? frameSize : to_imvec2(vec2(frameSize.x * frame.duration, frameSize.y)); - auto frameStart = type == TRIGGER ? frame.atFrame : frameTime; - auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; - if (frameEnd <= (float)frameMin || frameStart >= (float)frameMax) - { - if (type != TRIGGER) frameTime += frame.duration; - ImGui::PopID(); - continue; - } - auto buttonPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y); - - ImGui::SetCursorPos(buttonPos); - - auto buttonScreenPos = ImGui::GetCursorScreenPos(); - auto fillColor = - isSelected ? (isFrameVisible ? colorActive : colorActiveHidden) : (isFrameVisible ? color : colorHidden); - drawList->AddRectFilled(buttonScreenPos, - ImVec2(buttonScreenPos.x + buttonSize.x, buttonScreenPos.y + buttonSize.y), - ImGui::GetColorU32(fillColor), FRAME_ROUNDING); - - ImGui::PushStyleColor(ImGuiCol_Header, isFrameVisible ? colorActive : colorActiveHidden); - ImGui::PushStyleColor(ImGuiCol_HeaderActive, isFrameVisible ? colorActive : colorActiveHidden); - ImGui::PushStyleColor(ImGuiCol_HeaderHovered, isFrameVisible ? colorHovered : colorHoveredHidden); - ImGui::PushStyleColor(ImGuiCol_NavCursor, isFrameVisible ? colorHovered : colorHoveredHidden); - - ImGui::SetNextItemAllowOverlap(); - ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, FRAME_ROUNDING); - ImGui::SetNextItemSelectionUserData(frameIndex); - if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) - { - if (type == LAYER) - if (auto layer = ::item_get(model.content.layers, id)) - document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); - - if (type != TRIGGER) + if (!frameMoveDrag.isActive && !ImGui::IsKeyDown(ImGuiMod_Shift) && + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && + ImGui::IsMouseClicked(ImGuiMouseButton_Left) && !ImGui::IsAnyItemHovered()) { - if (ImGui::IsKeyDown(ImGuiMod_Alt)) - { - auto targetReference = frameReference; - edit_push(EDIT_FRAME_INTERPOLATION, - [=](Model& model) - { - if (auto frame = model.frame_edit(targetReference)) - frame->interpolation = frame->interpolation == Interpolation::NONE ? Interpolation::LINEAR - : Interpolation::NONE; - }); - } - - document.frameTime = frameTime; + isFrameBoxPending = true; + isFrameBoxAdditive = ImGui::IsKeyDown(ImGuiMod_Ctrl); + frameBoxStart = frame_box_content_point_get(); + frameBoxEnd = frameBoxStart; + frameBoxSelection.clear(); } - auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); - auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); - if (isShiftDown) - { - auto isRangeSelected = document.frames_range_select(frameSelectionAnchor.value_or(frameReference), - frameReference, isCtrlDown); - if (!isRangeSelected) document.frame_select(frameReference); - if (!frameSelectionAnchor || !isRangeSelected) frameSelectionAnchor = frameReference; - } - else - { - isCtrlDown ? document.frame_toggle(frameReference) : document.frame_select(frameReference); - frameSelectionAnchor = frameReference; - } - reference_set(frameReference); - isReferenced = true; - document.selected_clear(SelectionKind::REGIONS); - } - ImGui::PopStyleVar(); + bool isFrameMovePreview = false; + ImVec2 frameMovePreviewMin; + ImVec2 frameMovePreviewMax; + bool isFrameMoveHoveredFrame = false; + ImVec2 frameMoveHoveredFrameMin; + ImVec2 frameMoveHoveredFrameMax; - ImGui::PopStyleColor(4); - - if (!isDraggedFrameActive && ImGui::IsItemHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Left)) - { - if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) + if (frameMoveDrag.isActive && type != TRIGGER) { - if (type == TRIGGER || ImGui::IsKeyDown(ImGuiMod_Ctrl)) - { - isDraggedFrameActive = true; - draggedFrameReference = frameReference; - draggedFrameType = type; - draggedFrameStart = hoveredTime; - if (type != TRIGGER) draggedFrameStartDuration = frame.duration; - draggedFrameStartDurations.clear(); + auto mousePos = ImGui::GetIO().MousePos; + auto rowMin = cursorScreenPos; + auto rowMax = ImVec2(cursorScreenPos.x + width, cursorScreenPos.y + frameSize.y); + if (mousePos.x >= rowMin.x && mousePos.x < rowMax.x && mousePos.y >= rowMin.y && mousePos.y < rowMax.y) + { + auto mouseX = mousePos.x - cursorScreenPos.x; + auto targetTime = glm::max(0.0f, mouseX / frameSize.x); + int dropIndex = (int)item->frames.size(); + float dropFrameTime = 0; + float frameTime = 0; + int frameIndex = 0; + + for (auto& frame : item->frames) + { + auto frameStart = frameTime; + auto frameEnd = frameStart + frame.duration; + if (!isFrameMoveHoveredFrame && targetTime >= frameStart && targetTime < frameEnd) + { + isFrameMoveHoveredFrame = true; + frameMoveHoveredFrameMin = + ImVec2(cursorScreenPos.x + frameStart * frameSize.x, cursorScreenPos.y); + frameMoveHoveredFrameMax = + ImVec2(cursorScreenPos.x + frameEnd * frameSize.x, cursorScreenPos.y + frameSize.y); + } + + auto midpoint = frameStart + ((float)frame.duration * 0.5f); + if (targetTime < midpoint) + { + dropIndex = frameIndex; + dropFrameTime = frameStart; + break; + } + + frameTime = frameEnd; + dropFrameTime = frameTime; + ++frameIndex; + } + + frameMoveDropTarget = + Reference{reference.animationIndex, type, id, dropIndex, row.groupType, row.groupId}; + + auto dropX = cursorScreenPos.x + dropFrameTime * frameSize.x; + auto previewWidth = glm::max(frameSize.x, (float)frameMoveDrag.duration * frameSize.x); + frameMovePreviewMin = ImVec2(dropX, cursorScreenPos.y); + frameMovePreviewMax = ImVec2(dropX + previewWidth, cursorScreenPos.y + frameSize.y); + isFrameMovePreview = true; + } + } + + auto& selectedFrames = document.selection.uids[SelectionKind::FRAMES]; + for (int frameIndex = 0; frameIndex < (int)item->frames.size(); ++frameIndex) + { + auto& frame = item->frames[frameIndex]; + ImGui::PushID(frameIndex); + + auto frameReference = row_reference_make(frameIndex); + auto isFrameVisible = isVisible && frame.isVisible; + auto isReferenced = reference == frameReference; + auto isSelected = selectedFrames.contains(frame.uid); + + if (type == TRIGGER) + frameTime = frame.atFrame; + + auto buttonSize = + type == TRIGGER ? frameSize : to_imvec2(vec2(frameSize.x * frame.duration, frameSize.y)); + auto frameStart = type == TRIGGER ? frame.atFrame : frameTime; + auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; + if (frameEnd <= (float)frameMin || frameStart >= (float)frameMax) + { + if (type != TRIGGER) + frameTime += frame.duration; + ImGui::PopID(); + continue; + } + auto buttonPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y); + + ImGui::SetCursorPos(buttonPos); + + auto buttonScreenPos = ImGui::GetCursorScreenPos(); + auto fillColor = isSelected ? (isFrameVisible ? colorActive : colorActiveHidden) + : (isFrameVisible ? color : colorHidden); + drawList->AddRectFilled(buttonScreenPos, + ImVec2(buttonScreenPos.x + buttonSize.x, buttonScreenPos.y + buttonSize.y), + ImGui::GetColorU32(fillColor), FRAME_ROUNDING); + + ImGui::PushStyleColor(ImGuiCol_Header, isFrameVisible ? colorActive : colorActiveHidden); + ImGui::PushStyleColor(ImGuiCol_HeaderActive, isFrameVisible ? colorActive : colorActiveHidden); + ImGui::PushStyleColor(ImGuiCol_HeaderHovered, isFrameVisible ? colorHovered : colorHoveredHidden); + ImGui::PushStyleColor(ImGuiCol_NavCursor, isFrameVisible ? colorHovered : colorHoveredHidden); + + ImGui::SetNextItemAllowOverlap(); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, FRAME_ROUNDING); + ImGui::SetNextItemSelectionUserData(frameIndex); + if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) + { + if (type == LAYER) + if (auto layer = ::item_get(model.content.layers, id)) + document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); + + if (type != TRIGGER) + { + if (ImGui::IsKeyDown(ImGuiMod_Alt)) + { + auto targetReference = frameReference; + edit_push(EDIT_FRAME_INTERPOLATION, [=](Model& model) { + if (auto frame = model.frame_edit(targetReference)) + frame->interpolation = frame->interpolation == Interpolation::NONE + ? Interpolation::LINEAR + : Interpolation::NONE; + }); + } + + document.frameTime = frameTime; + } + + auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); + auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); + if (isShiftDown) + { + auto isRangeSelected = document.frames_range_select( + frameSelectionAnchor.value_or(frameReference), frameReference, isCtrlDown); + if (!isRangeSelected) + document.frame_select(frameReference); + if (!frameSelectionAnchor || !isRangeSelected) + frameSelectionAnchor = frameReference; + } + else + { + isCtrlDown ? document.frame_toggle(frameReference) : document.frame_select(frameReference); + frameSelectionAnchor = frameReference; + } + reference_set(frameReference); + isReferenced = true; + document.selected_clear(SelectionKind::REGIONS); + } + ImGui::PopStyleVar(); + + ImGui::PopStyleColor(4); + + if (!isDraggedFrameActive && ImGui::IsItemHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Left)) + { + if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) + { + if (type == TRIGGER || ImGui::IsKeyDown(ImGuiMod_Ctrl)) + { + isDraggedFrameActive = true; + draggedFrameReference = frameReference; + draggedFrameType = type; + draggedFrameStart = hoveredTime; + if (type != TRIGGER) + draggedFrameStartDuration = frame.duration; + draggedFrameStartDurations.clear(); + if (type != TRIGGER) + for (auto selectedReference : drag_frame_references_get(frameReference)) + if (auto selectedFrame = document.model.frame_get(selectedReference)) + draggedFrameStartDurations.push_back( + {selectedReference, selectedFrame->duration}); + draggedFrameStartMouseX = ImGui::GetIO().MousePos.x; + draggedFrameWidth = frameSize.x; + } + } + } + if (type != TRIGGER) - for (auto selectedReference : drag_frame_references_get(frameReference)) - if (auto selectedFrame = document.model.frame_get(selectedReference)) - draggedFrameStartDurations.push_back({selectedReference, selectedFrame->duration}); - draggedFrameStartMouseX = ImGui::GetIO().MousePos.x; - draggedFrameWidth = frameSize.x; - } - } - } + { + if (!isDraggedFrameActive && !frameMoveDrag.isActive && ImGui::IsItemActive() && + ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + auto selectedReferences = drag_frame_references_get(frameReference); + int dragDuration = 0; + for (auto selectedReference : selectedReferences) + if (auto selectedFrame = document.model.frame_get(selectedReference)) + dragDuration += selectedFrame->duration; + dragDuration = glm::max(1, dragDuration); - if (type != TRIGGER) - { - if (!isDraggedFrameActive && !frameMoveDrag.isActive && ImGui::IsItemActive() && - ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + frameMoveDrag = {.animationIndex = reference.animationIndex, + .duration = dragDuration, + .references = {selectedReferences.begin(), selectedReferences.end()}, + .isActive = true}; + } + } + + auto rectMin = ImGui::GetItemRectMin(); + auto rectMax = ImGui::GetItemRectMax(); + auto borderColor = isReferenced ? frameBorderColorReferenced : frameBorderColor; + auto borderThickness = isReferenced ? FRAME_BORDER_THICKNESS_REFERENCED : FRAME_BORDER_THICKNESS; + drawList->AddRect(rectMin, rectMax, ImGui::GetColorU32(borderColor), FRAME_ROUNDING, 0, + borderThickness); + + auto icon = type == TRIGGER ? ICON_TRIGGER : INTERPOLATION_ICONS[(int)frame.interpolation]; + auto iconPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), + cursorPos.y + (frameSize.y / 2) - (icon_size_get().y / 2)); + ImGui::SetCursorPos(iconPos); + ImGui::Image(resources.icon_id_get(icon), icon_size_get()); + overlay_icon(resources.icon_id_get(icon), iconTintDefault, false); + + if (type != TRIGGER) + frameTime += frame.duration; + + ImGui::PopID(); + } + + if (isFrameMovePreview) { - auto selectedReferences = drag_frame_references_get(frameReference); - int dragDuration = 0; - for (auto selectedReference : selectedReferences) - if (auto selectedFrame = document.model.frame_get(selectedReference)) - dragDuration += selectedFrame->duration; - dragDuration = glm::max(1, dragDuration); - - frameMoveDrag = {.animationIndex = reference.animationIndex, - .duration = dragDuration, - .references = {selectedReferences.begin(), selectedReferences.end()}, - .isActive = true}; + drawList->AddRectFilled(frameMovePreviewMin, frameMovePreviewMax, + ImGui::GetColorU32(ImGuiCol_DragDropTargetBg), FRAME_ROUNDING); + drawList->AddRect(frameMovePreviewMin, frameMovePreviewMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget), + FRAME_ROUNDING, 0, ImGui::GetStyle().DragDropTargetBorderSize); } - } - auto rectMin = ImGui::GetItemRectMin(); - auto rectMax = ImGui::GetItemRectMax(); - auto borderColor = isReferenced ? frameBorderColorReferenced : frameBorderColor; - auto borderThickness = isReferenced ? FRAME_BORDER_THICKNESS_REFERENCED : FRAME_BORDER_THICKNESS; - drawList->AddRect(rectMin, rectMax, ImGui::GetColorU32(borderColor), FRAME_ROUNDING, 0, borderThickness); + if (isFrameMoveHoveredFrame) + drawList->AddRect(frameMoveHoveredFrameMin, frameMoveHoveredFrameMax, + ImGui::GetColorU32(ImGuiCol_DragDropTarget), FRAME_ROUNDING, 0, + ImGui::GetStyle().DragDropTargetBorderSize * 1.5f); - auto icon = type == TRIGGER ? ICON_TRIGGER : INTERPOLATION_ICONS[(int)frame.interpolation]; - auto iconPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), - cursorPos.y + (frameSize.y / 2) - (icon_size_get().y / 2)); - ImGui::SetCursorPos(iconPos); - ImGui::Image(resources.icon_id_get(icon), icon_size_get()); - overlay_icon(resources.icon_id_get(icon), iconTintDefault, false); - - if (type != TRIGGER) frameTime += frame.duration; - - ImGui::PopID(); + if (!isFrameBoxSelecting && !frameMoveDrag.isActive && !isDraggedFrameActive && ImGui::IsWindowHovered() && + (ImGui::IsMouseReleased(ImGuiMouseButton_Left) || ImGui::IsMouseReleased(ImGuiMouseButton_Right)) && + !ImGui::IsAnyItemHovered()) + row_selection_set(row); } - - if (isFrameMovePreview) - { - drawList->AddRectFilled(frameMovePreviewMin, frameMovePreviewMax, - ImGui::GetColorU32(ImGuiCol_DragDropTargetBg), FRAME_ROUNDING); - drawList->AddRect(frameMovePreviewMin, frameMovePreviewMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget), - FRAME_ROUNDING, 0, ImGui::GetStyle().DragDropTargetBorderSize); - } - - if (isFrameMoveHoveredFrame) - drawList->AddRect(frameMoveHoveredFrameMin, frameMoveHoveredFrameMax, - ImGui::GetColorU32(ImGuiCol_DragDropTarget), FRAME_ROUNDING, 0, - ImGui::GetStyle().DragDropTargetBorderSize * 1.5f); - - if (!isFrameBoxSelecting && !frameMoveDrag.isActive && !isDraggedFrameActive && ImGui::IsWindowHovered() && - (ImGui::IsMouseReleased(ImGuiMouseButton_Left) || ImGui::IsMouseReleased(ImGuiMouseButton_Right)) && - !ImGui::IsAnyItemHovered()) - row_selection_set(row); - } } ImGui::EndChild(); - if (isLightTheme && isDefaultChild) ImGui::PopStyleColor(); + if (isLightTheme && isDefaultChild) + ImGui::PopStyleColor(); ImGui::PopStyleVar(); index++; ImGui::PopID(); - } +} - // Frame drags, once per frame after the rows: dropping moved frames, and resizing frames (or moving a trigger). - void TimelineContext::frame_drag_update() - { +// Frame drags, once per frame after the rows: dropping moved frames, and resizing frames (or moving a trigger). +void TimelineContext::frame_drag_update() +{ if (frameMoveDrag.isActive && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { - if (frameMoveDropTarget) frames_move_to(*frameMoveDropTarget); - frameMoveDrag = {}; + if (frameMoveDropTarget) + frames_move_to(*frameMoveDropTarget); + frameMoveDrag = {}; } - if (!isDraggedFrameActive) return; + if (!isDraggedFrameActive) + return; ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); auto durationDelta = draggedFrameWidth > 0.0f @@ -553,55 +586,55 @@ if (!isDraggedFrameSnapshot && isDraggedFrameChanged) { - isDraggedFrameSnapshot = true; - edit_begin_push(draggedFrameType == TRIGGER ? EDIT_TRIGGER_AT_FRAME : EDIT_FRAME_DURATION); + isDraggedFrameSnapshot = true; + edit_begin_push(draggedFrameType == TRIGGER ? EDIT_TRIGGER_AT_FRAME : EDIT_FRAME_DURATION); } if (isDraggedFrameSnapshot) { - auto targetReference = draggedFrameReference; - if (draggedFrameType == TRIGGER) - { - auto atFrame = glm::clamp(hoveredTime, 0, - settings.playbackIsClamp && animation ? animation->frameNum - 1 : FRAME_NUM_MAX - 1); - command_push([=](Manager&, Document& document) - { trigger_at_frame_set(document.model, targetReference, atFrame); }); - } - else - { - std::map durations; - if (draggedFrameStartDurations.empty()) durations[targetReference] = draggedFrameStartDuration + durationDelta; - for (auto frameDuration : draggedFrameStartDurations) - durations[frameDuration.reference] = frameDuration.duration + durationDelta; - command_push([=](Manager&, Document& document) { frame_durations_set(document.model, durations); }); - } + auto targetReference = draggedFrameReference; + if (draggedFrameType == TRIGGER) + { + auto atFrame = glm::clamp( + hoveredTime, 0, settings.playbackIsClamp && animation ? animation->frameNum - 1 : FRAME_NUM_MAX - 1); + command_push( + [=](Manager&, Document& document) { trigger_at_frame_set(document.model, targetReference, atFrame); }); + } + else + { + std::map durations; + if (draggedFrameStartDurations.empty()) + durations[targetReference] = draggedFrameStartDuration + durationDelta; + for (auto frameDuration : draggedFrameStartDurations) + durations[frameDuration.reference] = frameDuration.duration + durationDelta; + command_push([=](Manager&, Document& document) { frame_durations_set(document.model, durations); }); + } } if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { - auto targetReference = draggedFrameReference; - auto targetType = draggedFrameType; - command_push( - [=, this](Manager&, Document& document) - { + auto targetReference = draggedFrameReference; + auto targetType = draggedFrameType; + command_push([=, this](Manager&, Document& document) { auto item = document.model.track_edit(targetReference); - if (targetType == TRIGGER && item) frames_sort_by_at_frame(*item); + if (targetType == TRIGGER && item) + frames_sort_by_at_frame(*item); document.change(); - }); - isDraggedFrameActive = false; - draggedFrameReference = {}; - draggedFrameType = NONE; - draggedFrameStart = -1; - draggedFrameStartDuration = -1; - draggedFrameStartDurations.clear(); - draggedFrameStartMouseX = 0.0f; - draggedFrameWidth = 0.0f; - isDraggedFrameSnapshot = false; + }); + isDraggedFrameActive = false; + draggedFrameReference = {}; + draggedFrameType = NONE; + draggedFrameStart = -1; + draggedFrameStartDuration = -1; + draggedFrameStartDurations.clear(); + draggedFrameStartMouseX = 0.0f; + draggedFrameWidth = 0.0f; + isDraggedFrameSnapshot = false; } - } +} - void TimelineContext::frames_child() - { +void TimelineContext::frames_child() +{ auto cursorPos = ImGui::GetCursorPos(); ImGui::SetCursorPos(ImVec2(cursorPos.x + ITEM_CHILD_WIDTH, cursorPos.y)); @@ -609,311 +642,310 @@ if (ImGui::BeginChild("##Frames Child", framesChildSize, ImGuiChildFlags_Borders)) { - auto viewListChildSize = - ImVec2(ImGui::GetContentRegionAvail().x, - ImGui::GetContentRegionAvail().y - ImGui::GetTextLineHeightWithSpacing() - style.ItemSpacing.y * 2); + auto viewListChildSize = + ImVec2(ImGui::GetContentRegionAvail().x, + ImGui::GetContentRegionAvail().y - ImGui::GetTextLineHeightWithSpacing() - style.ItemSpacing.y * 2); - auto animationsLength = [&]() - { - int length = 0; - for (auto [index, item] : model.animations_get()) - length = std::max(length, animation_length_get(*item)); - return length; - }(); - auto childWidth = animationsLength * ImGui::GetTextLineHeight(); - if (animation && animation->frameNum > animationsLength) - childWidth = animation->frameNum * ImGui::GetTextLineHeight(); - childWidth = std::max(childWidth, ImGui::GetContentRegionAvail().x); + auto animationsLength = [&]() { + int length = 0; + for (auto [index, item] : model.animations_get()) + length = std::max(length, animation_length_get(*item)); + return length; + }(); + auto childWidth = animationsLength * ImGui::GetTextLineHeight(); + if (animation && animation->frameNum > animationsLength) + childWidth = animation->frameNum * ImGui::GetTextLineHeight(); + childWidth = std::max(childWidth, ImGui::GetContentRegionAvail().x); - childWidth *= WIDTH_MULTIPLIER; + childWidth *= WIDTH_MULTIPLIER; - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - if (ImGui::BeginChild("##Frames List Child", viewListChildSize, true, ImGuiWindowFlags_HorizontalScrollbar)) - { - playheadLineCenterX = 0.0f; - playheadLineTopY = 0.0f; - isPlayheadLineSet = false; - isFrameBoxClipSet = false; - if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + if (ImGui::BeginChild("##Frames List Child", viewListChildSize, true, ImGuiWindowFlags_HorizontalScrollbar)) { - group_selection_reset_for(document); - document.frame_references_set(document.selected_item_frame_references_get()); - } - - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && - ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) - { - if (!document.selection.uids[SelectionKind::FRAMES].empty()) - { - reference_set(item_reference_from_frame_get(reference)); - document.frame_references_clear(); - } - else if (reference.itemType != NONE || reference.itemID != -1) - group_selection_reset_for(document); - document.focus_clear(); - } - - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); - if (ImGui::BeginTable("##Frames List Table", 1, - ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) - { - ImGuiWindow* window = ImGui::GetCurrentWindow(); - window->Flags |= ImGuiWindowFlags_NoScrollWithMouse; - - scroll.x = ImGui::GetScrollX(); - scroll.y = ImGui::GetScrollY(); - - isHorizontalScroll = window->ScrollbarX; - - if (isWindowHovered) - { - auto& io = ImGui::GetIO(); - auto lineHeight = ImGui::GetTextLineHeightWithSpacing() * 2; - - scroll.x -= io.MouseWheelH * lineHeight; - scroll.y -= io.MouseWheel * lineHeight; - } - - ImGui::SetScrollX(scroll.x); - ImGui::SetScrollY(scroll.y); - - auto frameBoxDrawList = ImGui::GetWindowDrawList(); - frameBoxClipMin = frameBoxDrawList->GetClipRectMin(); - frameBoxClipMax = frameBoxDrawList->GetClipRectMax(); - isFrameBoxClipSet = true; - if (isFrameBoxPending || isFrameBoxSelecting) - { - auto& io = ImGui::GetIO(); - auto threshold = ImGui::GetTextLineHeightWithSpacing() * 0.125f; - frameBoxEnd = frame_box_content_point_get(); - auto distance = ImVec2(frameBoxEnd.x - frameBoxStart.x, frameBoxEnd.y - frameBoxStart.y); - if (isFrameBoxPending && distance.x * distance.x + distance.y * distance.y >= threshold * threshold) + playheadLineCenterX = 0.0f; + playheadLineTopY = 0.0f; + isPlayheadLineSet = false; + isFrameBoxClipSet = false; + if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) { - isFrameBoxPending = false; - isFrameBoxSelecting = true; + group_selection_reset_for(document); + document.frame_references_set(document.selected_item_frame_references_get()); } - auto edgeSize = ImGui::GetTextLineHeightWithSpacing(); - auto scrollStep = edgeSize * 0.5f; - if (isFrameBoxSelecting) + + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && + ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) { - if (io.MousePos.x < frameBoxClipMin.x + edgeSize) - scroll.x -= scrollStep; - else if (io.MousePos.x > frameBoxClipMax.x - edgeSize) - scroll.x += scrollStep; - if (io.MousePos.y < frameBoxClipMin.y + edgeSize) - scroll.y -= scrollStep; - else if (io.MousePos.y > frameBoxClipMax.y - edgeSize) - scroll.y += scrollStep; - ImGui::SetScrollX(scroll.x); - ImGui::SetScrollY(scroll.y); - frameBoxEnd = frame_box_content_point_get(); - frameBoxSelection.clear(); + if (!document.selection.uids[SelectionKind::FRAMES].empty()) + { + reference_set(item_reference_from_frame_get(reference)); + document.frame_references_clear(); + } + else if (reference.itemType != NONE || reference.itemID != -1) + group_selection_reset_for(document); + document.focus_clear(); } - } - int index = 0; - - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("##Frames"); - - auto frames_child_row = [&](const TimelineRow& row) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - frame_child(row, index, childWidth); - }; - - frames_child_row({.type = NONE}); - - if (animation) - { - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 2.0f); - - for (auto& row : timeline_item_rows_get()) + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); + if (ImGui::BeginTable("##Frames List Table", 1, + ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) { - frames_child_row(row); - for (auto& peek : peek_rows_get(row)) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - peek_frame_child(row, peek, index, childWidth); - } + ImGuiWindow* window = ImGui::GetCurrentWindow(); + window->Flags |= ImGuiWindowFlags_NoScrollWithMouse; + + scroll.x = ImGui::GetScrollX(); + scroll.y = ImGui::GetScrollY(); + + isHorizontalScroll = window->ScrollbarX; + + if (isWindowHovered) + { + auto& io = ImGui::GetIO(); + auto lineHeight = ImGui::GetTextLineHeightWithSpacing() * 2; + + scroll.x -= io.MouseWheelH * lineHeight; + scroll.y -= io.MouseWheel * lineHeight; + } + + ImGui::SetScrollX(scroll.x); + ImGui::SetScrollY(scroll.y); + + auto frameBoxDrawList = ImGui::GetWindowDrawList(); + frameBoxClipMin = frameBoxDrawList->GetClipRectMin(); + frameBoxClipMax = frameBoxDrawList->GetClipRectMax(); + isFrameBoxClipSet = true; + if (isFrameBoxPending || isFrameBoxSelecting) + { + auto& io = ImGui::GetIO(); + auto threshold = ImGui::GetTextLineHeightWithSpacing() * 0.125f; + frameBoxEnd = frame_box_content_point_get(); + auto distance = ImVec2(frameBoxEnd.x - frameBoxStart.x, frameBoxEnd.y - frameBoxStart.y); + if (isFrameBoxPending && distance.x * distance.x + distance.y * distance.y >= threshold * threshold) + { + isFrameBoxPending = false; + isFrameBoxSelecting = true; + } + auto edgeSize = ImGui::GetTextLineHeightWithSpacing(); + auto scrollStep = edgeSize * 0.5f; + if (isFrameBoxSelecting) + { + if (io.MousePos.x < frameBoxClipMin.x + edgeSize) + scroll.x -= scrollStep; + else if (io.MousePos.x > frameBoxClipMax.x - edgeSize) + scroll.x += scrollStep; + if (io.MousePos.y < frameBoxClipMin.y + edgeSize) + scroll.y -= scrollStep; + else if (io.MousePos.y > frameBoxClipMax.y - edgeSize) + scroll.y += scrollStep; + ImGui::SetScrollX(scroll.x); + ImGui::SetScrollY(scroll.y); + frameBoxEnd = frame_box_content_point_get(); + frameBoxSelection.clear(); + } + } + + int index = 0; + + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("##Frames"); + + auto frames_child_row = [&](const TimelineRow& row) { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + frame_child(row, index, childWidth); + }; + + frames_child_row({.type = NONE}); + + if (animation) + { + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 2.0f); + + for (auto& row : timeline_item_rows_get()) + { + frames_child_row(row); + for (auto& peek : peek_rows_get(row)) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + peek_frame_child(row, peek, index, childWidth); + } + } + + ImGui::PopStyleVar(); + } + ImGui::EndTable(); + } + + frame_drag_update(); + context_menu(); + + if (isFrameBoxClipSet) + { + auto overlayCursor = ImGui::GetCursorScreenPos(); + auto overlayPos = ImGui::GetWindowPos(); + auto overlaySize = ImGui::GetWindowSize(); + ImGui::SetCursorScreenPos(overlayPos); + if (ImGui::BeginChild("##Frames Overlay Child", overlaySize, ImGuiChildFlags_None, + ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoBackground | + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | + ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoNavInputs)) + frame_overlay_draw(ImGui::GetWindowDrawList(), frameBoxClipMin, frameBoxClipMax); + ImGui::EndChild(); + ImGui::SetCursorScreenPos(overlayCursor); + } + + if (isFrameBoxPending || isFrameBoxSelecting) + { + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + { + if (isFrameBoxSelecting) + { + group_selection_reset_for(document); + if (isFrameBoxAdditive) + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + selectedFrames.insert(frameBoxSelection.begin(), frameBoxSelection.end()); + document.frame_references_set(std::move(selectedFrames)); + } + else + document.frame_references_set(frameBoxSelection); + } + isFrameBoxPending = false; + isFrameBoxSelecting = false; + frameBoxSelection.clear(); + } } ImGui::PopStyleVar(); - } - ImGui::EndTable(); } - - frame_drag_update(); - context_menu(); - - if (isFrameBoxClipSet) - { - auto overlayCursor = ImGui::GetCursorScreenPos(); - auto overlayPos = ImGui::GetWindowPos(); - auto overlaySize = ImGui::GetWindowSize(); - ImGui::SetCursorScreenPos(overlayPos); - if (ImGui::BeginChild("##Frames Overlay Child", overlaySize, ImGuiChildFlags_None, - ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoBackground | - ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | - ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoNavInputs)) - frame_overlay_draw(ImGui::GetWindowDrawList(), frameBoxClipMin, frameBoxClipMax); - ImGui::EndChild(); - ImGui::SetCursorScreenPos(overlayCursor); - } - - if (isFrameBoxPending || isFrameBoxSelecting) - { - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) - { - if (isFrameBoxSelecting) - { - group_selection_reset_for(document); - if (isFrameBoxAdditive) - { - auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - selectedFrames.insert(frameBoxSelection.begin(), frameBoxSelection.end()); - document.frame_references_set(std::move(selectedFrames)); - } - else - document.frame_references_set(frameBoxSelection); - } - isFrameBoxPending = false; - isFrameBoxSelecting = false; - frameBoxSelection.clear(); - } - } - + ImGui::EndChild(); ImGui::PopStyleVar(); - } - ImGui::EndChild(); - ImGui::PopStyleVar(); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::SetCursorPos( - ImVec2(ImGui::GetStyle().WindowPadding.x, ImGui::GetCursorPos().y + ImGui::GetStyle().ItemSpacing.y)); + ImGui::SetCursorPos( + ImVec2(ImGui::GetStyle().WindowPadding.x, ImGui::GetCursorPos().y + ImGui::GetStyle().ItemSpacing.y)); - auto widgetSize = widget_size_with_row_get(10); + auto widgetSize = widget_size_with_row_get(10); - ImGui::BeginDisabled(!animation); - { - auto label = playback.isPlaying ? localize.get(LABEL_PAUSE) : localize.get(LABEL_PLAY); - auto tooltip = - playback.isPlaying ? localize.get(TOOLTIP_PAUSE_ANIMATION) : localize.get(TOOLTIP_PLAY_ANIMATION); - - shortcut(manager.chords[SHORTCUT_PLAY_PAUSE]); - if (ImGui::Button(label, widgetSize)) playback.toggle(); - set_item_tooltip_shortcut(tooltip, settings.shortcutPlayPause); - - ImGui::SameLine(); - - auto item = selected_item_get(); - auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - auto selectedBakeFrames = selectedFrames; - std::erase_if(selectedBakeFrames, is_trigger_reference); - - ImGui::BeginDisabled(!item); + ImGui::BeginDisabled(!animation); { - shortcut(manager.chords[SHORTCUT_INSERT_FRAME]); - if (ImGui::Button(localize.get(LABEL_INSERT), widgetSize)) frame_insert(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_INSERT_FRAME), settings.shortcutInsertFrame); + auto label = playback.isPlaying ? localize.get(LABEL_PAUSE) : localize.get(LABEL_PLAY); + auto tooltip = + playback.isPlaying ? localize.get(TOOLTIP_PAUSE_ANIMATION) : localize.get(TOOLTIP_PLAY_ANIMATION); - ImGui::SameLine(); - - ImGui::BeginDisabled(selectedFrames.empty()); - { - shortcut(manager.chords[SHORTCUT_REMOVE]); - if (ImGui::Button(localize.get(LABEL_DELETE), widgetSize)) frames_delete_action(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_DELETE_FRAMES), settings.shortcutRemove); + shortcut(manager.chords[SHORTCUT_PLAY_PAUSE]); + if (ImGui::Button(label, widgetSize)) + playback.toggle(); + set_item_tooltip_shortcut(tooltip, settings.shortcutPlayPause); ImGui::SameLine(); - ImGui::BeginDisabled(selectedBakeFrames.empty()); - if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) bakePopup.open(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_BAKE_FRAMES), settings.shortcutBake); + auto item = selected_item_get(); + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + auto selectedBakeFrames = selectedFrames; + std::erase_if(selectedBakeFrames, is_trigger_reference); + + ImGui::BeginDisabled(!item); + { + shortcut(manager.chords[SHORTCUT_INSERT_FRAME]); + if (ImGui::Button(localize.get(LABEL_INSERT), widgetSize)) + frame_insert(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_INSERT_FRAME), settings.shortcutInsertFrame); + + ImGui::SameLine(); + + ImGui::BeginDisabled(selectedFrames.empty()); + { + shortcut(manager.chords[SHORTCUT_REMOVE]); + if (ImGui::Button(localize.get(LABEL_DELETE), widgetSize)) + frames_delete_action(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_DELETE_FRAMES), settings.shortcutRemove); + + ImGui::SameLine(); + + ImGui::BeginDisabled(selectedBakeFrames.empty()); + if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) + bakePopup.open(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_BAKE_FRAMES), settings.shortcutBake); + ImGui::EndDisabled(); + } + ImGui::EndDisabled(); + } ImGui::EndDisabled(); - } - ImGui::EndDisabled(); + + ImGui::SameLine(); + + ImGui::BeginDisabled(!animation || animation->frameNum == animation_length_get(*animation)); + shortcut(manager.chords[SHORTCUT_FIT]); + if (ImGui::Button(localize.get(LABEL_FIT_ANIMATION_LENGTH), widgetSize)) + fit_animation_length(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_FIT_ANIMATION_LENGTH), settings.shortcutFit); + ImGui::EndDisabled(); + + ImGui::SameLine(); + + auto frameNum = animation ? animation->frameNum : dummy_value(); + auto currentAnimationIndex = reference.animationIndex; + ImGui::SetNextItemWidth(widgetSize.x); + auto isLengthChanged = + input_int_range(localize.get(LABEL_ANIMATION_LENGTH), frameNum, FRAME_NUM_MIN, FRAME_NUM_MAX, STEP, + STEP_FAST, !animation ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0); + if (ImGui::IsItemActivated()) + animationLengthEditIndex = currentAnimationIndex; + if (isLengthChanged && animation) + { + auto animationIndex = animationLengthEditIndex != -1 ? animationLengthEditIndex : currentAnimationIndex; + edit_push(EDIT_ANIMATION_LENGTH, [=](Model& model) { + if (auto animation = model.animation_edit(animationIndex)) + animation->frameNum = frameNum; + }); + } + if (ImGui::IsItemDeactivated()) + animationLengthEditIndex = -1; + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ANIMATION_LENGTH)); + + ImGui::SameLine(); + + auto isLoop = animation ? animation->isLoop : dummy_value(); + ImGui::SetNextItemWidth(widgetSize.x); + if (ImGui::Checkbox(localize.get(LABEL_LOOP), &isLoop) && animation) + { + auto animationIndex = reference.animationIndex; + edit_push(EDIT_LOOP, [=](Model& model) { + if (auto animation = model.animation_edit(animationIndex)) + animation->isLoop = isLoop; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LOOP_ANIMATION)); } ImGui::EndDisabled(); ImGui::SameLine(); - ImGui::BeginDisabled(!animation || animation->frameNum == animation_length_get(*animation)); - shortcut(manager.chords[SHORTCUT_FIT]); - if (ImGui::Button(localize.get(LABEL_FIT_ANIMATION_LENGTH), widgetSize)) fit_animation_length(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_FIT_ANIMATION_LENGTH), settings.shortcutFit); - ImGui::EndDisabled(); + auto fps = model.info.fps; + ImGui::SetNextItemWidth(widgetSize.x); + if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) + edit_push(EDIT_FPS, [=](Model& model) { model.info.fps = fps; }); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FPS)); ImGui::SameLine(); - auto frameNum = animation ? animation->frameNum : dummy_value(); - auto currentAnimationIndex = reference.animationIndex; + auto createdBy = model.info.createdBy; ImGui::SetNextItemWidth(widgetSize.x); - auto isLengthChanged = - input_int_range(localize.get(LABEL_ANIMATION_LENGTH), frameNum, FRAME_NUM_MIN, FRAME_NUM_MAX, STEP, - STEP_FAST, !animation ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0); - if (ImGui::IsItemActivated()) animationLengthEditIndex = currentAnimationIndex; - if (isLengthChanged && animation) - { - auto animationIndex = animationLengthEditIndex != -1 ? animationLengthEditIndex : currentAnimationIndex; - edit_push(EDIT_ANIMATION_LENGTH, - [=](Model& model) - { - if (auto animation = model.animation_edit(animationIndex)) animation->frameNum = frameNum; - }); - } - if (ImGui::IsItemDeactivated()) animationLengthEditIndex = -1; - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ANIMATION_LENGTH)); + if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) + edit_push(EDIT_AUTHOR, [=](Model& model) { model.info.createdBy = createdBy; }); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTHOR)); ImGui::SameLine(); - auto isLoop = animation ? animation->isLoop : dummy_value(); ImGui::SetNextItemWidth(widgetSize.x); - if (ImGui::Checkbox(localize.get(LABEL_LOOP), &isLoop) && animation) - { - auto animationIndex = reference.animationIndex; - edit_push(EDIT_LOOP, - [=](Model& model) - { - if (auto animation = model.animation_edit(animationIndex)) animation->isLoop = isLoop; - }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LOOP_ANIMATION)); - } - ImGui::EndDisabled(); + ImGui::Checkbox(localize.get(LABEL_SOUND), &settings.timelineIsSound); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SOUND)); - ImGui::SameLine(); - - auto fps = model.info.fps; - ImGui::SetNextItemWidth(widgetSize.x); - if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) - { - edit_push(EDIT_FPS, [=](Model& model) { model.info.fps = fps; }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FPS)); - - ImGui::SameLine(); - - auto createdBy = model.info.createdBy; - ImGui::SetNextItemWidth(widgetSize.x); - if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) - { - edit_push(EDIT_AUTHOR, [=](Model& model) { model.info.createdBy = createdBy; }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTHOR)); - - ImGui::SameLine(); - - ImGui::SetNextItemWidth(widgetSize.x); - ImGui::Checkbox(localize.get(LABEL_SOUND), &settings.timelineIsSound); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SOUND)); - - ImGui::PopStyleVar(); + ImGui::PopStyleVar(); } ImGui::EndChild(); ImGui::SetCursorPos(cursorPos); - } +} diff --git a/src/ui/timeline_menus.cpp b/src/ui/timeline_menus.cpp index 4908bb8..620218d 100644 --- a/src/ui/timeline_menus.cpp +++ b/src/ui/timeline_menus.cpp @@ -1,13 +1,13 @@ #include "ui/timeline_context.h" - constexpr StringType FRAME_PROPERTY_LABELS[] = { - BASIC_POSITION, BASIC_SCALE, BASIC_ROTATION, BASIC_SKEW, BASIC_PIVOT, BASIC_CROP, BASIC_SIZE, - BASIC_REGION, BASIC_TINT, BASIC_COLOR_OFFSET, BASIC_VISIBLE, BASIC_INTERPOLATED, BASIC_DURATION, BASIC_SHADER, - BASIC_DEPTH, BASIC_BLUR, LABEL_CHILD, LABEL_EVENTS, LABEL_SOUNDS}; - static_assert(std::size(FRAME_PROPERTY_LABELS) == (std::size_t)FrameProperty::COUNT); +constexpr StringType FRAME_PROPERTY_LABELS[] = { + BASIC_POSITION, BASIC_SCALE, BASIC_ROTATION, BASIC_SKEW, BASIC_PIVOT, BASIC_CROP, BASIC_SIZE, + BASIC_REGION, BASIC_TINT, BASIC_COLOR_OFFSET, BASIC_VISIBLE, BASIC_INTERPOLATED, BASIC_DURATION, BASIC_SHADER, + BASIC_DEPTH, BASIC_BLUR, LABEL_CHILD, LABEL_EVENTS, LABEL_SOUNDS}; +static_assert(std::size(FRAME_PROPERTY_LABELS) == (std::size_t)FrameProperty::COUNT); - void TimelineContext::frame_begin() - { +void TimelineContext::frame_begin() +{ iconTintDefault = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : ICON_TINT_DEFAULT_DARK; itemIconTint = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : iconTintDefault; frameBorderColor = isLightTheme ? FRAME_BORDER_COLOR_LIGHT : FRAME_BORDER_COLOR_DARK; @@ -22,59 +22,70 @@ timelinePlayheadRectColor = isLightTheme ? TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT : TIMELINE_PLAYHEAD_RECT_COLOR_DARK; timelineTickColor = isLightTheme ? TIMELINE_TICK_COLOR_LIGHT : frameBorderColor; itemTextColor = isLightTheme ? ITEM_TEXT_COLOR_LIGHT : ITEM_TEXT_COLOR_DARK; - } +} - void TimelineContext::overlay_icon(GLuint textureId, ImVec4 tint, bool isForced) - { - if (!isForced && !isLightTheme) return; +void TimelineContext::overlay_icon(GLuint textureId, ImVec4 tint, bool isForced) +{ + if (!isForced && !isLightTheme) + return; auto min = ImGui::GetItemRectMin(); auto max = ImGui::GetItemRectMax(); ImGui::GetWindowDrawList()->AddImage((ImTextureID)(intptr_t)textureId, min, max, ImVec2(0, 0), ImVec2(1, 1), ImGui::GetColorU32(tint)); - } +} - void TimelineContext::playback_stop() - { +void TimelineContext::playback_stop() +{ playback.isPlaying = false; playback.isFinished = false; playback.timing_reset(); - } +} - void TimelineContext::context_menu() - { +void TimelineContext::context_menu() +{ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - if (shortcut(manager.chords[SHORTCUT_CUT], SCOPE_FOCUSED)) cut(); - if (shortcut(manager.chords[SHORTCUT_COPY], SCOPE_FOCUSED)) copy(); - if (shortcut(manager.chords[SHORTCUT_PASTE], SCOPE_FOCUSED)) paste(); - if (shortcut(manager.chords[SHORTCUT_SPLIT], SCOPE_FOCUSED)) frame_split(); - if (shortcut(manager.chords[SHORTCUT_BAKE], SCOPE_FOCUSED)) frames_bake(); - if (shortcut(manager.chords[SHORTCUT_FIT], SCOPE_FOCUSED)) fit_animation_length(); + if (shortcut(manager.chords[SHORTCUT_CUT], SCOPE_FOCUSED)) + cut(); + if (shortcut(manager.chords[SHORTCUT_COPY], SCOPE_FOCUSED)) + copy(); + if (shortcut(manager.chords[SHORTCUT_PASTE], SCOPE_FOCUSED)) + paste(); + if (shortcut(manager.chords[SHORTCUT_SPLIT], SCOPE_FOCUSED)) + frame_split(); + if (shortcut(manager.chords[SHORTCUT_BAKE], SCOPE_FOCUSED)) + frames_bake(); + if (shortcut(manager.chords[SHORTCUT_FIT], SCOPE_FOCUSED)) + fit_animation_length(); - auto make_region = [&]() - { - auto targetReference = reference; - auto frame = frame_get(); - if (!frame || targetReference.itemType != LAYER || targetReference.itemID == -1) return; - if (frame->regionId != -1) return; - auto layer = ::item_get(model.content.layers, targetReference.itemID); - if (!layer) return; + auto make_region = [&]() { + auto targetReference = reference; + auto frame = frame_get(); + if (!frame || targetReference.itemType != LAYER || targetReference.itemID == -1) + return; + if (frame->regionId != -1) + return; + auto layer = ::item_get(model.content.layers, targetReference.itemID); + if (!layer) + return; - auto spritesheetID = layer->spritesheetId; - if (!::item_get(model.content.spritesheets, spritesheetID)) return; + auto spritesheetID = layer->spritesheetId; + if (!::item_get(model.content.spritesheets, spritesheetID)) + return; - auto settingsPtr = &settings; - command_push( - [=, this](Manager& manager, Document& document) - { + auto settingsPtr = &settings; + command_push([=, this](Manager& manager, Document& document) { auto frame = document.model.frame_get(targetReference); - if (!frame || frame->regionId != -1) return; + if (!frame || frame->regionId != -1) + return; auto layer = ::item_get(document.model.content.layers, targetReference.itemID); - if (!layer) return; + if (!layer) + return; auto spritesheetID = layer->spritesheetId; - if (!::item_get(document.model.content.spritesheets, spritesheetID)) return; + if (!::item_get(document.model.content.spritesheets, spritesheetID)) + return; Region region = {.crop = frame->crop, .size = frame->size, .pivot = frame->pivot}; @@ -83,7 +94,7 @@ manager.makeRegionSpritesheetId = spritesheetID; manager.makeRegion = region; manager.isMakeRegionRequested = true; - }); + }); }; auto item = selected_item_get(); @@ -92,13 +103,12 @@ auto selectedBakeFrames = selectedFrames; std::erase_if(selectedBakeFrames, is_trigger_reference); auto isReverseFrames = is_frames_reverse_available(selectedFrames); - auto is_region_makeable = [&](const Reference& frameReference) - { - if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return false; - auto frame = document.model.frame_get(frameReference); - auto layer = ::item_get(model.content.layers, frameReference.itemID); - return frame && frame->regionId == -1 && layer && - ::item_get(model.content.spritesheets, layer->spritesheetId); + auto is_region_makeable = [&](const Reference& frameReference) { + if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) + return false; + auto frame = document.model.frame_get(frameReference); + auto layer = ::item_get(model.content.layers, frameReference.itemID); + return frame && frame->regionId == -1 && layer && ::item_get(model.content.spritesheets, layer->spritesheetId); }; auto selectedRegionFrames = selectedFrames; std::erase_if(selectedRegionFrames, @@ -132,22 +142,21 @@ .shortcut = -1, .isEnabled = [=, this]() { return !selectedRootFrames.empty(); }, .run = [&]() { bakeIntoOtherFramesPopup.open(); }}); - actions.add( - {.label = LABEL_FIT_ANIMATION_LENGTH, - .shortcut = SHORTCUT_FIT, - .isEnabled = [&]() { return animation && animation->frameNum != animation_length_get(*animation); }, - .run = [&]() { fit_animation_length(); }}); + actions.add({.label = LABEL_FIT_ANIMATION_LENGTH, + .shortcut = SHORTCUT_FIT, + .isEnabled = [&]() { return animation && animation->frameNum != animation_length_get(*animation); }, + .run = [&]() { fit_animation_length(); }}); actions.separator(); actions.add({.label = isMakeManyRegions ? LABEL_MAKE_MANY_REGIONS : LABEL_MAKE_REGION, .shortcut = -1, .isEnabled = [=, this]() { return isMakeManyRegions || isMakeRegion; }, .run = - [&]() - { - if (!isMakeManyRegions) return make_region(); - makeManyRegionReferences = selectedRegionFrames; - makeManyRegionsPopup.open(); - }}); + [&]() { + if (!isMakeManyRegions) + return make_region(); + makeManyRegionReferences = selectedRegionFrames; + makeManyRegionsPopup.open(); + }}); actions.separator(); actions.add({.label = LABEL_DELETE, .shortcut = SHORTCUT_REMOVE, @@ -160,33 +169,35 @@ auto clipboardFrame = property_clipboard_frame_get(); // A submenu of the properties a frame type has. auto properties_get = [&](int itemType, std::function is_property_enabled, - std::function property_run) - { - Action properties = {.label = LABEL_PROPERTY}; - for (int i = 0; i < (int)FrameProperty::COUNT; ++i) - { - auto property = (FrameProperty)i; - if (!is_frame_property_valid(property, (ItemType)itemType)) continue; - properties.children.push_back({.label = FRAME_PROPERTY_LABELS[i], - .isEnabled = [=]() { return is_property_enabled(property); }, - .run = [=]() { property_run(property); }}); - } - properties.isEnabled = [children = properties.children]() - { return std::ranges::any_of(children, is_action_enabled); }; - return properties; + std::function property_run) { + Action properties = {.label = LABEL_PROPERTY}; + for (int i = 0; i < (int)FrameProperty::COUNT; ++i) + { + auto property = (FrameProperty)i; + if (!is_frame_property_valid(property, (ItemType)itemType)) + continue; + properties.children.push_back({.label = FRAME_PROPERTY_LABELS[i], + .isEnabled = [=]() { return is_property_enabled(property); }, + .run = [=]() { property_run(property); }}); + } + properties.isEnabled = [children = properties.children]() { + return std::ranges::any_of(children, is_action_enabled); + }; + return properties; }; - auto clipboard_menu_add = - [&](ActionType type, std::function isFrameEnabled, std::function frameRun, Action property) - { - actions.add({.label = ACTION_INFOS[type].label, - .children = {{.label = BASIC_FRAME, - .shortcut = ACTION_INFOS[type].shortcut, - .isEnabled = isFrameEnabled, - .run = frameRun}, - property}}); + auto clipboard_menu_add = [&](ActionType type, std::function isFrameEnabled, std::function frameRun, + Action property) { + actions.add({.label = ACTION_INFOS[type].label, + .children = {{.label = BASIC_FRAME, + .shortcut = ACTION_INFOS[type].shortcut, + .isEnabled = isFrameEnabled, + .run = frameRun}, + property}}); }; auto sourceType = source ? source->itemType : NONE; - auto is_source = [=](FrameProperty) { return sourceFrame != nullptr; }; + auto is_source = [=](FrameProperty) { + return sourceFrame != nullptr; + }; clipboard_menu_add( ACTION_CUT, [=, this]() { return !selectedFrames.empty(); }, [this]() { cut(); }, properties_get(sourceType, is_source, [this](FrameProperty property) { property_cut(property); })); @@ -198,72 +209,74 @@ clipboard_menu_add( ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, [this]() { paste(); }, {.label = LABEL_PROPERTY, - .isEnabled = [=, this]() - { return clipboardFrame && frameClipboard.property != -1 && is_property_pasteable(clipboardProperty); }, + .isEnabled = + [=, this]() { + return clipboardFrame && frameClipboard.property != -1 && is_property_pasteable(clipboardProperty); + }, .run = [=, this]() { property_paste(clipboardProperty); }}); // The numbered row has its own (marker) menu. if (isRulerHovered) - actions_popup_draw("##Context Menu", actions, settings); + actions_popup_draw("##Context Menu", actions, settings); else - actions_context_window_draw("##Context Menu", actions, settings, ImGuiPopupFlags_MouseButtonRight, - ImGuiHoveredFlags_ChildWindows); + actions_context_window_draw("##Context Menu", actions, settings, ImGuiPopupFlags_MouseButtonRight, + ImGuiHoveredFlags_ChildWindows); ImGui::PopStyleVar(2); - } +} - void TimelineContext::item_base_properties_open(int type, int id) - { +void TimelineContext::item_base_properties_open(int type, int id) +{ manager.item_properties_open(type == LAYER ? ElementType::LAYER_ELEMENT : ElementType::NULL_ELEMENT, id); - } +} - void TimelineContext::group_properties_open(const TimelineRow& row, const TrackGroup& group) - { +void TimelineContext::group_properties_open(const TimelineRow& row, const TrackGroup& group) +{ groupName = group.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group.name; groupAnimationIndex = reference.animationIndex; groupType = row.type; groupId = row.id; groupPropertiesPopup.open(); - } +} - void TimelineContext::group_properties_update() - { +void TimelineContext::group_properties_update() +{ groupPropertiesPopup.trigger(); if (ImGui::BeginPopupModal(groupPropertiesPopup.label(), &groupPropertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) { - auto childSize = child_size_get(1); - if (ImGui::BeginChild("##Group Properties Child", childSize, ImGuiChildFlags_Borders)) - { - if (groupPropertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); - input_text_string(localize.get(BASIC_NAME), &groupName); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); - } - ImGui::EndChild(); + auto childSize = child_size_get(1); + if (ImGui::BeginChild("##Group Properties Child", childSize, ImGuiChildFlags_Borders)) + { + if (groupPropertiesPopup.isJustOpened) + ImGui::SetKeyboardFocusHere(); + input_text_string(localize.get(BASIC_NAME), &groupName); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); + } + ImGui::EndChild(); - auto result = popup_buttons_draw(manager, localize.get(BASIC_CONFIRM)); - if (result == PopupButton::CONFIRM) - { - auto targetName = groupName; - auto targetAnimationIndex = groupAnimationIndex; - auto targetType = groupType; - auto targetId = groupId; - edit_push(EDIT_RENAME_GROUP, - [=](Model& model) - { - if (auto group = model.track_group_edit(targetAnimationIndex, targetType, targetId)) - group->name = targetName; - }); - } - if (result != PopupButton::NONE) groupPropertiesPopup.close(); + auto result = popup_buttons_draw(manager, localize.get(BASIC_CONFIRM)); + if (result == PopupButton::CONFIRM) + { + auto targetName = groupName; + auto targetAnimationIndex = groupAnimationIndex; + auto targetType = groupType; + auto targetId = groupId; + edit_push(EDIT_RENAME_GROUP, [=](Model& model) { + if (auto group = model.track_group_edit(targetAnimationIndex, targetType, targetId)) + group->name = targetName; + }); + } + if (result != PopupButton::NONE) + groupPropertiesPopup.close(); - ImGui::EndPopup(); + ImGui::EndPopup(); } groupPropertiesPopup.end(); - } +} - void TimelineContext::item_context_menu() - { +void TimelineContext::item_context_menu() +{ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); @@ -277,34 +290,33 @@ const TrackGroup* selectedGroup = nullptr; if (selectedRows.size() == 1 && selectedRows.front().isGroup) { - auto row = selectedRows.front(); - selectedGroupRow = row; - selectedGroup = row_group_get(selectedGroupRow); + auto row = selectedRows.front(); + selectedGroupRow = row; + selectedGroup = row_group_get(selectedGroupRow); } - auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRow& row) - { return row.type == LAYER || row.type == NULL_; }); - auto item_cut = [&]() - { - if (copyFrames.empty() || !isRemoveAvailable) return; - frame_references_copy(copyFrames); - item_remove(); + auto isRemoveAvailable = std::ranges::any_of( + selectedRows, [](const TimelineRow& row) { return row.type == LAYER || row.type == NULL_; }); + auto item_cut = [&]() { + if (copyFrames.empty() || !isRemoveAvailable) + return; + frame_references_copy(copyFrames); + item_remove(); }; if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && ImGui::IsMouseClicked(ImGuiMouseButton_Right)) - ImGui::OpenPopup("##Items Context Menu"); + ImGui::OpenPopup("##Items Context Menu"); Actions actions = {}; actions_undo_redo_add(actions, manager, document); actions.separator(); actions.add( ACTION_PROPERTIES, [&]() { return selectedGroup || (item && (type == LAYER || type == NULL_)); }, - [&]() - { - if (selectedGroup) - group_properties_open(selectedGroupRow, *selectedGroup); - else - item_base_properties_open(type, id); + [&]() { + if (selectedGroup) + group_properties_open(selectedGroupRow, *selectedGroup); + else + item_base_properties_open(type, id); }); actions.add(ACTION_ADD, [&]() { return animation; }, [&]() { itemProperties.open(); }); actions.add(ACTION_REMOVE, [=, this]() { return isRemoveAvailable; }, [&]() { item_remove(); }); @@ -314,10 +326,12 @@ actions.add(ACTION_COPY, [=, this]() { return !copyFrames.empty(); }, [this]() { copy(); }); actions.add(ACTION_PASTE, [&]() { return item && !clipboard.is_empty(); }, [this]() { paste(); }); if (shortcut(manager.chords[SHORTCUT_CUT], SCOPE_FOCUSED) && !copyFrames.empty() && isRemoveAvailable) - item_cut(); - if (shortcut(manager.chords[SHORTCUT_COPY], SCOPE_FOCUSED) && !copyFrames.empty()) copy(); - if (shortcut(manager.chords[SHORTCUT_PASTE], SCOPE_FOCUSED) && item && !clipboard.is_empty()) paste(); + item_cut(); + if (shortcut(manager.chords[SHORTCUT_COPY], SCOPE_FOCUSED) && !copyFrames.empty()) + copy(); + if (shortcut(manager.chords[SHORTCUT_PASTE], SCOPE_FOCUSED) && item && !clipboard.is_empty()) + paste(); actions_popup_draw("##Items Context Menu", actions, settings); ImGui::PopStyleVar(2); - } +} diff --git a/src/ui/timeline_selection.cpp b/src/ui/timeline_selection.cpp index 4695805..29c69cf 100644 --- a/src/ui/timeline_selection.cpp +++ b/src/ui/timeline_selection.cpp @@ -1,306 +1,333 @@ #include "ui/timeline_context.h" - const Track* TimelineContext::item_get(int type, int id, int groupType, int groupId) - { +const Track* TimelineContext::item_get(int type, int id, int groupType, int groupId) +{ return animation ? animation_track_get(*animation, type, id, groupType, groupId) : nullptr; - } +} - const TrackGroup* TimelineContext::track_group_get(int type, int groupId) - { +const TrackGroup* TimelineContext::track_group_get(int type, int groupId) +{ return animation ? animation_track_group_get(*animation, type, groupId) : nullptr; - } +} - bool TimelineContext::is_track_group_visible(int type, int groupId) - { - if (groupId == -1) return true; +bool TimelineContext::is_track_group_visible(int type, int groupId) +{ + if (groupId == -1) + return true; auto group = track_group_get(type, groupId); return !group || group->isVisible; - } +} - const TrackGroup* TimelineContext::row_group_get(const TimelineRow& row) - { +const TrackGroup* TimelineContext::row_group_get(const TimelineRow& row) +{ return row.isGroup ? track_group_get(row.type, row.id) : nullptr; - } +} - const Frame* TimelineContext::frame_get() { return document.model.frame_get(reference); } +const Frame* TimelineContext::frame_get() +{ + return document.model.frame_get(reference); +} - const Track* TimelineContext::selected_item_get() { return document.model.track_get(reference); } +const Track* TimelineContext::selected_item_get() +{ + return document.model.track_get(reference); +} - glm::vec4 TimelineContext::color_get(TimelineColor color, int type) - { +glm::vec4 TimelineContext::color_get(TimelineColor color, int type) +{ auto& colors = TIMELINE_COLORS[color]; return isLightTheme ? colors.light[std::clamp(type, 0, TRIGGER)] : colors.dark[type]; - } +} - std::set TimelineContext::drag_frame_references_get(const Reference& frameReference) - { +std::set TimelineContext::drag_frame_references_get(const Reference& frameReference) +{ auto selectedReferences = document.frame_references_get(Document::FrameReferenceFallback::NONE); - if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; + if (!selectedReferences.contains(frameReference)) + selectedReferences = {frameReference}; std::erase_if(selectedReferences, is_trigger_reference); return selectedReferences.empty() ? std::set{frameReference} : selectedReferences; - } +} - void TimelineContext::edit_begin_push(StringType label) - { +void TimelineContext::edit_begin_push(StringType label) +{ command_push([label](Manager&, Document& document) { document.edit_begin(label); }); - } +} - void TimelineContext::reference_set(Reference value) - { +void TimelineContext::reference_set(Reference value) +{ reference = value; document.reference_set(value); - } +} - Reference TimelineContext::item_reference_get(int type, int id, int groupType, int groupId) - { +Reference TimelineContext::item_reference_get(int type, int id, int groupType, int groupId) +{ return Reference{reference.animationIndex, type, id, -1, groupType, groupId}; - } +} - Reference TimelineContext::item_reference_from_frame_get(Reference frameReference) - { +Reference TimelineContext::item_reference_from_frame_get(Reference frameReference) +{ frameReference.frameIndex = -1; return frameReference; - } +} - bool TimelineContext::is_same_item(const Reference& left, const Reference& right) - { +bool TimelineContext::is_same_item(const Reference& left, const Reference& right) +{ return left.animationIndex == right.animationIndex && left.itemType == right.itemType && left.itemID == right.itemID && left.groupType == right.groupType && left.groupId == right.groupId; - } +} - void TimelineContext::group_selection_reset_for(Document& targetDocument) - { +void TimelineContext::group_selection_reset_for(Document& targetDocument) +{ targetDocument.selection.uids[SelectionKind::GROUPS].clear(); rowSelectionAnchor.reset(); - } +} - std::set TimelineContext::item_references_for_current_get() - { +std::set TimelineContext::item_references_for_current_get() +{ auto result = document.selected_get(SelectionKind::TRACKS); - if (result.empty() && reference.itemType != NONE) result.insert(item_reference_from_frame_get(reference)); + if (result.empty() && reference.itemType != NONE) + result.insert(item_reference_from_frame_get(reference)); return result; - } +} - std::set TimelineContext::copy_frame_references_get() - { +std::set TimelineContext::copy_frame_references_get() +{ auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - if (!selectedFrames.empty()) return selectedFrames; + if (!selectedFrames.empty()) + return selectedFrames; auto selectedItems = document.selected_get(SelectionKind::TRACKS); if (selectedItems.empty() && reference.itemType != NONE && reference.frameIndex < 0) - selectedItems.insert(item_reference_from_frame_get(reference)); + selectedItems.insert(item_reference_from_frame_get(reference)); std::set result; for (auto itemReference : selectedItems) { - itemReference.frameIndex = -1; - if (itemReference.itemType == TRIGGER) continue; - auto itemFrames = document.item_frame_references_get(itemReference); - result.insert(itemFrames.begin(), itemFrames.end()); + itemReference.frameIndex = -1; + if (itemReference.itemType == TRIGGER) + continue; + auto itemFrames = document.item_frame_references_get(itemReference); + result.insert(itemFrames.begin(), itemFrames.end()); } return result; - } +} - void TimelineContext::command_push(std::function run) - { +void TimelineContext::command_push(std::function run) +{ manager.command_push( {manager.selected, [run](Manager& manager, Document& document) mutable { run(manager, document); }}); - } +} - std::vector TimelineContext::timeline_item_rows_get() - { +std::vector TimelineContext::timeline_item_rows_get() +{ std::vector rows; - if (!animation) return rows; + if (!animation) + return rows; - auto is_track_shown = [&](const Track& track) - { return settings.timelineIsShowUnused || !track.frames.empty(); }; - // Layers are listed top-down in reverse file order; nulls in file order. - auto order_get = [](int count, bool isReversed) - { - std::vector order(count); - for (int i = 0; i < count; ++i) - order[i] = isReversed ? count - 1 - i : i; - return order; + auto is_track_shown = [&](const Track& track) { + return settings.timelineIsShowUnused || !track.frames.empty(); + }; + // Layers are listed top-down in reverse file order. Nulls in file order. + auto order_get = [](int count, bool isReversed) { + std::vector order(count); + for (int i = 0; i < count; ++i) + order[i] = isReversed ? count - 1 - i : i; + return order; }; rows.push_back({.type = ROOT}); for (auto type : {LAYER, NULL_}) { - auto& entries = animation_entries_get(*animation, type); - auto isReversed = type == LAYER; - for (auto index : order_get((int)entries.size(), isReversed)) - { - if (auto track = std::get_if(&entries[index])) + auto& entries = animation_entries_get(*animation, type); + auto isReversed = type == LAYER; + for (auto index : order_get((int)entries.size(), isReversed)) { - if (is_track_shown(*track)) rows.push_back({.type = type, .id = track->id, .index = index}); - continue; + if (auto track = std::get_if(&entries[index])) + { + if (is_track_shown(*track)) + rows.push_back({.type = type, .id = track->id, .index = index}); + continue; + } + auto& group = std::get(entries[index]); + rows.push_back({.type = type, .id = group.id, .index = index, .isGroup = true}); + if (!group.isExpanded) + continue; + rows.push_back({.type = ROOT, .groupType = type, .groupId = group.id, .depth = 1}); + for (auto trackIndex : order_get((int)group.tracks.size(), isReversed)) + if (auto& track = group.tracks[trackIndex]; is_track_shown(track)) + rows.push_back({.type = type, + .id = track.id, + .index = trackIndex, + .groupType = type, + .groupId = group.id, + .depth = 1}); } - auto& group = std::get(entries[index]); - rows.push_back({.type = type, .id = group.id, .index = index, .isGroup = true}); - if (!group.isExpanded) continue; - rows.push_back({.type = ROOT, .groupType = type, .groupId = group.id, .depth = 1}); - for (auto trackIndex : order_get((int)group.tracks.size(), isReversed)) - if (auto& track = group.tracks[trackIndex]; is_track_shown(track)) - rows.push_back({.type = type, - .id = track.id, - .index = trackIndex, - .groupType = type, - .groupId = group.id, - .depth = 1}); - } } rows.push_back({.type = TRIGGER}); for (auto& row : rows) { - row.documentIndex = manager.selected; - row.animationIndex = reference.animationIndex; + row.documentIndex = manager.selected; + row.animationIndex = reference.animationIndex; } return rows; - } +} - bool TimelineContext::is_row_selected(const TimelineRow& row) - { - if (row.isGroup) return is_row_reference_selected(row); +bool TimelineContext::is_row_selected(const TimelineRow& row) +{ + if (row.isGroup) + return is_row_reference_selected(row); auto itemReference = item_reference_get(row.type, row.id, row.groupType, row.groupId); auto tracks = document.selected_get(SelectionKind::TRACKS); return tracks.contains(itemReference) || (tracks.empty() && document.selection.uids[SelectionKind::GROUPS].empty() && is_same_item(reference, itemReference)); - } +} - Reference row_item_reference_get(const TimelineRow& row) - { +Reference row_item_reference_get(const TimelineRow& row) +{ return Reference{row.animationIndex, row.type, row.id, -1, row.groupType, row.groupId}; - } +} - Reference row_selection_reference_get(const TimelineRow& row) - { +Reference row_selection_reference_get(const TimelineRow& row) +{ return row.isGroup ? Reference{row.animationIndex, row.type, row.id} : row_item_reference_get(row); - } +} - static SelectionKind row_kind_get(const TimelineRow& row) - { +static SelectionKind row_kind_get(const TimelineRow& row) +{ return row.isGroup ? SelectionKind::GROUPS : SelectionKind::TRACKS; - } +} - void TimelineContext::row_selection_clear() - { +void TimelineContext::row_selection_clear() +{ document.selection.uids[SelectionKind::TRACKS].clear(); document.selection.uids[SelectionKind::GROUPS].clear(); - } +} - void TimelineContext::row_selection_insert(const TimelineRow& row) - { +void TimelineContext::row_selection_insert(const TimelineRow& row) +{ auto references = document.selected_get(row_kind_get(row)); references.insert(row_selection_reference_get(row)); document.selected_set(row_kind_get(row), references); - } +} - bool TimelineContext::is_row_reference_selected(const TimelineRow& row) - { +bool TimelineContext::is_row_reference_selected(const TimelineRow& row) +{ return document.selected_get(row_kind_get(row)).contains(row_selection_reference_get(row)); - } +} - void TimelineContext::row_selection_set(const TimelineRow& row) - { +void TimelineContext::row_selection_set(const TimelineRow& row) +{ auto rowReference = row; auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); if (row.isGroup) - reference_set({reference.animationIndex}); + reference_set({reference.animationIndex}); else { - if (row.type == LAYER) - if (auto layer = ::item_get(model.content.layers, row.id)) - document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); - reference_set(row_item_reference_get(rowReference)); + if (row.type == LAYER) + if (auto layer = ::item_get(model.content.layers, row.id)) + document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); + reference_set(row_item_reference_get(rowReference)); } document.frame_references_clear(); if (isShiftDown) { - auto rowSelection = timeline_item_rows_get(); - auto anchor = rowSelectionAnchor.value_or(rowReference); - auto first = std::find(rowSelection.begin(), rowSelection.end(), anchor); - auto last = std::find(rowSelection.begin(), rowSelection.end(), rowReference); - if (first == rowSelection.end() || last == rowSelection.end()) - { - if (!isCtrlDown) row_selection_clear(); - row_selection_insert(rowReference); - rowSelectionAnchor = rowReference; - } - else - { - auto firstIndex = (int)std::distance(rowSelection.begin(), first); - auto lastIndex = (int)std::distance(rowSelection.begin(), last); - if (firstIndex > lastIndex) std::swap(firstIndex, lastIndex); - if (!isCtrlDown) row_selection_clear(); - for (int i = firstIndex; i <= lastIndex; ++i) - row_selection_insert(rowSelection[i]); - if (!rowSelectionAnchor) rowSelectionAnchor = rowReference; - } + auto rowSelection = timeline_item_rows_get(); + auto anchor = rowSelectionAnchor.value_or(rowReference); + auto first = std::find(rowSelection.begin(), rowSelection.end(), anchor); + auto last = std::find(rowSelection.begin(), rowSelection.end(), rowReference); + if (first == rowSelection.end() || last == rowSelection.end()) + { + if (!isCtrlDown) + row_selection_clear(); + row_selection_insert(rowReference); + rowSelectionAnchor = rowReference; + } + else + { + auto firstIndex = (int)std::distance(rowSelection.begin(), first); + auto lastIndex = (int)std::distance(rowSelection.begin(), last); + if (firstIndex > lastIndex) + std::swap(firstIndex, lastIndex); + if (!isCtrlDown) + row_selection_clear(); + for (int i = firstIndex; i <= lastIndex; ++i) + row_selection_insert(rowSelection[i]); + if (!rowSelectionAnchor) + rowSelectionAnchor = rowReference; + } } else if (isCtrlDown) { - if (is_row_reference_selected(rowReference) && document.selection.uids[SelectionKind::TRACKS].size() + - document.selection.uids[SelectionKind::GROUPS].size() > - 1) - { - auto references = document.selected_get(row_kind_get(rowReference)); - references.erase(row_selection_reference_get(rowReference)); - document.selected_set(row_kind_get(rowReference), references); - } - else - row_selection_insert(rowReference); - rowSelectionAnchor = rowReference; + if (is_row_reference_selected(rowReference) && document.selection.uids[SelectionKind::TRACKS].size() + + document.selection.uids[SelectionKind::GROUPS].size() > + 1) + { + auto references = document.selected_get(row_kind_get(rowReference)); + references.erase(row_selection_reference_get(rowReference)); + document.selected_set(row_kind_get(rowReference), references); + } + else + row_selection_insert(rowReference); + rowSelectionAnchor = rowReference; } else { - row_selection_clear(); - row_selection_insert(rowReference); - rowSelectionAnchor = rowReference; + row_selection_clear(); + row_selection_insert(rowReference); + rowSelectionAnchor = rowReference; } - } +} - void TimelineContext::reference_set_adjacent_item(int direction) - { +void TimelineContext::reference_set_adjacent_item(int direction) +{ std::vector itemReferences; for (auto& row : timeline_item_rows_get()) - if (!row.isGroup) itemReferences.push_back(row_item_reference_get(row)); - if (itemReferences.empty()) return; + if (!row.isGroup) + itemReferences.push_back(row_item_reference_get(row)); + if (itemReferences.empty()) + return; auto it = std::find_if(itemReferences.begin(), itemReferences.end(), [&](const Reference& itemReference) { return is_same_item(itemReference, reference); }); int index = direction > 0 ? 0 : (int)itemReferences.size() - 1; - if (it != itemReferences.end()) index = (int)std::distance(itemReferences.begin(), it) + direction; + if (it != itemReferences.end()) + index = (int)std::distance(itemReferences.begin(), it) + direction; index = std::clamp(index, 0, (int)itemReferences.size() - 1); auto& itemReference = itemReferences[index]; group_selection_reset_for(document); document.track_select(itemReference); - } +} - std::vector TimelineContext::selected_row_references_get() - { +std::vector TimelineContext::selected_row_references_get() +{ std::vector result; for (auto& row : timeline_item_rows_get()) - if (is_row_selected(row)) result.push_back(row); + if (is_row_selected(row)) + result.push_back(row); return result; - } +} - std::vector TimelineContext::row_drag_references_get(const TimelineRow& row) - { +std::vector TimelineContext::row_drag_references_get(const TimelineRow& row) +{ auto clicked = row; - if (clicked.type != LAYER && clicked.type != NULL_) return std::vector{clicked}; + if (clicked.type != LAYER && clicked.type != NULL_) + return std::vector{clicked}; auto rows = selected_row_references_get(); - if (!is_row_reference_selected(clicked)) rows = {clicked}; - if (rows.empty()) rows = {clicked}; + if (!is_row_reference_selected(clicked)) + rows = {clicked}; + if (rows.empty()) + rows = {clicked}; std::erase_if(rows, [&](const TimelineRow& rowReference) { return rowReference.type != clicked.type; }); - if (rows.empty()) rows = {clicked}; + if (rows.empty()) + rows = {clicked}; return rows; - } +} diff --git a/src/ui/timeline_tracks.cpp b/src/ui/timeline_tracks.cpp index 7ea0d89..6926e11 100644 --- a/src/ui/timeline_tracks.cpp +++ b/src/ui/timeline_tracks.cpp @@ -1,215 +1,219 @@ #include "ui/timeline_context.h" - void TimelineContext::item_child(const TimelineRow& row, int index) - { +void TimelineContext::item_child(const TimelineRow& row, int index) +{ ImGui::PushID(index); auto type = row.type; auto id = row.id; - auto row_reference_make = [&]() - { return Reference{reference.animationIndex, type, id, -1, row.groupType, row.groupId}; }; + auto row_reference_make = [&]() { + return Reference{reference.animationIndex, type, id, -1, row.groupType, row.groupId}; + }; if (row.isGroup) { - auto group = row_group_get(row); - if (!group) - { + auto group = row_group_get(row); + if (!group) + { + ImGui::PopID(); + return; + } + + auto label = group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name; + auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); + auto isGroupVisible = group->isVisible; + auto colorVec = color_get(COLOR_ITEM_BASE, type); + if (is_row_reference_selected(row)) + colorVec = color_get(COLOR_ITEM_SELECTED, type); + auto color = to_imvec4(isGroupVisible ? colorVec : colorVec * COLOR_HIDDEN_MULTIPLIER); + ImGui::PushStyleColor(ImGuiCol_ChildBg, color); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + if (ImGui::BeginChild("##Group Child", itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) + { + auto cursorPos = ImGui::GetCursorPos(); + auto groupChildMin = ImGui::GetWindowPos(); + auto groupChildMax = + ImVec2(groupChildMin.x + ImGui::GetWindowSize().x, groupChildMin.y + ImGui::GetWindowSize().y); + + auto toggle_group = [&]() { + auto targetRow = row; + auto targetAnimationIndex = reference.animationIndex; + edit_push(EDIT_TOGGLE_GROUP_EXPANDED, [=](Model& model) { + if (auto group = model.track_group_edit(targetAnimationIndex, targetRow.type, targetRow.id)) + group->isExpanded = !group->isExpanded; + }); + }; + + ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); + ImGui::SetNextItemAllowOverlap(); + ImGui::InvisibleButton("##Group Button", itemSize); + auto groupButtonMin = ImGui::GetItemRectMin(); + auto groupButtonMax = ImGui::GetItemRectMax(); + auto mousePos = ImGui::GetIO().MousePos; + auto is_mouse_in_rect = [](ImVec2 mouse, ImVec2 min, ImVec2 max) { + return mouse.x >= min.x && mouse.x < max.x && mouse.y >= min.y && mouse.y < max.y; + }; + auto isGroupHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && + is_mouse_in_rect(mousePos, groupButtonMin, groupButtonMax); + bool isGroupTooltipDelayed = false; + if (isGroupHovered) + { + auto& imguiStyle = ImGui::GetStyle(); + auto previousTooltipDelay = imguiStyle.HoverDelayNormal; + imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; + isGroupTooltipDelayed = + ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | + ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoSharedDelay); + imguiStyle.HoverDelayNormal = previousTooltipDelay; + } + + if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) + { + rowDragReferences = row_drag_references_get(row); + ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), + (int)rowDragReferences.size() * (int)sizeof(TimelineRow)); + ImGui::EndDragDropSource(); + } + + if (ImGui::BeginDragDropTarget()) + { + if (auto payload = ImGui::AcceptDragDropPayload("Timeline Row Drag Drop", + ImGuiDragDropFlags_AcceptBeforeDelivery | + ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + { + auto groupDropThird = (groupButtonMax.y - groupButtonMin.y) / 3.0f; + auto dropZone = DropZone::BEFORE; + if (mousePos.y >= groupButtonMax.y - groupDropThird) + dropZone = DropZone::AFTER; + else if (mousePos.y >= groupButtonMin.y + groupDropThird) + dropZone = DropZone::INSIDE; + auto isDropAfter = dropZone != DropZone::BEFORE; + auto payloadRows = (TimelineRow*)payload->Data; + auto payloadCount = payload->DataSize / sizeof(TimelineRow); + std::vector draggedRows(payloadRows, payloadRows + payloadCount); + auto isDropIntoGroup = dropZone == DropZone::INSIDE && (row.type == LAYER || row.type == NULL_); + for (auto draggedRow : draggedRows) + if (draggedRow.isGroup || draggedRow.type != row.type) + isDropIntoGroup = false; + + if (isDropIntoGroup) + drop_box_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax); + else + drop_line_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax, isDropAfter); + + if (payload->IsDelivery()) + rows_move_to_row(draggedRows, row, isDropAfter, isDropIntoGroup); + } + ImGui::EndDragDropTarget(); + } + + ImGui::SetCursorPos(cursorPos); + auto folderIcon = group->isExpanded ? ICON_FOLDER_OPEN : ICON_FOLDER; + ImGui::Image(resources.icon_id_get(folderIcon), icon_size_get()); + auto iconMin = ImGui::GetItemRectMin(); + auto iconMax = ImGui::GetItemRectMax(); + overlay_icon(resources.icon_id_get(folderIcon), itemIconTint, false); + ImGui::SameLine(); + + ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); + ImGui::TextUnformatted(label.c_str()); + ImGui::PopStyleColor(); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + + ImGui::SetCursorPos( + ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + int visibleIcon = isGroupVisible ? ICON_VISIBLE : ICON_INVISIBLE; + if (ImGui::ImageButton("##Group Visible Toggle", resources.icon_id_get(visibleIcon), icon_size_get())) + { + auto targetAnimationIndex = reference.animationIndex; + auto targetType = type; + auto targetGroupId = group->id; + auto targetVisible = !isGroupVisible; + edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, [=](Model& model) { + if (auto group = model.track_group_edit(targetAnimationIndex, targetType, targetGroupId)) + group->isVisible = targetVisible; + }); + } + auto visibleButtonMin = ImGui::GetItemRectMin(); + auto visibleButtonMax = ImGui::GetItemRectMax(); + overlay_icon(resources.icon_id_get(visibleIcon), itemIconTint, false); + ImGui::SetItemTooltip("%s", isGroupVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) + : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + + auto isIconHovered = isGroupHovered && is_mouse_in_rect(mousePos, iconMin, iconMax); + auto isVisibleButtonHovered = + isGroupHovered && is_mouse_in_rect(mousePos, visibleButtonMin, visibleButtonMax); + if (isGroupTooltipDelayed && !isVisibleButtonHovered) + { + ImGui::BeginTooltip(); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); + ImGui::TextUnformatted(label.c_str()); + ImGui::PopFont(); + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(group->id)).c_str()); + auto groupItemsCount = (int)group->tracks.size(); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_ITEMS_COUNT), std::make_format_args(groupItemsCount)).c_str()); + ImGui::EndTooltip(); + } + if (isIconHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && + !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + toggle_group(); + else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && + ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + group_properties_open(row, *group); + else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && + ImGui::IsMouseReleased(ImGuiMouseButton_Left) && + !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + row_selection_set(row); + } + ImGui::EndChild(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); ImGui::PopID(); return; - } - - auto label = group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name; - auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); - auto isGroupVisible = group->isVisible; - auto colorVec = color_get(COLOR_ITEM_BASE, type); - if (is_row_reference_selected(row)) colorVec = color_get(COLOR_ITEM_SELECTED, type); - auto color = to_imvec4(isGroupVisible ? colorVec : colorVec * COLOR_HIDDEN_MULTIPLIER); - ImGui::PushStyleColor(ImGuiCol_ChildBg, color); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - if (ImGui::BeginChild("##Group Child", itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) - { - auto cursorPos = ImGui::GetCursorPos(); - auto groupChildMin = ImGui::GetWindowPos(); - auto groupChildMax = - ImVec2(groupChildMin.x + ImGui::GetWindowSize().x, groupChildMin.y + ImGui::GetWindowSize().y); - - auto toggle_group = [&]() - { - auto targetRow = row; - auto targetAnimationIndex = reference.animationIndex; - edit_push(EDIT_TOGGLE_GROUP_EXPANDED, - [=](Model& model) - { - if (auto group = model.track_group_edit(targetAnimationIndex, targetRow.type, targetRow.id)) - group->isExpanded = !group->isExpanded; - }); - }; - - ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); - ImGui::SetNextItemAllowOverlap(); - ImGui::InvisibleButton("##Group Button", itemSize); - auto groupButtonMin = ImGui::GetItemRectMin(); - auto groupButtonMax = ImGui::GetItemRectMax(); - auto mousePos = ImGui::GetIO().MousePos; - auto is_mouse_in_rect = [](ImVec2 mouse, ImVec2 min, ImVec2 max) - { return mouse.x >= min.x && mouse.x < max.x && mouse.y >= min.y && mouse.y < max.y; }; - auto isGroupHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && - is_mouse_in_rect(mousePos, groupButtonMin, groupButtonMax); - bool isGroupTooltipDelayed = false; - if (isGroupHovered) - { - auto& imguiStyle = ImGui::GetStyle(); - auto previousTooltipDelay = imguiStyle.HoverDelayNormal; - imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; - isGroupTooltipDelayed = - ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | - ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoSharedDelay); - imguiStyle.HoverDelayNormal = previousTooltipDelay; - } - - if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) - { - rowDragReferences = row_drag_references_get(row); - ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), - (int)rowDragReferences.size() * (int)sizeof(TimelineRow)); - ImGui::EndDragDropSource(); - } - - if (ImGui::BeginDragDropTarget()) - { - if (auto payload = ImGui::AcceptDragDropPayload("Timeline Row Drag Drop", - ImGuiDragDropFlags_AcceptBeforeDelivery | - ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) - { - auto groupDropThird = (groupButtonMax.y - groupButtonMin.y) / 3.0f; - auto dropZone = DropZone::BEFORE; - if (mousePos.y >= groupButtonMax.y - groupDropThird) - dropZone = DropZone::AFTER; - else if (mousePos.y >= groupButtonMin.y + groupDropThird) - dropZone = DropZone::INSIDE; - auto isDropAfter = dropZone != DropZone::BEFORE; - auto payloadRows = (TimelineRow*)payload->Data; - auto payloadCount = payload->DataSize / sizeof(TimelineRow); - std::vector draggedRows(payloadRows, payloadRows + payloadCount); - auto isDropIntoGroup = dropZone == DropZone::INSIDE && (row.type == LAYER || row.type == NULL_); - for (auto draggedRow : draggedRows) - if (draggedRow.isGroup || draggedRow.type != row.type) isDropIntoGroup = false; - - if (isDropIntoGroup) - drop_box_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax); - else - drop_line_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax, isDropAfter); - - if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, isDropIntoGroup); - } - ImGui::EndDragDropTarget(); - } - - ImGui::SetCursorPos(cursorPos); - auto folderIcon = group->isExpanded ? ICON_FOLDER_OPEN : ICON_FOLDER; - ImGui::Image(resources.icon_id_get(folderIcon), icon_size_get()); - auto iconMin = ImGui::GetItemRectMin(); - auto iconMax = ImGui::GetItemRectMax(); - overlay_icon(resources.icon_id_get(folderIcon), itemIconTint, false); - ImGui::SameLine(); - - ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); - ImGui::TextUnformatted(label.c_str()); - ImGui::PopStyleColor(); - - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - - ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - int visibleIcon = isGroupVisible ? ICON_VISIBLE : ICON_INVISIBLE; - if (ImGui::ImageButton("##Group Visible Toggle", resources.icon_id_get(visibleIcon), icon_size_get())) - { - auto targetAnimationIndex = reference.animationIndex; - auto targetType = type; - auto targetGroupId = group->id; - auto targetVisible = !isGroupVisible; - edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, - [=](Model& model) - { - if (auto group = model.track_group_edit(targetAnimationIndex, targetType, targetGroupId)) - group->isVisible = targetVisible; - }); - } - auto visibleButtonMin = ImGui::GetItemRectMin(); - auto visibleButtonMax = ImGui::GetItemRectMax(); - overlay_icon(resources.icon_id_get(visibleIcon), itemIconTint, false); - ImGui::SetItemTooltip("%s", isGroupVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) - : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(3); - - auto isIconHovered = isGroupHovered && is_mouse_in_rect(mousePos, iconMin, iconMax); - auto isVisibleButtonHovered = isGroupHovered && is_mouse_in_rect(mousePos, visibleButtonMin, visibleButtonMax); - if (isGroupTooltipDelayed && !isVisibleButtonHovered) - { - ImGui::BeginTooltip(); - ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); - ImGui::TextUnformatted(label.c_str()); - ImGui::PopFont(); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(group->id)).c_str()); - auto groupItemsCount = (int)group->tracks.size(); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_ITEMS_COUNT), std::make_format_args(groupItemsCount)).c_str()); - ImGui::EndTooltip(); - } - if (isIconHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && - !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - toggle_group(); - else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && - ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) - group_properties_open(row, *group); - else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && - ImGui::IsMouseReleased(ImGuiMouseButton_Left) && - !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - row_selection_set(row); - } - ImGui::EndChild(); - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(); - ImGui::PopID(); - return; } auto item = item_get(type, id, row.groupType, row.groupId); if (type != NONE && !item) { - ImGui::PopID(); - return; + ImGui::PopID(); + return; } auto isItemVisible = item ? item->isVisible : false; auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; if (item && type == ROOT && row.groupId != -1) - isVisible = item->isVisible && is_track_group_visible(row.groupType, row.groupId); + isVisible = item->isVisible && is_track_group_visible(row.groupType, row.groupId); auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; - if (isOnlyShowLayers && type != LAYER) isVisible = false; + if (isOnlyShowLayers && type != LAYER) + isVisible = false; auto isReferenced = is_same_item(reference, row_reference_make()); auto isItemSelected = is_row_selected(row); - auto label = [&]() -> std::string - { - if (type == LAYER) - { - auto layer = ::item_get(model.content.layers, id); - if (!layer) return localize.get(TYPE_STRINGS[type]); - return layer_label_get(*layer); - } - if (type == NULL_) - { - auto null = ::item_get(model.content.nulls, id); - if (!null) return localize.get(TYPE_STRINGS[type]); - return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); - } - return localize.get(TYPE_STRINGS[type]); + auto label = [&]() -> std::string { + if (type == LAYER) + { + auto layer = ::item_get(model.content.layers, id); + if (!layer) + return localize.get(TYPE_STRINGS[type]); + return layer_label_get(*layer); + } + if (type == NULL_) + { + auto null = ::item_get(model.content.nulls, id); + if (!null) + return localize.get(TYPE_STRINGS[type]); + return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); + } + return localize.get(TYPE_STRINGS[type]); }(); auto icon = TYPE_ICONS[type]; auto iconTintCurrent = isLightTheme && type == NONE ? ImVec4(1.0f, 1.0f, 1.0f, 1.0f) : itemIconTint; @@ -225,287 +229,308 @@ if (ImGui::BeginChild(label.c_str(), itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) { - auto cursorPos = ImGui::GetCursorPos(); - auto itemChildMin = ImGui::GetWindowPos(); - auto itemChildMax = ImVec2(itemChildMin.x + ImGui::GetWindowSize().x, itemChildMin.y + ImGui::GetWindowSize().y); + auto cursorPos = ImGui::GetCursorPos(); + auto itemChildMin = ImGui::GetWindowPos(); + auto itemChildMax = + ImVec2(itemChildMin.x + ImGui::GetWindowSize().x, itemChildMin.y + ImGui::GetWindowSize().y); - if (type != NONE) - { - ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); - ImGui::SetNextItemAllowOverlap(); - ImGui::SetNextItemStorageID(id); - ImGui::InvisibleButton("##Item Button", itemSize); - auto itemButtonMin = ImGui::GetItemRectMin(); - auto itemButtonMax = ImGui::GetItemRectMax(); - auto isItemButtonHovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); - - if (type == LAYER || type == NULL_) + if (type != NONE) { - if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) - { - rowDragReferences = row_drag_references_get(row); - ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), - (int)rowDragReferences.size() * (int)sizeof(TimelineRow)); - ImGui::EndDragDropSource(); - } + ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); + ImGui::SetNextItemAllowOverlap(); + ImGui::SetNextItemStorageID(id); + ImGui::InvisibleButton("##Item Button", itemSize); + auto itemButtonMin = ImGui::GetItemRectMin(); + auto itemButtonMax = ImGui::GetItemRectMax(); + auto isItemButtonHovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); - if (ImGui::BeginDragDropTarget()) - { - if (auto payload = ImGui::AcceptDragDropPayload("Timeline Row Drag Drop", - ImGuiDragDropFlags_AcceptBeforeDelivery | - ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + if (type == LAYER || type == NULL_) { - auto isDropAfter = is_drop_after(itemButtonMin, itemButtonMax); - drop_line_draw(ImGui::GetWindowDrawList(), itemChildMin, itemChildMax, isDropAfter); + if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) + { + rowDragReferences = row_drag_references_get(row); + ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), + (int)rowDragReferences.size() * (int)sizeof(TimelineRow)); + ImGui::EndDragDropSource(); + } - auto payloadRows = (TimelineRow*)payload->Data; - auto payloadCount = payload->DataSize / sizeof(TimelineRow); - std::vector draggedRows(payloadRows, payloadRows + payloadCount); - if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, false); - } - ImGui::EndDragDropTarget(); - } - } - - auto animationLayer = type == LAYER ? ::item_get(model.content.layers, id) : nullptr; - if (animationLayer && !animationLayer->is_animation()) animationLayer = nullptr; - if (isItemButtonHovered) - { - if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) - animationLayer ? child_step_in(row) : item_base_properties_open(type, id); - else if (ImGui::IsMouseReleased(ImGuiMouseButton_Left) && - !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - row_selection_set(row); - - auto& imguiStyle = ImGui::GetStyle(); - auto previousTooltipFlags = imguiStyle.HoverFlagsForTooltipMouse; - auto previousTooltipDelay = imguiStyle.HoverDelayNormal; - imguiStyle.HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | - ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoSharedDelay; - imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; - bool showItemTooltip = ImGui::BeginItemTooltip(); - imguiStyle.HoverFlagsForTooltipMouse = previousTooltipFlags; - imguiStyle.HoverDelayNormal = previousTooltipDelay; - - if (showItemTooltip) - { - auto yesNoLabel = [&](bool value) { return value ? localize.get(BASIC_YES) : localize.get(BASIC_NO); }; - auto visibleLabel = yesNoLabel(isVisible); - auto framesCount = item ? track_frames_count_get(*item) : 0; - - switch (type) - { - case ROOT: - { - ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); - ImGui::TextUnformatted(localize.get(BASIC_ROOT)); - ImGui::PopFont(); - - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - auto transformLabel = yesNoLabel(settings.previewIsRootTransform); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_TRANSFORM), std::make_format_args(transformLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - case LAYER: - { - auto layer = ::item_get(model.content.layers, id); - if (!layer) break; - ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); - ImGui::TextUnformatted(layer->name.c_str()); - ImGui::PopFont(); - - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); - layer_source_tooltip_draw(document, *layer); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - case NULL_: - { - auto nullInfo = ::item_get(model.content.nulls, id); - if (!nullInfo) break; - ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); - ImGui::TextUnformatted(nullInfo->name.c_str()); - ImGui::PopFont(); - - auto rectLabel = yesNoLabel(nullInfo->isShowRect); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_RECT), std::make_format_args(rectLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - case TRIGGER: - { - ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); - ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS)); - ImGui::PopFont(); - - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_TRIGGERS_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - default: - break; - } - - ImGui::EndTooltip(); - } - } - - auto contentCursorPos = cursorPos; - contentCursorPos.x += (float)row.depth * ImGui::GetTextLineHeightWithSpacing(); - ImGui::SetCursorPos(contentCursorPos); - - // An animation layer's icon is a folder that shows (or hides) its child's tracks. - auto isExpanded = item && expandedLayerTracks.contains(item->uid); - if (animationLayer) icon = isExpanded ? ICON_FOLDER_OPEN : ICON_FOLDER; - ImGui::Image(resources.icon_id_get(icon), icon_size_get()); - auto mousePos = ImGui::GetIO().MousePos; - auto iconMin = ImGui::GetItemRectMin(); - auto iconMax = ImGui::GetItemRectMax(); - auto isIconHovered = - mousePos.x >= iconMin.x && mousePos.x < iconMax.x && mousePos.y >= iconMin.y && mousePos.y < iconMax.y; - if (animationLayer && isItemButtonHovered && isIconHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && - !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - { - if (isExpanded) - expandedLayerTracks.erase(item->uid); - else - expandedLayerTracks.insert(item->uid); - } - overlay_icon(resources.icon_id_get(icon), iconTintCurrent, false); - ImGui::SameLine(); - if (isReferenced) ImGui::PushFont(resources.fonts[FONT_ITALICS].get(), FONT_SIZE); - ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); - ImGui::TextUnformatted(label.c_str()); - ImGui::PopStyleColor(); - if (isReferenced) ImGui::PopFont(); - - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - - ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - int visibleIcon = isItemVisible ? ICON_VISIBLE : ICON_INVISIBLE; - if (ImGui::ImageButton("##Visible Toggle", resources.icon_id_get(visibleIcon), icon_size_get())) - { - auto animationIndex = reference.animationIndex; - auto targetType = type; - auto targetID = id; - auto targetGroupType = row.groupType; - auto targetGroupId = row.groupId; - edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, - [=](Model& model) + if (ImGui::BeginDragDropTarget()) + { + if (auto payload = ImGui::AcceptDragDropPayload("Timeline Row Drag Drop", + ImGuiDragDropFlags_AcceptBeforeDelivery | + ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { - if (auto item = model.track_edit( - Reference{animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId})) - item->isVisible = !item->isVisible; - }); - } - overlay_icon(resources.icon_id_get(visibleIcon), iconTintCurrent, false); - ImGui::SetItemTooltip("%s", isItemVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) - : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); + auto isDropAfter = is_drop_after(itemButtonMin, itemButtonMax); + drop_line_draw(ImGui::GetWindowDrawList(), itemChildMin, itemChildMax, isDropAfter); - if (type == NULL_) + auto payloadRows = (TimelineRow*)payload->Data; + auto payloadCount = payload->DataSize / sizeof(TimelineRow); + std::vector draggedRows(payloadRows, payloadRows + payloadCount); + if (payload->IsDelivery()) + rows_move_to_row(draggedRows, row, isDropAfter, false); + } + ImGui::EndDragDropTarget(); + } + } + + auto animationLayer = type == LAYER ? ::item_get(model.content.layers, id) : nullptr; + if (animationLayer && !animationLayer->is_animation()) + animationLayer = nullptr; + if (isItemButtonHovered) + { + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + animationLayer ? child_step_in(row) : item_base_properties_open(type, id); + else if (ImGui::IsMouseReleased(ImGuiMouseButton_Left) && + !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + row_selection_set(row); + + auto& imguiStyle = ImGui::GetStyle(); + auto previousTooltipFlags = imguiStyle.HoverFlagsForTooltipMouse; + auto previousTooltipDelay = imguiStyle.HoverDelayNormal; + imguiStyle.HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | + ImGuiHoveredFlags_AllowWhenDisabled | + ImGuiHoveredFlags_NoSharedDelay; + imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; + bool showItemTooltip = ImGui::BeginItemTooltip(); + imguiStyle.HoverFlagsForTooltipMouse = previousTooltipFlags; + imguiStyle.HoverDelayNormal = previousTooltipDelay; + + if (showItemTooltip) + { + auto yesNoLabel = [&](bool value) { + return value ? localize.get(BASIC_YES) : localize.get(BASIC_NO); + }; + auto visibleLabel = yesNoLabel(isVisible); + auto framesCount = item ? track_frames_count_get(*item) : 0; + + switch (type) + { + case ROOT: + { + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); + ImGui::TextUnformatted(localize.get(BASIC_ROOT)); + ImGui::PopFont(); + + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)) + .c_str()); + auto transformLabel = yesNoLabel(settings.previewIsRootTransform); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_TRANSFORM), std::make_format_args(transformLabel)) + .c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)) + .c_str()); + break; + } + case LAYER: + { + auto layer = ::item_get(model.content.layers, id); + if (!layer) + break; + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); + ImGui::TextUnformatted(layer->name.c_str()); + ImGui::PopFont(); + + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); + layer_source_tooltip_draw(document, *layer); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)) + .c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)) + .c_str()); + break; + } + case NULL_: + { + auto nullInfo = ::item_get(model.content.nulls, id); + if (!nullInfo) + break; + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); + ImGui::TextUnformatted(nullInfo->name.c_str()); + ImGui::PopFont(); + + auto rectLabel = yesNoLabel(nullInfo->isShowRect); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_RECT), std::make_format_args(rectLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)) + .c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)) + .c_str()); + break; + } + case TRIGGER: + { + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); + ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS)); + ImGui::PopFont(); + + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)) + .c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_TRIGGERS_COUNT), std::make_format_args(framesCount)) + .c_str()); + break; + } + default: + break; + } + + ImGui::EndTooltip(); + } + } + + auto contentCursorPos = cursorPos; + contentCursorPos.x += (float)row.depth * ImGui::GetTextLineHeightWithSpacing(); + ImGui::SetCursorPos(contentCursorPos); + + // An animation layer's icon is a folder that shows (or hides) its child's tracks. + auto isExpanded = item && expandedLayerTracks.contains(item->uid); + if (animationLayer) + icon = isExpanded ? ICON_FOLDER_OPEN : ICON_FOLDER; + ImGui::Image(resources.icon_id_get(icon), icon_size_get()); + auto mousePos = ImGui::GetIO().MousePos; + auto iconMin = ImGui::GetItemRectMin(); + auto iconMax = ImGui::GetItemRectMax(); + auto isIconHovered = + mousePos.x >= iconMin.x && mousePos.x < iconMax.x && mousePos.y >= iconMin.y && mousePos.y < iconMax.y; + if (animationLayer && isItemButtonHovered && isIconHovered && + ImGui::IsMouseReleased(ImGuiMouseButton_Left) && + !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + { + if (isExpanded) + expandedLayerTracks.erase(item->uid); + else + expandedLayerTracks.insert(item->uid); + } + overlay_icon(resources.icon_id_get(icon), iconTintCurrent, false); + ImGui::SameLine(); + if (isReferenced) + ImGui::PushFont(resources.fonts[FONT_ITALICS].get(), FONT_SIZE); + ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); + ImGui::TextUnformatted(label.c_str()); + ImGui::PopStyleColor(); + if (isReferenced) + ImGui::PopFont(); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + + ImGui::SetCursorPos( + ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + int visibleIcon = isItemVisible ? ICON_VISIBLE : ICON_INVISIBLE; + if (ImGui::ImageButton("##Visible Toggle", resources.icon_id_get(visibleIcon), icon_size_get())) + { + auto animationIndex = reference.animationIndex; + auto targetType = type; + auto targetID = id; + auto targetGroupType = row.groupType; + auto targetGroupId = row.groupId; + edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, [=](Model& model) { + if (auto item = model.track_edit( + Reference{animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId})) + item->isVisible = !item->isVisible; + }); + } + overlay_icon(resources.icon_id_get(visibleIcon), iconTintCurrent, false); + ImGui::SetItemTooltip("%s", isItemVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) + : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); + + if (type == NULL_) + { + if (auto null = ::item_get(model.content.nulls, id)) + { + auto& isShowRect = null->isShowRect; + auto rectIcon = isShowRect ? ICON_SHOW_RECT : ICON_HIDE_RECT; + ImGui::SetCursorPos(ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - + ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + if (ImGui::ImageButton("##Rect Toggle", resources.icon_id_get(rectIcon), icon_size_get())) + { + auto nullID = id; + edit_push(EDIT_TOGGLE_NULL_RECT, [=](Model& model) { + if (auto null = ::item_get(model.content.nulls, nullID)) + null->isShowRect = !null->isShowRect; + }); + } + overlay_icon(resources.icon_id_get(rectIcon), iconTintCurrent, false); + ImGui::SetItemTooltip("%s", isShowRect ? localize.get(TOOLTIP_NULL_RECT_SHOWN) + : localize.get(TOOLTIP_NULL_RECT_HIDDEN)); + } + } + + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + } + else { - if (auto null = ::item_get(model.content.nulls, id)) - { - auto& isShowRect = null->isShowRect; - auto rectIcon = isShowRect ? ICON_SHOW_RECT : ICON_HIDE_RECT; + auto cursorPos = ImGui::GetCursorPos(); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + ImGui::SetCursorPos( + ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + + auto& isShowUnused = settings.timelineIsShowUnused; + auto unusedIcon = isShowUnused ? ICON_SHOW_UNUSED : ICON_HIDE_UNUSED; + if (ImGui::ImageButton("##Unused Toggle", resources.icon_id_get(unusedIcon), icon_size_get())) + isShowUnused = !isShowUnused; + overlay_icon(resources.icon_id_get(unusedIcon), iconTintCurrent, false); + ImGui::SetItemTooltip("%s", isShowUnused ? localize.get(TOOLTIP_UNUSED_ITEMS_SHOWN) + : localize.get(TOOLTIP_UNUSED_ITEMS_HIDDEN)); + + auto& showLayersOnly = settings.timelineIsOnlyShowLayers; + auto layersIcon = showLayersOnly ? ICON_SHOW_LAYERS : ICON_HIDE_LAYERS; ImGui::SetCursorPos( ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - if (ImGui::ImageButton("##Rect Toggle", resources.icon_id_get(rectIcon), icon_size_get())) - { - auto nullID = id; - edit_push(EDIT_TOGGLE_NULL_RECT, - [=](Model& model) - { - if (auto null = ::item_get(model.content.nulls, nullID)) - null->isShowRect = !null->isShowRect; - }); - } - overlay_icon(resources.icon_id_get(rectIcon), iconTintCurrent, false); - ImGui::SetItemTooltip("%s", isShowRect ? localize.get(TOOLTIP_NULL_RECT_SHOWN) - : localize.get(TOOLTIP_NULL_RECT_HIDDEN)); - } + if (ImGui::ImageButton("##Layers Toggle", resources.icon_id_get(layersIcon), icon_size_get())) + showLayersOnly = !showLayersOnly; + overlay_icon(resources.icon_id_get(layersIcon), iconTintCurrent, false); + ImGui::SetItemTooltip("%s", showLayersOnly ? localize.get(TOOLTIP_ONLY_LAYERS_VISIBLE) + : localize.get(TOOLTIP_ALL_ITEMS_VISIBLE)); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + + ImGui::SetCursorPos(cursorPos); + + ImGui::BeginDisabled(); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); + ImGui::Text("(?)"); + ImGui::PopStyleColor(); + auto tooltipShortcuts = std::vformat( + localize.get(TOOLTIP_TIMELINE_SHORTCUTS), + std::make_format_args(settings.shortcutMovePlayheadBack, settings.shortcutMovePlayheadForward, + settings.shortcutShortenFrame, settings.shortcutExtendFrame, + settings.shortcutPreviousFrame, settings.shortcutNextFrame, + settings.shortcutPreviousItem, settings.shortcutNextItem)); + ImGui::SetItemTooltip("%s", tooltipShortcuts.c_str()); + ImGui::EndDisabled(); } - - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(3); - } - else - { - auto cursorPos = ImGui::GetCursorPos(); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - - auto& isShowUnused = settings.timelineIsShowUnused; - auto unusedIcon = isShowUnused ? ICON_SHOW_UNUSED : ICON_HIDE_UNUSED; - if (ImGui::ImageButton("##Unused Toggle", resources.icon_id_get(unusedIcon), icon_size_get())) - isShowUnused = !isShowUnused; - overlay_icon(resources.icon_id_get(unusedIcon), iconTintCurrent, false); - ImGui::SetItemTooltip("%s", isShowUnused ? localize.get(TOOLTIP_UNUSED_ITEMS_SHOWN) - : localize.get(TOOLTIP_UNUSED_ITEMS_HIDDEN)); - - auto& showLayersOnly = settings.timelineIsOnlyShowLayers; - auto layersIcon = showLayersOnly ? ICON_SHOW_LAYERS : ICON_HIDE_LAYERS; - ImGui::SetCursorPos( - ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - if (ImGui::ImageButton("##Layers Toggle", resources.icon_id_get(layersIcon), icon_size_get())) - showLayersOnly = !showLayersOnly; - overlay_icon(resources.icon_id_get(layersIcon), iconTintCurrent, false); - ImGui::SetItemTooltip("%s", showLayersOnly ? localize.get(TOOLTIP_ONLY_LAYERS_VISIBLE) - : localize.get(TOOLTIP_ALL_ITEMS_VISIBLE)); - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(3); - - ImGui::SetCursorPos(cursorPos); - - ImGui::BeginDisabled(); - ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - ImGui::Text("(?)"); - ImGui::PopStyleColor(); - auto tooltipShortcuts = - std::vformat(localize.get(TOOLTIP_TIMELINE_SHORTCUTS), - std::make_format_args(settings.shortcutMovePlayheadBack, settings.shortcutMovePlayheadForward, - settings.shortcutShortenFrame, settings.shortcutExtendFrame, - settings.shortcutPreviousFrame, settings.shortcutNextFrame, - settings.shortcutPreviousItem, settings.shortcutNextItem)); - ImGui::SetItemTooltip("%s", tooltipShortcuts.c_str()); - ImGui::EndDisabled(); - } } ImGui::EndChild(); ImGui::PopStyleColor(); ImGui::PopStyleVar(2); ImGui::PopID(); - } +} - void TimelineContext::items_child() - { +void TimelineContext::items_child() +{ auto itemsChildSize = ImVec2(ITEM_CHILD_WIDTH, ImGui::GetContentRegionAvail().y); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); @@ -513,103 +538,102 @@ ImGui::PopStyleVar(); if (isItemsChildOpen) { - auto itemsListChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y - - ImGui::GetTextLineHeightWithSpacing() - - ImGui::GetStyle().ItemSpacing.y * 2); + auto itemsListChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y - + ImGui::GetTextLineHeightWithSpacing() - + ImGui::GetStyle().ItemSpacing.y * 2); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - if (ImGui::BeginChild("##Items List Child", itemsListChildSize, ImGuiChildFlags_Borders, - ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar)) - { - if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + if (ImGui::BeginChild("##Items List Child", itemsListChildSize, ImGuiChildFlags_Borders, + ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar)) { - auto rowReferences = timeline_item_rows_get(); - row_selection_clear(); - for (auto rowReference : rowReferences) - row_selection_insert(rowReference); - if (!rowReferences.empty()) - { - rowSelectionAnchor = rowReferences.front(); - } - document.frame_references_clear(); - } - - if (animation && shortcut(manager.chords[SHORTCUT_GROUP], SCOPE_FOCUSED) && - !item_references_groupable_get().empty()) - item_group(); - - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 0.0f); - if (ImGui::BeginTable("##Item Table", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) - { - ImGui::GetCurrentWindow()->Flags |= ImGuiWindowFlags_NoScrollWithMouse; - ImGui::SetScrollY(scroll.y); - - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("##Items"); - - auto item_child_row = [&](const TimelineRow& row, int index) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - item_child(row, index); - }; - - int index = 0; - item_child_row({.type = NONE}, index++); - if (animation) - for (auto& row : timeline_item_rows_get()) + if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) { - item_child_row(row, index++); - for (auto& peek : peek_rows_get(row)) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - peek_item_child(row, peek, index++); - } + auto rowReferences = timeline_item_rows_get(); + row_selection_clear(); + for (auto rowReference : rowReferences) + row_selection_insert(rowReference); + if (!rowReferences.empty()) + rowSelectionAnchor = rowReferences.front(); + document.frame_references_clear(); } - if (isHorizontalScroll && ImGui::GetCurrentWindow()->ScrollbarY) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - ImGui::Dummy(ImVec2(0, style.ScrollbarSize)); - } + if (animation && shortcut(manager.chords[SHORTCUT_GROUP], SCOPE_FOCUSED) && + !item_references_groupable_get().empty()) + item_group(); - ImGui::EndTable(); + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 0.0f); + if (ImGui::BeginTable("##Item Table", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) + { + ImGui::GetCurrentWindow()->Flags |= ImGuiWindowFlags_NoScrollWithMouse; + ImGui::SetScrollY(scroll.y); + + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("##Items"); + + auto item_child_row = [&](const TimelineRow& row, int index) { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + item_child(row, index); + }; + + int index = 0; + item_child_row({.type = NONE}, index++); + if (animation) + for (auto& row : timeline_item_rows_get()) + { + item_child_row(row, index++); + for (auto& peek : peek_rows_get(row)) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + peek_item_child(row, peek, index++); + } + } + + if (isHorizontalScroll && ImGui::GetCurrentWindow()->ScrollbarY) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::Dummy(ImVec2(0, style.ScrollbarSize)); + } + + ImGui::EndTable(); + } + ImGui::PopStyleVar(2); + + item_context_menu(); } ImGui::PopStyleVar(2); + ImGui::EndChild(); - item_context_menu(); - } - ImGui::PopStyleVar(2); - ImGui::EndChild(); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + style.WindowPadding.x, ImGui::GetCursorPosY())); + auto widgetSize = widget_size_with_row_get(2, ImGui::GetContentRegionAvail().x - style.WindowPadding.x); - ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + style.WindowPadding.x, ImGui::GetCursorPosY())); - auto widgetSize = widget_size_with_row_get(2, ImGui::GetContentRegionAvail().x - style.WindowPadding.x); + ImGui::BeginDisabled(!animation); + { + shortcut(manager.chords[SHORTCUT_ADD]); + if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) + itemProperties.open(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_ADD_ITEM), settings.shortcutAdd); + ImGui::SameLine(); - ImGui::BeginDisabled(!animation); - { - shortcut(manager.chords[SHORTCUT_ADD]); - if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) itemProperties.open(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_ADD_ITEM), settings.shortcutAdd); - ImGui::SameLine(); - - auto selectedRows = selected_row_references_get(); - auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRow& row) - { return row.type == LAYER || row.type == NULL_; }); - ImGui::BeginDisabled(!isRemoveAvailable); - shortcut(manager.chords[SHORTCUT_REMOVE]); - if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize)) item_remove(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_ITEMS), settings.shortcutRemove); + auto selectedRows = selected_row_references_get(); + auto isRemoveAvailable = std::ranges::any_of( + selectedRows, [](const TimelineRow& row) { return row.type == LAYER || row.type == NULL_; }); + ImGui::BeginDisabled(!isRemoveAvailable); + shortcut(manager.chords[SHORTCUT_REMOVE]); + if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize)) + item_remove(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_ITEMS), settings.shortcutRemove); + ImGui::EndDisabled(); + } ImGui::EndDisabled(); - } - ImGui::EndDisabled(); - ImGui::PopStyleVar(); + ImGui::PopStyleVar(); } ImGui::EndChild(); - } +} diff --git a/src/ui/toast.cpp b/src/ui/toast.cpp index fd31e7a..c722fc0 100644 --- a/src/ui/toast.cpp +++ b/src/ui/toast.cpp @@ -8,17 +8,17 @@ #include "types.h" - constexpr auto LIFETIME = 4.0f; - constexpr auto FADE_THRESHOLD = 1.0f; +constexpr auto LIFETIME = 4.0f; +constexpr auto FADE_THRESHOLD = 1.0f; - Toast::Toast(const std::string& message) - { +Toast::Toast(const std::string& message) +{ this->message = message; lifetime = LIFETIME; - } +} - void Toasts::update() - { +void Toasts::update() +{ auto borderColor = ImGui::GetStyleColorVec4(ImGuiCol_Border); auto textColor = ImGui::GetStyleColorVec4(ImGuiCol_Text); @@ -28,43 +28,47 @@ for (int i = (int)toasts.size() - 1; i >= 0; --i) { - Toast& toast = toasts[i]; + Toast& toast = toasts[i]; - if (toast.lifetime <= 0.0f) - { - toasts.erase(toasts.begin() + i); - i--; - continue; - } + if (toast.lifetime <= 0.0f) + { + toasts.erase(toasts.begin() + i); + i--; + continue; + } - toast.lifetime -= ImGui::GetIO().DeltaTime; + toast.lifetime -= ImGui::GetIO().DeltaTime; - auto alpha = toast.lifetime <= FADE_THRESHOLD ? toast.lifetime / FADE_THRESHOLD : 1.0f; - borderColor.w = alpha; - textColor.w = alpha; + auto alpha = toast.lifetime <= FADE_THRESHOLD ? toast.lifetime / FADE_THRESHOLD : 1.0f; + borderColor.w = alpha; + textColor.w = alpha; - ImGui::SetNextWindowPos(to_imvec2(position), ImGuiCond_None, {1.0f, 1.0f}); - ImGui::SetNextWindowSize(ImVec2(0, ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y)); - ImGui::PushStyleColor(ImGuiCol_Text, textColor); - ImGui::PushStyleColor(ImGuiCol_Border, borderColor); - ImGui::SetNextWindowBgAlpha(alpha); + ImGui::SetNextWindowPos(to_imvec2(position), ImGuiCond_None, {1.0f, 1.0f}); + ImGui::SetNextWindowSize(ImVec2(0, ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y)); + ImGui::PushStyleColor(ImGuiCol_Text, textColor); + ImGui::PushStyleColor(ImGuiCol_Border, borderColor); + ImGui::SetNextWindowBgAlpha(alpha); - if (ImGui::Begin(std::format("##Toast #{}", i).c_str(), nullptr, - ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | - ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | - ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) - { - ImGui::TextUnformatted(toast.message.c_str()); - position.y -= ImGui::GetWindowSize().y + ImGui::GetStyle().ItemSpacing.y; + if (ImGui::Begin(std::format("##Toast #{}", i).c_str(), nullptr, + ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) + { + ImGui::TextUnformatted(toast.message.c_str()); + position.y -= ImGui::GetWindowSize().y + ImGui::GetStyle().ItemSpacing.y; - if (ImGui::IsWindowHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) toast.lifetime = 0.0f; - } - ImGui::End(); - ImGui::PopStyleColor(2); + if (ImGui::IsWindowHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + toast.lifetime = 0.0f; + } + ImGui::End(); + ImGui::PopStyleColor(2); } - } +} - void Toasts::push(const std::string& message) { toasts.emplace_back(Toast(message)); } +void Toasts::push(const std::string& message) +{ + toasts.emplace_back(Toast(message)); +} Toasts toasts; diff --git a/src/ui/toast.h b/src/ui/toast.h index b73abe8..c3619a2 100644 --- a/src/ui/toast.h +++ b/src/ui/toast.h @@ -7,35 +7,34 @@ #include "log.h" #include "localization.h" - class Toast - { - public: +class Toast +{ +public: std::string message; float lifetime = 0; Toast(const std::string&); - }; +}; - class Toasts - { - public: +class Toasts +{ +public: std::vector toasts; void update(); void push(const std::string&); - }; +}; extern Toasts toasts; - template 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...)); +template 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)); - } +} diff --git a/src/ui/tools.cpp b/src/ui/tools.cpp index 789d4e5..82b14bd 100644 --- a/src/ui/tools.cpp +++ b/src/ui/tools.cpp @@ -11,90 +11,96 @@ using namespace glm; - void tools_update(Manager& manager, Settings& settings, Resources& resources, PopupHelper& colorEditPopup) - { +void tools_update(Manager& manager, Settings& settings, Resources& resources, PopupHelper& colorEditPopup) +{ auto& document = *manager.get(); if (ImGui::Begin(localize.get(LABEL_TOOLS_WINDOW), &settings.windowIsTools)) { - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 2)); - auto availableWidth = ImGui::GetContentRegionAvail().x; - auto size = vec2(ImGui::GetTextLineHeightWithSpacing() * 1.5f); - auto usedWidth = ImGui::GetStyle().WindowPadding.x; + auto availableWidth = ImGui::GetContentRegionAvail().x; + auto size = vec2(ImGui::GetTextLineHeightWithSpacing() * 1.5f); + auto usedWidth = ImGui::GetStyle().WindowPadding.x; - auto tool_use = [&](Tool type) - { - switch (type) + auto tool_use = [&](Tool type) { + switch (type) + { + case TOOL_UNDO: + if (document.is_able_to_undo()) + manager.command_push({manager.selected, [](Manager&, Document& document) { document.undo(); }}); + break; + case TOOL_REDO: + if (document.is_able_to_redo()) + manager.command_push({manager.selected, [](Manager&, Document& document) { document.redo(); }}); + break; + case TOOL_COLOR: + colorEditPopup.open(); + break; + default: + settings.tool = type; + break; + } + }; + + auto iconTint = settings.theme == THEME_LIGHT ? ImVec4(0.0f, 0.0f, 0.0f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + + for (int i = 0; i < TOOL_COUNT; i++) { - case TOOL_UNDO: - if (document.is_able_to_undo()) - manager.command_push({manager.selected, [](Manager&, Document& document) { document.undo(); }}); - break; - case TOOL_REDO: - if (document.is_able_to_redo()) - manager.command_push({manager.selected, [](Manager&, Document& document) { document.redo(); }}); - break; - case TOOL_COLOR: - colorEditPopup.open(); - break; - default: - settings.tool = type; - break; - } - }; + auto& info = TOOLS[i]; + auto isSelected = settings.tool == i; - auto iconTint = settings.theme == THEME_LIGHT ? ImVec4(0.0f, 0.0f, 0.0f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + if (isSelected) + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive)); - for (int i = 0; i < TOOL_COUNT; i++) - { - auto& info = TOOLS[i]; - auto isSelected = settings.tool == i; + if (shortcut(manager.chords[info.shortcut], SCOPE_GLOBAL)) + tool_use((Tool)i); - if (isSelected) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive)); + auto labelText = info.label; + if (i == TOOL_COLOR) + { + size += to_vec2(ImGui::GetStyle().FramePadding) * 2.0f; + if (ImGui::ColorButton(labelText, to_imvec4(settings.toolColor), ImGuiColorEditFlags_NoTooltip, + to_imvec2(size))) + tool_use((Tool)i); + } + else + { + if (i == TOOL_UNDO) + ImGui::BeginDisabled(!document.is_able_to_undo()); + if (i == TOOL_REDO) + ImGui::BeginDisabled(!document.is_able_to_redo()); + if (ImGui::ImageButton(labelText, resources.icon_id_get(info.icon), to_imvec2(size), ImVec2(0, 0), + ImVec2(1, 1), ImVec4(0, 0, 0, 0), iconTint)) + tool_use((Tool)i); + if (i == TOOL_UNDO) + ImGui::EndDisabled(); + if (i == TOOL_REDO) + ImGui::EndDisabled(); + } - if (shortcut(manager.chords[info.shortcut], SCOPE_GLOBAL)) tool_use((Tool)i); + auto widthIncrement = ImGui::GetItemRectSize().x + ImGui::GetStyle().ItemSpacing.x; + usedWidth += widthIncrement; - auto labelText = info.label; - if (i == TOOL_COLOR) - { - size += to_vec2(ImGui::GetStyle().FramePadding) * 2.0f; - if (ImGui::ColorButton(labelText, to_imvec4(settings.toolColor), ImGuiColorEditFlags_NoTooltip, - to_imvec2(size))) - tool_use((Tool)i); - } - else - { - if (i == TOOL_UNDO) ImGui::BeginDisabled(!document.is_able_to_undo()); - if (i == TOOL_REDO) ImGui::BeginDisabled(!document.is_able_to_redo()); - if (ImGui::ImageButton(labelText, resources.icon_id_get(info.icon), to_imvec2(size), ImVec2(0, 0), - ImVec2(1, 1), ImVec4(0, 0, 0, 0), iconTint)) - tool_use((Tool)i); - if (i == TOOL_UNDO) ImGui::EndDisabled(); - if (i == TOOL_REDO) ImGui::EndDisabled(); + if (usedWidth + widthIncrement < availableWidth) + ImGui::SameLine(); + else + usedWidth = ImGui::GetStyle().WindowPadding.x; + set_item_tooltip_shortcut(localize.get(info.tooltip), settings.*SHORTCUT_MEMBERS[info.shortcut]); + + if (isSelected) + ImGui::PopStyleColor(); } - auto widthIncrement = ImGui::GetItemRectSize().x + ImGui::GetStyle().ItemSpacing.x; - usedWidth += widthIncrement; + ImGui::PopStyleVar(); - if (usedWidth + widthIncrement < availableWidth) - ImGui::SameLine(); - else - usedWidth = ImGui::GetStyle().WindowPadding.x; - set_item_tooltip_shortcut(localize.get(info.tooltip), settings.*SHORTCUT_MEMBERS[info.shortcut]); + colorEditPopup.trigger(); - if (isSelected) ImGui::PopStyleColor(); - } - - ImGui::PopStyleVar(); - - colorEditPopup.trigger(); - - if (ImGui::BeginPopup(colorEditPopup.label())) - { - ImGui::ColorPicker4(colorEditPopup.label(), value_ptr(settings.toolColor)); - ImGui::EndPopup(); - } + if (ImGui::BeginPopup(colorEditPopup.label())) + { + ImGui::ColorPicker4(colorEditPopup.label(), value_ptr(settings.toolColor)); + ImGui::EndPopup(); + } } ImGui::End(); - } +} diff --git a/src/ui/tree.cpp b/src/ui/tree.cpp index 8de2ab1..c1639b1 100644 --- a/src/ui/tree.cpp +++ b/src/ui/tree.cpp @@ -1,8 +1,8 @@ #include "ui/tree.h" - TreeNodeInputTextResult tree_node_input_text(const std::string& label, const std::string& id, std::string& text, - bool isSelected, ImGuiTreeNodeFlags flags, RenameState& state) - { +TreeNodeInputTextResult tree_node_input_text(const std::string& label, const std::string& id, std::string& text, + bool isSelected, ImGuiTreeNodeFlags flags, RenameState& state) +{ TreeNodeInputTextResult result = {}; auto& editID = selectable_input_text_id(); auto isRename = editID == id; @@ -10,20 +10,20 @@ if (!isRename) { - result.isOpen = ImGui::TreeNodeEx(id.c_str(), treeFlags, "%s", label.c_str()); - result.isClicked = - ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); - result.isActivated = result.isClicked; + result.isOpen = ImGui::TreeNodeEx(id.c_str(), treeFlags, "%s", label.c_str()); + result.isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + result.isActivated = result.isClicked; - if (state == RENAME_FORCE_EDIT || (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))) - { - state = RENAME_BEGIN; - editID = id; - result.isActivated = true; - result.isRenameStarted = true; - } + if (state == RENAME_FORCE_EDIT || + (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))) + { + state = RENAME_BEGIN; + editID = id; + result.isActivated = true; + result.isRenameStarted = true; + } - return result; + return result; } result.isOpen = ImGui::TreeNodeEx(id.c_str(), treeFlags, "%s", ""); @@ -35,4 +35,4 @@ result.isActivated = input_text_rename_update(text, state, width); result.isRenameFinished = state == RENAME_FINISHED; return result; - } +} diff --git a/src/ui/tree.h b/src/ui/tree.h index bd5893d..812160c 100644 --- a/src/ui/tree.h +++ b/src/ui/tree.h @@ -6,14 +6,14 @@ #include "ui/selectable.h" - struct TreeNodeInputTextResult - { +struct TreeNodeInputTextResult +{ bool isOpen = false; bool isActivated = false; bool isClicked = false; bool isRenameStarted = false; bool isRenameFinished = false; - }; +}; - TreeNodeInputTextResult tree_node_input_text(const std::string&, const std::string&, std::string&, bool, - ImGuiTreeNodeFlags, RenameState&); +TreeNodeInputTextResult tree_node_input_text(const std::string&, const std::string&, std::string&, bool, + ImGuiTreeNodeFlags, RenameState&); diff --git a/src/ui/welcome.cpp b/src/ui/welcome.cpp index d20f5f4..354fde9 100644 --- a/src/ui/welcome.cpp +++ b/src/ui/welcome.cpp @@ -10,11 +10,12 @@ #include "ui/layout.h" #include "ui/selectable.h" - void welcome_update(Manager& manager, Resources& resources, Dialog& dialog, Taskbar& taskbar, Documents& documents) - { +void welcome_update(Manager& manager, Resources& resources, Dialog& dialog, Taskbar& taskbar, Documents& documents) +{ auto viewport = ImGui::GetMainViewport(); auto windowHeight = viewport->Size.y - taskbar.height - documents.height; - if (windowHeight < 1.0f) windowHeight = 1.0f; + if (windowHeight < 1.0f) + windowHeight = 1.0f; ImGui::SetNextWindowViewport(viewport->ID); ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + taskbar.height + documents.height)); @@ -25,43 +26,42 @@ ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { - ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE_LARGE); - ImGui::TextUnformatted(localize.get(LABEL_APPLICATION_NAME)); - ImGui::PopFont(); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE_LARGE); + ImGui::TextUnformatted(localize.get(LABEL_APPLICATION_NAME)); + ImGui::PopFont(); - ImGui::TextUnformatted(localize.get(LABEL_WELCOME_DESCRIPTION)); + ImGui::TextUnformatted(localize.get(LABEL_WELCOME_DESCRIPTION)); - auto widgetSize = widget_size_with_row_get(2); + auto widgetSize = widget_size_with_row_get(2); - if (ImGui::Button(localize.get(BASIC_NEW), widgetSize)) - dialog.file_save(Dialog::ANM2_CREATE); // handled in taskbar.cpp - ImGui::SameLine(); - if (ImGui::Button(localize.get(BASIC_OPEN), widgetSize)) - dialog.file_open(Dialog::ANM2_OPEN, true); // handled in taskbar.cpp + if (ImGui::Button(localize.get(BASIC_NEW), widgetSize)) + dialog.file_save(Dialog::ANM2_CREATE); // handled in taskbar.cpp + ImGui::SameLine(); + if (ImGui::Button(localize.get(BASIC_OPEN), widgetSize)) + dialog.file_open(Dialog::ANM2_OPEN, true); // handled in taskbar.cpp - if (ImGui::BeginChild("##Recent Files Child", {}, ImGuiChildFlags_Borders)) - { - auto recentFiles = manager.recent_files_ordered(); - for (auto [i, file] : std::views::enumerate(recentFiles)) + if (ImGui::BeginChild("##Recent Files Child", {}, ImGuiChildFlags_Borders)) { - ImGui::PushID(i); + auto recentFiles = manager.recent_files_ordered(); + for (auto [i, file] : std::views::enumerate(recentFiles)) + { + ImGui::PushID(i); - auto label = std::format(FILE_LABEL_FORMAT, path_to_utf8(file.filename()), path_to_utf8(file)); + auto label = std::format(FILE_LABEL_FORMAT, path_to_utf8(file.filename()), path_to_utf8(file)); - if (ImGui::Selectable(label.c_str())) - { - manager.command_push({.runManager = [file](Manager& manager) { manager.open(file); }}); - ImGui::PopID(); - break; - } + if (ImGui::Selectable(label.c_str())) + { + manager.command_push({.runManager = [file](Manager& manager) { manager.open(file); }}); + ImGui::PopID(); + break; + } - ImGui::PopID(); + ImGui::PopID(); + } } - } - ImGui::EndChild(); + ImGui::EndChild(); } ImGui::End(); selectable_input_text_id() = {}; - } - +} diff --git a/src/uid.h b/src/uid.h index 7631ef4..817bdc1 100644 --- a/src/uid.h +++ b/src/uid.h @@ -3,9 +3,9 @@ #include #include - // Process-unique, never reused; 0 means "none". - inline std::uint64_t uid_next() - { +// Process-unique, never reused. 0 means "none". +inline std::uint64_t uid_next() +{ static std::atomic next = 1; return next++; - } +} diff --git a/src/vector.h b/src/vector.h index ab3abcf..b1be7f7 100644 --- a/src/vector.h +++ b/src/vector.h @@ -5,42 +5,49 @@ #include #include - template T* vector_find(std::vector& v, int index) - { +template T* vector_find(std::vector& v, int index) +{ return index >= 0 && index < (int)v.size() ? &v[index] : nullptr; - } +} - template int vector_index_find(const std::vector& v, const T& value) - { +template int vector_index_find(const std::vector& v, const T& value) +{ auto it = std::find(v.begin(), v.end(), value); - if (it == v.end()) return -1; + if (it == v.end()) + return -1; return (int)(std::distance(v.begin(), it)); - } +} - template bool is_vector_in_bounds(std::vector& v, int index) { return index >= 0 && index < (int)v.size(); } +template bool is_vector_in_bounds(std::vector& v, int index) +{ + return index >= 0 && index < (int)v.size(); +} - template - std::set vector_indices_move(std::vector& v, const std::vector& indices, int insertPos) - { - if (indices.empty()) return {}; +template +std::set vector_indices_move(std::vector& v, const std::vector& indices, int insertPos) +{ + if (indices.empty()) + return {}; std::vector sorted = indices; std::sort(sorted.begin(), sorted.end()); sorted.erase(std::unique(sorted.begin(), sorted.end()), sorted.end()); std::erase_if(sorted, [&](int i) { return i < 0 || i >= (int)v.size(); }); - if (sorted.empty()) return {}; + if (sorted.empty()) + return {}; std::vector moveItems; moveItems.reserve(sorted.size()); for (int i : sorted) - moveItems.push_back(std::move(v[i])); + moveItems.push_back(std::move(v[i])); for (auto i : sorted | std::views::reverse) - v.erase(v.begin() + i); + v.erase(v.begin() + i); insertPos = std::clamp(insertPos, 0, (int)v.size() + (int)sorted.size()); for (int i : sorted) - if (i < insertPos) --insertPos; + if (i < insertPos) + --insertPos; insertPos = std::clamp(insertPos, 0, (int)v.size()); v.insert(v.begin() + insertPos, std::make_move_iterator(moveItems.begin()), @@ -48,7 +55,7 @@ std::set moveIndices; for (int i = 0; i < (int)moveItems.size(); i++) - moveIndices.insert(insertPos + i); + moveIndices.insert(insertPos + i); return moveIndices; - } +} diff --git a/src/working_directory.cpp b/src/working_directory.cpp index 7a86c8a..ce8a721 100644 --- a/src/working_directory.cpp +++ b/src/working_directory.cpp @@ -5,41 +5,42 @@ #include "log.h" #include "path.h" - WorkingDirectory::WorkingDirectory(const std::filesystem::path& path, Type type) - { +WorkingDirectory::WorkingDirectory(const std::filesystem::path& path, Type type) +{ std::error_code ec; previous = std::filesystem::current_path(ec); if (ec) { - logger.warning(std::format("Could not query current directory: {}", ec.message())); - previous.clear(); - ec.clear(); + logger.warning(std::format("Could not query current directory: {}", ec.message())); + previous.clear(); + ec.clear(); } if (type == FILE) { - std::filesystem::path filePath = path; - std::filesystem::path parentPath = filePath.parent_path(); - std::filesystem::current_path(parentPath, ec); - if (ec) - logger.warning( - std::format("Could not set current directory to {}: {}", path_to_utf8(parentPath), ec.message())); + std::filesystem::path filePath = path; + std::filesystem::path parentPath = filePath.parent_path(); + std::filesystem::current_path(parentPath, ec); + if (ec) + logger.warning( + std::format("Could not set current directory to {}: {}", path_to_utf8(parentPath), ec.message())); } else { - std::filesystem::current_path(path, ec); - if (ec) - logger.warning(std::format("Could not set current directory to {}: {}", path_to_utf8(path), ec.message())); + std::filesystem::current_path(path, ec); + if (ec) + logger.warning(std::format("Could not set current directory to {}: {}", path_to_utf8(path), ec.message())); } - } +} - WorkingDirectory::~WorkingDirectory() - { - if (previous.empty()) return; +WorkingDirectory::~WorkingDirectory() +{ + if (previous.empty()) + return; std::error_code ec; std::filesystem::current_path(previous, ec); if (ec) - logger.warning( - std::format("Could not restore current directory to {}: {}", path_to_utf8(previous), ec.message())); - } + logger.warning( + std::format("Could not restore current directory to {}: {}", path_to_utf8(previous), ec.message())); +} diff --git a/src/working_directory.h b/src/working_directory.h index 13e18cf..8860f09 100644 --- a/src/working_directory.h +++ b/src/working_directory.h @@ -2,17 +2,17 @@ #include - class WorkingDirectory - { - public: +class WorkingDirectory +{ +public: enum Type { - FILE, - DIRECTORY + FILE, + DIRECTORY }; std::filesystem::path previous; WorkingDirectory(const std::filesystem::path&, Type type = DIRECTORY); ~WorkingDirectory(); - }; +}; diff --git a/tests/assets.cpp b/tests/assets.cpp index 0bbba05..5a8b5c4 100644 --- a/tests/assets.cpp +++ b/tests/assets.cpp @@ -10,127 +10,128 @@ TEST_CASE("Image png round trip and uid tracking") { - const std::vector pixels = {255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 255, 0, 10, 20, 30, 40}; - Image image(pixels.data(), {2, 2}); - REQUIRE(image.is_valid()); + const std::vector pixels = {255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 255, 0, 10, 20, 30, 40}; + Image image(pixels.data(), {2, 2}); + REQUIRE(image.is_valid()); - auto path = std::filesystem::temp_directory_path() / "anm2ed_test_image.png"; - REQUIRE(image.write_png(path)); - Image loaded(path); - std::filesystem::remove(path); - CHECK(loaded.size == image.size); - CHECK(loaded.pixels == image.pixels); - CHECK(loaded.uid != image.uid); + auto path = std::filesystem::temp_directory_path() / "anm2ed_test_image.png"; + REQUIRE(image.write_png(path)); + Image loaded(path); + std::filesystem::remove(path); + CHECK(loaded.size == image.size); + CHECK(loaded.pixels == image.pixels); + CHECK(loaded.uid != image.uid); - auto copy = image; - CHECK(copy.uid == image.uid); - copy.pixel_set({1, 1}, {1.0f, 1.0f, 1.0f, 1.0f}); - CHECK(copy.uid != image.uid); - CHECK(copy.pixel_read({1, 1}) == glm::vec4(1.0f)); + auto copy = image; + CHECK(copy.uid == image.uid); + copy.pixel_set({1, 1}, {1.0f, 1.0f, 1.0f, 1.0f}); + CHECK(copy.uid != image.uid); + CHECK(copy.pixel_read({1, 1}) == glm::vec4(1.0f)); - auto merged = Image::compose({{&image, {}, image.size, {}}, {&loaded, {}, loaded.size, {image.size.x, 0}}}, - {image.size.x * 2, image.size.y}, false); - CHECK(merged.size == glm::ivec2(4, 2)); - CHECK(merged.pixel_read({2, 0}) == image.pixel_read({0, 0})); + auto merged = Image::compose({{&image, {}, image.size, {}}, {&loaded, {}, loaded.size, {image.size.x, 0}}}, + {image.size.x * 2, image.size.y}, false); + CHECK(merged.size == glm::ivec2(4, 2)); + CHECK(merged.pixel_read({2, 0}) == image.pixel_read({0, 0})); } TEST_CASE("AudioData holds file bytes") { - const unsigned char bytes[] = {'R', 'I', 'F', 'F'}; - AudioData audio(bytes, sizeof(bytes)); - CHECK(audio.is_valid()); - CHECK(audio.uid != 0); - CHECK_FALSE(AudioData(std::filesystem::path("missing.wav")).is_valid()); + const unsigned char bytes[] = {'R', 'I', 'F', 'F'}; + AudioData audio(bytes, sizeof(bytes)); + CHECK(audio.is_valid()); + CHECK(audio.uid != 0); + CHECK_FALSE(AudioData(std::filesystem::path("missing.wav")).is_valid()); } TEST_CASE("AssetStore keys assets by content") { - AssetStore store = {}; - const std::vector pixels = {1, 2, 3, 4}; - auto key = store.image_add(Image(pixels.data(), {1, 1})); - CHECK(key != 0); - CHECK(store.image_add(Image(pixels.data(), {1, 1})) == key); - CHECK(store.image_add(Image(pixels.data(), {1, 1}, true)) != key); - REQUIRE(store.image_get(key)); - CHECK(store.image_get(key)->pixels == pixels); - CHECK_FALSE(store.image_get(key + 1)); + AssetStore store = {}; + const std::vector pixels = {1, 2, 3, 4}; + auto key = store.image_add(Image(pixels.data(), {1, 1})); + CHECK(key != 0); + CHECK(store.image_add(Image(pixels.data(), {1, 1})) == key); + CHECK(store.image_add(Image(pixels.data(), {1, 1}, true)) != key); + REQUIRE(store.image_get(key)); + CHECK(store.image_get(key)->pixels == pixels); + CHECK_FALSE(store.image_get(key + 1)); - const unsigned char bytes[] = {'O', 'g', 'g', 'S'}; - auto audioKey = store.audio_add(AudioData(bytes, sizeof(bytes))); - CHECK(store.audio_add(AudioData(bytes, sizeof(bytes))) == audioKey); - CHECK(store.audio_get(audioKey)->bytes.size() == sizeof(bytes)); + const unsigned char bytes[] = {'O', 'g', 'g', 'S'}; + auto audioKey = store.audio_add(AudioData(bytes, sizeof(bytes))); + CHECK(store.audio_add(AudioData(bytes, sizeof(bytes))) == audioKey); + CHECK(store.audio_get(audioKey)->bytes.size() == sizeof(bytes)); } TEST_CASE("an SVG spritesheet loads in SVG units and draws again at any scale") { - Image image(TEST_DIR / "render" / "vector.svg"); - REQUIRE(image.is_valid()); - CHECK(image.is_vector()); - CHECK(image.size == glm::ivec2(32, 16)); - auto red = image.pixel_read({8.0f, 8.0f}); - CHECK(red.r > 0.8f); - CHECK(red.b < 0.2f); + Image image(TEST_DIR / "render" / "vector.svg"); + REQUIRE(image.is_valid()); + CHECK(image.is_vector()); + CHECK(image.size == glm::ivec2(32, 16)); + auto red = image.pixel_read({8.0f, 8.0f}); + CHECK(red.r > 0.8f); + CHECK(red.b < 0.2f); - auto large = image.vector_render(4.0f); - CHECK(large.size == glm::ivec2(128, 64)); - CHECK(large.unit_size_get() == image.unit_size_get()); - CHECK(large.uid != image.uid); + auto large = image.vector_render(4.0f); + CHECK(large.size == glm::ivec2(128, 64)); + CHECK(large.unit_size_get() == image.unit_size_get()); + CHECK(large.uid != image.uid); } TEST_CASE("SVG spritesheets compose into SVGs that draw the same") { - Image vector(TEST_DIR / "render" / "vector.svg"); - REQUIRE(vector.is_vector()); + Image vector(TEST_DIR / "render" / "vector.svg"); + REQUIRE(vector.is_vector()); - // The circle (left half) and the square (right half) swapped: each part is a clipped view of the drawing. - auto swapped = - Image::compose({{&vector, {16, 0}, {16, 16}, {0, 0}}, {&vector, {0, 0}, {16, 16}, {16, 0}}}, vector.size, true); - REQUIRE(swapped.is_vector()); - CHECK(swapped.size == vector.size); - CHECK(swapped.pixel_read({24.0f, 8.0f}) == vector.pixel_read({8.0f, 8.0f})); - CHECK(swapped.pixel_read({1.0f, 1.0f}) == glm::vec4()); + // The circle (left half) and the square (right half) swapped: each part is a clipped view of the drawing. + auto swapped = + Image::compose({{&vector, {16, 0}, {16, 16}, {0, 0}}, {&vector, {0, 0}, {16, 16}, {16, 0}}}, vector.size, true); + REQUIRE(swapped.is_vector()); + CHECK(swapped.size == vector.size); + CHECK(swapped.pixel_read({24.0f, 8.0f}) == vector.pixel_read({8.0f, 8.0f})); + CHECK(swapped.pixel_read({1.0f, 1.0f}) == glm::vec4()); - // A PNG part is embedded as an image, pixel for pixel; composing the result again still works. - const std::vector pixels = {255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255}; - Image raster(pixels.data(), {2, 2}); - auto mixed = Image::compose({{&swapped, {}, swapped.size, {}}, {&raster, {}, raster.size, {32, 0}}}, {34, 16}, true); - REQUIRE(mixed.is_vector()); - CHECK(mixed.pixel_read({33.0f, 1.0f}) == raster.pixel_read({1.0f, 1.0f})); - CHECK(Image::compose({{&mixed, {}, mixed.size, {}}}, mixed.size, true).pixel_read({24.0f, 8.0f}) == - vector.pixel_read({8.0f, 8.0f})); + // A PNG part is embedded as an image, pixel for pixel. Composing the result again still works. + const std::vector pixels = {255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255}; + Image raster(pixels.data(), {2, 2}); + auto mixed = + Image::compose({{&swapped, {}, swapped.size, {}}, {&raster, {}, raster.size, {32, 0}}}, {34, 16}, true); + REQUIRE(mixed.is_vector()); + CHECK(mixed.pixel_read({33.0f, 1.0f}) == raster.pixel_read({1.0f, 1.0f})); + CHECK(Image::compose({{&mixed, {}, mixed.size, {}}}, mixed.size, true).pixel_read({24.0f, 8.0f}) == + vector.pixel_read({8.0f, 8.0f})); } TEST_CASE("an SVG's shapes meet without a seam") { - // Two rectangles of one color meeting at x 10.5: the pixel they share is solid, while the outer edge at 20.5 keeps - // its anti-aliasing. - auto text = std::make_shared(R"( + // Two rectangles of one color meeting at x 10.5: the pixel they share is solid, while the outer edge at 20.5 keeps + // its anti-aliasing. + auto text = std::make_shared(R"( )"); - auto path = std::filesystem::temp_directory_path() / "anm2ed_seam.svg"; - file_save(path, *text); - Image image(path); - std::filesystem::remove(path); - REQUIRE(image.is_vector()); - auto seam = image.pixel_read({10.0f, 2.0f}); - CHECK(seam.a == 1.0f); - CHECK(glm::distance(glm::vec3(seam), glm::vec3(image.pixel_read({5.0f, 2.0f}))) < 2.0f / 255.0f); - CHECK(image.pixel_read({20.0f, 2.0f}).a < 1.0f); + auto path = std::filesystem::temp_directory_path() / "anm2ed_seam.svg"; + file_save(path, *text); + Image image(path); + std::filesystem::remove(path); + REQUIRE(image.is_vector()); + auto seam = image.pixel_read({10.0f, 2.0f}); + CHECK(seam.a == 1.0f); + CHECK(glm::distance(glm::vec3(seam), glm::vec3(image.pixel_read({5.0f, 2.0f}))) < 2.0f / 255.0f); + CHECK(image.pixel_read({20.0f, 2.0f}).a < 1.0f); } TEST_CASE("Embedded resources load") { - for (auto& info : FRIENDS) - { - INFO("friend: ", info.name); - Model model = {}; - std::string errorString; - CHECK(model_load_string(model, std::string_view((const char*)info.anm2->data, info.anm2->size), &errorString)); - CHECK(model.animations_count_get() > 0); - CHECK(Image(info.png->data, info.png->size).is_valid()); - } - for (auto& icon : ICONS) - CHECK(std::string_view((const char*)icon.svg->data, icon.svg->size).starts_with("size > 0); + for (auto& info : FRIENDS) + { + INFO("friend: ", info.name); + Model model = {}; + std::string errorString; + CHECK(model_load_string(model, std::string_view((const char*)info.anm2->data, info.anm2->size), &errorString)); + CHECK(model.animations_count_get() > 0); + CHECK(Image(info.png->data, info.png->size).is_valid()); + } + for (auto& icon : ICONS) + CHECK(std::string_view((const char*)icon.svg->data, icon.svg->size).starts_with("size > 0); } diff --git a/tests/common.h b/tests/common.h index 63b6ac8..9e5eadb 100644 --- a/tests/common.h +++ b/tests/common.h @@ -12,84 +12,88 @@ #include "model/json.h" #include "model/xml.h" - inline const std::filesystem::path TEST_DIR = ANM2ED_TEST_DIR; - inline const std::filesystem::path CORPUS_DIR = TEST_DIR / "corpus"; - inline const std::filesystem::path GOLDEN_DIR = TEST_DIR / "golden"; +inline const std::filesystem::path TEST_DIR = ANM2ED_TEST_DIR; +inline const std::filesystem::path CORPUS_DIR = TEST_DIR / "corpus"; +inline const std::filesystem::path GOLDEN_DIR = TEST_DIR / "golden"; - inline constexpr std::pair PRESETS[] = {{"default", SERIALIZE_DEFAULT}, - {"editor", SERIALIZE_EDITOR_DEFAULT}, - {"isaac", SERIALIZE_ISAAC_DEFAULT}, - {"anm2ed", SERIALIZE_ANM2ED_DEFAULT}}; - inline constexpr std::pair MERGES[] = {{"merge_prepend", MERGE_PREPEND}, - {"merge_append", MERGE_APPEND}, - {"merge_replace", MERGE_REPLACE}, - {"merge_ignore", MERGE_IGNORE}}; +inline constexpr std::pair PRESETS[] = {{"default", SERIALIZE_DEFAULT}, + {"editor", SERIALIZE_EDITOR_DEFAULT}, + {"isaac", SERIALIZE_ISAAC_DEFAULT}, + {"anm2ed", SERIALIZE_ANM2ED_DEFAULT}}; +inline constexpr std::pair MERGES[] = {{"merge_prepend", MERGE_PREPEND}, + {"merge_append", MERGE_APPEND}, + {"merge_replace", MERGE_REPLACE}, + {"merge_ignore", MERGE_IGNORE}}; - using Variant = std::pair; +using Variant = std::pair; - inline std::string file_load(const std::filesystem::path& path) - { +inline std::string file_load(const std::filesystem::path& path) +{ std::ifstream file(path, std::ios::binary); return {std::istreambuf_iterator(file), {}}; - } +} - inline void file_save(const std::filesystem::path& path, const std::string& text) - { +inline void file_save(const std::filesystem::path& path, const std::string& text) +{ std::filesystem::create_directories(path.parent_path()); std::ofstream(path, std::ios::binary) << text; - } +} - inline bool is_env_set(const char* name) { return std::getenv(name) != nullptr; } +inline bool is_env_set(const char* name) +{ + return std::getenv(name) != nullptr; +} - inline std::vector fixtures_get() - { +inline std::vector fixtures_get() +{ std::vector fixtures; for (auto& entry : std::filesystem::directory_iterator(CORPUS_DIR)) - if (entry.path().extension() == ".anm2") fixtures.push_back(entry.path()); + if (entry.path().extension() == ".anm2") + fixtures.push_back(entry.path()); std::ranges::sort(fixtures); return fixtures; - } +} - inline Model model_load(const std::string& text) - { +inline Model model_load(const std::string& text) +{ Model model = {}; REQUIRE(model_load_string(model, text)); return model; - } +} - // Every serialization and merge the editor can produce for a document; goldens lock each one down. - inline std::vector variants_get(const Model& model) - { +// Every serialization and merge the editor can produce for a document. Goldens lock each one down. +inline std::vector variants_get(const Model& model) +{ std::vector variants; for (auto [name, flags] : PRESETS) - variants.emplace_back(name, model_serialize(model, flags)); + variants.emplace_back(name, model_serialize(model, flags)); variants.emplace_back("save", model_to_string(model)); for (auto [name, type] : MERGES) { - auto merged = model; - std::set sources = {0, 1, 2}; - animations_merge(merged, 0, sources, type, type == MERGE_PREPEND || type == MERGE_REPLACE, - {}); - variants.emplace_back(name, model_serialize(merged, SERIALIZE_ANM2ED_DEFAULT)); + auto merged = model; + std::set sources = {0, 1, 2}; + animations_merge(merged, 0, sources, type, type == MERGE_PREPEND || type == MERGE_REPLACE, {}); + variants.emplace_back(name, model_serialize(merged, SERIALIZE_ANM2ED_DEFAULT)); } return variants; - } +} - // The outer document of a save with its SourceDocument (the root's last child, on lines of its own) removed: what - // the game reads. - inline std::string game_document_get(std::string text) - { +// The outer document of a save with its SourceDocument (the root's last child, on lines of its own) removed: what +// the game reads. +inline std::string game_document_get(std::string text) +{ constexpr std::string_view END = ""; auto start = text.find("\n {}(line)); - Model anm2 = {}; - std::string error; - if (!model_load(anm2, line, &error)) + auto baseline = is_env_set("ANM2ED_CORPUS_BASELINE") + ? std::filesystem::path(std::getenv("ANM2ED_CORPUS_BASELINE")) + : std::filesystem::path(std::getenv("HOME")) / ".cache/anm2ed/corpus"; + std::istringstream list(file_load(std::getenv("ANM2ED_CORPUS"))); + std::string line; + while (std::getline(list, line)) { - golden_check(baseline / (key + ".error.txt"), error, true); - continue; + if (line.empty()) + continue; + INFO("file: ", line); + auto key = std::format("{:016x}", std::hash{}(line)); + Model anm2 = {}; + std::string error; + if (!model_load(anm2, line, &error)) + { + golden_check(baseline / (key + ".error.txt"), error, true); + continue; + } + for (auto& [name, text] : variants_get(anm2)) + golden_check(baseline / std::format("{}.{}.xml", key, name), text, true); + invariants_check(anm2); } - for (auto& [name, text] : variants_get(anm2)) - golden_check(baseline / std::format("{}.{}.xml", key, name), text, true); - invariants_check(anm2); - } } diff --git a/tests/draw.cpp b/tests/draw.cpp index 6a1ac1d..7b092d8 100644 --- a/tests/draw.cpp +++ b/tests/draw.cpp @@ -6,210 +6,212 @@ TEST_CASE("draw lists put the root first and each item's onion samples before it") { - auto anm2 = model_load(file_load(CORPUS_DIR / "02_items.anm2")); - auto& animation = *anm2.animation_get(0); - auto draws = animation_draws_get(anm2, animation, {.time = 1.0f, .samples = {{-1.0f}, {1.0f}}}); - REQUIRE(!draws.empty()); - CHECK(draws.front().type == DrawType::ROOT); + auto anm2 = model_load(file_load(CORPUS_DIR / "02_items.anm2")); + auto& animation = *anm2.animation_get(0); + auto draws = animation_draws_get(anm2, animation, {.time = 1.0f, .samples = {{-1.0f}, {1.0f}}}); + REQUIRE(!draws.empty()); + CHECK(draws.front().type == DrawType::ROOT); - for (int i = 0; i + 1 < (int)draws.size(); ++i) - if (draws[i].sample != -1) CHECK((draws[i + 1].id == draws[i].id && draws[i + 1].type == draws[i].type)); + for (int i = 0; i + 1 < (int)draws.size(); ++i) + if (draws[i].sample != -1) + CHECK((draws[i + 1].id == draws[i].id && draws[i + 1].type == draws[i].type)); - auto layerDraws = std::ranges::count_if(draws, [](const Draw& draw) - { return draw.type == DrawType::LAYER && draw.sample == -1; }); - CHECK(layerDraws > 0); - CHECK(animation_rect(anm2, animation, true) != glm::vec4(-1.0f)); + auto layerDraws = std::ranges::count_if( + draws, [](const Draw& draw) { return draw.type == DrawType::LAYER && draw.sample == -1; }); + CHECK(layerDraws > 0); + CHECK(animation_rect(anm2, animation, true) != glm::vec4(-1.0f)); } TEST_CASE("root transforms fold into layer draws") { - auto anm2 = model_load(file_load(CORPUS_DIR / "04_group_root_transform.anm2")); - auto& animation = *anm2.animation_get(0); - auto plain = animation_draws_get(anm2, animation, {}); - auto rooted = animation_draws_get(anm2, animation, {.isRootTransform = true}); - REQUIRE(plain.size() == rooted.size()); - bool isAnyMoved = false; - for (int i = 0; i < (int)plain.size(); ++i) - isAnyMoved |= plain[i].type == DrawType::LAYER && plain[i].parent != rooted[i].parent; - CHECK(isAnyMoved); + auto anm2 = model_load(file_load(CORPUS_DIR / "04_group_root_transform.anm2")); + auto& animation = *anm2.animation_get(0); + auto plain = animation_draws_get(anm2, animation, {}); + auto rooted = animation_draws_get(anm2, animation, {.isRootTransform = true}); + REQUIRE(plain.size() == rooted.size()); + bool isAnyMoved = false; + for (int i = 0; i < (int)plain.size(); ++i) + isAnyMoved |= plain[i].type == DrawType::LAYER && plain[i].parent != rooted[i].parent; + CHECK(isAnyMoved); } TEST_CASE("a layer frame's depth moves it among the layers for that frame only") { - auto anm2 = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); - auto layer_ids_get = [&](float time) - { - std::vector ids; - for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {.time = time})) - if (draw.type == DrawType::LAYER) ids.push_back(draw.id); - return ids; - }; - CHECK(layer_ids_get(0.0f) == std::vector{1, 0}); + auto anm2 = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); + auto layer_ids_get = [&](float time) { + std::vector ids; + for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {.time = time})) + if (draw.type == DrawType::LAYER) + ids.push_back(draw.id); + return ids; + }; + CHECK(layer_ids_get(0.0f) == std::vector{1, 0}); - anm2.frame_edit({0, LAYER, 0, 0})->depth = -1; - CHECK(layer_ids_get(0.0f) == std::vector{0, 1}); - CHECK(layer_ids_get(5.0f) == std::vector{1, 0}); + anm2.frame_edit({0, LAYER, 0, 0})->depth = -1; + CHECK(layer_ids_get(0.0f) == std::vector{0, 1}); + CHECK(layer_ids_get(5.0f) == std::vector{1, 0}); - auto text = model_to_string(anm2); - CHECK(game_document_get(text).find("Depth") == std::string::npos); - CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->depth == -1); - CHECK(isaac_issues_get(anm2).depthFrames == 1); + auto text = model_to_string(anm2); + CHECK(game_document_get(text).find("Depth") == std::string::npos); + CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->depth == -1); + CHECK(isaac_issues_get(anm2).depthFrames == 1); } TEST_CASE("a layer frame's blur reaches its child's draws and stays out of the game's copy") { - auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); - anm2.frame_edit({0, LAYER, 1, 0})->blur = 6.0f; - bool isAnyChild = false; - for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {})) - if (draw.type == DrawType::LAYER && draw.id == 1) - { - isAnyChild = true; - CHECK(draw.frame.blur >= 6.0f); - } - CHECK(isAnyChild); + auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + anm2.frame_edit({0, LAYER, 1, 0})->blur = 6.0f; + bool isAnyChild = false; + for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {})) + if (draw.type == DrawType::LAYER && draw.id == 1) + { + isAnyChild = true; + CHECK(draw.frame.blur >= 6.0f); + } + CHECK(isAnyChild); - auto text = model_to_string(anm2); - CHECK(game_document_get(text).find("Blur") == std::string::npos); - CHECK(model_load(text).frame_get({0, LAYER, 1, 0})->blur == 6.0f); - CHECK(isaac_issues_get(anm2).blurFrames == 1); + auto text = model_to_string(anm2); + CHECK(game_document_get(text).find("Blur") == std::string::npos); + CHECK(model_load(text).frame_get({0, LAYER, 1, 0})->blur == 6.0f); + CHECK(isaac_issues_get(anm2).blurFrames == 1); } TEST_CASE("an animation layer draws its child animation, from this file or a library") { - auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); - auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); - DrawOptions options = {.library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }}; - auto red_position_get = [&](int layerId) - { - std::optional position{}; - for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), options)) - if (draw.type == DrawType::LAYER && draw.id == layerId && draw.frame.crop == glm::vec2()) - position = glm::vec2(draw.parent * glm::vec4(draw.frame.position, 0.0f, 1.0f)); - return position; - }; + auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); + DrawOptions options = {.library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }}; + auto red_position_get = [&](int layerId) { + std::optional position{}; + for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), options)) + if (draw.type == DrawType::LAYER && draw.id == layerId && draw.frame.crop == glm::vec2()) + position = glm::vec2(draw.parent * glm::vec4(draw.frame.position, 0.0f, 1.0f)); + return position; + }; - // The library's red square, half size at (40, 0), starts on its fifth frame (at x 16). - CHECK(red_position_get(0) == glm::vec2(48.0f, 0.0f)); - // This file's Inner holds its first frame however far the parent plays. - options.time = 1.0f; - CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f)); - // An animation never draws inside itself. - CHECK_FALSE(red_position_get(3)); + // The library's red square, half size at (40, 0), starts on its fifth frame (at x 16). + CHECK(red_position_get(0) == glm::vec2(48.0f, 0.0f)); + // This file's Inner holds its first frame however far the parent plays. + options.time = 1.0f; + CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f)); + // An animation never draws inside itself. + CHECK_FALSE(red_position_get(3)); - // Once stops on the child's last frame; Loop wraps around it. - options.time = 6.0f; - anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::ONCE; - CHECK(red_position_get(1) == glm::vec2(-40.0f, 10.0f)); - anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::LOOP; - CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f)); + // Once stops on the child's last frame. Loop wraps around it. + options.time = 6.0f; + anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::ONCE; + CHECK(red_position_get(1) == glm::vec2(-40.0f, 10.0f)); + anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::LOOP; + CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f)); - // Without the library loaded, its layer draws nothing. - options.library_get = {}; - CHECK_FALSE(red_position_get(0)); + // Without the library loaded, its layer draws nothing. + options.library_get = {}; + CHECK_FALSE(red_position_get(0)); - auto text = model_serialize(anm2, SERIALIZE_ANM2ED_DEFAULT); - CHECK(model_hash(model_load(text)) == model_hash(anm2)); - CHECK(isaac_issues_get(anm2).animationLayers == 3); - CHECK(game_document_get(model_to_string(anm2)).find(" Animation=\"") == std::string::npos); + auto text = model_serialize(anm2, SERIALIZE_ANM2ED_DEFAULT); + CHECK(model_hash(model_load(text)) == model_hash(anm2)); + CHECK(isaac_issues_get(anm2).animationLayers == 3); + CHECK(game_document_get(model_to_string(anm2)).find(" Animation=\"") == std::string::npos); } TEST_CASE("an alpha offset is kept by the editor's copy only") { - auto anm2 = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); - anm2.frame_edit({0, LAYER, 0, 0})->colorOffset.a = -0.5f; - auto text = model_to_string(anm2); - CHECK(game_document_get(text).find("AlphaOffset") == std::string::npos); - CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->colorOffset.a == doctest::Approx(-127.0f / 255.0f)); - CHECK(isaac_issues_get(anm2).alphaOffsetFrames == 1); + auto anm2 = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); + anm2.frame_edit({0, LAYER, 0, 0})->colorOffset.a = -0.5f; + auto text = model_to_string(anm2); + CHECK(game_document_get(text).find("AlphaOffset") == std::string::npos); + CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->colorOffset.a == doctest::Approx(-127.0f / 255.0f)); + CHECK(isaac_issues_get(anm2).alphaOffsetFrames == 1); } TEST_CASE("only SVG spritesheets that layers show count against Rebirth") { - auto anm2 = model_load(file_load(TEST_DIR / "render" / "vector.anm2")); - CHECK(spritesheets_vector_used_get(anm2) == std::set{0}); - anm2.content.layers.clear(); - CHECK(spritesheets_vector_used_get(anm2).empty()); + auto anm2 = model_load(file_load(TEST_DIR / "render" / "vector.anm2")); + CHECK(spritesheets_vector_used_get(anm2) == std::set{0}); + anm2.content.layers.clear(); + CHECK(spritesheets_vector_used_get(anm2).empty()); } TEST_CASE("child animations fire their triggers as they reach them") { - auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); - auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); - spin.content.events.push_back({.id = 0, .name = "spun"}); - spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}}); - anm2.content.events.push_back({.id = 0, .name = "inner"}); - anm2.animation_edit(1)->triggers.frames.push_back({.atFrame = 0, .eventIds = {0}}); - auto library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }; - auto sources_get = [&](int time) - { - std::vector sources; - for (auto& fire : animation_triggers_get(anm2, *anm2.animation_get(0), time, library_get)) - sources.push_back(fire.source); - return sources; - }; + auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); + spin.content.events.push_back({.id = 0, .name = "spun"}); + spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}}); + anm2.content.events.push_back({.id = 0, .name = "inner"}); + anm2.animation_edit(1)->triggers.frames.push_back({.atFrame = 0, .eventIds = {0}}); + auto library_get = [&](const Model&, int id) { + return id == 0 ? &spin : nullptr; + }; + auto sources_get = [&](int time) { + std::vector sources; + for (auto& fire : animation_triggers_get(anm2, *anm2.animation_get(0), time, library_get)) + sources.push_back(fire.source); + return sources; + }; - // Inner (held on its first frame) fires once, when the parent starts; the library's Spin, started on its fifth - // frame, reaches its sixth (and its trigger) one frame later. - CHECK(sources_get(0) == std::vector{&anm2}); - CHECK(sources_get(1) == std::vector{&spin}); - CHECK(sources_get(2).empty()); + // Inner (held on its first frame) fires once, when the parent starts. The library's Spin, started on its fifth + // frame, reaches its sixth (and its trigger) one frame later. + CHECK(sources_get(0) == std::vector{&anm2}); + CHECK(sources_get(1) == std::vector{&spin}); + CHECK(sources_get(2).empty()); } TEST_CASE("flattening animation layers bakes their children into plain layers that draw the same") { - auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); - auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); - auto library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }; - auto flat = - animation_layers_flatten(anm2, library_get, [](const Model&, const std::filesystem::path& path) - { return std::filesystem::path("library") / path; }); - CHECK(std::ranges::none_of(flat.content.layers, &Layer::is_animation)); - CHECK(flat.content.spritesheets.back().path == std::filesystem::path("library") / "sheet.png"); + auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); + auto library_get = [&](const Model&, int id) { + return id == 0 ? &spin : nullptr; + }; + auto flat = animation_layers_flatten(anm2, library_get, [](const Model&, const std::filesystem::path& path) { + return std::filesystem::path("library") / path; + }); + CHECK(std::ranges::none_of(flat.content.layers, &Layer::is_animation)); + CHECK(flat.content.spritesheets.back().path == std::filesystem::path("library") / "sheet.png"); - // Every frame, the plain layers draw where the animation layers' children did. - auto points_get = [&](const Model& model, const LibraryGet& get, float time) - { - std::vector points{}; - for (auto& draw : - animation_draws_get(model, *model.animation_get(0), {.time = time, .library_get = get})) - if (draw.type == DrawType::LAYER) - points.push_back(glm::round(glm::vec2(draw.parent * draw_quad_model_get(draw) * glm::vec4(1, 1, 0, 1)))); - std::ranges::sort(points, [](glm::vec2 a, glm::vec2 b) { return std::tie(a.x, a.y) < std::tie(b.x, b.y); }); - return points; - }; - for (float time = 0.0f; time < 8.0f; time += 1.0f) - CHECK(points_get(flat, {}, time) == points_get(anm2, library_get, time)); + // Every frame, the plain layers draw where the animation layers' children did. + auto points_get = [&](const Model& model, const LibraryGet& get, float time) { + std::vector points{}; + for (auto& draw : animation_draws_get(model, *model.animation_get(0), {.time = time, .library_get = get})) + if (draw.type == DrawType::LAYER) + points.push_back( + glm::round(glm::vec2(draw.parent * draw_quad_model_get(draw) * glm::vec4(1, 1, 0, 1)))); + std::ranges::sort(points, [](glm::vec2 a, glm::vec2 b) { return std::tie(a.x, a.y) < std::tie(b.x, b.y); }); + return points; + }; + for (float time = 0.0f; time < 8.0f; time += 1.0f) + CHECK(points_get(flat, {}, time) == points_get(anm2, library_get, time)); - auto text = model_to_string(anm2, {.gameModel = &flat}); - auto game = game_document_get(text); - CHECK(game.find(" Animation=\"") == std::string::npos); - CHECK(game.find("spin/red") != std::string::npos); - CHECK(std::ranges::count_if(model_load(text).content.layers, &Layer::is_animation) == 3); + auto text = model_to_string(anm2, {.gameModel = &flat}); + auto game = game_document_get(text); + CHECK(game.find(" Animation=\"") == std::string::npos); + CHECK(game.find("spin/red") != std::string::npos); + CHECK(std::ranges::count_if(model_load(text).content.layers, &Layer::is_animation) == 3); - // Children's triggers join the flattened animation's, their events found (or added) by name. - spin.content.events.push_back({.id = 0, .name = "spun"}); - spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}}); - flat = animation_layers_flatten(anm2, library_get, - [](const Model&, const std::filesystem::path& path) { return path; }); - auto& triggers = flat.animation_get(0)->triggers.frames; - REQUIRE(triggers.size() == 1); - CHECK(triggers.front().atFrame == 1); - CHECK(item_get(flat.content.events, triggers.front().eventIds.front())->name == "spun"); + // Children's triggers join the flattened animation's, their events found (or added) by name. + spin.content.events.push_back({.id = 0, .name = "spun"}); + spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}}); + flat = animation_layers_flatten(anm2, library_get, + [](const Model&, const std::filesystem::path& path) { return path; }); + auto& triggers = flat.animation_get(0)->triggers.frames; + REQUIRE(triggers.size() == 1); + CHECK(triggers.front().atFrame == 1); + CHECK(item_get(flat.content.events, triggers.front().eventIds.front())->name == "spun"); } TEST_CASE("an animation layer's child sits where the layer's frame puts it") { - auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); - auto placement = layer_child_transform_get(*anm2.animation_get(0), 0, 0.0f, true); - REQUIRE(placement); - CHECK(glm::vec2(*placement * glm::vec4(16.0f, 0.0f, 0.0f, 1.0f)) == glm::vec2(48.0f, 0.0f)); - CHECK_FALSE(layer_child_transform_get(*anm2.animation_get(0), 99, 0.0f, true)); + auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + auto placement = layer_child_transform_get(*anm2.animation_get(0), 0, 0.0f, true); + REQUIRE(placement); + CHECK(glm::vec2(*placement * glm::vec4(16.0f, 0.0f, 0.0f, 1.0f)) == glm::vec2(48.0f, 0.0f)); + CHECK_FALSE(layer_child_transform_get(*anm2.animation_get(0), 99, 0.0f, true)); } TEST_CASE("the game's copy stands in for depth and alpha offsets") { - auto anm2 = model_load(R"({ "sheets": [ { "path": "a.png" } ], + auto anm2 = model_load(R"({ "sheets": [ { "path": "a.png" } ], "layers": [ { "name": "a" }, { "name": "b" }, { "name": "c" } ], "animations": { "A": { "length": 6, "layers": [ { "layer": 0, "frames": [ { "crop": [0, 0], "size": [1, 1], "delay": 2 }, @@ -217,30 +219,28 @@ TEST_CASE("the game's copy stands in for depth and alpha offsets") { "crop": [1, 0], "size": [1, 1], "pos": [8, 0], "delay": 2, "depth": -1 } ] }, { "layer": 1, "frames": [ { "crop": [2, 0], "size": [1, 1], "delay": 6, "depth": -1 } ] }, { "layer": 2, "frames": [ { "crop": [3, 0], "size": [1, 1], "delay": 6, "offset": [0, 0, 0, -64] } ] } ] } } })"); - auto game = isaac_bridge(anm2); + auto game = isaac_bridge(anm2); - // Every frame, the same crops draw in the same order and places, with no depth left. - auto draws_get = [](const Model& model, float time) - { - std::vector> draws{}; - for (auto& draw : animation_draws_get(model, *model.animation_get(0), {.time = time})) - if (draw.type == DrawType::LAYER && draw.frame.isVisible) - draws.emplace_back(draw.frame.crop, draw.frame.position); - return draws; - }; - for (float time = 0.0f; time < 6.0f; time += 0.5f) - CHECK(draws_get(game, time) == draws_get(anm2, time)); - CHECK(isaac_issues_get(game).depthFrames == 0); - CHECK( - std::ranges::any_of(game.content.layers, [](const Layer& layer) { return layer.name == "a (depth +2)"; })); + // Every frame, the same crops draw in the same order and places, with no depth left. + auto draws_get = [](const Model& model, float time) { + std::vector> draws{}; + for (auto& draw : animation_draws_get(model, *model.animation_get(0), {.time = time})) + if (draw.type == DrawType::LAYER && draw.frame.isVisible) + draws.emplace_back(draw.frame.crop, draw.frame.position); + return draws; + }; + for (float time = 0.0f; time < 6.0f; time += 0.5f) + CHECK(draws_get(game, time) == draws_get(anm2, time)); + CHECK(isaac_issues_get(game).depthFrames == 0); + CHECK(std::ranges::any_of(game.content.layers, [](const Layer& layer) { return layer.name == "a (depth +2)"; })); - // The alpha offset joins the alpha tint. - auto& offsetFrame = *game.frame_get({0, LAYER, 2, 0}); - CHECK(offsetFrame.colorOffset.a == 0.0f); - CHECK(float_to_uint8(offsetFrame.tint.a) == 255 - 64); + // The alpha offset joins the alpha tint. + auto& offsetFrame = *game.frame_get({0, LAYER, 2, 0}); + CHECK(offsetFrame.colorOffset.a == 0.0f); + CHECK(float_to_uint8(offsetFrame.tint.a) == 255 - 64); - // A document saved with Ignore and Save remembers it, in either format. - anm2.info.isIsaacIgnored = true; - CHECK(model_load(model_to_string(anm2)).info.isIsaacIgnored); - CHECK(model_load(model_to_json(anm2)).info.isIsaacIgnored); + // A document saved with Ignore and Save remembers it, in either format. + anm2.info.isIsaacIgnored = true; + CHECK(model_load(model_to_string(anm2)).info.isIsaacIgnored); + CHECK(model_load(model_to_json(anm2)).info.isIsaacIgnored); } diff --git a/tests/invariants.cpp b/tests/invariants.cpp index 7d2a04e..59ad5a4 100644 --- a/tests/invariants.cpp +++ b/tests/invariants.cpp @@ -2,137 +2,137 @@ TEST_CASE("per-fixture invariants") { - for (auto& fixture : fixtures_get()) - { - INFO("fixture: ", fixture.filename().string()); - invariants_check(model_load(file_load(fixture))); - } + for (auto& fixture : fixtures_get()) + { + INFO("fixture: ", fixture.filename().string()); + invariants_check(model_load(file_load(fixture))); + } } TEST_CASE("saved text escapes what it holds, and reads back the same") { - auto model = model_load(file_load(CORPUS_DIR / "11_unknown.anm2")); - model.extras.children.emplace_back( - 0, XmlNode{.tag = "Note", - .attributes = {{"Quote", "it's \"x\" & "}}, - .text = "a & b > c 'd' \"e\"", - .children = {{.tag = "Inner", .children = {{.tag = "Leaf", .attributes = {{"A", "1"}}}}}}}); - auto text = model_to_string(model); - CHECK(text.find("Quote=\"it's "x" & <y>\"") != std::string::npos); - CHECK(text.find(">a & b > c 'd' \"e\"<") != std::string::npos); - auto reloaded = model_load(text).extras.children; - auto note = std::ranges::find(reloaded, std::string("Note"), [](const auto& child) { return child.second.tag; }); - REQUIRE(note != reloaded.end()); - CHECK(note->second == model.extras.children.back().second); + auto model = model_load(file_load(CORPUS_DIR / "11_unknown.anm2")); + model.extras.children.emplace_back( + 0, XmlNode{.tag = "Note", + .attributes = {{"Quote", "it's \"x\" & "}}, + .text = "a & b > c 'd' \"e\"", + .children = {{.tag = "Inner", .children = {{.tag = "Leaf", .attributes = {{"A", "1"}}}}}}}); + auto text = model_to_string(model); + CHECK(text.find("Quote=\"it's "x" & <y>\"") != std::string::npos); + CHECK(text.find(">a & b > c 'd' \"e\"<") != std::string::npos); + auto reloaded = model_load(text).extras.children; + auto note = std::ranges::find(reloaded, std::string("Note"), [](const auto& child) { return child.second.tag; }); + REQUIRE(note != reloaded.end()); + CHECK(note->second == model.extras.children.back().second); } TEST_CASE("saves leave out default colors, which read back the same") { - for (auto& fixture : fixtures_get()) - { - INFO("fixture: ", fixture.string()); - auto model = model_load(file_load(fixture)); - auto text = model_to_string(model); - CHECK(text.find("Tint=\"255\"") == std::string::npos); - CHECK(text.find("Offset=\"0\"") == std::string::npos); - CHECK(model_hash(model_load(text)) == model_hash(model)); - } + for (auto& fixture : fixtures_get()) + { + INFO("fixture: ", fixture.string()); + auto model = model_load(file_load(fixture)); + auto text = model_to_string(model); + CHECK(text.find("Tint=\"255\"") == std::string::npos); + CHECK(text.find("Offset=\"0\"") == std::string::npos); + CHECK(model_hash(model_load(text)) == model_hash(model)); + } } TEST_CASE("JSON documents read back as the editor's copy") { - for (auto& fixture : fixtures_get()) - { - INFO("fixture: ", fixture.string()); - auto model = model_load(file_load(fixture)); - auto text = model_to_json(model); - auto reloaded = model_load(text); - CHECK(model_to_json(reloaded) == text); - // Unknown XML, element order, dangling references and repeated animation names are not kept. - auto isQuirky = fixture.filename() == "09_legacy_quirks.anm2" || fixture.filename() == "11_unknown.anm2"; - if (!isQuirky) - CHECK(model_serialize(reloaded, SERIALIZE_ANM2ED_DEFAULT) == - model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); - } + for (auto& fixture : fixtures_get()) + { + INFO("fixture: ", fixture.string()); + auto model = model_load(file_load(fixture)); + auto text = model_to_json(model); + auto reloaded = model_load(text); + CHECK(model_to_json(reloaded) == text); + // Unknown XML, element order, dangling references and repeated animation names are not kept. + auto isQuirky = fixture.filename() == "09_legacy_quirks.anm2" || fixture.filename() == "11_unknown.anm2"; + if (!isQuirky) + CHECK(model_serialize(reloaded, SERIALIZE_ANM2ED_DEFAULT) == + model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); + } } TEST_CASE("JSON animations get unique names") { - auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); - model.animations.entries.push_back(model.animations.entries.front()); - auto reloaded = model_load(model_to_json(model)); - REQUIRE(reloaded.animations_count_get() == 2); - CHECK(reloaded.animation_get(1)->name == reloaded.animation_get(0)->name + " 2"); + auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); + model.animations.entries.push_back(model.animations.entries.front()); + auto reloaded = model_load(model_to_json(model)); + REQUIRE(reloaded.animations_count_get() == 2); + CHECK(reloaded.animation_get(1)->name == reloaded.animation_get(0)->name + " 2"); } TEST_CASE("JSON groups don't renumber an animation sharing their name") { - auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); - auto animation = std::get>(model.animations.entries.front()); - model.animations.entries = {AnimationGroup{.name = animation->name, .animations = {animation}}}; - auto reloaded = model_load(model_to_json(model)); - REQUIRE(reloaded.animations_count_get() == 1); - CHECK(reloaded.animation_get(0)->name == animation->name); + auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); + auto animation = std::get>(model.animations.entries.front()); + model.animations.entries = {AnimationGroup{.name = animation->name, .animations = {animation}}}; + auto reloaded = model_load(model_to_json(model)); + REQUIRE(reloaded.animations_count_get() == 1); + CHECK(reloaded.animation_get(0)->name == animation->name); } TEST_CASE("JSON markers are a pair, and a frame's child an object only when it has one") { - auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); - auto text = model_to_json(model); - CHECK(text.find("\"child\"") == std::string::npos); - model.animation_edit(0)->startMarker = 2; - model.animation_edit(0)->endMarker = 5; - auto frame = model.frame_edit({0, (int)ItemType::LAYER, 0, 0}); - REQUIRE(frame); - frame->childMode = ChildMode::HOLD; - frame->childStart = 3; - text = model_to_json(model); - CHECK(text.find("\"markers\": [2, 5]") != std::string::npos); - CHECK(text.find("\"child\": {\"mode\": \"hold\", \"start\": 3}") != std::string::npos); - auto reloaded = model_load(text); - CHECK(reloaded.animation_get(0)->endMarker == 5); - CHECK(model_to_json(reloaded) == text); + auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); + auto text = model_to_json(model); + CHECK(text.find("\"child\"") == std::string::npos); + model.animation_edit(0)->startMarker = 2; + model.animation_edit(0)->endMarker = 5; + auto frame = model.frame_edit({0, (int)ItemType::LAYER, 0, 0}); + REQUIRE(frame); + frame->childMode = ChildMode::HOLD; + frame->childStart = 3; + text = model_to_json(model); + CHECK(text.find("\"markers\": [2, 5]") != std::string::npos); + CHECK(text.find("\"child\": {\"mode\": \"hold\", \"start\": 3}") != std::string::npos); + auto reloaded = model_load(text); + CHECK(reloaded.animation_get(0)->endMarker == 5); + CHECK(model_to_json(reloaded) == text); } TEST_CASE("JSON dates are ISO 8601") { - auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); - for (auto [date, iso] : {std::pair{"01/01/2026 12:00:00 PM", "2026-01-01T12:00:00"}, - {"03/04/2025 12:30:05 AM", "2025-03-04T00:30:05"}, - {"12/31/2024 11:59:59 PM", "2024-12-31T23:59:59"}}) - { - model.info.createdOn = date; - auto text = model_to_json(model); - CHECK(text.find(iso) != std::string::npos); - CHECK(model_load(text).info.createdOn == date); - } + auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); + for (auto [date, iso] : {std::pair{"01/01/2026 12:00:00 PM", "2026-01-01T12:00:00"}, + {"03/04/2025 12:30:05 AM", "2025-03-04T00:30:05"}, + {"12/31/2024 11:59:59 PM", "2024-12-31T23:59:59"}}) + { + model.info.createdOn = date; + auto text = model_to_json(model); + CHECK(text.find(iso) != std::string::npos); + CHECK(model_load(text).info.createdOn == date); + } } TEST_CASE("JSON that can't be read is reported by where it is, and the rest still opens") { - auto text = R"({ "colour": 1, "info": { "fps": "fast" }, + auto text = R"({ "colour": 1, "info": { "fps": "fast" }, "layers": [ { "name": "a", "sheet": 4 } ], "animations": { "Idle": { "length": 3, "root": [ { "pos": [1], "ease": "bouncy", "delay": 3 } ] } } })"; - Model model = {}; - std::string issues; - REQUIRE(model_load_string(model, text, &issues)); - CHECK(model.animation_get(0)->frameNum == 3); - CHECK(model.animation_get(0)->root.frames[0].duration == 3); - for (auto issue : {"colour: unknown key", "info.fps: expected a number", "layers[0].sheet: no item at index 4", - "animations.Idle.root[0].pos: expected an array of 2 numbers", - "animations.Idle.root[0].ease: unknown value \"bouncy\""}) - CHECK_MESSAGE(issues.find(issue) != std::string::npos, issue); + Model model = {}; + std::string issues; + REQUIRE(model_load_string(model, text, &issues)); + CHECK(model.animation_get(0)->frameNum == 3); + CHECK(model.animation_get(0)->root.frames[0].duration == 3); + for (auto issue : {"colour: unknown key", "info.fps: expected a number", "layers[0].sheet: no item at index 4", + "animations.Idle.root[0].pos: expected an array of 2 numbers", + "animations.Idle.root[0].ease: unknown value \"bouncy\""}) + CHECK_MESSAGE(issues.find(issue) != std::string::npos, issue); - CHECK_FALSE(model_load_string(model, "{ \"fps\": 30, ", &issues)); + CHECK_FALSE(model_load_string(model, "{ \"fps\": 30, ", &issues)); } TEST_CASE("JSON layers can name a library listed after them in the file") { - auto text = R"({ "layers": [ { "name": "shadow", "library": 0, "animation": "Small" } ], + auto text = R"({ "layers": [ { "name": "shadow", "library": 0, "animation": "Small" } ], "libraries": [ "shared/shadows.anm2" ] })"; - Model model = {}; - std::string issues; - REQUIRE(model_load_string(model, text, &issues)); - CHECK(issues.empty()); - CHECK(model.content.layers[0].libraryId == 0); + Model model = {}; + std::string issues; + REQUIRE(model_load_string(model, text, &issues)); + CHECK(issues.empty()); + CHECK(model.content.layers[0].libraryId == 0); } diff --git a/tests/operations.cpp b/tests/operations.cpp index ac333f8..564b9d2 100644 --- a/tests/operations.cpp +++ b/tests/operations.cpp @@ -4,561 +4,553 @@ #include "playback.h" #include "pack.h" -static Model fixture_load(const char* name) { return model_load(file_load(CORPUS_DIR / name)); } +static Model fixture_load(const char* name) +{ + return model_load(file_load(CORPUS_DIR / name)); +} static void operation_check(const char* name, const Model& model) { - golden_check(GOLDEN_DIR / std::format("operation.{}.xml", name), - model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); + golden_check(GOLDEN_DIR / std::format("operation.{}.xml", name), model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); } static Track& layer_track_get(Model& model, int animationIndex, int layerId) { - auto track = model.track_edit({animationIndex, LAYER, layerId}); - REQUIRE(track); - return *track; + auto track = model.track_edit({animationIndex, LAYER, layerId}); + REQUIRE(track); + return *track; } static int groups_named_count(const Animation& animation, std::string_view name) { - int count = 0; - for (const auto* entries : {&animation.layers, &animation.nulls}) - groups_each(*entries, [&](const TrackGroup& group) { count += group.name == name; }); - return count; + int count = 0; + for (const auto* entries : {&animation.layers, &animation.nulls}) + groups_each(*entries, [&](const TrackGroup& group) { count += group.name == name; }); + return count; } TEST_CASE("animations_merge keeps one group per name") { - for (auto [name, type] : MERGES) - { - INFO("merge: ", std::string(name)); - auto model = fixture_load("03a_groups_nested.anm2"); - animations_merge(model, 0, {0, 1}, type, false, {}); - CHECK(groups_named_count(*model.animation_get(0), "Main") == 1); - } + for (auto [name, type] : MERGES) + { + INFO("merge: ", std::string(name)); + auto model = fixture_load("03a_groups_nested.anm2"); + animations_merge(model, 0, {0, 1}, type, false, {}); + CHECK(groups_named_count(*model.animation_get(0), "Main") == 1); + } } TEST_CASE("file_merge presets") { - constexpr std::pair PRESETS_FILE_MERGE[] = { - {"file_merge_by_name", FILE_MERGE_PRESET_MERGE_BY_NAME}, - {"file_merge_append", FILE_MERGE_PRESET_APPEND_AS_NEW}, - {"file_merge_replace", FILE_MERGE_PRESET_REPLACE_MATCHING}}; - for (auto [name, preset] : PRESETS_FILE_MERGE) - { - auto model = fixture_load("02_items.anm2"); - CHECK(file_merge(model, CORPUS_DIR / "05_regions.anm2", CORPUS_DIR, preset)); - operation_check(name, model); - } + constexpr std::pair PRESETS_FILE_MERGE[] = { + {"file_merge_by_name", FILE_MERGE_PRESET_MERGE_BY_NAME}, + {"file_merge_append", FILE_MERGE_PRESET_APPEND_AS_NEW}, + {"file_merge_replace", FILE_MERGE_PRESET_REPLACE_MATCHING}}; + for (auto [name, preset] : PRESETS_FILE_MERGE) + { + auto model = fixture_load("02_items.anm2"); + CHECK(file_merge(model, CORPUS_DIR / "05_regions.anm2", CORPUS_DIR, preset)); + operation_check(name, model); + } } TEST_CASE("item_add") { - auto model = fixture_load("02_items.anm2"); - CHECK(item_add(model, ItemType::LAYER, 0, -1, {.name = "added", .spritesheetId = 1}, {}, 1, - DESTINATION_ALL) == 2); - CHECK(item_add(model, ItemType::NULL_, 1, -1, {}, {.name = "thisOnly"}, -1, DESTINATION_THIS) == 2); - operation_check("item_add", model); + auto model = fixture_load("02_items.anm2"); + CHECK(item_add(model, ItemType::LAYER, 0, -1, {.name = "added", .spritesheetId = 1}, {}, 1, DESTINATION_ALL) == 2); + CHECK(item_add(model, ItemType::NULL_, 1, -1, {}, {.name = "thisOnly"}, -1, DESTINATION_THIS) == 2); + operation_check("item_add", model); } TEST_CASE("regions_generate and regions_scan") { - auto model = fixture_load("02_items.anm2"); - regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); - auto generated = model; - regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); - CHECK(is_model_equal(model, generated)); - operation_check("regions_generate", model); + auto model = fixture_load("02_items.anm2"); + regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); + auto generated = model; + regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); + CHECK(is_model_equal(model, generated)); + operation_check("regions_generate", model); - auto scanned = fixture_load("05_regions.anm2"); - regions_scan(scanned); - operation_check("regions_scan", scanned); + auto scanned = fixture_load("05_regions.anm2"); + regions_scan(scanned); + operation_check("regions_scan", scanned); } TEST_CASE("frames_change") { - constexpr std::pair CHANGES[] = {{"adjust", ChangeType::ADJUST}, - {"add", ChangeType::ADD}, - {"subtract", ChangeType::SUBTRACT}, - {"multiply", ChangeType::MULTIPLY}, - {"divide", ChangeType::DIVIDE}}; - for (auto [name, type] : CHANGES) - { - auto model = fixture_load("02_items.anm2"); - FrameChange change = {.cropX = 2.0f, .positionY = 4.0f, .scaleX = 50.0f, .rotation = 90.0f, .tintR = 0.5f}; - change.duration = 3; - change.interpolation = Interpolation::EASE_IN; - change.isFlipX = true; - frames_change(layer_track_get(model, 0, 0), change, ItemType::LAYER, type, {0, 1}); - operation_check(std::format("frames_change_{}", name).c_str(), model); - } + constexpr std::pair CHANGES[] = {{"adjust", ChangeType::ADJUST}, + {"add", ChangeType::ADD}, + {"subtract", ChangeType::SUBTRACT}, + {"multiply", ChangeType::MULTIPLY}, + {"divide", ChangeType::DIVIDE}}; + for (auto [name, type] : CHANGES) + { + auto model = fixture_load("02_items.anm2"); + FrameChange change = {.cropX = 2.0f, .positionY = 4.0f, .scaleX = 50.0f, .rotation = 90.0f, .tintR = 0.5f}; + change.duration = 3; + change.interpolation = Interpolation::EASE_IN; + change.isFlipX = true; + frames_change(layer_track_get(model, 0, 0), change, ItemType::LAYER, type, {0, 1}); + operation_check(std::format("frames_change_{}", name).c_str(), model); + } } TEST_CASE("frame_bake and frame_mix") { - auto model = fixture_load("07_special_interpolation.anm2"); - frame_bake(layer_track_get(model, 0, 0), 0, 2, true, false); - frame_bake(layer_track_get(model, 0, 0), 3, 1, false, true); - operation_check("frame_bake", model); + auto model = fixture_load("07_special_interpolation.anm2"); + frame_bake(layer_track_get(model, 0, 0), 0, 2, true, false); + frame_bake(layer_track_get(model, 0, 0), 3, 1, false, true); + operation_check("frame_bake", model); - Frame from = {}; - Frame to = {}; - to.position = {10.0f, -20.0f}; - to.skew = {30.0f, 0.0f}; - to.rotation = 90.0f; - to.tint = {0.0f, 1.0f, 1.0f, 0.5f}; - frame_mix(from, to, 0.5f); - CHECK(from.position == glm::vec2(5.0f, -10.0f)); - CHECK(from.skew == glm::vec2(15.0f, 0.0f)); - CHECK(from.rotation == doctest::Approx(45.0f)); - CHECK(from.tint.a == doctest::Approx(0.75f)); + Frame from = {}; + Frame to = {}; + to.position = {10.0f, -20.0f}; + to.skew = {30.0f, 0.0f}; + to.rotation = 90.0f; + to.tint = {0.0f, 1.0f, 1.0f, 0.5f}; + frame_mix(from, to, 0.5f); + CHECK(from.position == glm::vec2(5.0f, -10.0f)); + CHECK(from.skew == glm::vec2(15.0f, 0.0f)); + CHECK(from.rotation == doctest::Approx(45.0f)); + CHECK(from.tint.a == doctest::Approx(0.75f)); } TEST_CASE("rects_pack fits every rect without overlap") { - std::vector sizes{{16, 16}, {32, 8}, {8, 32}, {5, 7}, {64, 1}, {1, 1}}; - glm::ivec2 size{}; - std::vector positions{}; - REQUIRE(rects_pack(sizes, size, positions)); - REQUIRE(positions.size() == sizes.size()); - for (std::size_t i = 0; i < sizes.size(); ++i) - { - CHECK(glm::all(glm::greaterThanEqual(positions[i], glm::ivec2(0)))); - CHECK(glm::all(glm::lessThanEqual(positions[i] + sizes[i], size))); - for (std::size_t j = i + 1; j < sizes.size(); ++j) + std::vector sizes{{16, 16}, {32, 8}, {8, 32}, {5, 7}, {64, 1}, {1, 1}}; + glm::ivec2 size{}; + std::vector positions{}; + REQUIRE(rects_pack(sizes, size, positions)); + REQUIRE(positions.size() == sizes.size()); + for (std::size_t i = 0; i < sizes.size(); ++i) { - auto isSeparate = glm::any(glm::lessThanEqual(positions[i] + sizes[i], positions[j])) || - glm::any(glm::lessThanEqual(positions[j] + sizes[j], positions[i])); - CHECK(isSeparate); + CHECK(glm::all(glm::greaterThanEqual(positions[i], glm::ivec2(0)))); + CHECK(glm::all(glm::lessThanEqual(positions[i] + sizes[i], size))); + for (std::size_t j = i + 1; j < sizes.size(); ++j) + { + auto isSeparate = glm::any(glm::lessThanEqual(positions[i] + sizes[i], positions[j])) || + glm::any(glm::lessThanEqual(positions[j] + sizes[j], positions[i])); + CHECK(isSeparate); + } } - } } -// Each edit runs on a fixture; its result document is a golden, and every returned uid must resolve. +// Each edit runs on a fixture. Its result document is a golden, and every returned uid must resolve. TEST_CASE("edit layer operations") { - struct Case - { - const char* name; - const char* fixture; - std::function operation; - std::size_t uidCount; - }; + struct Case + { + const char* name; + const char* fixture; + std::function operation; + std::size_t uidCount; + }; - const Reference head = {0, LAYER, 0}; - const Case CASES[] = { - {"frame_insert", "02_items.anm2", - [&](Model& anm2) { return frame_insert(anm2, {0, LAYER, 0, 0}, 0); }, 1}, - {"trigger_insert", "02_items.anm2", - [&](Model& anm2) { return frame_insert(anm2, {0, TRIGGER, -1, 0}, 2); }, 1}, - {"frames_delete", "02_items.anm2", - [&](Model& anm2) { return frames_delete(anm2, {{0, LAYER, 0, 0}, {0, ROOT, -1, 1}}); }, 0}, - {"frames_duplicate", "02_items.anm2", [&](Model& anm2) - { return frames_duplicate(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, {0, LAYER, 0, 1}); }, 2}, - {"frames_reverse", "07_special_interpolation.anm2", - [&](Model& anm2) { return frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 2}}); }, 0}, - {"frames_bake", "07_special_interpolation.anm2", [&](Model& anm2) - { return frames_bake(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, 2, true, false); }, 5}, - {"frame_split", "02_items.anm2", [&](Model& anm2) { return frame_split(anm2, {0, LAYER, 1, 0}, 2); }, - 1}, - {"frames_move", "02_items.anm2", - [&](Model& anm2) { return frames_move(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}, head, 2); }, 2}, - {"frames_paste", "02_items.anm2", - [&](Model& anm2) - { - auto frame = anm2.frame_get(Reference{0, LAYER, 1, 0}); - auto text = frame_to_string(*frame, ItemType::LAYER) + frame_to_string(*frame, ItemType::LAYER); - return frames_paste(anm2, {0, LAYER, 0, 0}, {}, text, 0, nullptr); - }, - 2}, - {"root_bake_into", "04_group_root_transform.anm2", - [&](Model& anm2) - { - return root_bake_into(anm2, {{0, ROOT, -1, 0}}, {{0, LAYER, 2}}, - {.isRoundScale = true, .isMatchRootInterpolation = true}); - }, - 1}, - {"items_group", "03b_groups_legacy_flat.anm2", - [&](Model& anm2) { return items_group(anm2, 0, LAYER, {2}, "New"); }, 1}, - {"items_move", "03b_groups_legacy_flat.anm2", [&](Model& anm2) - { return items_move(anm2, 0, LAYER, {2}, {}, {true, LAYER, 0, -1}, false, true); }, 0}, - {"items_remove", "03b_groups_legacy_flat.anm2", - [&](Model& anm2) { return items_remove(anm2, 0, {{LAYER, {2}}}, {{NULL_, {3}}}); }, 0}, - {"animation_add", "03a_groups_nested.anm2", - [&](Model& anm2) { return animation_add(anm2, 1, 0, 0, "Added"); }, 1}, - {"animations_remove", "03a_groups_nested.anm2", - [&](Model& anm2) { return animations_remove(anm2, {1}, {0}); }, 0}, - {"animations_move", "02_items.anm2", [&](Model& anm2) - { return animations_move(anm2, {0}, {}, {.animationIndex = 1, .isAfter = true}); }, 1}, - {"animations_group", "02_items.anm2", - [&](Model& anm2) { return animations_group(anm2, {0, 1}, "Group"); }, 0}, - {"animations_paste", "02_items.anm2", - [&](Model& anm2) - { - std::set groupIds; - auto text = animation_to_string(*anm2.animation_get(1)); - return animations_paste(anm2, text, 0, -1, groupIds, nullptr); - }, - 1}, - {"regions_paste", "05_regions.anm2", - [&](Model& anm2) - { - auto region = item_get(item_get(anm2.content.spritesheets, 0)->regions, 1); - return regions_paste(anm2, 0, item_to_string(*region), 1, nullptr); - }, - 0}, - {"animation_grid_generate", "05_regions.anm2", - [&](Model& anm2) - { - return animation_grid_generate(anm2, {{0, LAYER, 0}}, - {{0, 0}, {8, 8}, {4, 4}, 2, 3, 2, true, "Grid {}"}); - }, - 3}, - {"frames_change_apply", "02_items.anm2", - [&](Model& anm2) - { - FrameChange change = {.positionX = 3.0f, .rotation = 10.0f}; - return frames_change_apply( - anm2, {.references = {{0, LAYER, 0, 1}, {0, NULL_, 0}}, .animations = {1}, .isRoot = true}, change, - ChangeType::ADD); - }, - 0}, - {"animations_merge", "03a_groups_nested.anm2", - [&](Model& anm2) { return animations_merge(anm2, 0, {1}, MERGE_APPEND, true, {0}); }, 1}, - }; + const Reference head = {0, LAYER, 0}; + const Case CASES[] = { + {"frame_insert", "02_items.anm2", [&](Model& anm2) { return frame_insert(anm2, {0, LAYER, 0, 0}, 0); }, 1}, + {"trigger_insert", "02_items.anm2", [&](Model& anm2) { return frame_insert(anm2, {0, TRIGGER, -1, 0}, 2); }, 1}, + {"frames_delete", "02_items.anm2", + [&](Model& anm2) { return frames_delete(anm2, {{0, LAYER, 0, 0}, {0, ROOT, -1, 1}}); }, 0}, + {"frames_duplicate", "02_items.anm2", + [&](Model& anm2) { return frames_duplicate(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, {0, LAYER, 0, 1}); }, + 2}, + {"frames_reverse", "07_special_interpolation.anm2", + [&](Model& anm2) { return frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 2}}); }, 0}, + {"frames_bake", "07_special_interpolation.anm2", + [&](Model& anm2) { return frames_bake(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, 2, true, false); }, 5}, + {"frame_split", "02_items.anm2", [&](Model& anm2) { return frame_split(anm2, {0, LAYER, 1, 0}, 2); }, 1}, + {"frames_move", "02_items.anm2", + [&](Model& anm2) { return frames_move(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}, head, 2); }, 2}, + {"frames_paste", "02_items.anm2", + [&](Model& anm2) { + auto frame = anm2.frame_get(Reference{0, LAYER, 1, 0}); + auto text = frame_to_string(*frame, ItemType::LAYER) + frame_to_string(*frame, ItemType::LAYER); + return frames_paste(anm2, {0, LAYER, 0, 0}, {}, text, 0, nullptr); + }, + 2}, + {"root_bake_into", "04_group_root_transform.anm2", + [&](Model& anm2) { + return root_bake_into(anm2, {{0, ROOT, -1, 0}}, {{0, LAYER, 2}}, + {.isRoundScale = true, .isMatchRootInterpolation = true}); + }, + 1}, + {"items_group", "03b_groups_legacy_flat.anm2", + [&](Model& anm2) { return items_group(anm2, 0, LAYER, {2}, "New"); }, 1}, + {"items_move", "03b_groups_legacy_flat.anm2", + [&](Model& anm2) { return items_move(anm2, 0, LAYER, {2}, {}, {true, LAYER, 0, -1}, false, true); }, 0}, + {"items_remove", "03b_groups_legacy_flat.anm2", + [&](Model& anm2) { return items_remove(anm2, 0, {{LAYER, {2}}}, {{NULL_, {3}}}); }, 0}, + {"animation_add", "03a_groups_nested.anm2", [&](Model& anm2) { return animation_add(anm2, 1, 0, 0, "Added"); }, + 1}, + {"animations_remove", "03a_groups_nested.anm2", [&](Model& anm2) { return animations_remove(anm2, {1}, {0}); }, + 0}, + {"animations_move", "02_items.anm2", + [&](Model& anm2) { return animations_move(anm2, {0}, {}, {.animationIndex = 1, .isAfter = true}); }, 1}, + {"animations_group", "02_items.anm2", [&](Model& anm2) { return animations_group(anm2, {0, 1}, "Group"); }, 0}, + {"animations_paste", "02_items.anm2", + [&](Model& anm2) { + std::set groupIds; + auto text = animation_to_string(*anm2.animation_get(1)); + return animations_paste(anm2, text, 0, -1, groupIds, nullptr); + }, + 1}, + {"regions_paste", "05_regions.anm2", + [&](Model& anm2) { + auto region = item_get(item_get(anm2.content.spritesheets, 0)->regions, 1); + return regions_paste(anm2, 0, item_to_string(*region), 1, nullptr); + }, + 0}, + {"animation_grid_generate", "05_regions.anm2", + [&](Model& anm2) { + return animation_grid_generate(anm2, {{0, LAYER, 0}}, {{0, 0}, {8, 8}, {4, 4}, 2, 3, 2, true, "Grid {}"}); + }, + 3}, + {"frames_change_apply", "02_items.anm2", + [&](Model& anm2) { + FrameChange change = {.positionX = 3.0f, .rotation = 10.0f}; + return frames_change_apply( + anm2, {.references = {{0, LAYER, 0, 1}, {0, NULL_, 0}}, .animations = {1}, .isRoot = true}, change, + ChangeType::ADD); + }, + 0}, + {"animations_merge", "03a_groups_nested.anm2", + [&](Model& anm2) { return animations_merge(anm2, 0, {1}, MERGE_APPEND, true, {0}); }, 1}, + }; - for (auto& entry : CASES) - { - INFO("operation: ", std::string(entry.name)); - auto anm2 = fixture_load(entry.fixture); - auto uids = entry.operation(anm2); - CHECK(uids.size() == entry.uidCount); - anm2.uids_repair(); - UidIndex index(anm2); - for (auto uid : uids) - CHECK(index.reference_get(uid)); - operation_check(entry.name, anm2); - } + for (auto& entry : CASES) + { + INFO("operation: ", std::string(entry.name)); + auto anm2 = fixture_load(entry.fixture); + auto uids = entry.operation(anm2); + CHECK(uids.size() == entry.uidCount); + anm2.uids_repair(); + UidIndex index(anm2); + for (auto uid : uids) + CHECK(index.reference_get(uid)); + operation_check(entry.name, anm2); + } } TEST_CASE("spritesheet pixel edits") { - auto image_make = [](glm::ivec2 size, std::vector opaque = {}) - { - std::vector pixels((std::size_t)size.x * size.y * IMAGE_CHANNELS, 0); - for (auto point : opaque) - std::fill_n(pixels.begin() + ((std::size_t)point.y * size.x + point.x) * IMAGE_CHANNELS, - IMAGE_CHANNELS, 255); - return Image(pixels.data(), size); - }; - auto sheet = image_make({64, 64}, {{4, 6}}); - auto other = image_make({16, 16}); + auto image_make = [](glm::ivec2 size, std::vector opaque = {}) { + std::vector pixels((std::size_t)size.x * size.y * IMAGE_CHANNELS, 0); + for (auto point : opaque) + std::fill_n(pixels.begin() + ((std::size_t)point.y * size.x + point.x) * IMAGE_CHANNELS, IMAGE_CHANNELS, + 255); + return Image(pixels.data(), size); + }; + auto sheet = image_make({64, 64}, {{4, 6}}); + auto other = image_make({16, 16}); - SUBCASE("regions_trim shrinks to content and keeps the custom pivot in place") - { - auto model = fixture_load("05_regions.anm2"); - CHECK(regions_trim(model, 0, {0, 1}, sheet)); - auto region = item_get(model.content.spritesheets[0].regions, 0); - CHECK(region->crop == glm::vec2(4, 6)); - CHECK(region->size == glm::vec2(1, 1)); - CHECK(region->pivot == glm::vec2(-1, -1)); - } + SUBCASE("regions_trim shrinks to content and keeps the custom pivot in place") + { + auto model = fixture_load("05_regions.anm2"); + CHECK(regions_trim(model, 0, {0, 1}, sheet)); + auto region = item_get(model.content.spritesheets[0].regions, 0); + CHECK(region->crop == glm::vec2(4, 6)); + CHECK(region->size == glm::vec2(1, 1)); + CHECK(region->pivot == glm::vec2(-1, -1)); + } - SUBCASE("spritesheet_pack returns an image holding every region") - { - auto model = fixture_load("05_regions.anm2"); - auto packed = spritesheet_pack(model, 0, sheet, 1); - REQUIRE(packed); - CHECK(packed->is_valid()); - for (auto& region : model.content.spritesheets[0].regions) - CHECK(glm::all(glm::lessThanEqual(glm::ivec2(region.crop + region.size), packed->size))); - } + SUBCASE("spritesheet_pack returns an image holding every region") + { + auto model = fixture_load("05_regions.anm2"); + auto packed = spritesheet_pack(model, 0, sheet, 1); + REQUIRE(packed); + CHECK(packed->is_valid()); + for (auto& region : model.content.spritesheets[0].regions) + CHECK(glm::all(glm::lessThanEqual(glm::ivec2(region.crop + region.size), packed->size))); + } - SUBCASE("spritesheets_merge appends images and moves layers onto the base sheet") - { - auto model = fixture_load("05_regions.anm2"); - auto image_get = [&](int id) { return id == 0 ? &sheet : &other; }; - auto merged = spritesheets_merge(model, {0, 1}, image_get, true, true, false, Origin::TOP_LEFT); - REQUIRE(merged); - CHECK(merged->size == glm::ivec2(80, 64)); - CHECK(model.content.spritesheets.size() == 1); - CHECK(item_get(model.content.layers, 1)->spritesheetId == 0); - operation_check("spritesheets_merge", model); - } + SUBCASE("spritesheets_merge appends images and moves layers onto the base sheet") + { + auto model = fixture_load("05_regions.anm2"); + auto image_get = [&](int id) { + return id == 0 ? &sheet : &other; + }; + auto merged = spritesheets_merge(model, {0, 1}, image_get, true, true, false, Origin::TOP_LEFT); + REQUIRE(merged); + CHECK(merged->size == glm::ivec2(80, 64)); + CHECK(model.content.spritesheets.size() == 1); + CHECK(item_get(model.content.layers, 1)->spritesheetId == 0); + operation_check("spritesheets_merge", model); + } } TEST_CASE("markers stay in the editor's copy and bound playback") { - auto model = fixture_load("01_minimal.anm2"); - auto animation = model.animation_edit(0); - REQUIRE(animation); - animation->frameNum = 10; - animation->startMarker = 2; - animation->endMarker = 5; - CHECK(animation_play_range_get(*animation) == glm::ivec2(2, 6)); + auto model = fixture_load("01_minimal.anm2"); + auto animation = model.animation_edit(0); + REQUIRE(animation); + animation->frameNum = 10; + animation->startMarker = 2; + animation->endMarker = 5; + CHECK(animation_play_range_get(*animation) == glm::ivec2(2, 6)); - auto text = model_to_string(model); - CHECK(game_document_get(text).find("Marker") == std::string::npos); - auto reloaded = model_load(text); - CHECK(reloaded.animation_get(0)->startMarker == 2); - CHECK(reloaded.animation_get(0)->endMarker == 5); + auto text = model_to_string(model); + CHECK(game_document_get(text).find("Marker") == std::string::npos); + auto reloaded = model_load(text); + CHECK(reloaded.animation_get(0)->startMarker == 2); + CHECK(reloaded.animation_get(0)->endMarker == 5); - Playback playback = {}; - playback.isPlaying = true; - playback.tick(10, 2, 6, true, 0.1f); - CHECK(playback.time == doctest::Approx(3.0f)); - playback.tick(10, 2, 6, true, 0.5f); - CHECK(playback.time == doctest::Approx(4.0f)); + Playback playback = {}; + playback.isPlaying = true; + playback.tick(10, 2, 6, true, 0.1f); + CHECK(playback.time == doctest::Approx(3.0f)); + playback.tick(10, 2, 6, true, 0.5f); + CHECK(playback.time == doctest::Approx(4.0f)); } TEST_CASE("isaac_issues_get counts what the game's copy changes") { - CHECK(isaac_issues_get(fixture_load("01_minimal.anm2")) == IsaacIssues{}); - CHECK(isaac_issues_get(fixture_load("07_special_interpolation.anm2")).easedFrames == 5); - CHECK(isaac_issues_get(fixture_load("04_group_root_transform.anm2")).groupTransforms > 0); - auto shaders = isaac_issues_get(fixture_load("06_shaders.anm2")); - CHECK(shaders.shaderFrames > 0); - CHECK(shaders.skewFrames > 0); - CHECK(isaac_issues_get(fixture_load("02_items.anm2")).triggerSounds > 0); + CHECK(isaac_issues_get(fixture_load("01_minimal.anm2")) == IsaacIssues{}); + CHECK(isaac_issues_get(fixture_load("07_special_interpolation.anm2")).easedFrames == 5); + CHECK(isaac_issues_get(fixture_load("04_group_root_transform.anm2")).groupTransforms > 0); + auto shaders = isaac_issues_get(fixture_load("06_shaders.anm2")); + CHECK(shaders.shaderFrames > 0); + CHECK(shaders.skewFrames > 0); + CHECK(isaac_issues_get(fixture_load("02_items.anm2")).triggerSounds > 0); } TEST_CASE("frames_property_set copies one property to the frames that have it") { - auto model = fixture_load("02_items.anm2"); - Frame source = {.crop = {7, 8}, .position = {3, 4}}; - Reference layer = {0, LAYER, 0, 0}; - Reference null = {0, NULL_, 0, 0}; - REQUIRE(model.frame_get(layer)); - REQUIRE(model.frame_get(null)); - auto nullCrop = model.frame_get(null)->crop; + auto model = fixture_load("02_items.anm2"); + Frame source = {.crop = {7, 8}, .position = {3, 4}}; + Reference layer = {0, LAYER, 0, 0}; + Reference null = {0, NULL_, 0, 0}; + REQUIRE(model.frame_get(layer)); + REQUIRE(model.frame_get(null)); + auto nullCrop = model.frame_get(null)->crop; - frames_property_set(model, {layer, null}, FrameProperty::POSITION, source); - CHECK(model.frame_get(layer)->position == glm::vec2(3, 4)); - CHECK(model.frame_get(null)->position == glm::vec2(3, 4)); + frames_property_set(model, {layer, null}, FrameProperty::POSITION, source); + CHECK(model.frame_get(layer)->position == glm::vec2(3, 4)); + CHECK(model.frame_get(null)->position == glm::vec2(3, 4)); - frames_property_set(model, {layer, null}, FrameProperty::CROP, source); - CHECK(model.frame_get(layer)->crop == glm::vec2(7, 8)); - CHECK(model.frame_get(null)->crop == nullCrop); + frames_property_set(model, {layer, null}, FrameProperty::CROP, source); + CHECK(model.frame_get(layer)->crop == glm::vec2(7, 8)); + CHECK(model.frame_get(null)->crop == nullCrop); - CHECK_FALSE(is_frame_property_valid(FrameProperty::EVENT, ItemType::LAYER)); - CHECK(is_frame_property_valid(FrameProperty::SOUNDS, ItemType::TRIGGER)); - CHECK_FALSE(is_frame_property_valid(FrameProperty::POSITION, ItemType::TRIGGER)); + CHECK_FALSE(is_frame_property_valid(FrameProperty::EVENT, ItemType::LAYER)); + CHECK(is_frame_property_valid(FrameProperty::SOUNDS, ItemType::TRIGGER)); + CHECK_FALSE(is_frame_property_valid(FrameProperty::POSITION, ItemType::TRIGGER)); } TEST_CASE("frames_split splits every selected frame that spans the time") { - auto model = fixture_load("02_items.anm2"); - auto layerTrack = model.track_get({0, LAYER, 0}); - auto nullTrack = model.track_get({0, NULL_, 0}); - REQUIRE(layerTrack); - REQUIRE(nullTrack); - auto layerCount = layerTrack->frames.size(); - auto nullCount = nullTrack->frames.size(); - REQUIRE(layerTrack->frames[0].duration > 1); - REQUIRE(nullTrack->frames[0].duration > 1); + auto model = fixture_load("02_items.anm2"); + auto layerTrack = model.track_get({0, LAYER, 0}); + auto nullTrack = model.track_get({0, NULL_, 0}); + REQUIRE(layerTrack); + REQUIRE(nullTrack); + auto layerCount = layerTrack->frames.size(); + auto nullCount = nullTrack->frames.size(); + REQUIRE(layerTrack->frames[0].duration > 1); + REQUIRE(nullTrack->frames[0].duration > 1); - auto uids = frames_split(model, {{0, LAYER, 0, 0}, {0, NULL_, 0, 0}}, 0); - CHECK(uids.size() == 2); - CHECK(model.track_get({0, LAYER, 0})->frames.size() == layerCount + 1); - CHECK(model.track_get({0, NULL_, 0})->frames.size() == nullCount + 1); - CHECK(model.track_get({0, LAYER, 0})->frames[0].duration == 1); + auto uids = frames_split(model, {{0, LAYER, 0, 0}, {0, NULL_, 0, 0}}, 0); + CHECK(uids.size() == 2); + CHECK(model.track_get({0, LAYER, 0})->frames.size() == layerCount + 1); + CHECK(model.track_get({0, NULL_, 0})->frames.size() == nullCount + 1); + CHECK(model.track_get({0, LAYER, 0})->frames[0].duration == 1); } TEST_CASE("change all frame properties changes layer depth only") { - auto model = fixture_load("02_items.anm2"); - Reference layer = {0, LAYER, 0, 0}; - Reference null = {0, NULL_, 0, 0}; - frames_change_apply(model, {.references = {layer, null}}, {.depth = 2}, ChangeType::ADD); - frames_change_apply(model, {.references = {layer, null}}, {.depth = 1}, ChangeType::SUBTRACT); - CHECK(model.frame_get(layer)->depth == 1); - CHECK(model.frame_get(null)->depth == 0); + auto model = fixture_load("02_items.anm2"); + Reference layer = {0, LAYER, 0, 0}; + Reference null = {0, NULL_, 0, 0}; + frames_change_apply(model, {.references = {layer, null}}, {.depth = 2}, ChangeType::ADD); + frames_change_apply(model, {.references = {layer, null}}, {.depth = 1}, ChangeType::SUBTRACT); + CHECK(model.frame_get(layer)->depth == 1); + CHECK(model.frame_get(null)->depth == 0); } TEST_CASE("change all frame properties blurs layers and changes only animation layers' children") { - auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); - Reference animationLayer = {0, LAYER, 1, 0}; - Reference spritesheetLayer = {1, LAYER, 2, 0}; - REQUIRE(model.frame_get(spritesheetLayer)); - frames_change_apply(model, {.references = {animationLayer, spritesheetLayer}}, - {.blur = 8.0f, .childAnimation = "Spin", .childMode = ChildMode::ONCE, .childStart = 3}, - ChangeType::ADJUST); - auto child = *model.frame_get(animationLayer); - CHECK(child.blur == 8.0f); - CHECK(child.childAnimation == "Spin"); - CHECK(child.childMode == ChildMode::ONCE); - CHECK(child.childStart == 3); - auto sprite = *model.frame_get(spritesheetLayer); - CHECK(sprite.blur == 8.0f); - CHECK(sprite.childAnimation.empty()); - CHECK(sprite.childMode == ChildMode::LOOP); - CHECK(sprite.childStart == 0); + auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + Reference animationLayer = {0, LAYER, 1, 0}; + Reference spritesheetLayer = {1, LAYER, 2, 0}; + REQUIRE(model.frame_get(spritesheetLayer)); + frames_change_apply(model, {.references = {animationLayer, spritesheetLayer}}, + {.blur = 8.0f, .childAnimation = "Spin", .childMode = ChildMode::ONCE, .childStart = 3}, + ChangeType::ADJUST); + auto child = *model.frame_get(animationLayer); + CHECK(child.blur == 8.0f); + CHECK(child.childAnimation == "Spin"); + CHECK(child.childMode == ChildMode::ONCE); + CHECK(child.childStart == 3); + auto sprite = *model.frame_get(spritesheetLayer); + CHECK(sprite.blur == 8.0f); + CHECK(sprite.childAnimation.empty()); + CHECK(sprite.childMode == ChildMode::LOOP); + CHECK(sprite.childStart == 0); - frames_change_apply(model, {.references = {animationLayer}}, {.blur = 1000.0f}, ChangeType::ADD); - CHECK(model.frame_get(animationLayer)->blur == FRAME_BLUR_MAX); + frames_change_apply(model, {.references = {animationLayer}}, {.blur = 1000.0f}, ChangeType::ADD); + CHECK(model.frame_get(animationLayer)->blur == FRAME_BLUR_MAX); } TEST_CASE("animations_merge moves triggers past the animation placed before them") { - auto model_make = []() - { - auto model = fixture_load("01_minimal.anm2"); - auto first = *model.animation_get(0); - first.frameNum = 10; - auto second = first; - second.uid = uid_next(); - second.triggers.frames = {Frame{.atFrame = 5}}; - model.animations.entries = {std::make_shared(first), - std::make_shared(second)}; - return model; - }; + auto model_make = []() { + auto model = fixture_load("01_minimal.anm2"); + auto first = *model.animation_get(0); + first.frameNum = 10; + auto second = first; + second.uid = uid_next(); + second.triggers.frames = {Frame{.atFrame = 5}}; + model.animations.entries = {std::make_shared(first), + std::make_shared(second)}; + return model; + }; - auto appended = model_make(); - animations_merge(appended, 0, {0, 1}, MERGE_APPEND, false, {}); - CHECK(appended.animation_get(0)->triggers.frames.at(0).atFrame == 15); + auto appended = model_make(); + animations_merge(appended, 0, {0, 1}, MERGE_APPEND, false, {}); + CHECK(appended.animation_get(0)->triggers.frames.at(0).atFrame == 15); - auto prepended = model_make(); - animations_merge(prepended, 1, {0, 1}, MERGE_PREPEND, false, {}); - CHECK(prepended.animation_get(1)->triggers.frames.at(0).atFrame == 15); + auto prepended = model_make(); + animations_merge(prepended, 1, {0, 1}, MERGE_PREPEND, false, {}); + CHECK(prepended.animation_get(1)->triggers.frames.at(0).atFrame == 15); } TEST_CASE("skew reads from the old Shear attributes too") { - auto frames = - frames_from_string(R"()", ItemType::NULL_); - REQUIRE(frames.size() == 2); - CHECK(frames[0].skew == glm::vec2(5, 6)); - CHECK(frames[1].skew.x == 7); - CHECK(frames[0].extras.attributes.empty()); + auto frames = frames_from_string(R"()", ItemType::NULL_); + REQUIRE(frames.size() == 2); + CHECK(frames[0].skew == glm::vec2(5, 6)); + CHECK(frames[1].skew.x == 7); + CHECK(frames[0].extras.attributes.empty()); } TEST_CASE("a trigger fires several events; the game's copy keeps the first") { - auto model = fixture_load("02_items.anm2"); - model.frame_edit({0, TRIGGER, -1, 0})->eventIds = {1, 0}; - auto text = model_to_string(model); - CHECK(model_load(text).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1, 0}); - CHECK(model_load(game_document_get(text)).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1}); - CHECK(isaac_issues_get(model).extraEvents == 1); + auto model = fixture_load("02_items.anm2"); + model.frame_edit({0, TRIGGER, -1, 0})->eventIds = {1, 0}; + auto text = model_to_string(model); + CHECK(model_load(text).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1, 0}); + CHECK(model_load(game_document_get(text)).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1}); + CHECK(isaac_issues_get(model).extraEvents == 1); } TEST_CASE("SVG spritesheets pack and merge into SVGs") { - auto model = model_load(file_load(TEST_DIR / "render" / "vector.anm2")); - Image vector(TEST_DIR / "render" / "vector.svg"); - auto& regions = model.content.spritesheets.front().regions; - regions.push_back({.id = 0, .name = "circle", .crop = {0, 0}, .size = {16, 16}}); - regions.push_back({.id = 1, .name = "square", .crop = {16, 0}, .size = {16, 16}}); + auto model = model_load(file_load(TEST_DIR / "render" / "vector.anm2")); + Image vector(TEST_DIR / "render" / "vector.svg"); + auto& regions = model.content.spritesheets.front().regions; + regions.push_back({.id = 0, .name = "circle", .crop = {0, 0}, .size = {16, 16}}); + regions.push_back({.id = 1, .name = "square", .crop = {16, 0}, .size = {16, 16}}); - // Packing keeps the drawing: each region shows the same pixels where it now sits. - auto packed = spritesheet_pack(model, 0, vector, 1); - REQUIRE(packed); - CHECK(packed->is_vector()); - for (auto [id, original] : {std::pair{0, glm::vec2(8, 8)}, std::pair{1, glm::vec2(24, 8)}}) - { - auto region = item_get(model.content.spritesheets.front().regions, id); - CHECK(packed->pixel_read(region->crop + glm::vec2(8, 8)) == vector.pixel_read(original)); - } + // Packing keeps the drawing: each region shows the same pixels where it now sits. + auto packed = spritesheet_pack(model, 0, vector, 1); + REQUIRE(packed); + CHECK(packed->is_vector()); + for (auto [id, original] : {std::pair{0, glm::vec2(8, 8)}, std::pair{1, glm::vec2(24, 8)}}) + { + auto region = item_get(model.content.spritesheets.front().regions, id); + CHECK(packed->pixel_read(region->crop + glm::vec2(8, 8)) == vector.pixel_read(original)); + } - // A PNG sheet merged after an SVG one: the result is an SVG holding the PNG; a PNG first takes the .svg name. - const std::vector pixels(4 * 4 * IMAGE_CHANNELS, 255); - Image raster(pixels.data(), {4, 4}); - model.content.spritesheets.push_back({.id = 1, .path = "white.png"}); - auto images = std::map{{0, &vector}, {1, &raster}}; - auto image_get = [&](int id) { return images.at(id); }; - auto mixed = model; - auto merged = spritesheets_merge(mixed, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT); - REQUIRE(merged); - CHECK(merged->is_vector()); - CHECK(merged->size == glm::ivec2(36, 16)); - CHECK(merged->pixel_read({33, 1}) == raster.pixel_read({1, 1})); - CHECK(mixed.content.spritesheets.front().path == "vector.svg"); + // A PNG sheet merged after an SVG one: the result is an SVG holding the PNG. A PNG first takes the .svg name. + const std::vector pixels(4 * 4 * IMAGE_CHANNELS, 255); + Image raster(pixels.data(), {4, 4}); + model.content.spritesheets.push_back({.id = 1, .path = "white.png"}); + auto images = std::map{{0, &vector}, {1, &raster}}; + auto image_get = [&](int id) { + return images.at(id); + }; + auto mixed = model; + auto merged = spritesheets_merge(mixed, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT); + REQUIRE(merged); + CHECK(merged->is_vector()); + CHECK(merged->size == glm::ivec2(36, 16)); + CHECK(merged->pixel_read({33, 1}) == raster.pixel_read({1, 1})); + CHECK(mixed.content.spritesheets.front().path == "vector.svg"); - std::swap(model.content.spritesheets.front().id, model.content.spritesheets.back().id); - images = {{1, &vector}, {0, &raster}}; - REQUIRE(spritesheets_merge(model, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT)); - CHECK(item_get(model.content.spritesheets, 0)->path == "white.svg"); + std::swap(model.content.spritesheets.front().id, model.content.spritesheets.back().id); + images = {{1, &vector}, {0, &raster}}; + REQUIRE(spritesheets_merge(model, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT)); + CHECK(item_get(model.content.spritesheets, 0)->path == "white.svg"); } TEST_CASE("content_remove takes what refers to an item with it") { - auto path_keep = [](const Model&, const std::filesystem::path& path) { return path; }; - auto remove = [&](Model& model, ElementType type, std::set ids, int spritesheetId = -1, - const LibraryGet& library_get = {}) - { content_remove(model, type, ids, spritesheetId, library_get, path_keep); }; - auto tracks_count = [](const Model& model, int layerId) - { - int count = 0; - for (auto [index, animation] : model.animations_get()) - tracks_each(animation->layers, [&](const Track& track, auto*) { count += track.id == layerId; }); - return count; - }; + auto path_keep = [](const Model&, const std::filesystem::path& path) { + return path; + }; + auto remove = [&](Model& model, ElementType type, std::set ids, int spritesheetId = -1, + const LibraryGet& library_get = {}) { + content_remove(model, type, ids, spritesheetId, library_get, path_keep); + }; + auto tracks_count = [](const Model& model, int layerId) { + int count = 0; + for (auto [index, animation] : model.animations_get()) + tracks_each(animation->layers, [&](const Track& track, auto*) { count += track.id == layerId; }); + return count; + }; - SUBCASE("a layer's tracks, and a spritesheet's plain layers") - { - auto model = fixture_load("02_items.anm2"); - CHECK(model.uses_count(ElementType::LAYER_ELEMENT, {0}) == tracks_count(model, 0)); - remove(model, ElementType::LAYER_ELEMENT, {0}); - CHECK_FALSE(item_get(model.content.layers, 0)); - CHECK(tracks_count(model, 0) == 0); - CHECK(tracks_count(model, 1) > 0); + SUBCASE("a layer's tracks, and a spritesheet's plain layers") + { + auto model = fixture_load("02_items.anm2"); + CHECK(model.uses_count(ElementType::LAYER_ELEMENT, {0}) == tracks_count(model, 0)); + remove(model, ElementType::LAYER_ELEMENT, {0}); + CHECK_FALSE(item_get(model.content.layers, 0)); + CHECK(tracks_count(model, 0) == 0); + CHECK(tracks_count(model, 1) > 0); - CHECK(model.uses_count(ElementType::SPRITESHEET, {1}) == 1); - remove(model, ElementType::SPRITESHEET, {1}); - CHECK(model.content.layers.empty()); - CHECK(tracks_count(model, 1) == 0); - CHECK(model.content.spritesheets.size() == 1); - } + CHECK(model.uses_count(ElementType::SPRITESHEET, {1}) == 1); + remove(model, ElementType::SPRITESHEET, {1}); + CHECK(model.content.layers.empty()); + CHECK(tracks_count(model, 1) == 0); + CHECK(model.content.spritesheets.size() == 1); + } - SUBCASE("an event or sound from its triggers, and triggers left with neither") - { - auto model = fixture_load("02_items.anm2"); - auto& triggers = model.animation_get(0)->triggers.frames; - REQUIRE(triggers.size() == 3); - CHECK(model.uses_count(ElementType::SOUND_ELEMENT, {1}) == 2); - remove(model, ElementType::SOUND_ELEMENT, {1}); - REQUIRE(triggers.size() == 2); - CHECK(triggers[1].soundIds == std::vector{0}); - remove(model, ElementType::EVENT_ELEMENT, {0}); - REQUIRE(triggers.size() == 2); - CHECK(triggers[0].eventIds.empty()); - CHECK(triggers[0].soundIds == std::vector{0}); - } + SUBCASE("an event or sound from its triggers, and triggers left with neither") + { + auto model = fixture_load("02_items.anm2"); + auto& triggers = model.animation_get(0)->triggers.frames; + REQUIRE(triggers.size() == 3); + CHECK(model.uses_count(ElementType::SOUND_ELEMENT, {1}) == 2); + remove(model, ElementType::SOUND_ELEMENT, {1}); + REQUIRE(triggers.size() == 2); + CHECK(triggers[1].soundIds == std::vector{0}); + remove(model, ElementType::EVENT_ELEMENT, {0}); + REQUIRE(triggers.size() == 2); + CHECK(triggers[0].eventIds.empty()); + CHECK(triggers[0].soundIds == std::vector{0}); + } - SUBCASE("a shader, and a region, from their frames") - { - auto shaders = fixture_load("06_shaders.anm2"); - remove(shaders, ElementType::SHADER, {0}); - CHECK(shaders.frame_get({0, LAYER, 0, 0})->shaderId == -1); - CHECK(shaders.frame_get({0, LAYER, 0, 1})->shaderId == 4); + SUBCASE("a shader, and a region, from their frames") + { + auto shaders = fixture_load("06_shaders.anm2"); + remove(shaders, ElementType::SHADER, {0}); + CHECK(shaders.frame_get({0, LAYER, 0, 0})->shaderId == -1); + CHECK(shaders.frame_get({0, LAYER, 0, 1})->shaderId == 4); - auto regions = fixture_load("05_regions.anm2"); - auto before = *regions.frame_get({0, LAYER, 0, 0}); - REQUIRE(before.regionId == 0); - CHECK(regions.uses_count(ElementType::REGION, {0}, 0) == 1); - remove(regions, ElementType::REGION, {0}, 0); - auto after = *regions.frame_get({0, LAYER, 0, 0}); - CHECK(after.regionId == -1); - CHECK(after.crop == before.crop); - CHECK(after.size == before.size); - CHECK(after.pivot == before.pivot); - CHECK_FALSE(item_get(regions.content.spritesheets.front().regions, 0)); - } + auto regions = fixture_load("05_regions.anm2"); + auto before = *regions.frame_get({0, LAYER, 0, 0}); + REQUIRE(before.regionId == 0); + CHECK(regions.uses_count(ElementType::REGION, {0}, 0) == 1); + remove(regions, ElementType::REGION, {0}, 0); + auto after = *regions.frame_get({0, LAYER, 0, 0}); + CHECK(after.regionId == -1); + CHECK(after.crop == before.crop); + CHECK(after.size == before.size); + CHECK(after.pivot == before.pivot); + CHECK_FALSE(item_get(regions.content.spritesheets.front().regions, 0)); + } - SUBCASE("a library's layers, flattened") - { - auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); - auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); - CHECK(model.uses_count(ElementType::LIBRARY, {0}) == 1); - remove(model, ElementType::LIBRARY, {0}, -1, - [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }); - CHECK(model.content.libraries.empty()); - CHECK_FALSE(item_get(model.content.layers, 0)); - CHECK( - std::ranges::any_of(model.content.layers, [](const Layer& layer) { return layer.name == "spin/red"; })); - // Layers playing this file's animations stay as they are. - CHECK(item_get(model.content.layers, 1)->is_animation()); - CHECK(item_get(model.content.layers, 3)->is_animation()); - } + SUBCASE("a library's layers, flattened") + { + auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); + CHECK(model.uses_count(ElementType::LIBRARY, {0}) == 1); + remove(model, ElementType::LIBRARY, {0}, -1, [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }); + CHECK(model.content.libraries.empty()); + CHECK_FALSE(item_get(model.content.layers, 0)); + CHECK(std::ranges::any_of(model.content.layers, [](const Layer& layer) { return layer.name == "spin/red"; })); + // Layers playing this file's animations stay as they are. + CHECK(item_get(model.content.layers, 1)->is_animation()); + CHECK(item_get(model.content.layers, 3)->is_animation()); + } } diff --git a/tests/render/render.cpp b/tests/render/render.cpp index 9ab3982..642d6b4 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -13,255 +13,258 @@ #include "image.h" #include "render.h" - const std::filesystem::path RENDER_TEST_DIR = std::filesystem::path(ANM2ED_TEST_DIR) / "render"; - const std::filesystem::path GOLDEN_DIR = RENDER_TEST_DIR / "golden"; - const std::filesystem::path OUTPUT_DIR = ANM2ED_RENDER_DIR; - constexpr int CHANNEL_TOLERANCE = 8; - constexpr double MISMATCH_RATIO_MAX = 0.01; - constexpr float SCALE = 3.0f; - constexpr glm::vec4 BACKGROUND = {0.2f, 0.2f, 0.2f, 1.0f}; +const std::filesystem::path RENDER_TEST_DIR = std::filesystem::path(ANM2ED_TEST_DIR) / "render"; +const std::filesystem::path GOLDEN_DIR = RENDER_TEST_DIR / "golden"; +const std::filesystem::path OUTPUT_DIR = ANM2ED_RENDER_DIR; +constexpr int CHANNEL_TOLERANCE = 8; +constexpr double MISMATCH_RATIO_MAX = 0.01; +constexpr float SCALE = 3.0f; +constexpr glm::vec4 BACKGROUND = {0.2f, 0.2f, 0.2f, 1.0f}; // Different OpenGL implementations round a little differently: a few pixels may differ, each only slightly. static void golden_image_check(const std::string& name) { - auto actualPath = OUTPUT_DIR / name; - auto goldenPath = GOLDEN_DIR / name; - INFO("render: ", actualPath.string()); - if (std::getenv("ANM2ED_UPDATE_GOLDEN")) - { - std::filesystem::copy_file(actualPath, goldenPath, std::filesystem::copy_options::overwrite_existing); - return; - } - Image actual(actualPath); - Image golden(goldenPath); - REQUIRE(golden.is_valid()); - REQUIRE(actual.size == golden.size); - int mismatches = 0; - for (std::size_t i = 0; i < actual.pixels.size(); ++i) - mismatches += std::abs((int)actual.pixels[i] - (int)golden.pixels[i]) > CHANNEL_TOLERANCE; - CHECK((double)mismatches / (double)actual.pixels.size() <= MISMATCH_RATIO_MAX); + auto actualPath = OUTPUT_DIR / name; + auto goldenPath = GOLDEN_DIR / name; + INFO("render: ", actualPath.string()); + if (std::getenv("ANM2ED_UPDATE_GOLDEN")) + { + std::filesystem::copy_file(actualPath, goldenPath, std::filesystem::copy_options::overwrite_existing); + return; + } + Image actual(actualPath); + Image golden(goldenPath); + REQUIRE(golden.is_valid()); + REQUIRE(actual.size == golden.size); + int mismatches = 0; + for (std::size_t i = 0; i < actual.pixels.size(); ++i) + mismatches += std::abs((int)actual.pixels[i] - (int)golden.pixels[i]) > CHANNEL_TOLERANCE; + CHECK((double)mismatches / (double)actual.pixels.size() <= MISMATCH_RATIO_MAX); } struct RenderFixture { - HeadlessGL gl = {}; - std::optional document; - std::optional shader; - std::optional canvas; - const Animation* animation = nullptr; - glm::vec4 bounds{}; + HeadlessGL gl = {}; + std::optional document; + std::optional shader; + std::optional canvas; + const Animation* animation = nullptr; + glm::vec4 bounds{}; - explicit RenderFixture(const char* file) - { - if (!gl.is_valid()) return; - std::filesystem::create_directories(OUTPUT_DIR); - document.emplace(RENDER_TEST_DIR / file, false); - auto& info = SHADERS[SHADER_TEXTURE]; - shader.emplace(info.vertex, info.fragment); - canvas.emplace(glm::vec2(1.0f)); - animation = document->model.animation_get(0); - bounds = animation_bounds_get(*document, *animation, true); - } + explicit RenderFixture(const char* file) + { + if (!gl.is_valid()) + return; + std::filesystem::create_directories(OUTPUT_DIR); + document.emplace(RENDER_TEST_DIR / file, false); + auto& info = SHADERS[SHADER_TEXTURE]; + shader.emplace(info.vertex, info.fragment); + canvas.emplace(glm::vec2(1.0f)); + animation = document->model.animation_get(0); + bounds = animation_bounds_get(*document, *animation, true); + } - std::vector frame_get(float time) - { - auto pixels = - animation_frame_render(*canvas, *shader, *document, *animation, time, bounds, SCALE, BACKGROUND, true); - pixels_unpremultiply(pixels); - return pixels; - } + std::vector frame_get(float time) + { + auto pixels = + animation_frame_render(*canvas, *shader, *document, *animation, time, bounds, SCALE, BACKGROUND, true); + pixels_unpremultiply(pixels); + return pixels; + } - glm::u8vec4 pixel_get(const std::vector& pixels, glm::vec2 point) - { - auto position = glm::ivec2((point - glm::vec2(bounds.x, bounds.y)) * SCALE); - auto index = ((std::size_t)position.y * (std::size_t)canvas->size.x + (std::size_t)position.x) * 4; - return {pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]}; - } + glm::u8vec4 pixel_get(const std::vector& pixels, glm::vec2 point) + { + auto position = glm::ivec2((point - glm::vec2(bounds.x, bounds.y)) * SCALE); + auto index = ((std::size_t)position.y * (std::size_t)canvas->size.x + (std::size_t)position.x) * 4; + return {pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]}; + } }; TEST_CASE("frames draw where the animation puts them") { - RenderFixture fixture("spin.anm2"); - if (!fixture.gl.is_valid()) - { - MESSAGE("skipped: no OpenGL context"); - return; - } - REQUIRE(fixture.document->is_valid()); + RenderFixture fixture("spin.anm2"); + if (!fixture.gl.is_valid()) + { + MESSAGE("skipped: no OpenGL context"); + return; + } + REQUIRE(fixture.document->is_valid()); - // At time 0 the red square is centered at (-16, 0) with its white dot up and left; the half-transparent blue - // square (32 x 32, at the origin) covers the middle. - auto pixels = fixture.frame_get(0.0f); - auto red = fixture.pixel_get(pixels, {-20.0f, 4.0f}); - CHECK(red.r > 200); - CHECK(red.g < 80); - auto dot = fixture.pixel_get(pixels, {-18.5f, -2.5f}); - CHECK(dot.g > 200); - auto blue = fixture.pixel_get(pixels, {12.0f, 12.0f}); - CHECK(blue.b > blue.r + 40); + // At time 0 the red square is centered at (-16, 0) with its white dot up and left. The half-transparent blue + // square (32 x 32, at the origin) covers the middle. + auto pixels = fixture.frame_get(0.0f); + auto red = fixture.pixel_get(pixels, {-20.0f, 4.0f}); + CHECK(red.r > 200); + CHECK(red.g < 80); + auto dot = fixture.pixel_get(pixels, {-18.5f, -2.5f}); + CHECK(dot.g > 200); + auto blue = fixture.pixel_get(pixels, {12.0f, 12.0f}); + CHECK(blue.b > blue.r + 40); - auto framePath = OUTPUT_DIR / "spin_frame_0.png"; - REQUIRE(Image::write_pixels_png(framePath, glm::ivec2(fixture.canvas->size), pixels.data())); - golden_image_check("spin_frame_0.png"); + auto framePath = OUTPUT_DIR / "spin_frame_0.png"; + REQUIRE(Image::write_pixels_png(framePath, glm::ivec2(fixture.canvas->size), pixels.data())); + golden_image_check("spin_frame_0.png"); } TEST_CASE("a recorded spritesheet holds every frame") { - RenderFixture fixture("spin.anm2"); - if (!fixture.gl.is_valid()) - { - MESSAGE("skipped: no OpenGL context"); - return; - } + RenderFixture fixture("spin.anm2"); + if (!fixture.gl.is_valid()) + { + MESSAGE("skipped: no OpenGL context"); + return; + } - RecorderOptions options{.type = RENDER_SPRITESHEET, - .path = OUTPUT_DIR / "spin_sheet.png", - .start = 0, - .end = fixture.animation->frameNum - 1, - .animationFps = fixture.document->model.info.fps, - .fps = fixture.document->model.info.fps}; - REQUIRE(animation_record(options, *fixture.canvas, *fixture.shader, *fixture.document, *fixture.animation, - fixture.bounds, SCALE, BACKGROUND, true)); - Image sheet(options.path); - auto layout = spritesheet_layout_get(0, 0, fixture.animation->frameNum); - CHECK(sheet.size == glm::ivec2(fixture.canvas->size) * glm::ivec2(layout.columns, layout.rows)); - golden_image_check("spin_sheet.png"); + RecorderOptions options{.type = RENDER_SPRITESHEET, + .path = OUTPUT_DIR / "spin_sheet.png", + .start = 0, + .end = fixture.animation->frameNum - 1, + .animationFps = fixture.document->model.info.fps, + .fps = fixture.document->model.info.fps}; + REQUIRE(animation_record(options, *fixture.canvas, *fixture.shader, *fixture.document, *fixture.animation, + fixture.bounds, SCALE, BACKGROUND, true)); + Image sheet(options.path); + auto layout = spritesheet_layout_get(0, 0, fixture.animation->frameNum); + CHECK(sheet.size == glm::ivec2(fixture.canvas->size) * glm::ivec2(layout.columns, layout.rows)); + golden_image_check("spin_sheet.png"); } TEST_CASE("animation layers draw their child animations") { - RenderFixture fixture("nested.anm2"); - if (!fixture.gl.is_valid()) - { - MESSAGE("skipped: no OpenGL context"); - return; - } - REQUIRE(fixture.document->is_valid()); + RenderFixture fixture("nested.anm2"); + if (!fixture.gl.is_valid()) + { + MESSAGE("skipped: no OpenGL context"); + return; + } + REQUIRE(fixture.document->is_valid()); - // The library's red square at half size starts on its fifth frame, centered at (48, 0); this file's Inner holds its - // red square at (-40, 0). - auto pixels = fixture.frame_get(0.0f); - for (auto point : {glm::vec2(48.0f, 0.0f), glm::vec2(-40.0f, 0.0f)}) - { - auto red = fixture.pixel_get(pixels, point); - CHECK(red.r > 200); - CHECK(red.g < 80); - } + // The library's red square at half size starts on its fifth frame, centered at (48, 0). This file's Inner holds its + // red square at (-40, 0). + auto pixels = fixture.frame_get(0.0f); + for (auto point : {glm::vec2(48.0f, 0.0f), glm::vec2(-40.0f, 0.0f)}) + { + auto red = fixture.pixel_get(pixels, point); + CHECK(red.r > 200); + CHECK(red.g < 80); + } - REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "nested_frame_0.png", glm::ivec2(fixture.canvas->size), - pixels.data())); - golden_image_check("nested_frame_0.png"); + REQUIRE( + Image::write_pixels_png(OUTPUT_DIR / "nested_frame_0.png", glm::ivec2(fixture.canvas->size), pixels.data())); + golden_image_check("nested_frame_0.png"); } TEST_CASE("a blurred layer spreads past its crop like Flash's blur filter") { - RenderFixture fixture("spin.anm2"); - if (!fixture.gl.is_valid()) - { - MESSAGE("skipped: no OpenGL context"); - return; - } - REQUIRE(fixture.document->is_valid()); + RenderFixture fixture("spin.anm2"); + if (!fixture.gl.is_valid()) + { + MESSAGE("skipped: no OpenGL context"); + return; + } + REQUIRE(fixture.document->is_valid()); - // The red square (16 x 16 at (-16, 0)) sharp leaves the canvas clear 2 above its top edge and solid 1 inside it; an - // 8 pixel box spreads a third of it out and takes as much from inside. - constexpr glm::vec2 OUTSIDE{-20.0f, -10.0f}, INSIDE{-20.0f, -7.0f}; - auto sharp = fixture.frame_get(0.0f); - fixture.document->model.frame_edit({0, LAYER, 0, 0})->blur = 8.0f; - fixture.animation = fixture.document->model.animation_get(0); - auto blurred = fixture.frame_get(0.0f); - CHECK(fixture.pixel_get(blurred, OUTSIDE).r > fixture.pixel_get(sharp, OUTSIDE).r + 40); - CHECK(fixture.pixel_get(blurred, INSIDE).r + 40 < fixture.pixel_get(sharp, INSIDE).r); + // The red square (16 x 16 at (-16, 0)) sharp leaves the canvas clear 2 above its top edge and solid 1 inside it. An + // 8 pixel box spreads a third of it out and takes as much from inside. + constexpr glm::vec2 OUTSIDE{-20.0f, -10.0f}, INSIDE{-20.0f, -7.0f}; + auto sharp = fixture.frame_get(0.0f); + fixture.document->model.frame_edit({0, LAYER, 0, 0})->blur = 8.0f; + fixture.animation = fixture.document->model.animation_get(0); + auto blurred = fixture.frame_get(0.0f); + CHECK(fixture.pixel_get(blurred, OUTSIDE).r > fixture.pixel_get(sharp, OUTSIDE).r + 40); + CHECK(fixture.pixel_get(blurred, INSIDE).r + 40 < fixture.pixel_get(sharp, INSIDE).r); - REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "spin_blur_frame_0.png", glm::ivec2(fixture.canvas->size), - blurred.data())); + REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "spin_blur_frame_0.png", glm::ivec2(fixture.canvas->size), + blurred.data())); } TEST_CASE("SVG spritesheets draw sharp at any scale") { - RenderFixture fixture("vector.anm2"); - if (!fixture.gl.is_valid()) - { - MESSAGE("skipped: no OpenGL context"); - return; - } - REQUIRE(fixture.document->is_valid()); + RenderFixture fixture("vector.anm2"); + if (!fixture.gl.is_valid()) + { + MESSAGE("skipped: no OpenGL context"); + return; + } + REQUIRE(fixture.document->is_valid()); - // Drawn at 600% (200% frames at a 3x render), the circle's edge stays within a pixel or two: just inside it is - // solid red, just outside it clear. - auto pixels = fixture.frame_get(0.0f); - auto inside = fixture.pixel_get(pixels, {-20.0f + 13.0f, 0.0f}); - auto outside = fixture.pixel_get(pixels, {-20.0f + 14.6f, 0.0f}); - CHECK(inside.r > 200); - CHECK(outside.r < 80); + // Drawn at 600% (200% frames at a 3x render), the circle's edge stays within a pixel or two: just inside it is + // solid red, just outside it clear. + auto pixels = fixture.frame_get(0.0f); + auto inside = fixture.pixel_get(pixels, {-20.0f + 13.0f, 0.0f}); + auto outside = fixture.pixel_get(pixels, {-20.0f + 14.6f, 0.0f}); + CHECK(inside.r > 200); + CHECK(outside.r < 80); - REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "vector_frame_0.png", glm::ivec2(fixture.canvas->size), - pixels.data())); - golden_image_check("vector_frame_0.png"); + REQUIRE( + Image::write_pixels_png(OUTPUT_DIR / "vector_frame_0.png", glm::ivec2(fixture.canvas->size), pixels.data())); + golden_image_check("vector_frame_0.png"); } TEST_CASE("converting SVG spritesheets writes PNGs beside them") { - auto directory = std::filesystem::temp_directory_path() / "anm2ed_vector_convert"; - std::filesystem::remove_all(directory); - std::filesystem::create_directories(directory); - for (auto name : {"vector.anm2", "vector.svg"}) - std::filesystem::copy_file(RENDER_TEST_DIR / name, directory / name); + auto directory = std::filesystem::temp_directory_path() / "anm2ed_vector_convert"; + std::filesystem::remove_all(directory); + std::filesystem::create_directories(directory); + for (auto name : {"vector.anm2", "vector.svg"}) + std::filesystem::copy_file(RENDER_TEST_DIR / name, directory / name); - Document document(directory / "vector.anm2", false); - REQUIRE(document.is_valid()); - document.spritesheets_vector_convert({0}); - CHECK(document.model.content.spritesheets.front().path == "vector.png"); - CHECK(std::filesystem::exists(directory / "vector.png")); - REQUIRE(document.texture_get(0)); - CHECK_FALSE(document.texture_get(0)->is_vector()); - CHECK(spritesheets_vector_used_get(document.model).empty()); + Document document(directory / "vector.anm2", false); + REQUIRE(document.is_valid()); + document.spritesheets_vector_convert({0}); + CHECK(document.model.content.spritesheets.front().path == "vector.png"); + CHECK(std::filesystem::exists(directory / "vector.png")); + REQUIRE(document.texture_get(0)); + CHECK_FALSE(document.texture_get(0)->is_vector()); + CHECK(spritesheets_vector_used_get(document.model).empty()); - document.undo(); - CHECK(document.model.content.spritesheets.front().path == "vector.svg"); - CHECK(document.texture_get(0)->is_vector()); - std::filesystem::remove_all(directory); + document.undo(); + CHECK(document.model.content.spritesheets.front().path == "vector.svg"); + CHECK(document.texture_get(0)->is_vector()); + std::filesystem::remove_all(directory); } TEST_CASE("a Rebirth save flattens animation layers for the game") { - auto directory = std::filesystem::temp_directory_path() / "anm2ed_flatten"; - std::filesystem::remove_all(directory); - std::filesystem::create_directories(directory / "library"); - std::filesystem::copy_file(RENDER_TEST_DIR / "nested.anm2", directory / "nested.anm2"); - for (auto name : {"spin.anm2", "sheet.png"}) - std::filesystem::copy_file(RENDER_TEST_DIR / name, directory / "library" / name); - auto text = std::string{}; - { - std::ifstream file(directory / "nested.anm2"); - text.assign(std::istreambuf_iterator(file), {}); - } - text.replace(text.find("Path=\"spin.anm2\""), std::string("Path=\"spin.anm2\"").size(), "Path=\"library/spin.anm2\""); - std::ofstream(directory / "nested.anm2") << text; + auto directory = std::filesystem::temp_directory_path() / "anm2ed_flatten"; + std::filesystem::remove_all(directory); + std::filesystem::create_directories(directory / "library"); + std::filesystem::copy_file(RENDER_TEST_DIR / "nested.anm2", directory / "nested.anm2"); + for (auto name : {"spin.anm2", "sheet.png"}) + std::filesystem::copy_file(RENDER_TEST_DIR / name, directory / "library" / name); + auto text = std::string{}; + { + std::ifstream file(directory / "nested.anm2"); + text.assign(std::istreambuf_iterator(file), {}); + } + text.replace(text.find("Path=\"spin.anm2\""), std::string("Path=\"spin.anm2\"").size(), + "Path=\"library/spin.anm2\""); + std::ofstream(directory / "nested.anm2") << text; - Document document(directory / "nested.anm2", false); - REQUIRE(document.is_valid()); - REQUIRE(document.save(directory / "rebirth.anm2")); - std::ifstream file(directory / "rebirth.anm2"); - std::string saved(std::istreambuf_iterator(file), {}); - auto game = saved.substr(0, saved.find("(file), {}); + auto game = saved.substr(0, saved.find("(file), {}); - } - auto game = saved.substr(0, saved.find(" \n"; - CHECK(game.find("SkewX") == std::string::npos); - CHECK(game.find("Blur") == std::string::npos); - std::ofstream(directory / "game.anm2") << game; - Document gameDocument(directory / "game.anm2", false); - REQUIRE(gameDocument.is_valid()); - - auto& info = SHADERS[SHADER_TEXTURE]; - ShaderProgram shader(info.vertex, info.fragment); - Canvas canvas(glm::vec2(1.0f)); - for (int index = 0; index < document.model.animations_count_get(); ++index) - { - auto& animation = *document.model.animation_get(index); - auto& gameAnimation = *gameDocument.model.animation_get(index); - INFO("animation: ", animation.name); - // On whole pixels, so the baked images land on the pixels they were drawn on. - auto bounds = animation_bounds_get(document, animation, true); - bounds = glm::vec4(glm::floor(glm::vec2(bounds)) - 8.0f, glm::ceil(glm::vec2(bounds.z, bounds.w)) + 16.0f); - for (int time = 0; time < animation.frameNum; ++time) + Document document(directory / "bake.anm2", false); + REQUIRE(document.is_valid()); + REQUIRE(document.save(directory / "saved.anm2")); + CHECK(std::filesystem::exists(directory / "saved.baked.png")); + std::string saved; { - INFO("time: ", time); - auto expected = animation_frame_render(canvas, shader, document, animation, (float)time, bounds, 1.0f, - glm::vec4(0.0f), true); - auto actual = animation_frame_render(canvas, shader, gameDocument, gameAnimation, (float)time, bounds, - 1.0f, glm::vec4(0.0f), true); - REQUIRE(actual.size() == expected.size()); - CHECK(std::ranges::any_of(expected, [](uint8_t channel) { return channel != 0; })); - int mismatches = 0; - for (std::size_t i = 0; i < actual.size(); ++i) - mismatches += std::abs((int)actual[i] - (int)expected[i]) > CHANNEL_TOLERANCE; - CHECK((double)mismatches / (double)actual.size() <= MISMATCH_RATIO_MAX); + std::ifstream file(directory / "saved.anm2"); + saved.assign(std::istreambuf_iterator(file), {}); } - } + auto game = saved.substr(0, saved.find(" \n"; + CHECK(game.find("SkewX") == std::string::npos); + CHECK(game.find("Blur") == std::string::npos); + std::ofstream(directory / "game.anm2") << game; + Document gameDocument(directory / "game.anm2", false); + REQUIRE(gameDocument.is_valid()); - // Ignore and Save leaves them out: no baked layers or spritesheet. - document.model.info.isIsaacIgnored = true; - REQUIRE(document.save(directory / "ignored.anm2")); - CHECK_FALSE(std::filesystem::exists(directory / "ignored.baked.png")); - std::ifstream ignored(directory / "ignored.anm2"); - CHECK(std::string(std::istreambuf_iterator(ignored), {}).find("(baked)") == std::string::npos); - if (!std::getenv("ANM2ED_KEEP")) std::filesystem::remove_all(directory); + auto& info = SHADERS[SHADER_TEXTURE]; + ShaderProgram shader(info.vertex, info.fragment); + Canvas canvas(glm::vec2(1.0f)); + for (int index = 0; index < document.model.animations_count_get(); ++index) + { + auto& animation = *document.model.animation_get(index); + auto& gameAnimation = *gameDocument.model.animation_get(index); + INFO("animation: ", animation.name); + // On whole pixels, so the baked images land on the pixels they were drawn on. + auto bounds = animation_bounds_get(document, animation, true); + bounds = glm::vec4(glm::floor(glm::vec2(bounds)) - 8.0f, glm::ceil(glm::vec2(bounds.z, bounds.w)) + 16.0f); + for (int time = 0; time < animation.frameNum; ++time) + { + INFO("time: ", time); + auto expected = animation_frame_render(canvas, shader, document, animation, (float)time, bounds, 1.0f, + glm::vec4(0.0f), true); + auto actual = animation_frame_render(canvas, shader, gameDocument, gameAnimation, (float)time, bounds, 1.0f, + glm::vec4(0.0f), true); + REQUIRE(actual.size() == expected.size()); + CHECK(std::ranges::any_of(expected, [](uint8_t channel) { return channel != 0; })); + int mismatches = 0; + for (std::size_t i = 0; i < actual.size(); ++i) + mismatches += std::abs((int)actual[i] - (int)expected[i]) > CHANNEL_TOLERANCE; + CHECK((double)mismatches / (double)actual.size() <= MISMATCH_RATIO_MAX); + } + } + + // Ignore and Save leaves them out: no baked layers or spritesheet. + document.model.info.isIsaacIgnored = true; + REQUIRE(document.save(directory / "ignored.anm2")); + CHECK_FALSE(std::filesystem::exists(directory / "ignored.baked.png")); + std::ifstream ignored(directory / "ignored.anm2"); + CHECK(std::string(std::istreambuf_iterator(ignored), {}).find("(baked)") == std::string::npos); + if (!std::getenv("ANM2ED_KEEP")) + std::filesystem::remove_all(directory); } diff --git a/tests/roundtrip.cpp b/tests/roundtrip.cpp index 85dd834..31e11c1 100644 --- a/tests/roundtrip.cpp +++ b/tests/roundtrip.cpp @@ -2,12 +2,12 @@ TEST_CASE("fixtures match goldens") { - auto fixtures = fixtures_get(); - REQUIRE(!fixtures.empty()); - for (auto& fixture : fixtures) - { - auto anm2 = model_load(file_load(fixture)); - for (auto& [name, text] : variants_get(anm2)) - golden_check(GOLDEN_DIR / std::format("{}.{}.xml", fixture.stem().string(), name), text); - } + auto fixtures = fixtures_get(); + REQUIRE(!fixtures.empty()); + for (auto& fixture : fixtures) + { + auto anm2 = model_load(file_load(fixture)); + for (auto& [name, text] : variants_get(anm2)) + golden_check(GOLDEN_DIR / std::format("{}.{}.xml", fixture.stem().string(), name), text); + } } diff --git a/tests/selection.cpp b/tests/selection.cpp index 75cc404..304e1fe 100644 --- a/tests/selection.cpp +++ b/tests/selection.cpp @@ -3,110 +3,111 @@ #include "edit/edit.h" #include "selection.h" -static Model fixture_load_with_uids(const char* name) { return model_load(file_load(CORPUS_DIR / name)); } +static Model fixture_load_with_uids(const char* name) +{ + return model_load(file_load(CORPUS_DIR / name)); +} // Applies an edit and follows the selection through it, the way a commit does. void selection_edit(Model& anm2, Selection& selection, auto&& edit) { - auto before = selection_focus_get(selection, UidIndex(anm2)); - edit(); - anm2.uids_repair(); - selection_follow(selection, anm2, UidIndex(anm2), before); + auto before = selection_focus_get(selection, UidIndex(anm2)); + edit(); + anm2.uids_repair(); + selection_follow(selection, anm2, UidIndex(anm2), before); } TEST_CASE("uids are unique and non-zero after load") { - for (auto& fixture : fixtures_get()) - { - auto anm2 = model_load(file_load(fixture)); - std::set uids; - bool isUnique = true; - for (auto [index, animation] : anm2.animations_get()) - animation_tracks_each(*animation, - [&](const Track& track) - { - isUnique &= uids.insert(track.uid).second; - for (auto& frame : track.frames) - isUnique &= uids.insert(frame.uid).second; - }); - INFO("fixture: ", fixture.filename().string()); - CHECK(isUnique); - } + for (auto& fixture : fixtures_get()) + { + auto anm2 = model_load(file_load(fixture)); + std::set uids; + bool isUnique = true; + for (auto [index, animation] : anm2.animations_get()) + animation_tracks_each(*animation, [&](const Track& track) { + isUnique &= uids.insert(track.uid).second; + for (auto& frame : track.frames) + isUnique &= uids.insert(frame.uid).second; + }); + INFO("fixture: ", fixture.filename().string()); + CHECK(isUnique); + } } TEST_CASE("selected frames and focus follow inserts and moves") { - auto anm2 = fixture_load_with_uids("02_items.anm2"); - Selection selection = {}; - selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}, {0, LAYER, 1, 0}}); - selection_focus_set(selection, anm2, {0, LAYER, 0, 1}); + auto anm2 = fixture_load_with_uids("02_items.anm2"); + Selection selection = {}; + selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}, {0, LAYER, 1, 0}}); + selection_focus_set(selection, anm2, {0, LAYER, 0, 1}); - selection_edit(anm2, selection, [&] { frame_insert(anm2, {0, LAYER, 0, -1}, 0); }); - selection_edit(anm2, selection, [&] { frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}); }); + selection_edit(anm2, selection, [&] { frame_insert(anm2, {0, LAYER, 0, -1}, 0); }); + selection_edit(anm2, selection, [&] { frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}); }); - UidIndex index(anm2); - CHECK(selection_focus_get(selection, index) == Reference{0, LAYER, 0, 0}); - CHECK(selection_references_get(selection, index, SelectionKind::FRAMES) == - std::set{{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}); + UidIndex index(anm2); + CHECK(selection_focus_get(selection, index) == Reference{0, LAYER, 0, 0}); + CHECK(selection_references_get(selection, index, SelectionKind::FRAMES) == + std::set{{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}); } TEST_CASE("a removed focus falls back to its nearest survivor") { - auto anm2 = fixture_load_with_uids("02_items.anm2"); - Selection selection = {}; - selection_focus_set(selection, anm2, {0, LAYER, 0, 1}); - selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}}); + auto anm2 = fixture_load_with_uids("02_items.anm2"); + Selection selection = {}; + selection_focus_set(selection, anm2, {0, LAYER, 0, 1}); + selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}}); - selection_edit(anm2, selection, [&] { frames_delete(anm2, {{0, LAYER, 0, 1}}); }); - CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, LAYER, 0, 0}); - CHECK(selection.uids[SelectionKind::FRAMES].empty()); + selection_edit(anm2, selection, [&] { frames_delete(anm2, {{0, LAYER, 0, 1}}); }); + CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, LAYER, 0, 0}); + CHECK(selection.uids[SelectionKind::FRAMES].empty()); - selection_edit(anm2, selection, [&] { items_remove(anm2, 0, {{LAYER, {0}}}, {}); }); - CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT}); + selection_edit(anm2, selection, [&] { items_remove(anm2, 0, {{LAYER, {0}}}, {}); }); + CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT}); - selection_focus_set(selection, anm2, {1, ROOT, -1, 0}); - selection_edit(anm2, selection, [&] { animations_remove(anm2, {1}, {}); }); - CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT}); + selection_focus_set(selection, anm2, {1, ROOT, -1, 0}); + selection_edit(anm2, selection, [&] { animations_remove(anm2, {1}, {}); }); + CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT}); } TEST_CASE("track and group selection follow regrouping") { - auto anm2 = fixture_load_with_uids("03a_groups_nested.anm2"); - const TrackGroup* group = nullptr; - groups_each(anm2.animation_get(0)->layers, [&](const TrackGroup& candidate) { group = &candidate; }); - REQUIRE(group); - auto groupId = group->id; - Selection selection = {}; - selection_references_set(selection, anm2, SelectionKind::TRACKS, {{0, LAYER, 0, -1, LAYER, groupId}}); - selection_references_set(selection, anm2, SelectionKind::GROUPS, {{0, LAYER, groupId}}); + auto anm2 = fixture_load_with_uids("03a_groups_nested.anm2"); + const TrackGroup* group = nullptr; + groups_each(anm2.animation_get(0)->layers, [&](const TrackGroup& candidate) { group = &candidate; }); + REQUIRE(group); + auto groupId = group->id; + Selection selection = {}; + selection_references_set(selection, anm2, SelectionKind::TRACKS, {{0, LAYER, 0, -1, LAYER, groupId}}); + selection_references_set(selection, anm2, SelectionKind::GROUPS, {{0, LAYER, groupId}}); - selection_edit(anm2, selection, - [&] { items_move(anm2, 0, LAYER, {0}, {}, {false, LAYER, 2, -1}, false, false); }); + selection_edit(anm2, selection, [&] { items_move(anm2, 0, LAYER, {0}, {}, {false, LAYER, 2, -1}, false, false); }); - UidIndex index(anm2); - CHECK(selection_references_get(selection, index, SelectionKind::TRACKS) == std::set{{0, LAYER, 0}}); - CHECK(selection_references_get(selection, index, SelectionKind::GROUPS) == std::set{{0, LAYER, groupId}}); + UidIndex index(anm2); + CHECK(selection_references_get(selection, index, SelectionKind::TRACKS) == std::set{{0, LAYER, 0}}); + CHECK(selection_references_get(selection, index, SelectionKind::GROUPS) == + std::set{{0, LAYER, groupId}}); } TEST_CASE("content selection follows items, and regions follow the focused spritesheet") { - auto anm2 = fixture_load_with_uids("05_regions.anm2"); - Selection selection = {}; - auto& regions = item_get(anm2.content.spritesheets, 0)->regions; - REQUIRE(regions.size() > 1); - auto regionId = regions[1].id; + auto anm2 = fixture_load_with_uids("05_regions.anm2"); + Selection selection = {}; + auto& regions = item_get(anm2.content.spritesheets, 0)->regions; + REQUIRE(regions.size() > 1); + auto regionId = regions[1].id; - selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId}); - CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty()); + selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId}); + CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty()); - selection_focus_id_set(selection, anm2, SelectionKind::SPRITESHEETS, 0); - selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId}); - selection_focus_id_set(selection, anm2, SelectionKind::REGIONS, regionId); - regions.erase(regions.begin()); - CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS) == std::set{regionId}); - CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == regionId); + selection_focus_id_set(selection, anm2, SelectionKind::SPRITESHEETS, 0); + selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId}); + selection_focus_id_set(selection, anm2, SelectionKind::REGIONS, regionId); + regions.erase(regions.begin()); + CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS) == std::set{regionId}); + CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == regionId); - std::erase_if(regions, [&](const Region& region) { return region.id == regionId; }); - CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty()); - CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == -1); + std::erase_if(regions, [&](const Region& region) { return region.id == regionId; }); + CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty()); + CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == -1); } diff --git a/tests/undo.cpp b/tests/undo.cpp index 14381c8..67493e7 100644 --- a/tests/undo.cpp +++ b/tests/undo.cpp @@ -11,124 +11,129 @@ constexpr int UNDO_LIMIT = 1000; static std::vector references_all_get(const Model& anm2, bool isFrames) { - UidIndex index(anm2); - std::vector result; - auto add = [&](std::uint64_t uid) - { - auto reference = index.reference_get(uid); - if (!reference || reference->itemType == NONE || reference->itemType == TRIGGER) return; - if (isFrames == (reference->frameIndex >= 0)) result.push_back(*reference); - }; - for (auto [i, animation] : anm2.animations_get()) - animation_tracks_each(*animation, - [&](const Track& track) - { - add(track.uid); - for (auto& frame : track.frames) - add(frame.uid); - }); - return result; + UidIndex index(anm2); + std::vector result; + auto add = [&](std::uint64_t uid) { + auto reference = index.reference_get(uid); + if (!reference || reference->itemType == NONE || reference->itemType == TRIGGER) + return; + if (isFrames == (reference->frameIndex >= 0)) + result.push_back(*reference); + }; + for (auto [i, animation] : anm2.animations_get()) + animation_tracks_each(*animation, [&](const Track& track) { + add(track.uid); + for (auto& frame : track.frames) + add(frame.uid); + }); + return result; } -// One random edit on randomly chosen live elements; returns false when nothing applicable exists. +// One random edit on randomly chosen live elements. Returns false when nothing applicable exists. static bool edit_random_apply(Model& anm2, std::mt19937& random) { - auto frames = references_all_get(anm2, true); - auto tracks = references_all_get(anm2, false); - if (frames.empty() || tracks.empty()) return false; - auto pick = [&](const auto& items) - { return items[std::uniform_int_distribution(0, (int)items.size() - 1)(random)]; }; - auto frame = pick(frames); - auto other = pick(frames); + auto frames = references_all_get(anm2, true); + auto tracks = references_all_get(anm2, false); + if (frames.empty() || tracks.empty()) + return false; + auto pick = [&](const auto& items) { + return items[std::uniform_int_distribution(0, (int)items.size() - 1)(random)]; + }; + auto frame = pick(frames); + auto other = pick(frames); - switch (std::uniform_int_distribution(0, 8)(random)) - { - case 0: - frame_insert(anm2, frame, 0); - break; - case 1: - if (frames.size() > 4) frames_delete(anm2, {frame, other}); - break; - case 2: - frames_duplicate(anm2, {frame, other}, frame); - break; - case 3: - frames_reverse(anm2, {frame, other}); - break; - case 4: - frames_bake(anm2, {frame}, 1, false, false); - break; - case 5: - frame_split(anm2, frame, 1); - break; - case 6: - if (frame.itemType != ROOT) frames_move(anm2, {frame}, pick(tracks), 0); - break; - case 7: - animation_add(anm2, 0, -1, frame.animationIndex, "Walk"); - break; - default: - animations_move(anm2, {frame.animationIndex}, {}, {.animationIndex = 0}); - break; - } - return true; + switch (std::uniform_int_distribution(0, 8)(random)) + { + case 0: + frame_insert(anm2, frame, 0); + break; + case 1: + if (frames.size() > 4) + frames_delete(anm2, {frame, other}); + break; + case 2: + frames_duplicate(anm2, {frame, other}, frame); + break; + case 3: + frames_reverse(anm2, {frame, other}); + break; + case 4: + frames_bake(anm2, {frame}, 1, false, false); + break; + case 5: + frame_split(anm2, frame, 1); + break; + case 6: + if (frame.itemType != ROOT) + frames_move(anm2, {frame}, pick(tracks), 0); + break; + case 7: + animation_add(anm2, 0, -1, frame.animationIndex, "Walk"); + break; + default: + animations_move(anm2, {frame.animationIndex}, {}, {.animationIndex = 0}); + break; + } + return true; } TEST_CASE("undo and redo restore every state of a random edit walk") { - SnapshotStack::max_size_set(UNDO_LIMIT); - for (auto name : - {"02_items.anm2", "03a_groups_nested.anm2", "04_group_root_transform.anm2", "07_special_interpolation.anm2"}) - { - INFO("fixture: ", name); - Snapshots snapshots = {}; - snapshots.current.model = model_load(file_load(CORPUS_DIR / name)); - std::mt19937 random(WALK_SEED); - - std::vector hashes{model_hash(snapshots.current.model)}; - for (int step = 0; step < WALK_STEPS; ++step) + SnapshotStack::max_size_set(UNDO_LIMIT); + for (auto name : + {"02_items.anm2", "03a_groups_nested.anm2", "04_group_root_transform.anm2", "07_special_interpolation.anm2"}) { - snapshots.push("Edit"); - if (!edit_random_apply(snapshots.current.model, random)) break; - auto count = snapshots.undoStack.size(); - snapshots.commit(); - if (snapshots.undoStack.size() != count) hashes.push_back(model_hash(snapshots.current.model)); - } - REQUIRE(hashes.size() > 1); + INFO("fixture: ", name); + Snapshots snapshots = {}; + snapshots.current.model = model_load(file_load(CORPUS_DIR / name)); + std::mt19937 random(WALK_SEED); - for (auto it = hashes.rbegin() + 1; it != hashes.rend(); ++it) - { - REQUIRE(snapshots.undo()); - CHECK(model_hash(snapshots.current.model) == *it); - } - CHECK_FALSE(snapshots.undo()); + std::vector hashes{model_hash(snapshots.current.model)}; + for (int step = 0; step < WALK_STEPS; ++step) + { + snapshots.push("Edit"); + if (!edit_random_apply(snapshots.current.model, random)) + break; + auto count = snapshots.undoStack.size(); + snapshots.commit(); + if (snapshots.undoStack.size() != count) + hashes.push_back(model_hash(snapshots.current.model)); + } + REQUIRE(hashes.size() > 1); - for (auto it = hashes.begin() + 1; it != hashes.end(); ++it) - { - REQUIRE(snapshots.redo()); - CHECK(model_hash(snapshots.current.model) == *it); + for (auto it = hashes.rbegin() + 1; it != hashes.rend(); ++it) + { + REQUIRE(snapshots.undo()); + CHECK(model_hash(snapshots.current.model) == *it); + } + CHECK_FALSE(snapshots.undo()); + + for (auto it = hashes.begin() + 1; it != hashes.end(); ++it) + { + REQUIRE(snapshots.redo()); + CHECK(model_hash(snapshots.current.model) == *it); + } } - } } TEST_CASE("selection follows its frame through an edit and its undo") { - Snapshots snapshots = {}; - auto& current = snapshots.current; - current.model = model_load(file_load(CORPUS_DIR / "02_items.anm2")); - selection_focus_set(current.selection, current.model, {0, LAYER, 0, 1}); - selection_references_set(current.selection, current.model, SelectionKind::FRAMES, {{0, LAYER, 0, 1}}); + Snapshots snapshots = {}; + auto& current = snapshots.current; + current.model = model_load(file_load(CORPUS_DIR / "02_items.anm2")); + selection_focus_set(current.selection, current.model, {0, LAYER, 0, 1}); + selection_references_set(current.selection, current.model, SelectionKind::FRAMES, {{0, LAYER, 0, 1}}); - snapshots.push("Insert"); - frame_insert(current.model, {0, LAYER, 0, -1}, 0); - auto& track = *current.model.track_edit(Reference{0, LAYER, 0}); - std::rotate(track.frames.begin(), track.frames.end() - 1, track.frames.end()); - snapshots.commit(); - UidIndex index(current.model); - CHECK(selection_focus_get(current.selection, index) == Reference{0, LAYER, 0, 2}); - CHECK(selection_references_get(current.selection, index, SelectionKind::FRAMES) == - std::set{{0, LAYER, 0, 2}}); + snapshots.push("Insert"); + frame_insert(current.model, {0, LAYER, 0, -1}, 0); + auto& track = *current.model.track_edit(Reference{0, LAYER, 0}); + std::rotate(track.frames.begin(), track.frames.end() - 1, track.frames.end()); + snapshots.commit(); + UidIndex index(current.model); + CHECK(selection_focus_get(current.selection, index) == Reference{0, LAYER, 0, 2}); + CHECK(selection_references_get(current.selection, index, SelectionKind::FRAMES) == + std::set{{0, LAYER, 0, 2}}); - REQUIRE(snapshots.undo()); - CHECK(selection_focus_get(current.selection, UidIndex(current.model)) == Reference{0, LAYER, 0, 1}); + REQUIRE(snapshots.undo()); + CHECK(selection_focus_get(current.selection, UidIndex(current.model)) == Reference{0, LAYER, 0, 1}); }