packages feed

nano-ui-sdl-0.2.0.0: cbits/nano_ui_render.c

#define SDL_OPENGL_1_NO_PROTOTYPES
#include <SDL3/SDL.h>
#include <SDL3/SDL_opengl.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "nano_ui_ttf_shared.h"

/* The batch reads the core's draw buffer in place as SDL_Vertex: x and y,
 * then red, green, blue and alpha, then u and v, as 32-bit floats. */
_Static_assert(sizeof(SDL_Vertex) == NANO_UI_VERTEX_BYTES, "SDL_Vertex must be the core's 32-byte vertex");
_Static_assert(offsetof(SDL_Vertex, position) == 0, "SDL_Vertex starts with its position");
_Static_assert(offsetof(SDL_Vertex, color) == 8, "SDL_Vertex colour follows the 2-float position");
_Static_assert(offsetof(SDL_Vertex, tex_coord) == 24, "SDL_Vertex UV follows the 4-float colour");
_Static_assert(sizeof(SDL_FColor) == 16, "SDL_Vertex colour is four floats");

/* OpenGL 3.2 functions loaded dynamically via SDL_GL_GetProcAddress so
 * nano-ui-sdl needs no GL link libraries. GL 1.0/1.1 entries carry explicit
 * signatures (SDL 3.2/3.4.0's SDL_opengl.h omits their PFNGL typedefs);
 * GL 1.2+ entries reuse the PFNGL*PROC typedefs from SDL_opengl_glext.h. */
#define NUI_GL_FUNCS(C, E) \
    C(const GLubyte *, GetString, (GLenum)) \
    C(void, Viewport, (GLint, GLint, GLsizei, GLsizei)) \
    C(void, Scissor, (GLint, GLint, GLsizei, GLsizei)) \
    C(void, Enable, (GLenum)) \
    C(void, Disable, (GLenum)) \
    C(void, DrawElements, (GLenum, GLsizei, GLenum, const void *)) \
    C(void, DrawArrays, (GLenum, GLint, GLsizei)) \
    C(void, GenTextures, (GLsizei, GLuint *)) \
    C(void, BindTexture, (GLenum, GLuint)) \
    C(void, TexParameteri, (GLenum, GLenum, GLint)) \
    C(void, TexImage2D, (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *)) \
    C(void, DeleteTextures, (GLsizei, const GLuint *)) \
    E(ACTIVETEXTURE, ActiveTexture) \
    E(BLENDFUNCSEPARATE, BlendFuncSeparate) \
    E(BLENDEQUATION, BlendEquation) \
    E(CREATESHADER, CreateShader) \
    E(SHADERSOURCE, ShaderSource) \
    E(COMPILESHADER, CompileShader) \
    E(GETSHADERIV, GetShaderiv) \
    E(GETSHADERINFOLOG, GetShaderInfoLog) \
    E(DELETESHADER, DeleteShader) \
    E(CREATEPROGRAM, CreateProgram) \
    E(ATTACHSHADER, AttachShader) \
    E(BINDATTRIBLOCATION, BindAttribLocation) \
    E(LINKPROGRAM, LinkProgram) \
    E(GETPROGRAMIV, GetProgramiv) \
    E(GETPROGRAMINFOLOG, GetProgramInfoLog) \
    E(DELETEPROGRAM, DeleteProgram) \
    E(USEPROGRAM, UseProgram) \
    E(GETUNIFORMLOCATION, GetUniformLocation) \
    E(GETUNIFORMBLOCKINDEX, GetUniformBlockIndex) \
    E(UNIFORMBLOCKBINDING, UniformBlockBinding) \
    E(BINDBUFFERBASE, BindBufferBase) \
    E(UNIFORM4F, Uniform4f) \
    E(GENVERTEXARRAYS, GenVertexArrays) \
    E(BINDVERTEXARRAY, BindVertexArray) \
    E(DELETEVERTEXARRAYS, DeleteVertexArrays) \
    E(GENBUFFERS, GenBuffers) \
    E(BINDBUFFER, BindBuffer) \
    E(BUFFERDATA, BufferData) \
    E(BUFFERSUBDATA, BufferSubData) \
    E(DELETEBUFFERS, DeleteBuffers) \
    E(ENABLEVERTEXATTRIBARRAY, EnableVertexAttribArray) \
    E(VERTEXATTRIBPOINTER, VertexAttribPointer)

typedef struct {
#define NUI_C(ret, name, args) ret (APIENTRY *name) args;
#define NUI_E(UP, name) PFNGL##UP##PROC name;
    NUI_GL_FUNCS(NUI_C, NUI_E)
#undef NUI_C
#undef NUI_E
} NanoUiGlApi;

typedef struct {
    uint64_t hash;
    GLuint program;
    GLint uXform;
} NanoUiGlShaderEntry;

