Canvas windows, settings and manager: share view code and list I/O

- CanvasView base holds checker pan sync, zoom step, grid panel, view buttons and view context menu
- frame_parent_model_get replaces five root/group transform compositions
- Canvas builds VAOs through one helper, unifies uniform setters and frees the texture VAO/VBO/EBO (leak fix)
- Settings load/save loop over component suffix tables; unused settings Type enum removed
- Manager shares one path-list load/save for recent and autosave files
- Anonymous namespaces removed per project style

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-03 13:50:13 -04:00
1 parent a4638a422d
commit ec72a30ce0
16 files changed
+558 -814

No files matched your search

+3 -6
View File
@@ -43,8 +43,7 @@ namespace anm2ed
if (isRootTransform && root)
{
auto rootFrame = frame_generate(*root, t);
transform *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale),
rootFrame.rotation, math::percent_to_unit(rootFrame.shear));
transform *= frame_parent_model_get(rootFrame);
}
auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS);
@@ -61,9 +60,7 @@ namespace anm2ed
if (auto groupRoot = child_first_get(*group, ElementType::ROOT_ANIMATION))
{
auto groupRootFrame = frame_generate(*groupRoot, t);
itemTransform *= math::quad_model_parent_get(
groupRootFrame.position, {}, math::percent_to_unit(groupRootFrame.scale),
groupRootFrame.rotation, math::percent_to_unit(groupRootFrame.shear));
itemTransform *= frame_parent_model_get(groupRootFrame);
}
auto frame = frame_effective(layerAnimation.layerId, frame_generate(layerAnimation, t));
@@ -90,7 +87,7 @@ namespace anm2ed
}
int Anm2::item_add(ItemType type, int animationIndex, const Element& item, int insertBeforeId,
types::destination::Type destination)
types::destination::Type destination)
{
auto row = track_container_get(type);
auto elements = row ? element_get(row->elements) : nullptr;
+1
View File
@@ -523,6 +523,7 @@ namespace anm2ed
float interpolation_factor(Interpolation, float);
void frame_mix(Element&, const Element&, float);
Element frame_generate(const Element&, float);
glm::mat4 frame_parent_model_get(const Element&);
int frame_index_from_at_frame_get(const Element&, int);
int frame_index_from_time_get(const Element&, float);
float frame_time_from_index_get(const Element&, int);
+6
View File
@@ -40,6 +40,12 @@ namespace anm2ed
return frames;
}
glm::mat4 frame_parent_model_get(const Element& frame)
{
return math::quad_model_parent_get(frame.position, {}, math::percent_to_unit(frame.scale), frame.rotation,
math::percent_to_unit(frame.shear));
}
Element frame_generate(const Element& track, float time)
{
auto frame = element_make(track_frame_type_get(track));
+80 -168
View File
@@ -25,86 +25,51 @@ namespace anm2ed
glEnable(GL_BLEND);
}
void vertex_array_make(GLuint& vao, GLuint& vbo, const void* data, GLsizeiptr size, GLenum usage,
std::initializer_list<int> attributeSizes)
{
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, size, data, usage);
auto stride = 0;
for (auto attributeSize : attributeSizes)
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;
}
}
Canvas::Canvas() = default;
Canvas::Canvas(vec2 size)
{
Framebuffer::size_set(size);
// Axis
glGenVertexArrays(1, &axisVAO);
glGenBuffers(1, &axisVBO);
glBindVertexArray(axisVAO);
glBindBuffer(GL_ARRAY_BUFFER, axisVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(AXIS_VERTICES), AXIS_VERTICES, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
// Grid
glGenVertexArrays(1, &gridVAO);
glBindVertexArray(gridVAO);
glGenBuffers(1, &gridVBO);
glBindBuffer(GL_ARRAY_BUFFER, gridVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(GRID_VERTICES), GRID_VERTICES, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, (void*)(sizeof(float) * 2));
glBindVertexArray(0);
// Rect
glGenVertexArrays(1, &rectVAO);
glGenBuffers(1, &rectVBO);
glBindVertexArray(rectVAO);
glBindBuffer(GL_ARRAY_BUFFER, rectVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(RECT_VERTICES), RECT_VERTICES, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
// Texture
glGenVertexArrays(1, &textureVAO);
glGenBuffers(1, &textureVBO);
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});
vertex_array_make(rectVAO, rectVBO, RECT_VERTICES, sizeof(RECT_VERTICES), GL_STATIC_DRAW, {2});
vertex_array_make(textureVAO, textureVBO, nullptr, sizeof(TEXTURE_VERTICES), GL_DYNAMIC_DRAW, {2, 2});
glGenBuffers(1, &textureEBO);
glBindVertexArray(textureVAO);
glBindBuffer(GL_ARRAY_BUFFER, textureVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * 4, nullptr, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, textureEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(TEXTURE_INDICES), TEXTURE_INDICES, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
glBindVertexArray(0);
}
Canvas::~Canvas()
{
if (!Framebuffer::is_valid()) return;
glDeleteVertexArrays(1, &axisVAO);
glDeleteBuffers(1, &axisVBO);
glDeleteVertexArrays(1, &gridVAO);
glDeleteBuffers(1, &gridVBO);
glDeleteVertexArrays(1, &rectVAO);
glDeleteBuffers(1, &rectVBO);
for (auto vao : {axisVAO, gridVAO, rectVAO, textureVAO})
glDeleteVertexArrays(1, &vao);
for (auto buffer : {axisVBO, gridVBO, rectVBO, textureVBO, textureEBO})
glDeleteBuffers(1, &buffer);
}
mat4 Canvas::transform_get(float zoom, vec2 pan) const
@@ -165,68 +130,30 @@ namespace anm2ed
canvas_blend_straight_set();
}
void texture_uniform_vec4_set(const shader::Uniform& uniform, vec4 value)
void texture_uniform_set(const shader::Uniform& uniform, vec4 value)
{
if (uniform.location == -1) return;
switch (uniform.valueType)
if (uniform.valueType == shader::UNIFORM_VALUE_INT || uniform.valueType == shader::UNIFORM_VALUE_SAMPLER2D)
return glUniform1i(uniform.location, uniform.intValue);
switch (shader::UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount)
{
case shader::UNIFORM_VALUE_FLOAT:
glUniform1f(uniform.location, value.x);
break;
case shader::UNIFORM_VALUE_VEC2:
glUniform2fv(uniform.location, 1, value_ptr(value));
break;
case shader::UNIFORM_VALUE_VEC3:
glUniform3fv(uniform.location, 1, value_ptr(value));
break;
case shader::UNIFORM_VALUE_VEC4:
glUniform4fv(uniform.location, 1, value_ptr(value));
break;
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:
break;
if (uniform.valueType == shader::UNIFORM_VALUE_FLOAT) glUniform1f(uniform.location, value.x);
}
}
void texture_uniform_manual_set(const shader::Uniform& uniform)
vec4 texture_uniform_components_get(const shader::Uniform& uniform, float playbackTime)
{
if (uniform.location == -1) return;
switch (uniform.valueType)
{
case shader::UNIFORM_VALUE_FLOAT:
glUniform1f(uniform.location, uniform.value.x);
break;
case shader::UNIFORM_VALUE_INT:
case shader::UNIFORM_VALUE_SAMPLER2D:
glUniform1i(uniform.location, uniform.intValue);
break;
case shader::UNIFORM_VALUE_VEC2:
glUniform2fv(uniform.location, 1, value_ptr(uniform.value));
break;
case shader::UNIFORM_VALUE_VEC3:
glUniform3fv(uniform.location, 1, value_ptr(uniform.value));
break;
case shader::UNIFORM_VALUE_VEC4:
glUniform4fv(uniform.location, 1, value_ptr(uniform.value));
break;
default:
break;
}
}
float texture_uniform_component_value_get(const shader::Uniform::Component& component, float playbackTime)
{
if (component.binding == shader::UNIFORM_BINDING_PLAYBACK_TIME) return playbackTime;
return component.value;
}
vec4 texture_uniform_component_vec4_get(const shader::Uniform& uniform, float playbackTime)
{
return {texture_uniform_component_value_get(uniform.components[0], playbackTime),
texture_uniform_component_value_get(uniform.components[1], playbackTime),
texture_uniform_component_value_get(uniform.components[2], playbackTime),
texture_uniform_component_value_get(uniform.components[3], playbackTime)};
vec4 result{};
for (int i = 0; i < (int)uniform.components.size(); ++i)
result[i] = uniform.components[i].binding == shader::UNIFORM_BINDING_PLAYBACK_TIME ? playbackTime
: uniform.components[i].value;
return result;
}
void texture_uniforms_set(Shader& shader, mat4 transform, vec4 tint, vec3 colorOffset, vec2 textureSize,
@@ -255,22 +182,22 @@ namespace anm2ed
glUniformMatrix4fv(uniform.location, 1, GL_FALSE, value_ptr(transform));
break;
case shader::UNIFORM_BINDING_FRAME_TINT:
texture_uniform_vec4_set(uniform, tint);
texture_uniform_set(uniform, tint);
break;
case shader::UNIFORM_BINDING_COLOR_OFFSET:
texture_uniform_vec4_set(uniform, vec4(colorOffset, 0.0f));
texture_uniform_set(uniform, vec4(colorOffset, 0.0f));
break;
case shader::UNIFORM_BINDING_TEXTURE_SIZE:
texture_uniform_vec4_set(uniform, vec4(textureSize, 0.0f, 0.0f));
texture_uniform_set(uniform, vec4(textureSize, 0.0f, 0.0f));
break;
case shader::UNIFORM_BINDING_PLAYBACK_TIME:
texture_uniform_vec4_set(uniform, vec4(playbackTime));
texture_uniform_set(uniform, vec4(playbackTime));
break;
case shader::UNIFORM_BINDING_COMPONENTS:
texture_uniform_vec4_set(uniform, texture_uniform_component_vec4_get(uniform, playbackTime));
texture_uniform_set(uniform, texture_uniform_components_get(uniform, playbackTime));
break;
case shader::UNIFORM_BINDING_MANUAL:
texture_uniform_manual_set(uniform);
texture_uniform_set(uniform, uniform.value);
break;
default:
break;
@@ -306,62 +233,47 @@ namespace anm2ed
canvas_blend_straight_set();
}
void Canvas::rect_render(Shader& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength,
float dashGap, float dashOffset) const
void rect_begin(Shader& shader, const mat4& transform, const mat4& model, vec4 color)
{
canvas_blend_premultiplied_set();
glUseProgram(shader.id);
glUniformMatrix4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform));
if (auto location = glGetUniformLocation(shader.id, shader::UNIFORM_MODEL); location != -1)
glUniformMatrix4fv(location, 1, GL_FALSE, value_ptr(model));
glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_COLOR), 1, value_ptr(color));
}
auto origin = model * vec4(0.0f, 0.0f, 0.0f, 1.0f);
auto edgeX = model * vec4(1.0f, 0.0f, 0.0f, 1.0f);
auto edgeY = model * vec4(0.0f, 1.0f, 0.0f, 1.0f);
auto axisX = vec2(edgeX - origin);
auto axisY = vec2(edgeY - origin);
if (auto location = glGetUniformLocation(shader.id, shader::UNIFORM_AXIS_X); location != -1)
glUniform2fv(location, 1, value_ptr(axisX));
if (auto location = glGetUniformLocation(shader.id, shader::UNIFORM_AXIS_Y); location != -1)
glUniform2fv(location, 1, value_ptr(axisY));
if (auto location = glGetUniformLocation(shader.id, shader::UNIFORM_DASH_LENGTH); location != -1)
glUniform1f(location, dashLength);
if (auto location = glGetUniformLocation(shader.id, shader::UNIFORM_DASH_GAP); location != -1)
glUniform1f(location, dashGap);
if (auto location = glGetUniformLocation(shader.id, shader::UNIFORM_DASH_OFFSET); location != -1)
glUniform1f(location, dashOffset);
glBindVertexArray(rectVAO);
glDrawArrays(GL_LINE_LOOP, 0, 4);
void rect_end(GLuint vao, GLenum mode)
{
glBindVertexArray(vao);
glDrawArrays(mode, 0, 4);
glBindVertexArray(0);
glUseProgram(0);
canvas_blend_straight_set();
}
void Canvas::rect_render(Shader& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength,
float dashGap, float dashOffset) 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{shader::UNIFORM_AXIS_X, vec4(1.0f, 0.0f, 0.0f, 1.0f)},
std::pair{shader::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{shader::UNIFORM_DASH_LENGTH, dashLength}, std::pair{shader::UNIFORM_DASH_GAP, dashGap},
std::pair{shader::UNIFORM_DASH_OFFSET, dashOffset}})
if (auto location = glGetUniformLocation(shader.id, name); location != -1) glUniform1f(location, value);
rect_end(rectVAO, GL_LINE_LOOP);
}
void Canvas::rect_fill_render(Shader& shader, const mat4& transform, const mat4& model, vec4 color) const
{
canvas_blend_premultiplied_set();
glUseProgram(shader.id);
glUniformMatrix4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform));
if (auto location = glGetUniformLocation(shader.id, shader::UNIFORM_MODEL); location != -1)
glUniformMatrix4fv(location, 1, GL_FALSE, value_ptr(model));
glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_COLOR), 1, value_ptr(color));
glBindVertexArray(rectVAO);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glBindVertexArray(0);
glUseProgram(0);
canvas_blend_straight_set();
rect_begin(shader, transform, model, color);
rect_end(rectVAO, GL_TRIANGLE_FAN);
}
float Canvas::zoom_level_get(float zoom, int levelDelta) const
+209 -296
View File
@@ -42,225 +42,218 @@ namespace anm2ed::imgui
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);
namespace
struct OverlayAnimationOption
{
struct OverlayAnimationOption
uint64_t documentId{};
int animationIndex{-1};
std::string label{};
};
std::vector<OverlayAnimationOption> overlay_animation_options_get(Manager& manager)
{
std::vector<OverlayAnimationOption> options{{.label = std::string(localize.get(BASIC_NONE))}};
for (auto& document : manager.documents)
{
uint64_t documentId{};
int animationIndex{-1};
std::string label{};
};
std::vector<OverlayAnimationOption> overlay_animation_options_get(Manager& manager)
{
std::vector<OverlayAnimationOption> options{{.label = std::string(localize.get(BASIC_NONE))}};
for (auto& document : manager.documents)
{
auto documentLabel = path::to_utf8(document.filename_get());
int animationIndex{};
if (auto animations = document.anm2.element_get(ElementType::ANIMATIONS))
for (auto& animation : animations->children)
{
if (animation.type != ElementType::ANIMATION) continue;
auto label = std::format("{} ({})", animation.name, documentLabel);
options.push_back({.documentId = document.tabId, .animationIndex = animationIndex, .label = label});
++animationIndex;
}
}
return options;
}
std::vector<const char*> overlay_animation_option_labels_get(std::vector<OverlayAnimationOption>& options)
{
std::vector<const char*> labels{};
labels.reserve(options.size());
for (auto& option : options)
labels.push_back(option.label.c_str());
return labels;
}
int overlay_animation_option_index_get(const Document& document, const std::vector<OverlayAnimationOption>& 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;
return -1;
}
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;
return nullptr;
}
std::optional<vec4> animation_rects_merge(std::optional<vec4> 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);
}
std::optional<vec4> animation_render_rect_get(Manager& manager, Document& document, Element* animation,
bool isRootTransform)
{
std::optional<vec4> rect{};
if (animation) rect = animation_rects_merge(rect, document.anm2.animation_rect(*animation, isRootTransform));
if (auto overlayDocument = overlay_animation_document_get(manager, document))
if (auto overlayAnimation = overlayDocument->anm2.element_get(ElementType::ANIMATION, document.overlayIndex))
rect = animation_rects_merge(rect, overlayDocument->anm2.animation_rect(*overlayAnimation, isRootTransform));
return rect;
}
std::filesystem::path render_destination_directory(const std::filesystem::path& path, int type)
{
if (type == render::PNGS) return path;
auto directory = path.parent_path();
if (directory.empty()) directory = std::filesystem::current_path();
return directory;
}
std::filesystem::path render_frame_filename(const std::filesystem::path& format, int index, int type)
{
if (type != render::PNGS) return path::from_utf8(std::format("frame_{:06}.png", index));
auto formatString = path::to_utf8(format);
try
{
auto name = std::vformat(formatString, std::make_format_args(index));
auto filename = path::from_utf8(name).filename();
if (filename.empty()) return path::from_utf8(std::format("frame_{:06}.png", index));
if (filename.extension().empty()) filename.replace_extension(render::EXTENSIONS[render::SPRITESHEET]);
return filename;
}
catch (...)
{
return path::from_utf8(std::format("frame_{:06}.png", index));
}
}
std::filesystem::path render_temp_directory_create(const std::filesystem::path& directory)
{
auto timestamp = (uint64_t)std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
for (int suffix = 0; suffix < 1000; ++suffix)
{
auto tempDirectory = directory / path::from_utf8(std::format(".anm2ed_render_tmp_{}_{}", timestamp, suffix));
std::error_code ec;
if (std::filesystem::create_directories(tempDirectory, ec)) return tempDirectory;
}
return {};
}
void render_temp_cleanup(std::filesystem::path& directory, std::vector<std::filesystem::path>& frames)
{
std::error_code ec;
if (!directory.empty()) std::filesystem::remove_all(directory, ec);
directory.clear();
frames.clear();
}
void pixels_unpremultiply_alpha(std::vector<uint8_t>& pixels)
{
for (size_t index = 0; index + 3 < pixels.size(); index += 4)
{
auto alpha = pixels[index + 3];
if (alpha == 0)
auto documentLabel = path::to_utf8(document.filename_get());
int animationIndex{};
if (auto animations = document.anm2.element_get(ElementType::ANIMATIONS))
for (auto& animation : animations->children)
{
pixels[index + 0] = 0;
pixels[index + 1] = 0;
pixels[index + 2] = 0;
continue;
if (animation.type != ElementType::ANIMATION) continue;
auto label = std::format("{} ({})", animation.name, documentLabel);
options.push_back({.documentId = document.tabId, .animationIndex = animationIndex, .label = label});
++animationIndex;
}
if (alpha == 255) continue;
float alphaUnit = (float)alpha / 255.0f;
pixels[index + 0] = (uint8_t)glm::clamp((float)std::round((float)pixels[index + 0] / alphaUnit), 0.0f, 255.0f);
pixels[index + 1] = (uint8_t)glm::clamp((float)std::round((float)pixels[index + 1] / alphaUnit), 0.0f, 255.0f);
pixels[index + 2] = (uint8_t)glm::clamp((float)std::round((float)pixels[index + 2] / alphaUnit), 0.0f, 255.0f);
}
}
int trigger_sound_id_get(Document& document, Element* animation, float time, int deterministicIndex = -1)
return options;
}
std::vector<const char*> overlay_animation_option_labels_get(std::vector<OverlayAnimationOption>& options)
{
std::vector<const char*> labels{};
labels.reserve(options.size());
for (auto& option : options)
labels.push_back(option.label.c_str());
return labels;
}
int overlay_animation_option_index_get(const Document& document, const std::vector<OverlayAnimationOption>& 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;
return -1;
}
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;
return nullptr;
}
std::optional<vec4> animation_rects_merge(std::optional<vec4> 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);
}
std::optional<vec4> animation_render_rect_get(Manager& manager, Document& document, Element* animation,
bool isRootTransform)
{
std::optional<vec4> rect{};
if (animation) rect = animation_rects_merge(rect, document.anm2.animation_rect(*animation, isRootTransform));
if (auto overlayDocument = overlay_animation_document_get(manager, document))
if (auto overlayAnimation = overlayDocument->anm2.element_get(ElementType::ANIMATION, document.overlayIndex))
rect = animation_rects_merge(rect, overlayDocument->anm2.animation_rect(*overlayAnimation, isRootTransform));
return rect;
}
std::filesystem::path render_destination_directory(const std::filesystem::path& path, int type)
{
if (type == render::PNGS) return path;
auto directory = path.parent_path();
if (directory.empty()) directory = std::filesystem::current_path();
return directory;
}
std::filesystem::path render_frame_filename(const std::filesystem::path& format, int index, int type)
{
if (type != render::PNGS) return path::from_utf8(std::format("frame_{:06}.png", index));
auto formatString = path::to_utf8(format);
try
{
if (!animation) return -1;
auto triggers = animation_item_get(*animation, ItemType::TRIGGER);
if (!triggers || !triggers->isVisible) return -1;
auto trigger = frame_generate(*triggers, time);
if (!trigger.isVisible || trigger.soundIds.empty()) return -1;
size_t soundIndex{};
if (trigger.soundIds.size() > 1)
soundIndex = deterministicIndex >= 0 ? (size_t)deterministicIndex % trigger.soundIds.size()
: (size_t)math::random_in_range(0.0f, (float)trigger.soundIds.size());
soundIndex = std::min(soundIndex, trigger.soundIds.size() - 1);
auto soundID = trigger.soundIds[soundIndex];
return document.sound_get(soundID) ? soundID : -1;
auto name = std::vformat(formatString, std::make_format_args(index));
auto filename = path::from_utf8(name).filename();
if (filename.empty()) return path::from_utf8(std::format("frame_{:06}.png", index));
if (filename.extension().empty()) filename.replace_extension(render::EXTENSIONS[render::SPRITESHEET]);
return filename;
}
bool render_audio_stream_generate(AudioStream& audioStream, std::map<int, Audio>& sounds,
const std::vector<int>& frameSoundIDs, int fps)
catch (...)
{
audioStream.stream.clear();
if (frameSoundIDs.empty() || fps <= 0) return true;
SDL_AudioSpec mixSpec = audioStream.spec;
mixSpec.format = SDL_AUDIO_F32;
auto* mixer = MIX_CreateMixer(&mixSpec);
if (!mixer) return false;
auto channels = std::max(mixSpec.channels, 1);
auto sampleRate = std::max(mixSpec.freq, 1);
auto framesPerStep = (double)sampleRate / (double)fps;
auto sampleFrameAccumulator = 0.0;
auto frameBuffer = std::vector<float>{};
for (auto soundID : frameSoundIDs)
{
if (soundID != -1 && sounds.contains(soundID)) sounds.at(soundID).play(false, mixer);
sampleFrameAccumulator += framesPerStep;
auto sampleFramesToGenerate = (int)std::floor(sampleFrameAccumulator);
sampleFramesToGenerate = std::max(sampleFramesToGenerate, 1);
sampleFrameAccumulator -= (double)sampleFramesToGenerate;
frameBuffer.resize((std::size_t)sampleFramesToGenerate * (std::size_t)channels);
if (!MIX_Generate(mixer, frameBuffer.data(), (int)(frameBuffer.size() * sizeof(float))))
{
for (auto& [_, sound] : sounds)
sound.track_detach(mixer);
MIX_DestroyMixer(mixer);
audioStream.stream.clear();
return false;
}
audioStream.stream.insert(audioStream.stream.end(), frameBuffer.begin(), frameBuffer.end());
}
for (auto& [_, sound] : sounds)
sound.track_detach(mixer);
MIX_DestroyMixer(mixer);
return true;
return path::from_utf8(std::format("frame_{:06}.png", index));
}
}
AnimationPreview::AnimationPreview() : Canvas(vec2()) {}
std::filesystem::path render_temp_directory_create(const std::filesystem::path& directory)
{
auto timestamp = (uint64_t)std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
for (int suffix = 0; suffix < 1000; ++suffix)
{
auto tempDirectory = directory / path::from_utf8(std::format(".anm2ed_render_tmp_{}_{}", timestamp, suffix));
std::error_code ec;
if (std::filesystem::create_directories(tempDirectory, ec)) return tempDirectory;
}
return {};
}
bool AnimationPreview::is_focused_get() const { return isFocused; }
void render_temp_cleanup(std::filesystem::path& directory, std::vector<std::filesystem::path>& frames)
{
std::error_code ec;
if (!directory.empty()) std::filesystem::remove_all(directory, ec);
directory.clear();
frames.clear();
}
void pixels_unpremultiply_alpha(std::vector<uint8_t>& pixels)
{
for (size_t index = 0; index + 3 < pixels.size(); index += 4)
{
auto alpha = pixels[index + 3];
if (alpha == 0)
{
pixels[index + 0] = 0;
pixels[index + 1] = 0;
pixels[index + 2] = 0;
continue;
}
if (alpha == 255) continue;
float alphaUnit = (float)alpha / 255.0f;
pixels[index + 0] = (uint8_t)glm::clamp((float)std::round((float)pixels[index + 0] / alphaUnit), 0.0f, 255.0f);
pixels[index + 1] = (uint8_t)glm::clamp((float)std::round((float)pixels[index + 1] / alphaUnit), 0.0f, 255.0f);
pixels[index + 2] = (uint8_t)glm::clamp((float)std::round((float)pixels[index + 2] / alphaUnit), 0.0f, 255.0f);
}
}
int trigger_sound_id_get(Document& document, Element* animation, float time, int deterministicIndex = -1)
{
if (!animation) return -1;
auto triggers = animation_item_get(*animation, ItemType::TRIGGER);
if (!triggers || !triggers->isVisible) return -1;
auto trigger = frame_generate(*triggers, time);
if (!trigger.isVisible || trigger.soundIds.empty()) return -1;
size_t soundIndex{};
if (trigger.soundIds.size() > 1)
soundIndex = deterministicIndex >= 0 ? (size_t)deterministicIndex % trigger.soundIds.size()
: (size_t)math::random_in_range(0.0f, (float)trigger.soundIds.size());
soundIndex = std::min(soundIndex, trigger.soundIds.size() - 1);
auto soundID = trigger.soundIds[soundIndex];
return document.sound_get(soundID) ? soundID : -1;
}
bool render_audio_stream_generate(AudioStream& audioStream, std::map<int, Audio>& sounds,
const std::vector<int>& frameSoundIDs, int fps)
{
audioStream.stream.clear();
if (frameSoundIDs.empty() || fps <= 0) return true;
SDL_AudioSpec mixSpec = audioStream.spec;
mixSpec.format = SDL_AUDIO_F32;
auto* mixer = MIX_CreateMixer(&mixSpec);
if (!mixer) return false;
auto channels = std::max(mixSpec.channels, 1);
auto sampleRate = std::max(mixSpec.freq, 1);
auto framesPerStep = (double)sampleRate / (double)fps;
auto sampleFrameAccumulator = 0.0;
auto frameBuffer = std::vector<float>{};
for (auto soundID : frameSoundIDs)
{
if (soundID != -1 && sounds.contains(soundID)) sounds.at(soundID).play(false, mixer);
sampleFrameAccumulator += framesPerStep;
auto sampleFramesToGenerate = (int)std::floor(sampleFrameAccumulator);
sampleFramesToGenerate = std::max(sampleFramesToGenerate, 1);
sampleFrameAccumulator -= (double)sampleFramesToGenerate;
frameBuffer.resize((std::size_t)sampleFramesToGenerate * (std::size_t)channels);
if (!MIX_Generate(mixer, frameBuffer.data(), (int)(frameBuffer.size() * sizeof(float))))
{
for (auto& [_, sound] : sounds)
sound.track_detach(mixer);
MIX_DestroyMixer(mixer);
audioStream.stream.clear();
return false;
}
audioStream.stream.insert(audioStream.stream.end(), frameBuffer.begin(), frameBuffer.end());
}
for (auto& [_, sound] : sounds)
sound.track_detach(mixer);
MIX_DestroyMixer(mixer);
return true;
}
void AnimationPreview::tick(Manager& manager, Settings& settings, float deltaSeconds)
{
@@ -487,33 +480,6 @@ namespace anm2ed::imgui
auto& shaderAxes = resources.shaders[shader::AXIS];
auto& shaderGrid = resources.shaders[shader::GRID];
auto& shaderTexture = resources.shaders[shader::TEXTURE];
auto reset_checker_pan = [&]()
{
checkerPan = pan;
checkerSyncPan = pan;
checkerSyncZoom = zoom;
isCheckerPanInitialized = true;
hasPendingZoomPanAdjust = false;
};
auto sync_checker_pan = [&]()
{
if (!isCheckerPanInitialized)
{
reset_checker_pan();
return;
}
if (pan != checkerSyncPan || zoom != checkerSyncZoom)
{
bool ignorePanDelta = hasPendingZoomPanAdjust && zoom != checkerSyncZoom;
if (!ignorePanDelta) checkerPan += pan - checkerSyncPan;
checkerSyncPan = pan;
checkerSyncZoom = zoom;
if (ignorePanDelta) hasPendingZoomPanAdjust = false;
}
};
auto center_view = [&]() { pan = vec2(); };
auto fit_view = [&]()
@@ -521,17 +487,6 @@ namespace anm2ed::imgui
if (animation) set_to_rect(zoom, pan, anm2.animation_rect(*animation, isRootTransform));
};
auto zoom_adjust = [&](int levelDelta)
{
auto focus = position_translate(zoom, pan, size * 0.5f);
auto previousZoom = zoom;
zoom_level_adjust(zoom, pan, focus, levelDelta);
if (zoom != previousZoom) hasPendingZoomPanAdjust = true;
};
auto zoom_in = [&]() { zoom_adjust(ZOOM_LEVEL_STEP); };
auto zoom_out = [&]() { zoom_adjust(-ZOOM_LEVEL_STEP); };
manager.isAbleToRecord = false;
if (ImGui::Begin(localize.get(LABEL_ANIMATION_PREVIEW_WINDOW), &settings.windowIsAnimationPreview))
@@ -542,21 +497,7 @@ namespace anm2ed::imgui
auto childSize = ImVec2(row_widget_width_get(4),
(ImGui::GetTextLineHeightWithSpacing() * 4) + (ImGui::GetStyle().WindowPadding.y * 2));
if (ImGui::BeginChild("##Grid Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar))
{
ImGui::Checkbox(localize.get(BASIC_GRID), &isGrid);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_VISIBILITY));
ImGui::SameLine();
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));
}
ImGui::EndChild();
grid_child_draw(childSize, isGrid, gridColor, gridSize, gridOffset);
ImGui::SameLine();
@@ -565,17 +506,7 @@ namespace anm2ed::imgui
ImGui::InputFloat(localize.get(BASIC_ZOOM), &zoom, 0.0f, 0.0f, "%.0f%%");
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PREVIEW_ZOOM));
auto widgetSize = widget_size_with_row_get(2);
shortcut(manager.chords[SHORTCUT_CENTER_VIEW]);
if (ImGui::Button(localize.get(LABEL_CENTER_VIEW), widgetSize)) center_view();
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_view();
set_item_tooltip_shortcut(localize.get(TOOLTIP_FIT), settings.shortcutFit);
view_buttons_draw(manager, settings, center_view, fit_view);
auto readoutSize = ImVec2(row_widget_width_get(2), ImGui::GetTextLineHeightWithSpacing());
auto mousePosInt = ivec2(mousePos);
@@ -903,9 +834,7 @@ namespace anm2ed::imgui
if (isRootTransform && root)
{
auto rootFrame = frame_generate(*root, t);
sampleTransform *=
math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale),
rootFrame.rotation, math::percent_to_unit(rootFrame.shear));
sampleTransform *= frame_parent_model_get(rootFrame);
}
return sampleTransform;
};
@@ -936,9 +865,7 @@ namespace anm2ed::imgui
auto itemTransform = sampleTransform;
if (isRootTransform)
if (auto groupRootFrame = group_root_frame_get(container, track, t))
itemTransform *= math::quad_model_parent_get(
groupRootFrame->position, {}, math::percent_to_unit(groupRootFrame->scale), groupRootFrame->rotation,
math::percent_to_unit(groupRootFrame->shear));
itemTransform *= frame_parent_model_get(*groupRootFrame);
return itemTransform;
};
@@ -981,9 +908,7 @@ namespace anm2ed::imgui
if (isOnlyShowLayers || !rootFrame.isVisible || !groupRoot->isVisible) return;
auto itemTransform = sampleTransform;
if (isRootTransform)
itemTransform *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale),
rootFrame.rotation, math::percent_to_unit(rootFrame.shear));
if (isRootTransform) itemTransform *= frame_parent_model_get(rootFrame);
auto rootModel = isRootTransform
? math::quad_model_get(TARGET_SIZE, {}, TARGET_SIZE * 0.5f)
@@ -1270,7 +1195,7 @@ namespace anm2ed::imgui
if (isTransparent)
{
sync_checker_pan();
checker_pan_sync(zoom, pan);
render_checker_background(ImGui::GetWindowDrawList(), min, max, -size - checkerPan, CHECKER_SIZE);
}
image_premultiplied_draw(texture, to_imvec2(size));
@@ -1645,26 +1570,14 @@ namespace anm2ed::imgui
if (mouseWheel != 0 || isZoomIn || isZoomOut)
{
auto previousZoom = zoom;
zoom_level_adjust(zoom, pan, vec2(mousePos),
(mouseWheel > 0 || isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP);
if (zoom != previousZoom) hasPendingZoomPanAdjust = true;
zoom_step(zoom, pan, vec2(mousePos), (mouseWheel > 0 || isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP);
}
}
}
if (tool == tool::PAN)
{
Actions actions{};
actions_undo_redo_add(actions, manager, document);
actions.separator();
actions.add(ACTION_CENTER_VIEW, []() { return true; }, center_view);
actions.add(ACTION_FIT_VIEW, [&]() { return animation; }, fit_view);
actions.separator();
actions.add(ACTION_ZOOM_IN, []() { return true; }, zoom_in);
actions.add(ACTION_ZOOM_OUT, []() { return true; }, zoom_out);
actions_context_window_draw("##Animation Preview Context Menu", actions, settings);
}
view_context_menu_draw("##Animation Preview Context Menu", manager, settings, document, zoom, pan, center_view,
fit_view, animation != nullptr);
manager.progressPopup.trigger();
@@ -1721,7 +1634,7 @@ namespace anm2ed::imgui
{
center_view();
zoom = settings.previewStartZoom;
reset_checker_pan();
checker_pan_reset(zoom, pan);
document.isAnimationPreviewSet = true;
}
+2 -11
View File
@@ -4,19 +4,18 @@
#include <filesystem>
#include "audio_stream.hpp"
#include "canvas.hpp"
#include "canvas_view.hpp"
#include "manager.hpp"
#include "resources.hpp"
#include "settings.hpp"
namespace anm2ed::imgui
{
class AnimationPreview : public Canvas
class AnimationPreview : public CanvasView
{
MIX_Mixer* mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr);
AudioStream audioStream = AudioStream(mixer);
bool wasPlaybackPlaying{};
bool isFocused{};
bool isPreviewHovered{};
bool isSizeTrySet{true};
Settings savedSettings{};
@@ -24,12 +23,6 @@ namespace anm2ed::imgui
glm::vec2 savedPan{};
int savedOverlayIndex{};
uint64_t savedOverlayDocumentId{};
glm::vec2 mousePos{};
glm::vec2 checkerPan{};
glm::vec2 checkerSyncPan{};
float checkerSyncZoom{};
bool isCheckerPanInitialized{};
bool hasPendingZoomPanAdjust{};
bool isMoveDragging{};
glm::vec2 moveOffset{};
glm::vec2 nullRectScaleAnchor{};
@@ -43,8 +36,6 @@ namespace anm2ed::imgui
int renderFrameSoundTimePrev{-1};
public:
AnimationPreview();
bool is_focused_get() const;
void tick(Manager&, Settings&, float);
void update(Manager&, Settings&, Resources&);
};
+102
View File
@@ -0,0 +1,102 @@
#include "canvas_view.hpp"
#include <glm/gtc/type_ptr.hpp>
#include "actions.hpp"
#include "util/imgui/input.hpp"
#include "util/imgui/layout.hpp"
#include "util/imgui/shortcut.hpp"
#include "util/imgui/tooltip.hpp"
using namespace glm;
namespace anm2ed::imgui
{
CanvasView::CanvasView() : Canvas(vec2()) {}
bool CanvasView::is_focused_get() const { return isFocused; }
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;
auto isPanDeltaIgnored = hasPendingZoomPanAdjust && zoom != checkerSyncZoom;
if (!isPanDeltaIgnored) checkerPan += pan - checkerSyncPan;
checkerSyncPan = pan;
checkerSyncZoom = zoom;
if (isPanDeltaIgnored) hasPendingZoomPanAdjust = false;
}
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;
}
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::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));
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<void()>& center,
const std::function<void()>& 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();
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();
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<void()>& center,
const std::function<void()>& 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);
actions.separator();
actions.add(ACTION_CENTER_VIEW, []() { return true; }, center);
actions.add(ACTION_FIT_VIEW, [isFitEnabled]() { return isFitEnabled; }, fit);
actions.separator();
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);
}
}
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <functional>
#include "canvas.hpp"
#include "manager.hpp"
#include "settings.hpp"
namespace anm2ed::imgui
{
class CanvasView : public Canvas
{
protected:
glm::vec2 mousePos{};
glm::vec2 checkerPan{};
glm::vec2 checkerSyncPan{};
float checkerSyncZoom{};
bool isCheckerPanInitialized{};
bool hasPendingZoomPanAdjust{};
bool isFocused{};
void checker_pan_reset(float, glm::vec2);
void checker_pan_sync(float, glm::vec2);
void zoom_step(float&, glm::vec2&, glm::vec2, int);
void grid_child_draw(ImVec2, bool&, glm::vec4&, glm::ivec2&, glm::ivec2&, bool* = nullptr);
void view_buttons_draw(Manager&, Settings&, const std::function<void()>&, const std::function<void()>&);
void view_context_menu_draw(const char*, Manager&, Settings&, Document&, float&, glm::vec2&,
const std::function<void()>&, const std::function<void()>&, bool);
public:
CanvasView();
bool is_focused_get() const;
};
}
+7 -89
View File
@@ -24,10 +24,6 @@ using namespace glm;
namespace anm2ed::imgui
{
SpritesheetEditor::SpritesheetEditor() : Canvas(vec2()) {}
bool SpritesheetEditor::is_focused_get() const { return isFocused; }
void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources& resources)
{
isFocused = false;
@@ -74,33 +70,6 @@ namespace anm2ed::imgui
auto& regionReference = document.region.reference;
auto& regionSelection = document.region.selection;
auto reset_checker_pan = [&]()
{
checkerPan = pan;
checkerSyncPan = pan;
checkerSyncZoom = zoom;
isCheckerPanInitialized = true;
hasPendingZoomPanAdjust = false;
};
auto sync_checker_pan = [&]()
{
if (!isCheckerPanInitialized)
{
reset_checker_pan();
return;
}
if (pan != checkerSyncPan || zoom != checkerSyncZoom)
{
bool ignorePanDelta = hasPendingZoomPanAdjust && zoom != checkerSyncZoom;
if (!ignorePanDelta) checkerPan += pan - checkerSyncPan;
checkerSyncPan = pan;
checkerSyncZoom = zoom;
if (ignorePanDelta) hasPendingZoomPanAdjust = false;
}
};
auto center_view = [&]() { pan = -size * 0.5f; };
auto fit_view = [&]()
@@ -110,17 +79,6 @@ namespace anm2ed::imgui
set_to_rect(zoom, pan, {0, 0, (float)fitTexture->size.x, (float)fitTexture->size.y});
};
auto zoom_adjust = [&](int levelDelta)
{
auto focus = position_translate(zoom, pan, size * 0.5f);
auto previousZoom = zoom;
zoom_level_adjust(zoom, pan, focus, levelDelta);
if (zoom != previousZoom) hasPendingZoomPanAdjust = true;
};
auto zoom_in = [&]() { zoom_adjust(ZOOM_LEVEL_STEP); };
auto zoom_out = [&]() { zoom_adjust(-ZOOM_LEVEL_STEP); };
auto region_get = [&](int id)
{ return spritesheet ? child_id_get(*spritesheet, ElementType::REGION, id) : nullptr; };
@@ -131,24 +89,7 @@ namespace anm2ed::imgui
auto childSize = ImVec2(imgui::row_widget_width_get(3),
(ImGui::GetTextLineHeightWithSpacing() * 4) + (ImGui::GetStyle().WindowPadding.y * 2));
if (ImGui::BeginChild("##Grid Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar))
{
ImGui::Checkbox(localize.get(BASIC_GRID), &isGrid);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_VISIBILITY));
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));
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();
grid_child_draw(childSize, isGrid, gridColor, gridSize, gridOffset, &isGridSnap);
ImGui::SameLine();
@@ -157,17 +98,7 @@ namespace anm2ed::imgui
ImGui::InputFloat(localize.get(BASIC_ZOOM), &zoom, 0.0f, 0.0f, "%.0f%%");
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EDITOR_ZOOM));
auto widgetSize = ImVec2(imgui::row_widget_width_get(2), 0);
imgui::shortcut(manager.chords[SHORTCUT_CENTER_VIEW]);
if (ImGui::Button(localize.get(LABEL_CENTER_VIEW), widgetSize)) center_view();
imgui::set_item_tooltip_shortcut(localize.get(TOOLTIP_CENTER_VIEW), settings.shortcutCenterView);
ImGui::SameLine();
imgui::shortcut(manager.chords[SHORTCUT_FIT]);
if (ImGui::Button(localize.get(LABEL_FIT), widgetSize)) fit_view();
imgui::set_item_tooltip_shortcut(localize.get(TOOLTIP_FIT), settings.shortcutFit);
view_buttons_draw(manager, settings, center_view, fit_view);
auto mousePosInt = ivec2(mousePos);
ImGui::TextUnformatted(
@@ -322,7 +253,7 @@ namespace anm2ed::imgui
unbind();
sync_checker_pan();
checker_pan_sync(zoom, pan);
if (isTransparent)
render_checker_background(drawList, min, max, -size * 0.5f - checkerPan, CHECKER_SIZE);
else
@@ -1007,27 +938,14 @@ namespace anm2ed::imgui
auto focus = mouseWheel != 0 ? vec2(mousePos) : vec2();
if (texture && mouseWheel == 0) focus = texture->size / 2;
auto previousZoom = zoom;
zoom_level_adjust(zoom, pan, focus, (mouseWheel > 0 || isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP);
if (zoom != previousZoom) hasPendingZoomPanAdjust = true;
zoom_step(zoom, pan, focus, (mouseWheel > 0 || isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP);
}
}
}
if (tool == tool::PAN)
{
Actions actions{};
actions_undo_redo_add(actions, manager, document);
actions.separator();
actions.add(ACTION_CENTER_VIEW, []() { return true; }, center_view);
actions.add(
ACTION_FIT_VIEW,
[&]() { return (baseTexture && baseTexture->is_valid()) || (texture && texture->is_valid()); }, fit_view);
actions.separator();
actions.add(ACTION_ZOOM_IN, []() { return true; }, zoom_in);
actions.add(ACTION_ZOOM_OUT, []() { return true; }, zoom_out);
actions_context_window_draw("##Spritesheet Editor Context Menu", actions, settings);
}
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)
{
@@ -1035,7 +953,7 @@ namespace anm2ed::imgui
zoom = settings.editorStartZoom;
set();
center_view();
reset_checker_pan();
checker_pan_reset(zoom, pan);
document.isSpritesheetEditorSet = true;
}
+2 -11
View File
@@ -1,28 +1,19 @@
#pragma once
#include "canvas.hpp"
#include "canvas_view.hpp"
#include "manager.hpp"
#include "resources.hpp"
#include "settings.hpp"
namespace anm2ed::imgui
{
class SpritesheetEditor : public Canvas
class SpritesheetEditor : public CanvasView
{
glm::vec2 mousePos{};
glm::vec2 previousMousePos{};
glm::vec2 cropAnchor{};
glm::vec2 checkerPan{};
glm::vec2 checkerSyncPan{};
float checkerSyncZoom{};
bool isCheckerPanInitialized{};
bool hasPendingZoomPanAdjust{};
bool isFocused{};
int hoveredRegionId{-1};
public:
SpritesheetEditor();
bool is_focused_get() const;
void update(Manager&, Settings&, Resources&);
};
}
+54 -89
View File
@@ -21,25 +21,54 @@ namespace anm2ed
{
constexpr std::size_t RECENT_LIMIT = 10;
namespace
void ensure_parent_directory_exists(const std::filesystem::path& path)
{
void ensure_parent_directory_exists(const std::filesystem::path& path)
{
auto parent = path.parent_path();
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()));
}
auto parent = path.parent_path();
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()));
}
void autosave_file_remove(const std::filesystem::path& path)
{
if (path.empty()) return;
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()));
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()));
}
std::vector<std::filesystem::path> path_list_load(const std::filesystem::path& path, std::string_view name)
{
std::string fileData{};
if (!file::read_to_string(path, &fileData, "rb"))
{
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)));
std::vector<std::filesystem::path> result{};
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);
}
return result;
}
void path_list_save(const std::filesystem::path& path, const std::vector<std::filesystem::path>& entries,
std::string_view name)
{
ensure_parent_directory_exists(path);
std::ostringstream file{};
for (auto& entry : entries)
file << path::to_utf8(entry) << '\n';
if (!file::write_string(path, file.str(), "wb"))
logger.warning(std::format("Could not write {} to: {}. Skipping...", name, path::to_utf8(path)));
}
void Manager::selection_history_push(int index)
@@ -276,58 +305,23 @@ namespace anm2ed
void Manager::recent_files_load()
{
auto path = recent_files_path_get();
std::string fileData{};
if (!file::read_to_string(path, &fileData, "rb"))
{
logger.warning(std::format("Could not load recent files from: {}. Skipping...", path::to_utf8(path)));
return;
}
std::istringstream file(fileData);
logger.info(std::format("Loading recent files from: {}", path::to_utf8(path)));
std::string line{};
std::vector<std::string> loaded{};
std::unordered_set<std::string> seen{};
while (std::getline(file, line))
{
if (line.empty()) continue;
if (!line.empty() && line.back() == '\r') line.pop_back();
auto entry = path::from_utf8(line);
std::error_code ec{};
if (!std::filesystem::exists(entry, ec))
{
logger.warning(std::format("Skipping missing recent file: {}", line));
continue;
}
auto entryString = path::to_utf8(entry);
if (!seen.insert(entryString).second) continue;
loaded.emplace_back(std::move(entryString));
}
recentFiles.clear();
recentFilesCounter = 0;
auto loaded = path_list_load(recent_files_path_get(), "recent files");
for (auto it = loaded.rbegin(); it != loaded.rend(); ++it)
{
recentFiles[*it] = ++recentFilesCounter;
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()
{
auto path = recent_files_path_get();
ensure_parent_directory_exists(path);
std::ostringstream file;
auto ordered = recent_files_ordered();
for (auto& entry : ordered)
file << path::to_utf8(entry) << '\n';
if (!file::write_string(path, file.str(), "wb"))
logger.warning(std::format("Could not write recent files to: {}. Skipping...", path::to_utf8(path)));
path_list_save(recent_files_path_get(), recent_files_ordered(), "recent files");
}
void Manager::recent_files_clear()
@@ -352,40 +346,11 @@ namespace anm2ed
void Manager::autosave_files_load()
{
auto path = autosave_path_get();
std::string fileData{};
if (!file::read_to_string(path, &fileData, "rb"))
{
logger.warning(std::format("Could not load autosave files from: {}. Skipping...", path::to_utf8(path)));
return;
}
std::istringstream file(fileData);
logger.info(std::format("Loading autosave files from: {}", path::to_utf8(path)));
std::string line{};
while (std::getline(file, line))
{
if (line.empty()) continue;
if (!line.empty() && line.back() == '\r') line.pop_back();
auto entry = path::from_utf8(line);
if (std::find(autosaveFiles.begin(), autosaveFiles.end(), entry) != autosaveFiles.end()) continue;
autosaveFiles.emplace_back(std::move(entry));
}
for (auto& entry : path_list_load(autosave_path_get(), "autosave files"))
if (std::ranges::find(autosaveFiles, entry) == autosaveFiles.end()) autosaveFiles.push_back(entry);
}
void Manager::autosave_files_write()
{
ensure_parent_directory_exists(autosave_path_get());
std::ostringstream autosaveWriteFile;
for (auto& path : autosaveFiles)
autosaveWriteFile << path::to_utf8(path) << "\n";
if (!file::write_string(autosave_path_get(), autosaveWriteFile.str(), "wb"))
logger.warning(
std::format("Could not write autosave files to: {}. Skipping...", path::to_utf8(autosave_path_get())));
}
void Manager::autosave_files_write() { path_list_save(autosave_path_get(), autosaveFiles, "autosave files"); }
void Manager::autosave_files_clear(bool removeFiles)
{
+29 -99
View File
@@ -11,6 +11,23 @@ using namespace glm;
namespace anm2ed
{
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 <class T>
concept GlmVector = requires(T value) {
T::length();
value[0];
};
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"(
[Window][##DockSpace]
Pos=0,54
@@ -212,86 +229,20 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991
[&](const std::string& key, std::istringstream& ss, const std::string& name, auto& value, std::string_view type)
{
using T = std::decay_t<decltype(value)>;
auto is_match = [&](const char* suffix) { return key == name + suffix; };
if constexpr (std::is_same_v<T, ivec2> || std::is_same_v<T, vec2>)
if constexpr (GlmVector<T>)
{
if (type.ends_with("_WH"))
{
if (is_match("W"))
auto suffixes = component_suffixes_get(type);
for (int i = 0; i < T::length(); ++i)
if (key == name + suffixes[i])
{
stream_assign(value.x, ss);
stream_assign(value[i], ss);
return true;
}
if (is_match("H"))
{
stream_assign(value.y, ss);
return true;
}
}
else
{
if (is_match("X"))
{
stream_assign(value.x, ss);
return true;
}
if (is_match("Y"))
{
stream_assign(value.y, ss);
return true;
}
}
}
else if constexpr (std::is_same_v<T, vec3>)
else if (key == name)
{
if (is_match("R"))
{
stream_assign(value.x, ss);
return true;
}
if (is_match("G"))
{
stream_assign(value.y, ss);
return true;
}
if (is_match("B"))
{
stream_assign(value.z, ss);
return true;
}
}
else if constexpr (std::is_same_v<T, vec4>)
{
if (is_match("R"))
{
stream_assign(value.x, ss);
return true;
}
if (is_match("G"))
{
stream_assign(value.y, ss);
return true;
}
if (is_match("B"))
{
stream_assign(value.z, ss);
return true;
}
if (is_match("A"))
{
stream_assign(value.w, ss);
return true;
}
}
else
{
if (key == name)
{
value_set(value, ss);
return true;
}
value_set(value, ss);
return true;
}
return false;
@@ -313,7 +264,6 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991
SETTINGS_MEMBERS SETTINGS_SHORTCUTS SETTINGS_WINDOWS
#undef X
}
}
Options Settings::anm2_options_get() const
@@ -390,31 +340,11 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991
{
using T = std::decay_t<decltype(value)>;
if constexpr (std::is_same_v<T, ivec2> || std::is_same_v<T, vec2>)
if constexpr (GlmVector<T>)
{
if (type.ends_with("_WH"))
{
value_save(name + "W", value.x);
value_save(name + "H", value.y);
}
else
{
value_save(name + "X", value.x);
value_save(name + "Y", value.y);
}
}
else if constexpr (std::is_same_v<T, vec3>)
{
value_save(name + "R", value.x);
value_save(name + "G", value.y);
value_save(name + "B", value.z);
}
else if constexpr (std::is_same_v<T, vec4>)
{
value_save(name + "R", value.x);
value_save(name + "G", value.y);
value_save(name + "B", value.z);
value_save(name + "A", value.w);
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);
-7
View File
@@ -42,13 +42,6 @@ namespace anm2ed
X(VEC3, glm::vec3) \
X(VEC4, glm::vec4)
enum Type
{
#define X(name, type) name,
SETTINGS_TYPES
#undef X
};
#define X(name, type) using TYPE_##name = type;
SETTINGS_TYPES
#undef X
+17 -20
View File
@@ -5,30 +5,27 @@
namespace anm2ed
{
namespace
#ifdef _WIN32
struct WSAInitializer
{
WSAInitializer()
{
WSADATA data{};
WSAStartup(MAKEWORD(2, 2), &data);
}
~WSAInitializer() { WSACleanup(); }
};
WSAInitializer initializer{};
#endif
int socket_last_error()
{
#ifdef _WIN32
struct WSAInitializer
{
WSAInitializer()
{
WSADATA data{};
WSAStartup(MAKEWORD(2, 2), &data);
}
~WSAInitializer() { WSACleanup(); }
};
WSAInitializer initializer{};
#endif
int socket_last_error()
{
#ifdef _WIN32
return WSAGetLastError();
return WSAGetLastError();
#else
return errno;
return errno;
#endif
}
}
Socket::Socket() : handle(SOCKET_INVALID), role(CLIENT), lastError(0) {}
+5 -8
View File
@@ -8,15 +8,12 @@
namespace anm2ed::util::path
{
namespace
template <typename CharT> CharT to_lower_char(CharT character)
{
template <typename CharT> CharT to_lower_char(CharT character)
{
if constexpr (std::is_same_v<CharT, wchar_t>)
return static_cast<CharT>(std::towlower(static_cast<wint_t>(character)));
else
return static_cast<CharT>(std::tolower(static_cast<unsigned char>(character)));
}
if constexpr (std::is_same_v<CharT, wchar_t>)
return static_cast<CharT>(std::towlower(static_cast<wint_t>(character)));
else
return static_cast<CharT>(std::tolower(static_cast<unsigned char>(character)));
}
std::filesystem::path to_lower(const std::filesystem::path& path)
+7 -10
View File
@@ -8,17 +8,14 @@
namespace anm2ed::util
{
#ifdef WIN32
namespace
std::wstring utf8_to_wstring(const char* text)
{
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 {};
std::wstring wide(static_cast<std::size_t>(sizeRequired - 1), L'\0');
MultiByteToWideChar(CP_UTF8, 0, text, -1, wide.data(), sizeRequired);
return wide;
}
if (!text) return {};
auto sizeRequired = MultiByteToWideChar(CP_UTF8, 0, text, -1, nullptr, 0);
if (sizeRequired <= 0) return {};
std::wstring wide(static_cast<std::size_t>(sizeRequired - 1), L'\0');
MultiByteToWideChar(CP_UTF8, 0, text, -1, wide.data(), sizeRequired);
return wide;
}
#endif