Stage 9c: Recorder for renders; no settings override; spritesheet follows selection

- Recorder (imgui/window/recorder.*) owns a render: frame times, captured
  frames on disk, per-frame trigger sounds, and assembling PNGs, spritesheets
  (Image::paste) or ffmpeg output. Start, finish, cancel and failure share one
  stop path.
- Isolated and bounded renders no longer overwrite and restore Settings, pan,
  zoom and overlay: the preview draws with view values derived for the render.
- Image::region_get replaces the region export's own pixel copy.
- Selecting layer frames focuses their spritesheet (Document::frame_references_set)
  instead of the spritesheet editor forcing it every frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-03 18:15:06 -04:00
1 parent 39ccfb723a
commit 4d16f21541
9 files changed
+402 -506

No files matched your search

+5
View File
@@ -895,6 +895,11 @@ namespace anm2ed
selected_set(SelectionKind::FRAMES, frameReferences);
selected_set(SelectionKind::TRACKS, tracks);
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);
}
void Document::frame_references_clear() { selection.uids[SelectionKind::FRAMES].clear(); }
+96 -450
View File
@@ -121,76 +121,6 @@ namespace anm2ed::imgui
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)
{
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, const model::Animation* animation, float time,
int deterministicIndex = -1)
{
@@ -209,65 +139,12 @@ namespace anm2ed::imgui
return document.sound_get(soundID) ? soundID : -1;
}
void sounds_detach(const Document& document, MIX_Mixer* mixer)
{
for (auto& [id, _] : document.sounds)
if (auto sound = document.sound_get(id)) audio::track_detach(*sound, mixer);
}
bool render_audio_stream_generate(AudioStream& audioStream, const Document& document,
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 (auto sound = document.sound_get(soundID)) audio::play(*sound, 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))))
{
sounds_detach(document, mixer);
MIX_DestroyMixer(mixer);
audioStream.stream.clear();
return false;
}
audioStream.stream.insert(audioStream.stream.end(), frameBuffer.begin(), frameBuffer.end());
}
sounds_detach(document, mixer);
MIX_DestroyMixer(mixer);
return true;
}
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& zoom = document.previewZoom;
auto& overlayIndex = document.overlayIndex;
auto& overlayDocumentId = document.overlayDocumentId;
auto& pan = document.previewPan;
auto stop_all_sounds = [&]()
{
@@ -277,140 +154,10 @@ namespace anm2ed::imgui
if (manager.isRecording)
{
auto& ffmpegPath = settings.renderFFmpegPath;
auto& path = settings.renderPath;
auto pathString = path::to_utf8(path);
auto& type = settings.renderType;
auto isRenderPreviewOverridden = settings.renderIsUseAnimationBounds || settings.renderIsUseIsolatedAnimation;
auto render_preview_restore = [&]()
if (recorder.is_done())
{
if (!isRenderPreviewOverridden) return;
settings = savedSettings;
pan = savedPan;
zoom = savedZoom;
overlayIndex = savedOverlayIndex;
overlayDocumentId = savedOverlayDocumentId;
isSizeTrySet = true;
hasPendingZoomPanAdjust = false;
isCheckerPanInitialized = false;
};
if (renderFrameIndex >= renderFrameCount)
{
if (type == render::PNGS)
{
if (!renderTempFrames.empty())
{
toast_log(Level::INFO, TOAST_EXPORT_RENDERED_FRAMES, pathString);
}
else
{
toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_FRAMES_FAILED, pathString);
}
}
else if (type == render::SPRITESHEET)
{
auto& rows = settings.renderRows;
auto& columns = settings.renderColumns;
auto layout = render::spritesheet_layout_get(rows, columns, (int)renderTempFrames.size());
rows = layout.rows;
columns = layout.columns;
if (renderTempFrames.empty())
{
toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES);
}
else
{
auto firstFrame = Image(renderTempFrames.front());
if (firstFrame.size.x <= 0 || firstFrame.size.y <= 0 || firstFrame.pixels.empty())
{
toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY);
}
else
{
auto frameWidth = firstFrame.size.x;
auto frameHeight = firstFrame.size.y;
ivec2 spritesheetSize = ivec2(frameWidth * columns, frameHeight * rows);
std::vector<uint8_t> spritesheet((size_t)(spritesheetSize.x) * spritesheetSize.y * CHANNELS);
for (std::size_t index = 0; index < renderTempFrames.size(); ++index)
{
auto frame = Image(renderTempFrames[index]);
auto row = (int)(index / columns);
auto column = (int)(index % columns);
if (row >= rows || column >= columns) break;
if ((int)frame.pixels.size() < frameWidth * frameHeight * CHANNELS) continue;
for (int y = 0; y < frameHeight; ++y)
{
auto destY = (size_t)(row * frameHeight + y);
auto destX = (size_t)(column * frameWidth);
auto destOffset = (destY * spritesheetSize.x + destX) * CHANNELS;
auto srcOffset = (size_t)(y * frameWidth) * CHANNELS;
std::copy_n(frame.pixels.data() + srcOffset, frameWidth * CHANNELS, spritesheet.data() + destOffset);
}
}
Image spritesheetTexture(spritesheet.data(), spritesheetSize);
if (spritesheetTexture.write_png(path))
{
toast_log(Level::INFO, TOAST_EXPORT_SPRITESHEET, pathString);
}
else
{
toast_log(Level::ERROR, TOAST_EXPORT_SPRITESHEET_FAILED, pathString);
}
}
}
}
else
{
if (settings.timelineIsSound && type != render::GIF)
{
if (!render_audio_stream_generate(audioStream, document, renderFrameSoundIDs, renderFrameRate))
{
toasts.push(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED));
logger.error("Failed to generate deterministic render audio stream; exporting without audio.");
audioStream.stream.clear();
}
}
else
audioStream.stream.clear();
if (animation_render(ffmpegPath, path, renderTempFrames, audioStream, (render::Type)type, renderFrameRate))
{
toast_log(Level::INFO, TOAST_EXPORT_RENDERED_ANIMATION, pathString);
}
else
{
toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString);
}
}
if (type == render::PNGS)
{
renderTempDirectory.clear();
renderTempFrames.clear();
renderFrameSoundIDs.clear();
}
else
{
render_temp_cleanup(renderTempDirectory, renderTempFrames);
renderFrameSoundIDs.clear();
}
render_preview_restore();
playback.isPlaying = false;
playback.isFinished = false;
manager.isRecording = false;
manager.isRecordingStart = false;
renderFrameIndex = 0;
renderFrameCount = 0;
manager.progressPopup.close();
recorder.finish(document, audioStream);
recording_stop(manager, document);
}
stop_all_sounds();
wasPlaybackPlaying = false;
@@ -448,6 +195,61 @@ namespace anm2ed::imgui
wasPlaybackPlaying = playback.isPlaying;
}
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 model::Animation* animation)
{
auto animationFps = std::max(document.model.info.fps, 1);
RecorderOptions options{.type = (render::Type)settings.renderType,
.path = settings.renderPath,
.format = settings.renderFormat,
.ffmpegPath = settings.renderFFmpegPath,
.start = manager.recordingStart,
.end = manager.recordingEnd,
.animationFps = animationFps,
.fps = render::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) * 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);
}
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)
{
isFocused = false;
@@ -630,109 +432,27 @@ namespace anm2ed::imgui
auto min = cursorScreenPos;
auto max = to_imvec2(to_vec2(min) + size);
if (manager.isRecordingStart)
{
savedSettings = settings;
auto isRenderPreviewOverridden = settings.renderIsUseAnimationBounds || settings.renderIsUseIsolatedAnimation;
if (isRenderPreviewOverridden)
{
savedOverlayIndex = overlayIndex;
savedOverlayDocumentId = overlayDocumentId;
savedZoom = zoom;
savedPan = pan;
}
if (settings.renderIsUseIsolatedAnimation)
{
overlayIndex = -1;
overlayDocumentId = 0;
settings.animationPreviewTransparent = true;
settings.timelineIsOnlyShowLayers = true;
settings.previewIsAxes = false;
settings.previewIsGrid = false;
settings.previewIsPivots = false;
settings.previewIsAltIcons = false;
settings.previewIsBorder = false;
settings.onionskinIsEnabled = false;
}
if (settings.renderIsUseAnimationBounds)
{
if (auto rect = animation_render_rect_get(manager, document, animation, isRootTransform))
{
size_set(vec2(rect->z, rect->w) * settings.renderScale);
set_to_rect(zoom, pan, *rect);
}
isSizeTrySet = false;
}
manager.isRecordingStart = false;
manager.isRecording = true;
renderFrameIndex = 0;
renderAnimationFps = std::max(model.info.fps, 1);
renderFrameRate = render::fps_get(settings.renderFpsMode, renderAnimationFps, settings.playbackTickRate);
renderFrameCount =
render::frame_count_get(manager.recordingStart, manager.recordingEnd, renderAnimationFps, renderFrameRate);
renderTempFrames.clear();
renderFrameSoundIDs.clear();
renderFrameSoundTimePrev = -1;
if (settings.renderType == render::PNGS)
{
renderTempDirectory = settings.renderPath;
std::error_code ec;
std::filesystem::create_directories(renderTempDirectory, ec);
}
else
{
auto destinationDirectory = render_destination_directory(settings.renderPath, settings.renderType);
std::error_code ec;
std::filesystem::create_directories(destinationDirectory, ec);
renderTempDirectory = render_temp_directory_create(destinationDirectory);
}
if (renderTempDirectory.empty())
{
if (isRenderPreviewOverridden)
{
settings = savedSettings;
pan = savedPan;
zoom = savedZoom;
overlayIndex = savedOverlayIndex;
overlayDocumentId = savedOverlayDocumentId;
isSizeTrySet = true;
hasPendingZoomPanAdjust = false;
isCheckerPanInitialized = false;
}
auto pathString = path::to_utf8(settings.renderPath);
toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString);
manager.isRecording = false;
manager.isRecordingStart = false;
renderFrameIndex = 0;
renderFrameCount = 0;
manager.progressPopup.close();
playback.isPlaying = false;
playback.isFinished = false;
return;
}
playback.isPlaying = true;
playback.timing_reset();
playback.time =
render::frame_time_get(manager.recordingStart, renderFrameIndex, renderAnimationFps, renderFrameRate);
document.frameTime = playback.time;
}
if (manager.isRecording && renderFrameIndex < renderFrameCount)
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 =
render::frame_time_get(manager.recordingStart, renderFrameIndex, renderAnimationFps, renderFrameRate);
playback.time = recorder.time_get();
document.frameTime = playback.time;
}
if (isSizeTrySet)
// 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);
@@ -748,12 +468,12 @@ namespace anm2ed::imgui
bind();
viewport_set();
clear(isTransparent ? vec4(0) : vec4(backgroundColor, 1.0f));
clear(isViewTransparent ? vec4(0) : vec4(backgroundColor, 1.0f));
if (isAxes) axes_render(shaderAxes, zoom, pan, axesColor);
if (isGrid) grid_render(shaderGrid, zoom, pan, gridSize, gridOffset, gridColor);
if (isAxes && !isIsolated) axes_render(shaderAxes, viewZoom, viewPan, axesColor);
if (isGrid && !isIsolated) grid_render(shaderGrid, viewZoom, viewPan, gridSize, gridOffset, gridColor);
auto baseTransform = transform_get(zoom, pan);
auto baseTransform = transform_get(viewZoom, viewPan);
auto frameTime = document.frameTime > -1 && !playback.isPlaying ? document.frameTime : playback.time;
model::DrawOptions drawOptions{.time = frameTime,
@@ -770,7 +490,7 @@ namespace anm2ed::imgui
sampleAlphas.push_back((1.0f / (count + 1)) * i);
}
};
if (settings.onionskinIsEnabled)
if (settings.onionskinIsEnabled && !isIsolated)
{
samples_add(settings.onionskinBeforeCount, -1, settings.onionskinBeforeColor);
samples_add(settings.onionskinAfterCount, 1, settings.onionskinAfterColor);
@@ -794,7 +514,7 @@ namespace anm2ed::imgui
{
auto isActiveDocument = &sampleDocument == &document;
auto& sampleModel = sampleDocument.model;
auto targetIcon = resources.icon_id_get(isAltIcons ? icon::TARGET_ALT : icon::TARGET);
auto targetIcon = resources.icon_id_get(isAltIcons && !isIsolated ? icon::TARGET_ALT : icon::TARGET);
for (const auto& draw : model::animation_draws_get(sampleModel, sampleAnimation, drawOptions))
{
auto isOnion = draw.sample != -1;
@@ -812,7 +532,7 @@ namespace anm2ed::imgui
if (draw.type == model::DrawType::ROOT || draw.type == model::DrawType::GROUP_ROOT)
{
if (isOnlyShowLayers) continue;
if (isViewOnlyLayers) continue;
auto isSelected = isActiveDocument && draw.type == model::DrawType::GROUP_ROOT &&
referenceItemType == ItemType::ROOT && reference.groupType == draw.groupType &&
reference.groupId == draw.id;
@@ -844,12 +564,12 @@ namespace anm2ed::imgui
auto color = isOnion ? onionColor
: isActiveDocument && is_layer_selected(draw.id) ? SELECTED_LAYER_BORDER_COLOR
: color::RED;
if (isBorder) rect_render(shaderLine, layerTransform, layerModel, color);
if (isPivots)
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 (!isOnlyShowLayers)
else if (!isViewOnlyLayers)
{
auto isShowRect = model::item_get(sampleModel.content.nulls, draw.id)->isShowRect;
auto isSelected = isActiveDocument && draw.id == reference.itemID && referenceItemType == ItemType::NULL_;
@@ -869,7 +589,7 @@ namespace anm2ed::imgui
{
auto overlay_render = [&]()
{
if (auto overlayDocument = overlay_animation_document_get(manager, document))
if (auto overlayDocument = isIsolated ? nullptr : overlay_animation_document_get(manager, document))
if (auto overlayAnimation = overlayDocument->model.animation_get(overlayIndex))
render(*overlayDocument, *overlayAnimation, 1.0f - math::percent_to_unit(overlayTransparency));
};
@@ -879,62 +599,22 @@ namespace anm2ed::imgui
if (overlayDrawOrder == overlay_draw_order::OVER) overlay_render();
}
if (manager.isRecording && renderFrameIndex < renderFrameCount)
if (isRecordingFrame)
{
auto renderType = settings.renderType;
auto isRenderPreviewOverridden = settings.renderIsUseAnimationBounds || settings.renderIsUseIsolatedAnimation;
auto render_capture_fail = [&]()
auto soundId = settings.timelineIsSound && animation && recorder.is_sound_frame()
? trigger_sound_id_get(document, animation, frameTime, recorder.index)
: -1;
if (!recorder.frame_capture(pixels_get(), size, soundId))
{
auto pathString = path::to_utf8(settings.renderPath);
toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString);
if (renderType != render::PNGS) render_temp_cleanup(renderTempDirectory, renderTempFrames);
renderFrameSoundIDs.clear();
if (isRenderPreviewOverridden)
{
settings = savedSettings;
pan = savedPan;
zoom = savedZoom;
overlayIndex = savedOverlayIndex;
overlayDocumentId = savedOverlayDocumentId;
isSizeTrySet = true;
hasPendingZoomPanAdjust = false;
isCheckerPanInitialized = false;
}
playback.isPlaying = false;
playback.isFinished = false;
manager.isRecording = false;
manager.isRecordingStart = false;
renderFrameIndex = 0;
renderFrameCount = 0;
manager.progressPopup.close();
};
auto frameSoundID = -1;
if (settings.timelineIsSound && !document.sounds.empty())
{
auto soundTime = (int)std::floor(frameTime);
if (soundTime != renderFrameSoundTimePrev && animation)
frameSoundID = trigger_sound_id_get(document, animation, frameTime, renderFrameIndex);
renderFrameSoundTimePrev = soundTime;
toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, path::to_utf8(recorder.options.path));
recorder.cancel();
recording_stop(manager, document);
}
renderFrameSoundIDs.push_back(frameSoundID);
auto pixels = pixels_get();
if (isRenderPreviewOverridden) pixels_unpremultiply_alpha(pixels);
auto framePath =
renderTempDirectory / render_frame_filename(settings.renderFormat, renderFrameIndex, settings.renderType);
if (Image::write_pixels_png(framePath, size, pixels.data()))
{
renderTempFrames.push_back(framePath);
++renderFrameIndex;
}
else
render_capture_fail();
}
unbind();
if (isTransparent)
if (isViewTransparent)
{
checker_pan_sync(zoom, pan);
render_checker_background(ImGui::GetWindowDrawList(), min, max, -size - checkerPan, CHECKER_SIZE);
@@ -1108,48 +788,14 @@ namespace anm2ed::imgui
if (ImGui::BeginPopupModal(manager.progressPopup.label(), &manager.progressPopup.isOpen, ImGuiWindowFlags_NoResize))
{
auto progress = renderFrameCount > 0 ? (float)renderFrameIndex / (float)renderFrameCount : 0.0f;
ImGui::ProgressBar(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)))
{
auto renderType = settings.renderType;
auto isRenderPreviewOverridden = settings.renderIsUseAnimationBounds || settings.renderIsUseIsolatedAnimation;
if (renderType == render::PNGS)
{
renderTempDirectory.clear();
renderTempFrames.clear();
renderFrameSoundIDs.clear();
}
else
{
render_temp_cleanup(renderTempDirectory, renderTempFrames);
renderFrameSoundIDs.clear();
}
if (isRenderPreviewOverridden)
{
pan = savedPan;
zoom = savedZoom;
settings = savedSettings;
overlayIndex = savedOverlayIndex;
overlayDocumentId = savedOverlayDocumentId;
isSizeTrySet = true;
hasPendingZoomPanAdjust = false;
isCheckerPanInitialized = false;
}
playback.isPlaying = false;
playback.isFinished = false;
manager.isRecording = false;
manager.isRecordingStart = false;
renderFrameIndex = 0;
renderFrameCount = 0;
manager.progressPopup.close();
recorder.cancel();
recording_stop(manager, document);
}
ImGui::EndPopup();
+8 -14
View File
@@ -6,6 +6,7 @@
#include "audio_stream.hpp"
#include "canvas_view.hpp"
#include "manager.hpp"
#include "recorder.hpp"
#include "resources.hpp"
#include "settings.hpp"
@@ -17,23 +18,16 @@ namespace anm2ed::imgui
AudioStream audioStream = AudioStream(mixer);
bool wasPlaybackPlaying{};
bool isPreviewHovered{};
bool isSizeTrySet{true};
Settings savedSettings{};
float savedZoom{};
glm::vec2 savedPan{};
int savedOverlayIndex{};
uint64_t savedOverlayDocumentId{};
bool isMoveDragging{};
glm::vec2 moveOffset{};
glm::vec2 nullRectScaleAnchor{};
std::filesystem::path renderTempDirectory{};
std::vector<std::filesystem::path> renderTempFrames{};
std::vector<int> renderFrameSoundIDs{};
int renderFrameIndex{};
int renderFrameCount{};
int renderFrameRate{1};
int renderAnimationFps{1};
int renderFrameSoundTimePrev{-1};
Recorder recorder{};
glm::vec2 recordSize{};
glm::vec2 recordPan{};
float recordZoom{};
void recording_start(Manager&, Settings&, Document&, const model::Animation*);
void recording_stop(Manager&, Document&);
public:
void tick(Manager&, Settings&, float);
+203
View File
@@ -0,0 +1,203 @@
#include "recorder.hpp"
#include <chrono>
#include <cmath>
#include <format>
#include "audio.hpp"
#include "log.hpp"
#include "path.hpp"
#include "toast.hpp"
using namespace anm2ed::resource;
using namespace anm2ed::util;
namespace anm2ed::imgui
{
constexpr int TEMP_DIRECTORY_ATTEMPTS = 1000;
constexpr int ALPHA_OPAQUE = 255;
constexpr float CHANNEL_MAX = 255.0f;
std::filesystem::path frame_filename_get(const std::filesystem::path& format, int index, render::Type type)
{
auto fallback = path::from_utf8(std::format("frame_{:06}.png", index));
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;
}
catch (...)
{
return fallback;
}
}
// PNG sequences go straight to their folder; other outputs collect frames in a temporary folder beside the output.
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;
}
auto directory = options.path.parent_path();
if (directory.empty()) directory = std::filesystem::current_path();
std::filesystem::create_directories(directory, ec);
auto timestamp =
std::chrono::duration_cast<std::chrono::milliseconds>(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;
}
return {};
}
// Rendered pixels are premultiplied; outputs on a transparent background want straight alpha.
void pixels_unpremultiply(std::vector<uint8_t>& 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);
}
}
void sounds_detach(const Document& document, MIX_Mixer* mixer)
{
for (auto& [id, _] : document.sounds)
if (auto sound = document.sound_get(id)) audio::track_detach(*sound, mixer);
}
// Mixes each frame's trigger sound into one stream at the render frame rate.
bool audio_stream_generate(AudioStream& audioStream, const Document& document, const std::vector<int>& soundIds,
int fps)
{
audioStream.stream.clear();
if (soundIds.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 framesPerStep = (double)std::max(mixSpec.freq, 1) / (double)fps;
auto accumulator = 0.0;
std::vector<float> buffer{};
auto isGenerated = true;
for (auto soundId : soundIds)
{
if (auto sound = document.sound_get(soundId)) 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();
return isGenerated;
}
bool Recorder::start(const RecorderOptions& recorderOptions)
{
options = recorderOptions;
index = 0;
count = render::frame_count_get(options.start, options.end, options.animationFps, options.fps);
frames.clear();
soundIds.clear();
soundTime = -1;
directory = frames_directory_create(options);
return !directory.empty();
}
bool Recorder::is_done() const { return index >= count; }
float Recorder::time_get() const
{
return render::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; }
bool Recorder::frame_capture(std::vector<uint8_t> pixels, glm::ivec2 size, int soundId)
{
soundTime = (int)std::floor(time_get());
soundIds.push_back(soundId);
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;
frames.push_back(framePath);
++index;
return true;
}
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);
else if (options.type == render::SPRITESHEET)
{
auto layout = render::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, soundIds, 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()
{
std::error_code ec{};
if (options.type != render::PNGS && !directory.empty()) std::filesystem::remove_all(directory, ec);
directory.clear();
frames.clear();
soundIds.clear();
index = count = 0;
}
}
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include <filesystem>
#include <vector>
#include "audio_stream.hpp"
#include "document.hpp"
#include "render.hpp"
namespace anm2ed::imgui
{
struct RecorderOptions
{
render::Type type{};
std::filesystem::path path{};
std::filesystem::path format{};
std::filesystem::path ffmpegPath{};
int start{};
int end{};
int animationFps{1};
int fps{1};
int rows{};
int columns{};
bool isSound{};
bool isIsolated{};
bool isBounded{};
};
// A render in progress: which animation times to capture, the frames captured so far (written to disk) and the
// trigger sound of each, and assembling the output when done.
class Recorder
{
public:
RecorderOptions options{};
int index{};
int count{};
bool start(const RecorderOptions&);
bool is_done() const;
float time_get() const;
bool is_sound_frame() const;
bool frame_capture(std::vector<uint8_t>, glm::ivec2, int);
void finish(const Document&, AudioStream&);
void cancel();
private:
std::filesystem::path directory{};
std::vector<std::filesystem::path> frames{};
std::vector<int> soundIds{};
int soundTime{-1};
};
}
+6 -24
View File
@@ -85,25 +85,6 @@ namespace anm2ed::imgui
.isValid = true};
}
bool region_pixels_get(const model::Region& region, const Image& texture, std::vector<uint8_t>& pixels, ivec2& size)
{
auto minPoint = ivec2(glm::min(region.crop, region.crop + region.size));
size = ivec2(glm::max(region.crop, region.crop + region.size)) - minPoint;
if (size.x <= 0 || size.y <= 0 || texture.size.x <= 0 || texture.size.y <= 0 || texture.pixels.empty())
return false;
pixels.assign((size_t)size.x * size.y * image::CHANNELS, 0);
for (int y = 0; y < size.y; y++)
for (int x = 0; x < size.x; x++)
{
auto source = minPoint + ivec2(x, y);
if (source.x < 0 || source.y < 0 || source.x >= texture.size.x || source.y >= texture.size.y) continue;
std::copy_n(texture.pixels.data() + ((size_t)source.y * texture.size.x + source.x) * image::CHANNELS,
image::CHANNELS, pixels.data() + ((size_t)y * size.x + x) * image::CHANNELS);
}
return true;
}
bool region_export(Document& document, const RegionExportOptions& options)
{
auto pathString = options.path.empty() ? std::string("in memory") : path::to_utf8(options.path);
@@ -116,14 +97,15 @@ namespace anm2ed::imgui
auto spritesheet = model::item_get(document.model.content.spritesheets, options.spritesheetId);
auto region = spritesheet ? model::item_get(spritesheet->regions, options.regionId) : nullptr;
auto texture = document.texture_get(options.spritesheetId);
std::vector<uint8_t> pixels{};
ivec2 exportSize{};
if (!region || !texture || !texture->is_valid() || !region_pixels_get(*region, *texture, pixels, exportSize))
auto minPoint = region ? ivec2(glm::min(region->crop, region->crop + region->size)) : ivec2();
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;
}
auto exportedImage = texture->region_get(minPoint, exportSize);
auto sourceRegion = *region;
auto outputPath = options.path;
if (!outputPath.empty())
@@ -132,7 +114,7 @@ namespace anm2ed::imgui
pathString = path::to_utf8(outputPath);
WorkingDirectory workingDirectory(document.directory_get());
path::ensure_directory(outputPath.parent_path());
if (!Image::write_pixels_png(outputPath, exportSize, pixels.data()))
if (!exportedImage.write_png(outputPath))
{
toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, sourceRegion.name, pathString);
return false;
@@ -165,7 +147,7 @@ namespace anm2ed::imgui
exported.regions.push_back(exportedRegion);
spritesheets.push_back(exported);
document.texture_set(exported.id, Image(pixels.data(), exportSize));
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);
-18
View File
@@ -44,24 +44,6 @@ namespace anm2ed::imgui
auto& isGridSnap = settings.editorIsGridSnap;
auto& isBorder = settings.editorIsBorder;
auto& isTransparent = settings.editorIsTransparent;
auto selected_layer_spritesheet_get = [&]()
{
for (auto frameReference : document.frame_references_get())
{
if (frameReference.itemType != LAYER) continue;
if (auto layer = model::item_get(model.content.layers, frameReference.itemID)) return layer->spritesheetId;
}
if (reference.frameIndex >= 0 && reference.itemType == LAYER)
if (auto layer = model::item_get(model.content.layers, reference.itemID)) return layer->spritesheetId;
return -1;
};
if (auto selectedLayerSpritesheet = selected_layer_spritesheet_get();
selectedLayerSpritesheet != -1 && document.editTarget != Document::EditTarget::REGION &&
document.editTarget != Document::EditTarget::SPRITESHEET)
{
referenceSpritesheet = selectedLayerSpritesheet;
document.focused_id_set(SelectionKind::SPRITESHEETS, referenceSpritesheet);
}
auto spritesheet = model::item_get(model.content.spritesheets, referenceSpritesheet);
auto baseTexture = document.texture_get(referenceSpritesheet);
auto texture = baseTexture;
+30
View File
@@ -1,5 +1,6 @@
#include "image.hpp"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <filesystem>
@@ -91,6 +92,35 @@ namespace anm2ed::resource
return false;
}
// Copies a size-sized block between images; pixels outside either image are skipped.
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);
}
}
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
{
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;
}
Image Image::merge_append(const Image& base, const Image& append, bool isAppendRight)
{
if (base.size.x <= 0 || base.size.y <= 0) return append;
+2
View File
@@ -33,6 +33,8 @@ namespace anm2ed::resource
bool write_png(const std::filesystem::path&) const;
static bool write_pixels_png(const std::filesystem::path&, glm::ivec2, const uint8_t*);
static Image merge_append(const Image&, const Image&, bool);
void paste(const Image&, glm::ivec2);
Image region_get(glm::ivec2, glm::ivec2) const;
glm::vec4 pixel_read(glm::vec2) const;
void pixel_set(glm::ivec2, glm::vec4);
void pixel_line(glm::ivec2, glm::ivec2, glm::vec4);