typedef struct {
    SDL_Renderer *renderer;
    int index_total;
    /* Device pixels per layout unit and logical origin subtracted when drawing
     * into an offscreen Tier 2 effect target (0, 0 on the main target). */
    float scale;
    float origin_x, origin_y;
    /* Current renderer clip state mirrored from Haskell so GL scissor matches. */
    int has_clip;
    SDL_Rect clip;
    /* Scaled x, y pairs of the pass's vertices for SDL_RenderGeometryRaw when
     * scale != 1 or origin != (0, 0); [xy_lo, xy_hi) of xy_verts are filled. */
    float *xy;
    int xy_cap, xy_lo, xy_hi;
    const uint8_t *xy_verts;
#if !SDL_VERSION_ATLEAST(3, 4, 0)
    /* Rebased indices for SDL 3.2 vertex narrowing (see narrow). */
    int *rebased;
    int rebased_cap;
#endif
    /* OpenGL 3.2 / GLSL 150 direct batching and shader state (active only when
     * SDL uses the "opengl" driver). */
    int init_state; /* 0 = unchecked, 1 = ready, -1 = unavailable */
    SDL_Window *win;
    SDL_GLContext ctx;
    NanoUiGlApi api;
    GLuint vs;
    GLuint vao, vbo, ebo;
    size_t vbo_cap, ebo_cap;
    GLuint quad_vao, quad_vbo;
    GLuint ubo, white_tex;
    NanoUiGlShaderEntry plain;
    const uint8_t *uploaded_verts;
    int uploaded_vert_count;
    const uint8_t *uploaded_indices;
    int uploaded_index_count;
    int pass_active;
    int cur_w, cur_h, is_target;
    int blend_enabled;
    int xform_valid;
    float xform_ox, xform_oy, xform_scale;
    GLuint bound_prog, bound_tex, bound_vao;
    NanoUiGlShaderEntry *shaders;
    int shader_count, shader_cap;
} NanoUiGl;

/* ---- Shared helpers and tight raw-buffer loops ---- */

static int is_opengl_renderer(SDL_Renderer *renderer)
{
    const char *name = renderer ? SDL_GetRendererName(renderer) : NULL;
    return name && strcmp(name, "opengl") == 0;
}

static void index_bounds(const int *idx, int n, int *out_lo, int *out_hi)
{
    int lo = idx[0], hi = idx[0];
    for (int k = 1; k < n; k++) {
        if (idx[k] < lo) lo = idx[k];
        if (idx[k] > hi) hi = idx[k];
    }
    *out_lo = lo;
    *out_hi = hi;
}

/* Commands may contain independent triangles, not just axis-aligned quads.
 * Reject a range only when every triangle is outside the damage bounds. SDL
 * clips intersecting triangles; this just avoids submitting invisible ranges. */
int nano_ui_range_visible(
    const uint8_t *verts, int vert_count, const uint8_t *indices, int index_start, int count,
    float x, float y, float w, float h)
{
    const SDL_Vertex *v = (const SDL_Vertex *)verts;
    const int *ix = (const int *)indices + index_start;
    const float rx = x + w, ry = y + h;
    for (int i = 0; i + 2 < count; i += 3) {
        if ((unsigned)ix[i] >= (unsigned)vert_count ||
            (unsigned)ix[i + 1] >= (unsigned)vert_count ||
            (unsigned)ix[i + 2] >= (unsigned)vert_count) {
            return 1;
        }
        const SDL_FPoint a = v[ix[i]].position;
        const SDL_FPoint b = v[ix[i + 1]].position;
        const SDL_FPoint c = v[ix[i + 2]].position;
        if (!((a.x < x && b.x < x && c.x < x) ||
              (a.x >= rx && b.x >= rx && c.x >= rx) ||
              (a.y < y && b.y < y && c.y < y) ||
              (a.y >= ry && b.y >= ry && c.y >= ry))) {
            return 1;
        }
    }
    return 0;
}

#if !SDL_VERSION_ATLEAST(3, 4, 0)
/* Narrow a batch's vertices to the range its indices use, rebasing indices to
 * its start. SDL 3.2 scans every vertex a textured call is given, and batches
 * share one frame buffer, so passing all of it makes a frame cost draws * verts. */
static void narrow(NanoUiGl *g, const SDL_Vertex **v, const int **idx, int n, int *nv)
{
    const int *ix = *idx;
    int lo, hi;
    index_bounds(ix, n, &lo, &hi);
    if (lo < 0 || hi >= *nv) return;
    *nv = hi + 1;
    if (lo == 0) return;
    if (g->rebased_cap < n) {
        int *grown = (int *)realloc(g->rebased, sizeof(int) * (size_t)n * 2);
        if (!grown) return;
        g->rebased = grown;
        g->rebased_cap = n * 2;
    }
    for (int k = 0; k < n; k++) {
        g->rebased[k] = ix[k] - lo;
    }
    *idx = g->rebased;
    *v += lo;
    *nv = hi - lo + 1;
}
#endif

