From bf7e306ed3f2800c062576ab789fbdd8ffd80bc7 Mon Sep 17 00:00:00 2001 From: Mark Gaiser Date: Tue, 7 Jul 2026 20:14:32 +0200 Subject: [PATCH] renderer/image: add interruptible transition rendering with custom shaders Adds an animated wallpaper transition path to CImageElement: a two-texture blend (start -> end) driven by fadeLayersIn/Out durations, with an optional custom GLSL fragment shader supplied by path. - CImageElement::transitionTo captures the in-flight blend to an FBO when a transition is interrupted mid-way, using that as the new start texture so a fresh transition can begin to the new target (no flicker, no black flash). - IRenderer gains renderTransition / captureTransitionState / ensureTransitionShader. Custom shaders are stat()-checked once at transition start and recompiled only on mtime change; the per-frame render path is a single cache lookup + draw, with no filesystem or compile work. - CFramebuffer sets m_tex->m_size after glTexImage2D so captured textures report the right size to the shader's tex1Size/tex2Size uniforms. - A captured texture keeps its owning CFramebuffer alive via m_tempFramebuffer. - All fit modes (stretch/cover/contain/tile) are honoured; the host pushes the config duration to u_duration each frame (GLES cannot initialize uniforms). --- include/hyprtoolkit/element/Image.hpp | 30 + src/element/image/Image.cpp | 227 +++++++- src/element/image/Image.hpp | 36 +- src/renderer/Renderer.hpp | 37 +- src/renderer/gl/Framebuffer.cpp | 1 + src/renderer/gl/GLTexture.hpp | 5 + src/renderer/gl/OpenGL.cpp | 556 ++++++++++++++++++- src/renderer/gl/OpenGL.hpp | 34 ++ src/renderer/gl/Shader.hpp | 5 + src/renderer/gl/shaders/glsl/transition.frag | 17 + 10 files changed, 913 insertions(+), 35 deletions(-) create mode 100644 src/renderer/gl/shaders/glsl/transition.frag diff --git a/include/hyprtoolkit/element/Image.hpp b/include/hyprtoolkit/element/Image.hpp index c88bb2fd..6066aafb 100644 --- a/include/hyprtoolkit/element/Image.hpp +++ b/include/hyprtoolkit/element/Image.hpp @@ -48,10 +48,37 @@ namespace Hyprtoolkit { Hyprutils::Memory::CSharedPointer rebuild(); virtual Hyprutils::Math::Vector2D size(); + // Starts a transition to the image at `path`. + // + // duration <= 0 means an immediate (non-animated) swap: the transition + // completes on the first rendered frame. + // + // The caller supplies the fragment stage only; the vertex stage is the fixed + // built-in tex300.vert (declares `in vec2 pos; in vec2 texcoord; uniform mat3 proj;` + // and emits v_texcoord). The custom fragment must declare + // `uniform sampler2D tex1, tex2; uniform float progress;` and should consume + // v_texcoord (a fragment that ignores v_texcoord can have the attribute + // dead-stripped). Optional uniforms: alpha, topLeft, fullSize, radius, + // randomPixel, u_duration. A shader that fails to compile/link, or that is + // missing any of pos/texcoord/proj/tex1/tex2/progress, is rejected and the + // default transition shader is used instead. + void transitionTo(const std::string& path, + eImageFitMode fitMode, + float duration, + const std::string& shaderSource = ""); + + bool isTransitioning() const; + + float getTransitionProgressOut() const; + float getTransitionProgressIn() const; + private: CImageElement(const SImageData& data); static Hyprutils::Memory::CSharedPointer create(const SImageData& data); + // NOTE: calling replaceData() while a transitionTo()-driven transition is + // active is not a supported interleaving: replaceData bumps the request + // generation and updates the data, but does not touch transition state. void replaceData(const SImageData& data); // @@ -64,8 +91,11 @@ namespace Hyprtoolkit { void renderTex(); + void renderTransition(); + Hyprutils::Memory::CUniquePointer m_impl; friend class CImageBuilder; + friend struct SImageImpl; }; }; diff --git a/src/element/image/Image.cpp b/src/element/image/Image.cpp index ac917832..0464df3f 100644 --- a/src/element/image/Image.cpp +++ b/src/element/image/Image.cpp @@ -8,6 +8,7 @@ #include "../../system/Icons.hpp" #include "../../resource/assetCache/AssetCache.hpp" #include "../../renderer/RendererTexture.hpp" +#include #include "../Element.hpp" @@ -25,14 +26,19 @@ CImageElement::CImageElement(const SImageData& data) : IElement(), m_impl(makeUn } void CImageElement::paint() { - if (m_impl->failed) + if (m_impl->transition.active) { // precedence over the failed/fallback guard + renderTransition(); return; + } auto assetToUse = m_impl->cacheEntry; if (!assetToUse || !assetToUse->tex()) assetToUse = m_impl->oldCacheEntry; + if (m_impl->failed && (!assetToUse || !assetToUse->tex())) + return; // blank only if failed AND nothing to show + if (!assetToUse || !assetToUse->tex()) { if (!m_impl->waitingForTex) renderTex(); @@ -55,11 +61,14 @@ void CImageElement::paint() { .texture = assetToUse->tex(), .a = m_impl->data.a, .rounding = m_impl->data.rounding, + .fitMode = m_impl->data.fitMode, }); } void CImageElement::renderTex() { - const uint64_t GENERATION = ++m_impl->requestGeneration; + const uint64_t GENERATION = ++m_impl->requestedGen; + // Disarm any prior cached-listener so a stale callback for an old request cannot + // fire after this new request. m_impl->listeners.cacheEntryDone.reset(); m_impl->failed = false; if (m_impl->cacheEntry && m_impl->cacheEntry->tex()) @@ -74,16 +83,16 @@ void CImageElement::renderTex() { m_impl->failed = false; m_impl->cacheEntry = ASSET; if (ASSET->status() == Asset::CACHE_ENTRY_DONE) - m_impl->postImageScheduleRecalc(); + m_impl->postImageScheduleRecalc(m_impl->requestedGen); else { m_impl->waitingForTex = true; m_impl->listeners.cacheEntryDone = ASSET->m_events.done.listen([this, self = impl->self, generation = GENERATION, entry = WP{ASSET}] { - if (!self || generation != m_impl->requestGeneration) - return; + if (!self || generation != m_impl->requestedGen) + return; // stale callback: a newer request superseded this one const auto ENTRY = entry.lock(); m_impl->failed = !ENTRY || ENTRY->status() == Asset::CACHE_ENTRY_FAILED; - m_impl->postImageScheduleRecalc(); + m_impl->postImageScheduleRecalc(generation); m_impl->listeners.cacheEntryDone.reset(); }); } @@ -118,6 +127,8 @@ void CImageElement::renderTex() { m_impl->requests.emplace_back(REQUEST); m_impl->waitingForTex = true; + m_impl->inflightGen = m_impl->requestedGen; + m_impl->failed = false; // a fresh attempt is not blocked by a stale failure flag ASP resourceGeneric(REQUEST->resource); @@ -168,31 +179,46 @@ void SImageImpl::postImageLoad(const SP& request) { g_logger->log(HT_LOG_ERROR, "Image: failed loading, hyprgraphics couldn't load asset {}", request->path); } - const bool CURRENT = request->generation == requestGeneration; + const bool CURRENT = request->generation == requestedGen; if (CURRENT) { cacheEntry = request->cacheEntry; failed = !loaded; - if (loaded) - size = request->resource->m_asset.pixelSize; - oldCacheEntry.reset(); + if (loaded) { + size = request->resource->m_asset.pixelSize; + oldCacheEntry.reset(); // only on success: on failure keep it as the visible fallback + } } std::erase(requests, request); if (CURRENT) - postImageScheduleRecalc(); + postImageScheduleRecalc(request->generation); } -void SImageImpl::postImageScheduleRecalc() { +void SImageImpl::postImageScheduleRecalc(uint64_t gen) { + // Ignore a stale callback when a load for the newest request is already in flight + // (e.g. a cached-listener for an old request firing after a newer load started). + if (gen != requestedGen && inflightGen == requestedGen) + return; + waitingForTex = false; - if (!failed) { - if (cacheEntry && cacheEntry->tex()) - size = cacheEntry->tex()->size(); - self->impl->damageEntire(); + satisfiedGen = gen; - if (self->impl->window) - self->impl->window->scheduleReposition(self); + // Newest request unsatisfied AND no load for it in flight -> load it now (current data). + if (satisfiedGen != requestedGen && inflightGen != requestedGen) { + self->renderTex(); + return; // defer damage until the newest request settles } + + // Settled on the newest request. On failure this size update is a deliberate + // no-op: paint() owns fallback display (oldCacheEntry is kept alive on failure); + // we still damage below so the fallback is repainted. + if (!failed && cacheEntry && cacheEntry->tex()) + size = cacheEntry->tex()->size(); + self->impl->damageEntire(); + + if (self->impl->window) + self->impl->window->scheduleReposition(self); } std::string SImageImpl::getCacheString() { @@ -220,6 +246,7 @@ SP CImageElement::rebuild() { } void CImageElement::replaceData(const SImageData& data) { + m_impl->requestedGen++; m_impl->data = data; renderTex(); @@ -282,3 +309,167 @@ Vector2D SImageImpl::preferredSvgSize() { return Vector2D{max * lastScale, max * lastScale}.round(); } + +void CImageElement::transitionTo(const std::string& path, + eImageFitMode fitMode, + float duration, + const std::string& shaderSource) { + // New transition: drop the previous transition's cached fit-resolved FBOs. + g_renderer->clearTransitionCache(); + + if (m_impl->transition.active) { + // Capture the in-flight blend to an FBO and use it as the new start texture. + if (m_impl->transition.startTexture && m_impl->transition.endTexture) { + IRenderer::STransitionRenderData captureData = { + .box = impl->position, + .startTexture = m_impl->transition.startTexture, + .endTexture = m_impl->transition.endTexture, + .progress = m_impl->transition.progress, + .a = 1.F, + .fitMode = m_impl->data.fitMode, + .shaderKey = m_impl->transition.shaderKey, + .randomPixel = m_impl->transition.randomPixel, + .duration = m_impl->transition.duration, + }; + + auto capturedTex = g_renderer->captureTransitionState(captureData); + if (capturedTex) + m_impl->transition.startTexture = capturedTex; + } + } else if (m_impl->cacheEntry && m_impl->cacheEntry->tex()) { + // Pre-render the current wallpaper to a full-screen, fit-resolved frame at the fit + // mode it is currently displayed with (data.fitMode is still the outgoing mode here; + // it is reassigned below). The fit mode is consumed at pre-render time and is not + // carried as transition state, so the start frame stays fixed for the whole transition. + m_impl->transition.startTexture = g_renderer->renderFitFrame(m_impl->cacheEntry->tex(), impl->position, m_impl->data.fitMode); + } + + m_impl->transition.active = true; + m_impl->transition.progress = 0.0f; + m_impl->transition.shaderKey = g_renderer->ensureTransitionShader(shaderSource); + m_impl->transition.startTime = std::chrono::steady_clock::now(); + + m_impl->transition.randomPixel = Hyprutils::Math::Vector2D( + static_cast(rand() % 1000) / 1000.0f, + static_cast(rand() % 1000) / 1000.0f + ); + + // GLES cannot initialize uniform values, so u_duration is pushed to the shader + // each frame; a shader may further remap progress via a local const. + // duration <= 0 means an immediate (non-animated) swap. + m_impl->transition.duration = std::max(0.0f, duration); + + // Populated once the new asset finishes loading. + m_impl->transition.endTexture.reset(); + + m_impl->requestedGen++; + m_impl->data.path = path; + m_impl->data.fitMode = fitMode; + renderTex(); + + if (impl->window) + impl->window->scheduleReposition(impl->self.lock()); +} + +bool CImageElement::isTransitioning() const { + return m_impl->transition.active; +} + +float CImageElement::getTransitionProgressOut() const { + return m_impl->transition.progress; +} + +float CImageElement::getTransitionProgressIn() const { + return m_impl->transition.progress; +} + +void CImageElement::renderTransition() { + auto& trans = m_impl->transition; + + auto now = std::chrono::steady_clock::now(); + float elapsed = std::chrono::duration(now - trans.startTime).count(); + trans.progress = (trans.duration > 0.0f) ? std::clamp(elapsed / trans.duration, 0.0f, 1.0f) : 1.0f; + + const bool targetReady = m_impl->cacheEntry && m_impl->cacheEntry->tex(); + const bool targetFailed = m_impl->failed; + + if (trans.progress >= 1.0f) { + if (targetReady) { + // Normal completion. + trans.active = false; + trans.startTexture.reset(); + trans.endTexture.reset(); + g_renderer->clearTransitionCache(); + g_renderer->renderTexture({ + .box = impl->position, + .texture = m_impl->cacheEntry->tex(), + .a = 1.F, + .rounding = 0, + .fitMode = m_impl->data.fitMode, + }); + return; + } + if (targetFailed) { + // Failure completion: stop transitioning. oldCacheEntry is kept alive on + // failure, so the next paint() shows the previous image. Render the start + // texture for this frame if present. + trans.active = false; + g_renderer->clearTransitionCache(); + if (trans.startTexture) + g_renderer->renderTexture({ + .box = impl->position, + .texture = trans.startTexture, + .a = 1.F, + .rounding = 0, + }); + trans.startTexture.reset(); + trans.endTexture.reset(); + return; + } + // Still loading after the duration elapsed: keep showing the outgoing frame and + // DO NOT schedule animation frames (progress is saturated). + // postImageScheduleRecalc() damages on load completion. + if (trans.startTexture) + g_renderer->renderTexture({ + .box = impl->position, + .texture = trans.startTexture, + .a = 1.F, + .rounding = 0, + }); + return; // no scheduleReposition -> no busy-repaint while waiting + } + + // The end texture is resolved once the new asset finishes loading. + SP endTex; + if (m_impl->cacheEntry && m_impl->cacheEntry->tex()) { + endTex = m_impl->cacheEntry->tex(); + trans.endTexture = endTex; + } else + endTex = trans.endTexture; + + if (trans.startTexture && endTex) { + g_renderer->renderTransition({ + .box = impl->position, + .startTexture = trans.startTexture, + .endTexture = endTex, + .progress = trans.progress, + .a = 1.F, + .rounding = 0, + .fitMode = m_impl->data.fitMode, + .shaderKey = trans.shaderKey, + .randomPixel = trans.randomPixel, + .duration = trans.duration, + }); + } else if (trans.startTexture) { + // End texture not loaded yet, keep showing the start. + g_renderer->renderTexture({ + .box = impl->position, + .texture = trans.startTexture, + .a = 1.F, + .rounding = 0, + }); + } + + if (impl->window) + impl->window->scheduleReposition(impl->self.lock()); +} diff --git a/src/element/image/Image.hpp b/src/element/image/Image.hpp index f3d586b3..5177af41 100644 --- a/src/element/image/Image.hpp +++ b/src/element/image/Image.hpp @@ -39,20 +39,40 @@ namespace Hyprtoolkit { Hyprutils::Math::Vector2D size; bool waitingForTex = false, failed = false; - uint64_t requestGeneration = 0; std::vector> requests; - std::string lastPath = ""; - void* lastData = nullptr; + // Request-generation model (supersession): requestedGen is bumped on every new + // image request (renderTex / replaceData / transitionTo); inflightGen is the gen + // of the load currently in flight; satisfiedGen is the gen satisfied by the + // current cacheEntry (load completion OR cache hit). A request is satisfied iff + // satisfiedGen == requestedGen. + uint64_t requestedGen = 0; + uint64_t inflightGen = 0; + uint64_t satisfiedGen = 0; - Hyprutils::Math::Vector2D preferredSvgSize(); - void postImageLoad(const SP& request); - void postImageScheduleRecalc(); - std::string getCacheString(); - bool scalable() const; + std::string lastPath = ""; + void* lastData = nullptr; + + Hyprutils::Math::Vector2D preferredSvgSize(); + void postImageLoad(const SP& request); + void postImageScheduleRecalc(uint64_t gen); + std::string getCacheString(); + bool scalable() const; struct { Hyprutils::Signal::CHyprSignalListener cacheEntryDone; } listeners; + + struct { + bool active = false; + float progress = 0.0f; + float duration = 1.0f; + size_t shaderKey = 0; + std::chrono::steady_clock::time_point startTime; + Hyprutils::Math::Vector2D randomPixel; + + Hyprutils::Memory::CSharedPointer startTexture; + Hyprutils::Memory::CSharedPointer endTexture; + } transition; }; } diff --git a/src/renderer/Renderer.hpp b/src/renderer/Renderer.hpp index 5265bd59..cf412184 100644 --- a/src/renderer/Renderer.hpp +++ b/src/renderer/Renderer.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include "../helpers/Memory.hpp" @@ -19,6 +20,7 @@ namespace Hyprtoolkit { class IToolkitWindow; class IRendererTexture; class CSyncTimeline; + class CFramebuffer; class IRenderer { public: @@ -37,12 +39,13 @@ namespace Hyprtoolkit { }; struct STextureRenderData { - CBox box; - SP texture; - float a = 1.F; - int rounding = 0; - std::optional tint; - bool tintGrayscaleOnly = false; + CBox box; + SP texture; + float a = 1.F; + int rounding = 0; + std::optional tint; + bool tintGrayscaleOnly = false; + std::optional fitMode; // if unset, falls back to the texture's stored fit mode }; struct SBorderRenderData { @@ -65,6 +68,19 @@ namespace Hyprtoolkit { int thick = 2; }; + struct STransitionRenderData { + CBox box; + SP startTexture; + SP endTexture; + float progress = 0.0f; + float a = 1.F; + int rounding = 0; + eImageFitMode fitMode = IMAGE_FIT_MODE_COVER; + size_t shaderKey = 0; + Vector2D randomPixel; + float duration = 0.0f; // passed to shader via u_duration + }; + virtual void beginRendering(SP window, SP buf) = 0; virtual void beginRenderingExternal(SP window, uint32_t bufferAge) = 0; virtual void render(bool ignoreSync = false) = 0; @@ -72,8 +88,17 @@ namespace Hyprtoolkit { virtual void renderRectangle(const SRectangleRenderData& data) = 0; virtual SP uploadTexture(const STextureData& data) = 0; virtual void renderTexture(const STextureRenderData& data) = 0; + virtual void renderTransition(const STransitionRenderData& data) = 0; virtual void renderBorder(const SBorderRenderData& data) = 0; virtual void renderPolygon(const SPolygonRenderData& data) = 0; + virtual SP captureTransitionState(const STransitionRenderData& data) = 0; + // Pre-render a single texture to a fit-resolved offscreen FBO and return the + // resolved texture. Cached; the transition shaders are pure crossfades. + virtual SP renderFitFrame(const SP& src, const CBox& box, eImageFitMode fitMode) = 0; + // Drop all cached fit-resolved pre-render FBOs (call when a transition starts/ends). + virtual void clearTransitionCache() = 0; + // Compile a transition shader from raw GLSL source and cache it. Returns the cache key. + virtual size_t ensureTransitionShader(const std::string& source) = 0; virtual void renderLine(const SLineRenderData& data) = 0; virtual void signalRenderPoint(SP timeline) = 0; diff --git a/src/renderer/gl/Framebuffer.cpp b/src/renderer/gl/Framebuffer.cpp index b8c1e874..d9c634b6 100644 --- a/src/renderer/gl/Framebuffer.cpp +++ b/src/renderer/gl/Framebuffer.cpp @@ -49,6 +49,7 @@ bool CFramebuffer::alloc(int w, int h, uint32_t drmFormat) { if (firstAlloc || m_size != Vector2D(w, h)) { m_tex->bind(); glTexImage2D(GL_TEXTURE_2D, 0, glFormat, w, h, 0, GL_RGBA, glType, nullptr); + m_tex->m_size = Vector2D(w, h); glBindFramebuffer(GL_FRAMEBUFFER, m_fb); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_tex->m_texID, 0); diff --git a/src/renderer/gl/GLTexture.hpp b/src/renderer/gl/GLTexture.hpp index 0b8d99a3..44ea7752 100644 --- a/src/renderer/gl/GLTexture.hpp +++ b/src/renderer/gl/GLTexture.hpp @@ -12,6 +12,7 @@ namespace Hyprtoolkit { struct SBackendLifetime; + class CFramebuffer; enum eGLTextureType : uint8_t { TEXTURE_INVALID, // Invalid TEXTURE_RGBA, // 4 channels @@ -48,6 +49,10 @@ namespace Hyprtoolkit { ASP m_resource; WP m_lifetime; + // True when this texture is already a fit-resolved full-screen frame; + // renderFitFrame returns it unchanged so it is never fit-transformed twice. + bool m_fitApplied = false; + void upload(); void uploadOnContext(WP self); void releaseFromRenderer(); diff --git a/src/renderer/gl/OpenGL.cpp b/src/renderer/gl/OpenGL.cpp index 6f65ee68..cba2fd8e 100644 --- a/src/renderer/gl/OpenGL.cpp +++ b/src/renderer/gl/OpenGL.cpp @@ -12,6 +12,8 @@ #include "Sync.hpp" #include +#include +#include #include #include @@ -110,6 +112,72 @@ static GLuint createProgram(const std::string& vert, const std::string& frag) { return prog; } +// Non-fatal variants of compileShader()/createProgram() for untrusted, caller-supplied +// transition shaders (hyprpaper config/IPC). On failure they log nothing themselves but +// fill `err` (including the GLSL info log) and delete every GL object created so far. +static bool tryCompileShader(const GLuint& type, const std::string& src, GLuint& outShader, std::string& err) { + auto shader = glCreateShader(type); + + auto shaderSource = src.c_str(); + + glShaderSource(shader, 1, &shaderSource, nullptr); + glCompileShader(shader); + + GLint ok; + glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); + + if (ok == GL_FALSE) { + GLint logLen = 0; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLen); + std::string log(sc(logLen > 0 ? logLen : 1), '\0'); + glGetShaderInfoLog(shader, logLen, nullptr, log.data()); + err = std::format("shader compilation failed: {}", log); + glDeleteShader(shader); + return false; + } + + outShader = shader; + return true; +} + +static bool tryCreateProgram(const std::string& vert, const std::string& frag, GLuint& outProg, std::string& err) { + GLuint vertCompiled = 0; + if (!tryCompileShader(GL_VERTEX_SHADER, vert, vertCompiled, err)) + return false; + + GLuint fragCompiled = 0; + if (!tryCompileShader(GL_FRAGMENT_SHADER, frag, fragCompiled, err)) { + glDeleteShader(vertCompiled); + return false; + } + + auto prog = glCreateProgram(); + glAttachShader(prog, vertCompiled); + glAttachShader(prog, fragCompiled); + glLinkProgram(prog); + + glDetachShader(prog, vertCompiled); + glDetachShader(prog, fragCompiled); + glDeleteShader(vertCompiled); + glDeleteShader(fragCompiled); + + GLint ok; + glGetProgramiv(prog, GL_LINK_STATUS, &ok); + + if (ok == GL_FALSE) { + GLint logLen = 0; + glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLen); + std::string log(sc(logLen > 0 ? logLen : 1), '\0'); + glGetProgramInfoLog(prog, logLen, nullptr, log.data()); + err = std::format("program link failed: {}", log); + glDeleteProgram(prog); + return false; + } + + outProg = prog; + return true; +} + static void glMessageCallbackA(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { if (type != GL_DEBUG_TYPE_ERROR) return; @@ -433,6 +501,22 @@ void COpenGLRenderer::initGLResources() { m_borderShader.alpha = glGetUniformLocation(prog, "alpha"); m_borderShader.roundingPower = glGetUniformLocation(prog, "roundingPower"); + const auto TRANSFRAGSRC = processShader("transition.frag", includes); + prog = createProgram(VERTSRC, TRANSFRAGSRC); + m_transitionShader.program = prog; + m_transitionShader.proj = glGetUniformLocation(prog, "proj"); + m_transitionShader.tex = glGetUniformLocation(prog, "tex1"); + m_transitionShader.tex2 = glGetUniformLocation(prog, "tex2"); + m_transitionShader.progress = glGetUniformLocation(prog, "progress"); + m_transitionShader.alpha = glGetUniformLocation(prog, "alpha"); + m_transitionShader.posAttrib = glGetAttribLocation(prog, "pos"); + m_transitionShader.texAttrib = glGetAttribLocation(prog, "texcoord"); + m_transitionShader.topLeft = glGetUniformLocation(prog, "topLeft"); + m_transitionShader.fullSize = glGetUniformLocation(prog, "fullSize"); + m_transitionShader.radius = glGetUniformLocation(prog, "radius"); + m_transitionShader.uDuration = glGetUniformLocation(prog, "u_duration"); + m_transitionShader.randomPixel = glGetUniformLocation(prog, "randomPixel"); + glGenVertexArrays(1, &m_vao); glGenBuffers(1, &m_vbo); m_polyRenderFb = makeShared(); @@ -560,9 +644,12 @@ COpenGLRenderer::~COpenGLRenderer() { } m_textures.clear(); m_polyRenderFb.reset(); + m_fitFrameCache.clear(); // release cached fit-resolved transition frames while the context is current + m_customShaders.clear(); m_rectShader.destroy(); m_texShader.destroy(); m_borderShader.destroy(); + m_transitionShader.destroy(); if (m_vao) glDeleteVertexArrays(1, &m_vao); @@ -1125,7 +1212,12 @@ void COpenGLRenderer::renderTexture(const STextureRenderData& data) { SP tex = reinterpretPointerCast(data.texture); - const auto SOURCE_LAYOUT = data.texture->fitMode() == IMAGE_FIT_MODE_CONTAIN ? containImage(data.box, tex->m_size) : data.box; + // A fit-applied texture is already a fit-resolved full-screen frame (e.g. a transition + // start or capture): sample it with the identity mapping (STRETCH), never re-fit it. + // Otherwise a per-call fit mode overrides the texture's stored mode. + const eImageFitMode fit = tex->m_fitApplied ? IMAGE_FIT_MODE_STRETCH : data.fitMode.value_or(data.texture->fitMode()); + + const auto SOURCE_LAYOUT = fit == IMAGE_FIT_MODE_CONTAIN ? containImage(data.box, tex->m_size) : data.box; const auto SOURCE_BOX = presentationBox(SOURCE_LAYOUT); const auto ROUNDEDBOX = logicalToGL(SOURCE_BOX); const auto UNTRANSFORMED = logicalToGL(SOURCE_BOX, false); @@ -1167,9 +1259,9 @@ void COpenGLRenderer::renderTexture(const STextureRenderData& data) { std::array texVerts = { fullVerts[0], fullVerts[1], fullVerts[2], fullVerts[3], fullVerts[4], fullVerts[5], fullVerts[6], fullVerts[7], }; - if (data.texture->fitMode() == IMAGE_FIT_MODE_COVER) + if (fit == IMAGE_FIT_MODE_COVER) texVerts = coverImage(data.box, tex->m_size); - else if (data.texture->fitMode() == IMAGE_FIT_MODE_TILE) { + else if (fit == IMAGE_FIT_MODE_TILE) { texVerts = tileImage(data.box, tex->m_size); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_T, GL_REPEAT); @@ -1196,6 +1288,464 @@ void COpenGLRenderer::renderTexture(const STextureRenderData& data) { glBindTexture(tex->m_target, 0); } +size_t COpenGLRenderer::ensureTransitionShader(const std::string& source) { + if (source.empty()) + return 0; + + // May be invoked from the IPC handler outside the render loop. + makeEGLCurrent(); + + const auto KEY = std::hash{}(source); + + if (m_customShaders.contains(KEY)) + return KEY; + + // Caller-supplied shader: compile non-fatally. On any failure, log (including the + // GLSL info log) and fall back to the default transition shader. + GLuint prog = 0; + std::string err; + if (!tryCreateProgram(loadShader("tex300.vert"), source, prog, err)) { + g_logger->log(HT_LOG_ERROR, "ensureTransitionShader: failed to compile shader program: {}", err); + return 0; + } + + const GLint posAttrib = glGetAttribLocation(prog, "pos"); + const GLint texAttrib = glGetAttribLocation(prog, "texcoord"); + const GLint proj = glGetUniformLocation(prog, "proj"); + const GLint tex = glGetUniformLocation(prog, "tex1"); + const GLint tex2 = glGetUniformLocation(prog, "tex2"); + const GLint progress = glGetUniformLocation(prog, "progress"); + const GLint alpha = glGetUniformLocation(prog, "alpha"); + const GLint topLeft = glGetUniformLocation(prog, "topLeft"); + const GLint fullSize = glGetUniformLocation(prog, "fullSize"); + const GLint radius = glGetUniformLocation(prog, "radius"); + const GLint uDuration = glGetUniformLocation(prog, "u_duration"); + const GLint randomPixel = glGetUniformLocation(prog, "randomPixel"); + + // Mandatory interface validation: attribs `pos`/`texcoord` (a -1 here makes + // glVertexAttribPointer/glEnableVertexAttribArray raise GL_INVALID_VALUE and break + // the draw) and uniforms `proj`/`tex1`/`tex2`/`progress` (a program missing these + // renders garbage; glUniform with -1 is a silent no-op, so validate explicitly). + // `pos`/`proj` come from the fixed vertex stage and are always active, so their + // check is redundant-but-harmless. Optional uniforms (`alpha`, `topLeft`, + // `fullSize`, `radius`, `randomPixel`, `u_duration`) may be -1; glUniform on them + // is a defined no-op. + if (posAttrib < 0 || texAttrib < 0 || proj < 0 || tex < 0 || tex2 < 0 || progress < 0) { + glDeleteProgram(prog); + g_logger->log(HT_LOG_ERROR, + "ensureTransitionShader: shader is missing required interface (pos={}, texcoord={}, proj={}, tex1={}, tex2={}, progress={}); " + "the custom fragment must declare `uniform sampler2D tex1, tex2; uniform float progress;` and consume v_texcoord", + posAttrib, texAttrib, proj, tex, tex2, progress); + return 0; + } + + // Build directly into the cache so the program outlives this scope. + auto& entry = m_customShaders[KEY]; + auto& sh = entry.shader; + sh.program = prog; + sh.posAttrib = posAttrib; + sh.texAttrib = texAttrib; + sh.proj = proj; + sh.tex = tex; + sh.tex2 = tex2; + sh.progress = progress; + sh.alpha = alpha; + sh.topLeft = topLeft; + sh.fullSize = fullSize; + sh.radius = radius; + sh.uDuration = uDuration; + sh.randomPixel = randomPixel; + + return KEY; +} + +void COpenGLRenderer::renderTransition(const STransitionRenderData& data) { + RASSERT(data.startTexture->type() == IRendererTexture::TEXTURE_GL, "OpenGL renderer: passed a non-gl start texture"); + RASSERT(data.endTexture->type() == IRendererTexture::TEXTURE_GL, "OpenGL renderer: passed a non-gl end texture"); + + SP startTex = reinterpretPointerCast(data.startTexture); + SP endTex = reinterpretPointerCast(data.endTexture); + + const auto ROUNDEDBOX = logicalToGL(data.box); + const auto UNTRANSFORMED = logicalToGL(data.box, false); + Mat3x3 matrix = m_projMatrix.projectBox(ROUNDEDBOX, HYPRUTILS_TRANSFORM_FLIPPED_180, data.box.rot); + Mat3x3 glMatrix = m_projection.copy().multiply(matrix); + + const auto DAMAGE = damageWithClip(); + + if (DAMAGE.copy().intersect(UNTRANSFORMED).empty()) + return; + + // Pre-render both frames to fit-resolved offscreen FBOs (cached). The transition + // shaders are pure crossfades, so all fit handling lives here. + SP startFitTex = reinterpretPointerCast(renderFitFrame(startTex, data.box, data.fitMode)); + SP endFitTex = reinterpretPointerCast(renderFitFrame(endTex, data.box, data.fitMode)); + if (!startFitTex || !endFitTex) + return; + + CShader* activeShader = &m_transitionShader; + if (data.shaderKey) { + // Shader was loaded by ensureTransitionShader() at transition start; just look it up. + auto it = m_customShaders.find(data.shaderKey); + if (it != m_customShaders.end()) + activeShader = &it->second.shader; + } + + glUseProgram(activeShader->program); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(startFitTex->m_target, startFitTex->m_texID); + glUniform1i(activeShader->tex, 0); + + glActiveTexture(GL_TEXTURE1); + glBindTexture(endFitTex->m_target, endFitTex->m_texID); + glUniform1i(activeShader->tex2, 1); + + glUniformMatrix3fv(activeShader->proj, 1, GL_TRUE, glMatrix.getMatrix().data()); + glUniform1f(activeShader->progress, data.progress); + glUniform1f(activeShader->alpha, data.a); + + const auto TOPLEFT = Vector2D(UNTRANSFORMED.x, UNTRANSFORMED.y); + const auto FULLSIZE = Vector2D(UNTRANSFORMED.width, UNTRANSFORMED.height); + glUniform2f(activeShader->topLeft, TOPLEFT.x, TOPLEFT.y); + glUniform2f(activeShader->fullSize, FULLSIZE.x, FULLSIZE.y); + glUniform1f(activeShader->radius, data.rounding * m_scale); + glUniform2f(activeShader->randomPixel, data.randomPixel.x, data.randomPixel.y); + if (activeShader->uDuration >= 0) + glUniform1f(activeShader->uDuration, data.duration); + + std::array vertices; + std::ranges::copy(fullVerts, vertices.begin()); + std::ranges::copy(fullVerts, vertices.begin() + 8); + uploadVertices(vertices.data(), sizeof(vertices)); + glVertexAttribPointer(activeShader->posAttrib, 2, GL_FLOAT, GL_FALSE, 0, nullptr); + glVertexAttribPointer(activeShader->texAttrib, 2, GL_FLOAT, GL_FALSE, 0, rc(sizeof(fullVerts))); + + glEnableVertexAttribArray(activeShader->posAttrib); + glEnableVertexAttribArray(activeShader->texAttrib); + + DAMAGE.forEachRect([this](const auto& RECT) { + scissor(&RECT); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + }); + + glDisableVertexAttribArray(activeShader->posAttrib); + glDisableVertexAttribArray(activeShader->texAttrib); + + // Unbind textures + glActiveTexture(GL_TEXTURE1); + glBindTexture(endFitTex->m_target, 0); + glActiveTexture(GL_TEXTURE0); + glBindTexture(startFitTex->m_target, 0); +} + +SP COpenGLRenderer::captureTransitionState(const STransitionRenderData& data) { + if (!data.startTexture || !data.endTexture) + return nullptr; + + RASSERT(data.startTexture->type() == IRendererTexture::TEXTURE_GL, "OpenGL renderer: passed a non-gl start texture"); + RASSERT(data.endTexture->type() == IRendererTexture::TEXTURE_GL, "OpenGL renderer: passed a non-gl end texture"); + + // Capture may be called from the IPC handler, outside the render loop. + makeEGLCurrent(); + + SP startTex = reinterpretPointerCast(data.startTexture); + SP endTex = reinterpretPointerCast(data.endTexture); + + // Pre-render both source frames (fit-resolved) so the captured blend is correct + // for every fit mode; the transition shader is a pure crossfade. + SP startFitTex = reinterpretPointerCast(renderFitFrame(startTex, data.box, data.fitMode)); + SP endFitTex = reinterpretPointerCast(renderFitFrame(endTex, data.box, data.fitMode)); + if (!startFitTex || !endFitTex) + return nullptr; + + int w = static_cast(data.box.width * m_scale); + int h = static_cast(data.box.height * m_scale); + if (w <= 0 || h <= 0) + return nullptr; + + // Save GL state before alloc(): alloc() rebinds GL_FRAMEBUFFER and leaves the + // binding at 0, so prevFb must be captured beforehand to restore it afterwards. + GLint prevViewport[4]; + glGetIntegerv(GL_VIEWPORT, prevViewport); + GLint prevFb = 0; + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prevFb); + GLboolean prevScissor = glIsEnabled(GL_SCISSOR_TEST); + GLboolean prevBlend = glIsEnabled(GL_BLEND); + GLint prevScissorBox[4]; + glGetIntegerv(GL_SCISSOR_BOX, prevScissorBox); + + auto captureFb = makeShared(); + if (!captureFb->alloc(w, h)) { + g_logger->log(HT_LOG_ERROR, "captureTransitionState: failed to allocate framebuffer"); + glBindFramebuffer(GL_FRAMEBUFFER, prevFb); + return nullptr; + } + + glBindFramebuffer(GL_FRAMEBUFFER, captureFb->getFBID()); + glViewport(0, 0, w, h); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_BLEND); + + // This FBO is the *result* of the blend (not a per-image pre-render), so an + // opaque black clear is correct — the full-box draw overwrites it. + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + + // Use the cached custom shader if any (it was loaded by a prior renderTransition). + CShader* activeShader = &m_transitionShader; + if (data.shaderKey) { + auto it = m_customShaders.find(data.shaderKey); + if (it != m_customShaders.end()) + activeShader = &it->second.shader; + else + g_logger->log(HT_LOG_ERROR, "captureTransitionState: custom shader not in cache: {}", data.shaderKey); + } + + glUseProgram(activeShader->program); + + // Project a box covering the full FBO into 0..1 vertices. + CBox captureBox{0, 0, (float)w, (float)h}; + Mat3x3 captureProj = Mat3x3::outputProjection(Vector2D{w, h}, HYPRUTILS_TRANSFORM_FLIPPED_180); + Mat3x3 captureMat = captureProj.projectBox(captureBox, HYPRUTILS_TRANSFORM_FLIPPED_180, 0); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(startFitTex->m_target, startFitTex->m_texID); + glUniform1i(activeShader->tex, 0); + + glActiveTexture(GL_TEXTURE1); + glBindTexture(endFitTex->m_target, endFitTex->m_texID); + glUniform1i(activeShader->tex2, 1); + + glUniformMatrix3fv(activeShader->proj, 1, GL_TRUE, captureMat.getMatrix().data()); + glUniform1f(activeShader->progress, data.progress); + glUniform1f(activeShader->alpha, data.a); + + const auto TOPLEFT = Vector2D(0, 0); + const auto FULLSIZE = Vector2D(w, h); + glUniform2f(activeShader->topLeft, TOPLEFT.x, TOPLEFT.y); + glUniform2f(activeShader->fullSize, FULLSIZE.x, FULLSIZE.y); + glUniform1f(activeShader->radius, data.rounding * m_scale); + glUniform2f(activeShader->randomPixel, data.randomPixel.x, data.randomPixel.y); + if (activeShader->uDuration >= 0) + glUniform1f(activeShader->uDuration, data.duration); + + GLfloat fullVerts[] = { 0, 0, 1, 0, 0, 1, 1, 1 }; + std::array vertices; + std::ranges::copy(fullVerts, vertices.begin()); + std::ranges::copy(fullVerts, vertices.begin() + 8); + uploadVertices(vertices.data(), sizeof(vertices)); + glVertexAttribPointer(activeShader->posAttrib, 2, GL_FLOAT, GL_FALSE, 0, nullptr); + glVertexAttribPointer(activeShader->texAttrib, 2, GL_FLOAT, GL_FALSE, 0, rc(sizeof(fullVerts))); + + glEnableVertexAttribArray(activeShader->posAttrib); + glEnableVertexAttribArray(activeShader->texAttrib); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + glDisableVertexAttribArray(activeShader->posAttrib); + glDisableVertexAttribArray(activeShader->texAttrib); + + glActiveTexture(GL_TEXTURE1); + glBindTexture(endFitTex->m_target, 0); + glActiveTexture(GL_TEXTURE0); + glBindTexture(startFitTex->m_target, 0); + + glUseProgram(0); + glViewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]); + if (prevScissor) { + glEnable(GL_SCISSOR_TEST); + glScissor(prevScissorBox[0], prevScissorBox[1], prevScissorBox[2], prevScissorBox[3]); + } else + glDisable(GL_SCISSOR_TEST); + if (prevBlend) + glEnable(GL_BLEND); + else + glDisable(GL_BLEND); + + SP capturedTex = captureFb->getTexture(); + if (!capturedTex) { + // NOTE: dead branch — getTexture() is non-null after a successful alloc(); kept for consistency. + g_logger->log(HT_LOG_ERROR, "captureTransitionState: failed to get texture from framebuffer"); + captureFb.reset(); // releases the FBO (binds 0) before restoring the caller's binding + glBindFramebuffer(GL_FRAMEBUFFER, prevFb); + return nullptr; + } + + // The captured blend is already fit-resolved, so mark it to prevent a second fit pass. + capturedTex->m_fitApplied = true; + + // Release the FBO before restoring the caller's framebuffer binding: ~CFramebuffer + // -> release() issues glBindFramebuffer(0) and would clobber the restored binding. + // The EGL context is current here (makeEGLCurrent() above), so the GL calls in + // release() are safe. + captureFb.reset(); + glBindFramebuffer(GL_FRAMEBUFFER, prevFb); // restore the caller's render target AFTER the FBO release + + return capturedTex; +} + +SP COpenGLRenderer::renderFitFrame(const SP& src, const CBox& box, eImageFitMode fitMode) { + RASSERT(src->type() == IRendererTexture::TEXTURE_GL, "OpenGL renderer: passed a non-gl texture to renderFitFrame"); + + SP tex = reinterpretPointerCast(src); + + // Already a fit-resolved frame (the output of an earlier pre-render or + // capture). Return it unchanged so it is never fit-transformed twice. + if (tex->m_fitApplied) + return src; + + // May run from the IPC handler, outside the render loop. + makeEGLCurrent(); + + const int w = static_cast(box.width * m_scale); + const int h = static_cast(box.height * m_scale); + if (w <= 0 || h <= 0) + return nullptr; + + // Re-render only when the source identity, its size, the target box, or the + // fit mode changes; otherwise reuse the cached fit-resolved frame. + const SFitFrameKey key{tex->m_texID, tex->m_size, w, h, static_cast(fitMode)}; + auto cached = m_fitFrameCache.find(key); + if (cached != m_fitFrameCache.end() && cached->second) + return cached->second; + + // Save the GL state up front: captureFb->alloc() rebinds GL_FRAMEBUFFER and leaves + // the binding at 0, so prevFb must be captured beforehand in order to restore the + // caller's framebuffer (the surface) after the pre-render. + GLint prevViewport[4]; + glGetIntegerv(GL_VIEWPORT, prevViewport); + GLint prevFb = 0; + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prevFb); + GLboolean prevScissor = glIsEnabled(GL_SCISSOR_TEST); + GLboolean prevBlend = glIsEnabled(GL_BLEND); + GLint prevActiveTex = 0; + glGetIntegerv(GL_ACTIVE_TEXTURE, &prevActiveTex); + + auto captureFb = makeShared(); + if (!captureFb->alloc(w, h)) { + g_logger->log(HT_LOG_ERROR, "renderFitFrame: failed to allocate framebuffer"); + glBindFramebuffer(GL_FRAMEBUFFER, prevFb); + return nullptr; + } + + glBindFramebuffer(GL_FRAMEBUFFER, captureFb->getFBID()); + glViewport(0, 0, w, h); + glDisable(GL_SCISSOR_TEST); + + // CONTAIN letterbox must stay transparent to match renderTexture's + // left-untouched clear. (This is a per-image pre-render, NOT the blend + // result, so it differs from captureTransitionState's opaque clear.) + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + glClear(GL_COLOR_BUFFER_BIT); + + // Premultiplied-alpha texture draw, mirroring renderTexture's environment. + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + + CShader* shader = &m_texShader; + glUseProgram(shader->program); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(tex->m_target, tex->m_texID); + glUniform1i(shader->tex, 0); + + // Project the (possibly contain-shrunk) box into the full FBO. The box is in + // FBO-pixel units so it matches outputProjection's {w,h} size. + const CBox srcBox = fitMode == IMAGE_FIT_MODE_CONTAIN + ? containImage(CBox{0, 0, (float)w, (float)h}, tex->m_size) + : CBox{0, 0, (float)w, (float)h}; + Mat3x3 outProj = Mat3x3::outputProjection(Vector2D{w, h}, HYPRUTILS_TRANSFORM_FLIPPED_180); + Mat3x3 drawMat = outProj.projectBox(srcBox, HYPRUTILS_TRANSFORM_FLIPPED_180, 0); + glUniformMatrix3fv(shader->proj, 1, GL_TRUE, drawMat.getMatrix().data()); + glUniform1f(shader->alpha, 1.F); + + // Plain textured quad: no rounding, no discard, no tint (same as renderTexture). + glUniform2f(shader->topLeft, 0.0f, 0.0f); + glUniform2f(shader->fullSize, (float)w, (float)h); + glUniform1f(shader->radius, 0.F); + glUniform1f(shader->roundingPower, 2.F); + glUniform1i(shader->discardOpaque, 0); + glUniform1i(shader->discardAlpha, 0); + glUniform1i(shader->applyTint, 0); + + // Per-mode geometry / texcoords / wrap — identical rules to renderTexture. + // coverImage/tileImage only need the box aspect ratio, so the logical box is fine. + std::array texVerts = { + fullVerts[0], fullVerts[1], fullVerts[2], fullVerts[3], fullVerts[4], fullVerts[5], fullVerts[6], fullVerts[7], + }; + if (fitMode == IMAGE_FIT_MODE_COVER) + texVerts = coverImage(box, tex->m_size); + else if (fitMode == IMAGE_FIT_MODE_TILE) { + texVerts = tileImage(box, tex->m_size); + glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_T, GL_REPEAT); + } + + std::array fitVertices; + std::ranges::copy(fullVerts, fitVertices.begin()); + std::ranges::copy(texVerts, fitVertices.begin() + 8); + uploadVertices(fitVertices.data(), sizeof(fitVertices)); + glVertexAttribPointer(shader->posAttrib, 2, GL_FLOAT, GL_FALSE, 0, nullptr); + glVertexAttribPointer(shader->texAttrib, 2, GL_FLOAT, GL_FALSE, 0, rc(sizeof(fullVerts))); + + glEnableVertexAttribArray(shader->posAttrib); + glEnableVertexAttribArray(shader->texAttrib); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + glDisableVertexAttribArray(shader->posAttrib); + glDisableVertexAttribArray(shader->texAttrib); + + // Restore TILE wrap so it never leaks into the crossfade or later draws. + if (fitMode == IMAGE_FIT_MODE_TILE) { + glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + + glBindTexture(tex->m_target, 0); + glUseProgram(0); + + // Restore GL state (framebuffer binding is restored last, after the FBO release below). + glViewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]); + if (prevScissor) + glEnable(GL_SCISSOR_TEST); + else + glDisable(GL_SCISSOR_TEST); + if (prevBlend) + glEnable(GL_BLEND); + else + glDisable(GL_BLEND); + glActiveTexture(prevActiveTex); + + SP capturedTex = captureFb->getTexture(); + if (!capturedTex) { + // NOTE: dead branch — getTexture() is non-null after a successful alloc(); kept for consistency. + g_logger->log(HT_LOG_ERROR, "renderFitFrame: failed to get texture from framebuffer"); + captureFb.reset(); // releases the FBO (binds 0) before restoring the caller's binding + glBindFramebuffer(GL_FRAMEBUFFER, prevFb); + return nullptr; + } + + // Mark the fit-resolved texture so it is never fit-transformed again. + capturedTex->m_fitApplied = true; + + m_fitFrameCache[key] = capturedTex; + + // Release the FBO before restoring the caller's framebuffer binding: ~CFramebuffer + // -> release() issues glBindFramebuffer(0) and would clobber the restored binding. + // The EGL context is current here (makeEGLCurrent() above), so the GL calls in + // release() are safe. + captureFb.reset(); + glBindFramebuffer(GL_FRAMEBUFFER, prevFb); // restore the caller's render target AFTER the FBO release + + return capturedTex; +} + +void COpenGLRenderer::clearTransitionCache() { + m_fitFrameCache.clear(); +} + void COpenGLRenderer::renderBorder(const SBorderRenderData& data) { const auto PRESENTED = presentationBox(data.box); const auto ROUNDEDBOX = logicalToGL(PRESENTED); diff --git a/src/renderer/gl/OpenGL.hpp b/src/renderer/gl/OpenGL.hpp index 38e6930f..afcdbe7d 100644 --- a/src/renderer/gl/OpenGL.hpp +++ b/src/renderer/gl/OpenGL.hpp @@ -38,8 +38,14 @@ namespace Hyprtoolkit { virtual void renderRectangle(const SRectangleRenderData& data); virtual SP uploadTexture(const STextureData& data); virtual void renderTexture(const STextureRenderData& data); + virtual void renderTransition(const STransitionRenderData& data); virtual void renderBorder(const SBorderRenderData& data); virtual void renderPolygon(const SPolygonRenderData& data); + virtual SP captureTransitionState(const STransitionRenderData& data); + // Pre-render a single texture to a fit-resolved offscreen FBO (cached). + SP renderFitFrame(const SP& src, const CBox& box, eImageFitMode fitMode); + void clearTransitionCache(); + virtual size_t ensureTransitionShader(const std::string& source); virtual void renderLine(const SLineRenderData& data); virtual SP exportSync(SP buf); virtual void signalRenderPoint(SP timeline); @@ -174,8 +180,36 @@ namespace Hyprtoolkit { CShader m_rectShader; CShader m_texShader; + CShader m_transitionShader; CShader m_borderShader; + // Custom transition shaders, cached by source hash. + struct SCachedShader { + CShader shader; + }; + std::unordered_map m_customShaders; + + // Fit-resolved pre-render cache for transitions. Keyed by the source texture + // identity, its size, the target box (pixels) and fit mode, so a frame is only + // re-rendered when one of those changes. + struct SFitFrameKey { + GLuint texID = 0; + Vector2D size; + int boxW = 0; + int boxH = 0; + int fitMode = 0; + bool operator==(const SFitFrameKey& o) const { + return texID == o.texID && size == o.size && boxW == o.boxW && boxH == o.boxH && fitMode == o.fitMode; + } + }; + struct SFitFrameKeyHash { + size_t operator()(const SFitFrameKey& k) const { + return std::hash()(k.texID) ^ std::hash()(k.size.x) ^ std::hash()(k.size.y) ^ + std::hash()(k.boxW) ^ std::hash()(k.boxH) ^ std::hash()(k.fitMode); + } + }; + std::unordered_map, SFitFrameKeyHash> m_fitFrameCache; + Mat3x3 m_projMatrix = Mat3x3::identity(); Mat3x3 m_projection; diff --git a/src/renderer/gl/Shader.hpp b/src/renderer/gl/Shader.hpp index e3e32d75..4556ae33 100644 --- a/src/renderer/gl/Shader.hpp +++ b/src/renderer/gl/Shader.hpp @@ -54,6 +54,11 @@ class CShader { GLint distort = -1; GLint wl_output = -1; + // Transition shader + GLint progress = -1; + GLint uDuration = -1; // uniform u_duration (host-passed) + GLint randomPixel = -1; + // Blur prepare GLint contrast = -1; diff --git a/src/renderer/gl/shaders/glsl/transition.frag b/src/renderer/gl/shaders/glsl/transition.frag new file mode 100644 index 00000000..a82199f8 --- /dev/null +++ b/src/renderer/gl/shaders/glsl/transition.frag @@ -0,0 +1,17 @@ +#version 300 es + +precision highp float; + +in vec2 v_texcoord; + +uniform sampler2D tex1; // Start frame (fit pre-resolved in C++ via renderFitFrame) +uniform sampler2D tex2; // End frame (fit pre-resolved in C++) +uniform float progress; // 0.0 = fully start, 1.0 = fully end +uniform float alpha; // Overall opacity + +layout(location = 0) out vec4 fragColor; + +void main() { + vec4 blended = mix(texture(tex1, v_texcoord), texture(tex2, v_texcoord), progress); + fragColor = blended * alpha; +}