static void scale_range(NanoUiGl *g, const SDL_Vertex *v, int from, int to)
{
    const float s = g->scale, ox = g->origin_x, oy = g->origin_y;
    for (int i = from; i < to; i++) {
        g->xy[2 * i] = (v[i].position.x - ox) * s;
        g->xy[2 * i + 1] = (v[i].position.y - oy) * s;
    }
}

/* Scaled positions covering the vertices the n indices idx use, counting from
 * vertex off of verts; NULL on allocation failure. */
static const float *scaled_positions(
    NanoUiGl *g, const uint8_t *verts, int total, int off, const int *idx, int n)
{
    if (g->xy_cap < total) {
        float *grown = (float *)realloc(g->xy, sizeof(float) * 2 * (size_t)total);
        if (!grown) return NULL;
        g->xy = grown;
        g->xy_cap = total;
    }
    int lo, hi;
    index_bounds(idx, n, &lo, &hi);
    lo += off;
    hi += off + 1;
    if (lo < 0) lo = 0;
    if (hi > total) hi = total;
    const SDL_Vertex *all = (const SDL_Vertex *)verts;
    if (g->xy_verts != verts || g->xy_lo >= g->xy_hi) {
        scale_range(g, all, lo, hi);
        g->xy_verts = verts;
        g->xy_lo = lo;
        g->xy_hi = hi;
    } else {
        if (lo < g->xy_lo) {
            scale_range(g, all, lo, g->xy_lo);
            g->xy_lo = lo;
        }
        if (hi > g->xy_hi) {
            scale_range(g, all, g->xy_hi, hi);
            g->xy_hi = hi;
        }
    }
    return g->xy + 2 * (size_t)off;
}

/* Submit an indexed range from the core's interleaved SDL_Vertex buffer via
 * SDL_RenderGeometryRaw, applying scale/origin transform on CPU when needed.
 * Untextured calls pass UVs too (every vertex has the white texel's UV):
 * SDL 3.4.0's software renderer reads UVs while merging triangles into rects
 * without checking for NULL, and segfaults. */
int nano_ui_sdl_draw_raw(
    NanoUiGl *g, SDL_Texture *tex,
    const uint8_t *verts, int vert_count,
    const uint8_t *indices, int index_start, int index_n)
{
    if (!g || !g->renderer || !verts || !indices || vert_count <= 0 || index_n < 3) return 0;
    const SDL_Vertex *v = (const SDL_Vertex *)verts;
    const int *idx = (const int *)indices + index_start;
    int nv = vert_count;
#if !SDL_VERSION_ATLEAST(3, 4, 0)
    narrow(g, &v, &idx, index_n, &nv);
#endif
    const int stride = (int)sizeof(SDL_Vertex);
    const float *xy = &v->position.x;
    int xy_stride = stride;
    if (g->scale != 1.f || g->origin_x != 0.f || g->origin_y != 0.f) {
        int off = (int)(v - (const SDL_Vertex *)verts);
        xy = scaled_positions(g, verts, vert_count, off, idx, index_n);
        xy_stride = (int)(2 * sizeof(float));
        if (!xy) return 0;
    }
    return SDL_RenderGeometryRaw(g->renderer, tex,
                                 xy, xy_stride, &v->color, stride,
                                 &v->tex_coord.x, stride,
                                 nv, idx, index_n, (int)sizeof(int)) ? 1 : 0;
}

/* ---- OpenGL 3.2 / GLSL 150 backend ---- */

/* Parse "major.minor..." from GL_VERSION and require OpenGL 3.2+ for GLSL 150. */
static int nui_gl_load(NanoUiGlApi *gl)
{
#define NUI_C(ret, name, args) \
    if (!(gl->name = (ret (APIENTRY *) args)SDL_GL_GetProcAddress("gl" #name))) return 0;
#define NUI_E(UP, name) \
    if (!(gl->name = (PFNGL##UP##PROC)SDL_GL_GetProcAddress("gl" #name))) return 0;
    NUI_GL_FUNCS(NUI_C, NUI_E)
#undef NUI_C
#undef NUI_E
    const GLubyte *ver = gl->GetString(GL_VERSION);
    int major = 0, minor = 0;
    return ver && sscanf((const char *)ver, "%d.%d", &major, &minor) >= 1 &&
           (major > 3 || (major == 3 && minor >= 2));
}

int nano_ui_gl_probe(SDL_Renderer *renderer)
{
    if (!is_opengl_renderer(renderer)) return 0;
    NanoUiGlApi tmp;
    return nui_gl_load(&tmp);
}

static const char *nui_gl_vertex_src =
    "#version 150\n"
    "in vec2 aPos;\n"
    "in vec4 aColor;\n"
    "in vec2 aUV;\n"
    "uniform vec4 uXform;\n"
    "out vec4 vColor;\n"
    "out vec2 vUV;\n"
    "void main() {\n"
    "  gl_Position = vec4(aPos * uXform.xy + uXform.zw, 0.0, 1.0);\n"
    "  vColor = aColor;\n"
    "  vUV = aUV;\n"
    "}\n";

/* Sampler uniform uInput defaults to texture unit 0 on link per OpenGL 3.2. */
static const char *nui_gl_plain_frag_src =
    "#version 150\n"
    "in vec4 vColor;\n"
    "in vec2 vUV;\n"
    "uniform sampler2D uInput;\n"
    "out vec4 fragColor;\n"
    "void main() {\n"
    "  fragColor = vColor * texture(uInput, vUV);\n"
    "}\n";

static int nui_gl_make_current(NanoUiGl *g)
{
    if (g->ctx && g->win && SDL_GL_GetCurrentContext() != g->ctx) {
        return SDL_GL_MakeCurrent(g->win, g->ctx) ? 1 : 0;
    }
    return 1;
}

static void nui_gl_set_linear_clamp(NanoUiGlApi *gl)
{
    gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}

static void nui_gl_init_vao(NanoUiGlApi *gl, GLuint *vao, GLuint *vbo, GLuint *ebo)
{
    gl->GenVertexArrays(1, vao);
    gl->GenBuffers(1, vbo);
    gl->BindVertexArray(*vao);
    gl->BindBuffer(GL_ARRAY_BUFFER, *vbo);
    if (ebo) {
        gl->GenBuffers(1, ebo);
        gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, *ebo);
    }
    const GLsizei stride = (GLsizei)sizeof(SDL_Vertex);
    gl->EnableVertexAttribArray(0);
    gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride, (const void *)offsetof(SDL_Vertex, position));
    gl->EnableVertexAttribArray(1);
    gl->VertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, stride, (const void *)offsetof(SDL_Vertex, color));
    gl->EnableVertexAttribArray(2);
    gl->VertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride, (const void *)offsetof(SDL_Vertex, tex_coord));
}

static GLuint nui_gl_compile(NanoUiGlApi *gl, GLenum type, const char *src, GLint len)
{
    GLuint sh = gl->CreateShader(type);
    GLint ok = 0;
    gl->ShaderSource(sh, 1, &src, len >= 0 ? &len : NULL);
    gl->CompileShader(sh);
    gl->GetShaderiv(sh, GL_COMPILE_STATUS, &ok);
    if (!ok) {
        char log[1024];
        gl->GetShaderInfoLog(sh, (GLsizei)sizeof(log), NULL, log);
        fprintf(stderr, "nano-ui-sdl: OpenGL shader compile failed: %s\n", log);
        gl->DeleteShader(sh);
        return 0;
    }
    return sh;
}

static void nui_gl_link_program(
    NanoUiGlApi *gl, GLuint vs, const char *frag_src, GLint frag_len, NanoUiGlShaderEntry *out)
{
    out->program = 0;
    out->uXform = -1;
    if (!vs || !frag_src || frag_len == 0) return;
    GLuint fs = nui_gl_compile(gl, GL_FRAGMENT_SHADER, frag_src, frag_len);
    if (!fs) return;
    GLuint prog = gl->CreateProgram();
    gl->AttachShader(prog, vs);
    gl->AttachShader(prog, fs);
    gl->BindAttribLocation(prog, 0, "aPos");
    gl->BindAttribLocation(prog, 1, "aColor");
    gl->BindAttribLocation(prog, 2, "aUV");
    gl->LinkProgram(prog);
    gl->DeleteShader(fs);
    GLint ok = 0;
    gl->GetProgramiv(prog, GL_LINK_STATUS, &ok);
    if (!ok) {
        char log[1024];
        gl->GetProgramInfoLog(prog, (GLsizei)sizeof(log), NULL, log);
        fprintf(stderr, "nano-ui-sdl: OpenGL shader link failed: %s\n", log);
        gl->DeleteProgram(prog);
        return;
    }
    GLuint blk = gl->GetUniformBlockIndex(prog, "NanoShaderBlock");
    if (blk != GL_INVALID_INDEX) gl->UniformBlockBinding(prog, blk, 0);
    out->program = prog;
    out->uXform = gl->GetUniformLocation(prog, "uXform");
}

static int nui_gl_ensure_init(NanoUiGl *g)
{
    if (g->init_state) return g->init_state > 0;
    if (!is_opengl_renderer(g->renderer)) {
        g->init_state = -1;
        return 0;
    }
    SDL_FlushRenderer(g->renderer);
    if (!g->win) g->win = SDL_GetRenderWindow(g->renderer);
    if (g->ctx) {
        if (!nui_gl_make_current(g)) return 0;
    } else {
        /* Only bind the current context when it belongs to this window, so a
         * multi-window session never attaches another window's GL context. */
        SDL_GLContext cur = SDL_GL_GetCurrentContext();
        if (!cur || (g->win && SDL_GL_GetCurrentWindow() != g->win)) return 0;
        g->ctx = cur;
    }
    g->init_state = -1;
    if (!nui_gl_load(&g->api)) return 0;

    NanoUiGlApi *gl = &g->api;
    nui_gl_init_vao(gl, &g->vao, &g->vbo, &g->ebo);
    nui_gl_init_vao(gl, &g->quad_vao, &g->quad_vbo, NULL);
    gl->BindVertexArray(0);
    gl->BindBuffer(GL_ARRAY_BUFFER, 0);
    gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    gl->GenBuffers(1, &g->ubo);

    gl->GenTextures(1, &g->white_tex);
    gl->ActiveTexture(GL_TEXTURE0);
    gl->BindTexture(GL_TEXTURE_2D, g->white_tex);
    nui_gl_set_linear_clamp(gl);
    const uint32_t white = 0xFFFFFFFFu;
    gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &white);
    gl->BindTexture(GL_TEXTURE_2D, 0);

    g->vs = nui_gl_compile(gl, GL_VERTEX_SHADER, nui_gl_vertex_src, -1);
    nui_gl_link_program(gl, g->vs, nui_gl_plain_frag_src, -1, &g->plain);
    SDL_FlushRenderer(g->renderer);
    g->init_state = 1;
    return 1;
}

static void nui_gl_apply_scissor(NanoUiGl *g)
{
    NanoUiGlApi *gl = &g->api;
    if (g->has_clip) {
        int sw = g->clip.w > 0 ? g->clip.w : 0;
        int sh = g->clip.h > 0 ? g->clip.h : 0;
        int sy = g->is_target ? g->clip.y : (g->cur_h - g->clip.y - sh);
        gl->Enable(GL_SCISSOR_TEST);
        gl->Scissor(g->clip.x, sy, sw, sh);
    } else {
        gl->Disable(GL_SCISSOR_TEST);
    }
}

static GLuint nui_gl_texture_id(SDL_Texture *tex)
{
    SDL_PropertiesID props = tex ? SDL_GetTextureProperties(tex) : 0;
    return props ? (GLuint)SDL_GetNumberProperty(props, SDL_PROP_TEXTURE_OPENGL_TEXTURE_NUMBER, 0) : 0;
}

/* Resolve the GL texture id and blend state for a standard plain batch,
 * returning 0 when a custom blend mode or texture format requires SDL's
 * fallback geometry path (such as transparent windows). */
static int nui_gl_plain_texture_id(NanoUiGl *g, SDL_Texture *tex, GLuint *out_tex, int *out_blend)
{
    SDL_BlendMode bm = SDL_BLENDMODE_NONE;
    bool got_bm = tex ? SDL_GetTextureBlendMode(tex, &bm)
                      : SDL_GetRenderDrawBlendMode(g->renderer, &bm);
    if (!got_bm || (bm != SDL_BLENDMODE_BLEND && bm != SDL_BLENDMODE_NONE)) return 0;
    *out_blend = (bm == SDL_BLENDMODE_BLEND);
    if (!tex) {
        *out_tex = g->white_tex;
        return 1;
    }
    SDL_PropertiesID props = SDL_GetTextureProperties(tex);
    if (!props ||
        SDL_GetNumberProperty(props, SDL_PROP_TEXTURE_OPENGL_TEXTURE_TARGET_NUMBER, 0) != GL_TEXTURE_2D ||
        SDL_GetFloatProperty(props, SDL_PROP_TEXTURE_OPENGL_TEX_W_FLOAT, 0.0f) != 1.0f ||
        SDL_GetFloatProperty(props, SDL_PROP_TEXTURE_OPENGL_TEX_H_FLOAT, 0.0f) != 1.0f) {
        return 0;
    }
    GLuint id = (GLuint)SDL_GetNumberProperty(props, SDL_PROP_TEXTURE_OPENGL_TEXTURE_NUMBER, 0);
    if (!id) return 0;
    *out_tex = id;
    return 1;
}

/* Take ownership of the OpenGL context from SDL for one or more consecutive
 * plain or shader draws against the current render target. */
static int nui_gl_enter_pass(NanoUiGl *g)
{
    if (g->pass_active) return 1;
    SDL_FlushRenderer(g->renderer);
    if (!nui_gl_make_current(g)) return 0;

    int cur_w = 0, cur_h = 0, is_target = 0;
    SDL_Texture *cur = SDL_GetRenderTarget(g->renderer);
    if (cur) {
        float tw = 0.f, th = 0.f;
        SDL_GetTextureSize(cur, &tw, &th);
        cur_w = (int)tw;
        cur_h = (int)th;
        is_target = 1;
    } else {
        SDL_GetRenderOutputSize(g->renderer, &cur_w, &cur_h);
    }
    if (cur_w <= 0 || cur_h <= 0) return 0;

    NanoUiGlApi *gl = &g->api;
    g->cur_w = cur_w;
    g->cur_h = cur_h;
    g->is_target = is_target;
    gl->Viewport(0, 0, cur_w, cur_h);
    gl->Disable(GL_DEPTH_TEST);
    gl->Disable(GL_CULL_FACE);
    nui_gl_apply_scissor(g);
    gl->BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    gl->BlendEquation(GL_FUNC_ADD);
    gl->ActiveTexture(GL_TEXTURE0);
    g->bound_prog = 0;
    g->bound_tex = 0;
    g->bound_vao = 0;
    g->blend_enabled = -1;
    g->xform_valid = 0;
    g->pass_active = 1;
    return 1;
}

/* Leave the OpenGL 3.2 pass and hand GL state back to SDL. */
void nano_ui_gl_leave_pass(NanoUiGl *g)
{
    if (!g || !g->pass_active) return;
    g->pass_active = 0;
    if (nui_gl_make_current(g)) {
        NanoUiGlApi *gl = &g->api;
        gl->UseProgram(0);
        gl->BindVertexArray(0);
        gl->BindBuffer(GL_ARRAY_BUFFER, 0);
        gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        gl->BindBuffer(GL_UNIFORM_BUFFER, 0);
        gl->ActiveTexture(GL_TEXTURE0);
        gl->BindTexture(GL_TEXTURE_2D, 0);
        gl->Disable(GL_SCISSOR_TEST);
        SDL_FlushRenderer(g->renderer);
    }
    if (g->renderer) {
        SDL_SetRenderClipRect(g->renderer, g->has_clip ? &g->clip : NULL);
    }
}

static NanoUiGlShaderEntry *nui_gl_resolve_shader(
    NanoUiGl *g, uint64_t hash, const uint8_t *glsl, int glsl_len)
{
    if (!glsl || glsl_len <= 0 || !nui_gl_ensure_init(g) || !nui_gl_enter_pass(g)) return NULL;
    for (int i = 0; i < g->shader_count; i++) {
        if (g->shaders[i].hash == hash) {
            return g->shaders[i].program ? &g->shaders[i] : NULL;
        }
    }
    if (g->shader_count == g->shader_cap) {
        int new_cap = g->shader_cap > 0 ? g->shader_cap * 2 : 16;
        NanoUiGlShaderEntry *grown = (NanoUiGlShaderEntry *)realloc(
            g->shaders, (size_t)new_cap * sizeof(*grown));
        if (!grown) return NULL;
        g->shaders = grown;
        g->shader_cap = new_cap;
    }
    NanoUiGlShaderEntry *entry = &g->shaders[g->shader_count++];
    entry->hash = hash;
    nui_gl_link_program(&g->api, g->vs, (const char *)glsl, (GLint)glsl_len, entry);
    return entry->program ? entry : NULL;
}

/* Bind program, affine transform, blend state, texture, and optional UBO
 * inside the active GL pass, skipping redundant state transitions. */
static int nui_gl_bind_draw(
    NanoUiGl *g, const NanoUiGlShaderEntry *entry,
    float ox, float oy, float scale, GLuint gl_tex, int want_blend,
    const uint8_t *uniform_bytes, int uniform_len)
{
    if (!nui_gl_enter_pass(g)) return 0;
    NanoUiGlApi *gl = &g->api;
    if (g->bound_prog != entry->program) {
        gl->UseProgram(entry->program);
        g->bound_prog = entry->program;
        g->xform_valid = 0;
    }
    if (!g->xform_valid || ox != g->xform_ox || oy != g->xform_oy || scale != g->xform_scale) {
        if (entry->uXform >= 0) {
            float flip = g->is_target ? 1.0f : -1.0f;
            float sx = 2.0f * scale / (float)g->cur_w;
            float sy = flip * 2.0f * scale / (float)g->cur_h;
            gl->Uniform4f(entry->uXform, sx, sy, -ox * sx - 1.0f, -oy * sy - flip);
        }
        g->xform_ox = ox;
        g->xform_oy = oy;
        g->xform_scale = scale;
        g->xform_valid = 1;
    }
    if (want_blend != g->blend_enabled) {
        if (want_blend) gl->Enable(GL_BLEND);
        else gl->Disable(GL_BLEND);
        g->blend_enabled = want_blend;
    }
    GLuint tex = gl_tex ? gl_tex : g->white_tex;
    if (tex != g->bound_tex) {
        gl->BindTexture(GL_TEXTURE_2D, tex);
        g->bound_tex = tex;
    }
    if (uniform_len > 0 && uniform_bytes != NULL) {
        gl->BindBuffer(GL_UNIFORM_BUFFER, g->ubo);
        gl->BufferData(GL_UNIFORM_BUFFER, (GLsizeiptr)uniform_len, uniform_bytes, GL_STREAM_DRAW);
        gl->BindBufferBase(GL_UNIFORM_BUFFER, 0, g->ubo);
    }
    return 1;
}

/* Orphan-and-subdata upload with power-of-two capacity so resizing frames do
 * not free/reallocate variable-sized driver buffer storage on every pixel. */
static void nui_gl_upload_buffer(
    NanoUiGlApi *gl, GLenum target, GLuint buf,
    size_t *cap, size_t min_cap, const void *data, size_t bytes)
{
    gl->BindBuffer(target, buf);
    if (bytes == 0) return;
    size_t c = *cap;
    if (c < bytes) {
        if (c < min_cap) c = min_cap;
        while (c < bytes && c <= SIZE_MAX / 2) c *= 2;
        if (c < bytes) c = bytes;
        *cap = c;
    }
    gl->BufferData(target, (GLsizeiptr)c, NULL, GL_STREAM_DRAW);
    gl->BufferSubData(target, 0, (GLsizeiptr)bytes, data);
}

/* Upload pass vertices and indices into the pooled VBO/EBO at most once per
 * pass, then issue one indexed triangle draw using the given shader entry. */
static int nui_gl_draw_indexed(
    NanoUiGl *g, const NanoUiGlShaderEntry *entry,
    GLuint gl_tex, int want_blend,
    const uint8_t *verts, int vert_count,
    const uint8_t *indices, int index_start, int index_n,
    const uint8_t *uniform_bytes, int uniform_len)
{
    if (!nui_gl_bind_draw(g, entry, g->origin_x, g->origin_y, g->scale,
                          gl_tex, want_blend, uniform_bytes, uniform_len)) {
        return 0;
    }
    NanoUiGlApi *gl = &g->api;
    if (g->bound_vao != g->vao) {
        gl->BindVertexArray(g->vao);
        g->bound_vao = g->vao;
    }
    if (g->uploaded_verts != verts || g->uploaded_vert_count != vert_count) {
        nui_gl_upload_buffer(gl, GL_ARRAY_BUFFER, g->vbo, &g->vbo_cap, 65536,
                             verts, (size_t)vert_count * sizeof(SDL_Vertex));
        g->uploaded_verts = verts;
        g->uploaded_vert_count = vert_count;
    }
    const void *index_offset;
    if (g->index_total > 0 && index_start >= 0 && index_n <= g->index_total - index_start) {
        if (g->uploaded_indices != indices || g->uploaded_index_count != g->index_total) {
            nui_gl_upload_buffer(gl, GL_ELEMENT_ARRAY_BUFFER, g->ebo, &g->ebo_cap, 32768,
                                 indices, (size_t)g->index_total * sizeof(int));
            g->uploaded_indices = indices;
            g->uploaded_index_count = g->index_total;
        }
        index_offset = (const void *)((size_t)index_start * sizeof(int));
    } else {
        nui_gl_upload_buffer(gl, GL_ELEMENT_ARRAY_BUFFER, g->ebo, &g->ebo_cap, 32768,
                             (const int *)indices + index_start, (size_t)index_n * sizeof(int));
        g->uploaded_indices = NULL;
        g->uploaded_index_count = 0;
        index_offset = (const void *)0;
    }
    gl->DrawElements(GL_TRIANGLES, (GLsizei)index_n, GL_UNSIGNED_INT, index_offset);
    return 1;
}

/* ---- Public C entry points called by NanoUI.Sdl.Internal.Render ---- */

NanoUiGl *nano_ui_gl_create(SDL_Renderer *renderer)
{
    if (!renderer) return NULL;
    NanoUiGl *g = (NanoUiGl *)calloc(1, sizeof(NanoUiGl));
    if (!g) return NULL;
    g->renderer = renderer;
    g->scale = 1.f;
    if (is_opengl_renderer(renderer)) {
        g->win = SDL_GetRenderWindow(renderer);
        if (g->win && SDL_GL_GetCurrentWindow() == g->win) {
            g->ctx = SDL_GL_GetCurrentContext();
        }
    }
    return g;
}

void nano_ui_gl_destroy(NanoUiGl *g)
{
    if (!g) return;
    nano_ui_gl_leave_pass(g);
    if (g->init_state > 0 && nui_gl_make_current(g)) {
        NanoUiGlApi *gl = &g->api;
        for (int i = 0; i < g->shader_count; i++) {
            gl->DeleteProgram(g->shaders[i].program);
        }
        gl->DeleteProgram(g->plain.program);
        gl->DeleteShader(g->vs);
        gl->DeleteTextures(1, &g->white_tex);
        const GLuint bufs[] = { g->vbo, g->ebo, g->quad_vbo, g->ubo };
        const GLuint vaos[] = { g->vao, g->quad_vao };
        gl->DeleteBuffers(4, bufs);
        gl->DeleteVertexArrays(2, vaos);
    }
    free(g->shaders);
#if !SDL_VERSION_ATLEAST(3, 4, 0)
    free(g->rebased);
#endif
    free(g->xy);
    free(g);
}

void nano_ui_gl_begin_pass(NanoUiGl *g, float scale, int index_total)
{
    if (!g) return;
    nano_ui_gl_leave_pass(g);
    g->scale = scale > 0.f ? scale : 1.f;
    g->origin_x = 0.f;
    g->origin_y = 0.f;
    g->index_total = index_total > 0 ? index_total : 0;
    g->xy_verts = NULL;
    g->xy_lo = g->xy_hi = 0;
    g->uploaded_verts = NULL;
    g->uploaded_vert_count = 0;
    g->uploaded_indices = NULL;
    g->uploaded_index_count = 0;
    g->has_clip = 0;
    if (g->renderer) SDL_SetRenderClipRect(g->renderer, NULL);
}

void nano_ui_gl_end_pass(NanoUiGl *g)
{
    if (!g) return;
    g->has_clip = 0;
    if (g->pass_active) {
        nano_ui_gl_leave_pass(g);
    } else if (g->renderer) {
        SDL_SetRenderClipRect(g->renderer, NULL);
    }
}

void nano_ui_gl_set_clip(NanoUiGl *g, int has_clip, int x, int y, int w, int h)
{
    if (!g || !g->renderer) return;
    g->has_clip = has_clip != 0;
    g->clip = (SDL_Rect){ x, y, w, h };
    if (g->pass_active) {
        nui_gl_apply_scissor(g);
    } else {
        SDL_SetRenderClipRect(g->renderer, g->has_clip ? &g->clip : NULL);
    }
}

void nano_ui_gl_set_origin(NanoUiGl *g, float ox, float oy)
{
    if (!g) return;
    nano_ui_gl_leave_pass(g);
    g->origin_x = ox;
    g->origin_y = oy;
    g->xy_verts = NULL;
    g->xy_lo = g->xy_hi = 0;
}

/* Draw one coalesced plain range through OpenGL 3.2 VAO/VBO/EBO when available,
 * falling back to SDL_RenderGeometryRaw otherwise. */
void nano_ui_gl_draw_plain(
    NanoUiGl *g, const uint8_t *verts, int vert_count,
    const uint8_t *indices, int index_start, int index_n, SDL_Texture *texture)
{
    if (!g || !g->renderer || !verts || !indices || vert_count <= 0 || index_n < 3) return;
    if (nui_gl_ensure_init(g) && g->plain.program) {
        GLuint gl_tex = 0;
        int want_blend = 1;
        if (nui_gl_plain_texture_id(g, texture, &gl_tex, &want_blend)) {
            if (nui_gl_draw_indexed(g, &g->plain, gl_tex, want_blend,
                                    verts, vert_count, indices, index_start, index_n, NULL, 0)) {
                return;
            }
        } else {
            nano_ui_gl_leave_pass(g);
        }
    }
    nano_ui_sdl_draw_raw(g, texture, verts, vert_count, indices, index_start, index_n);
}

/* Draw one Tier 1 GLSL 150 custom shader range inside the active GL pass. */
int nano_ui_gl_draw_shader(
    NanoUiGl *g, const uint8_t *verts, int vert_count,
    const uint8_t *indices, int index_start, int index_n,
    SDL_Texture *texture, uint64_t hash,
    const uint8_t *glsl, int glsl_len,
    const uint8_t *uniform_bytes, int uniform_len)
{
    if (!g || !g->renderer || !verts || !indices || vert_count <= 0 || index_n < 3) return 0;
    NanoUiGlShaderEntry *entry = nui_gl_resolve_shader(g, hash, glsl, glsl_len);
    if (!entry) return 0;
    return nui_gl_draw_indexed(g, entry, nui_gl_texture_id(texture), 1,
                               verts, vert_count, indices, index_start, index_n,
                               uniform_bytes, uniform_len);
}

/* Composite one Tier 2 offscreen texture quad through a cached GLSL 150 shader. */
int nano_ui_gl_composite_effect(
    NanoUiGl *g, SDL_Texture *src_tex,
    float px, float py, float pw, float ph,
    float u0, float v0, float u1, float v1,
    uint64_t hash, const uint8_t *glsl, int glsl_len,
    const uint8_t *uniform_bytes, int uniform_len)
{
    if (!g || !g->renderer || !src_tex) return 0;
    GLuint gl_src = nui_gl_texture_id(src_tex);
    NanoUiGlShaderEntry *entry = gl_src ? nui_gl_resolve_shader(g, hash, glsl, glsl_len) : NULL;
    if (!entry || !nui_gl_bind_draw(g, entry, 0.0f, 0.0f, 1.0f, gl_src, 1, uniform_bytes, uniform_len)) {
        return 0;
    }
    const SDL_FColor white = { 1.f, 1.f, 1.f, 1.f };
    const SDL_Vertex quad[4] = {
        { { px,      py      }, white, { u0, v0 } },
        { { px + pw, py      }, white, { u1, v0 } },
        { { px + pw, py + ph }, white, { u1, v1 } },
        { { px,      py + ph }, white, { u0, v1 } },
    };
    NanoUiGlApi *gl = &g->api;
    nui_gl_set_linear_clamp(gl);
    gl->BindVertexArray(g->quad_vao);
    g->bound_vao = g->quad_vao;
    gl->BindBuffer(GL_ARRAY_BUFFER, g->quad_vbo);
    gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)sizeof(quad), quad, GL_STREAM_DRAW);
    gl->DrawArrays(GL_TRIANGLE_FAN, 0, 4);
    return 1;
}