Imposters

From Nebulavenus/forge-gpu · View interactive version

Imposters is an AI agent skill from the GitHub repository Nebulavenus/forge-gpu. Add imposter billboard LOD with baked multi-angle atlas to an SDL GPU project

How to use this skill

Skill file

imposters

Add distance-based LOD to a scene by replacing far 3D instances with

camera-facing billboard imposters. Near objects render as full meshes;

beyond a transition zone they render as textured quads sampled from a

pre-baked multi-angle atlas.

Prerequisites

Data structures

/* Per-instance data for imposter billboards — 96 bytes, vertex buffer slot 1 */
typedef struct ImposterInstance {
    mat4  transform;    /* 64B — world position + scale                  */
    float atlas_uv[4]; /* 16B — u_offset, v_offset, u_scale, v_scale    */
    float alpha;        /* 4B  — cross-fade alpha [0..1]                 */
    float color[3];     /* 12B — RGB tint (multiplied with atlas)        */
} ImposterInstance;

/* Push constants for the imposter vertex shader (slot 0) */
typedef struct ImposterVertUniforms {
    mat4  vp;           /* camera view-projection matrix                 */
    float cam_pos[3];   /* world-space camera position for billboard facing */
    float _pad;         /* explicit padding to 80 bytes                  */
} ImposterVertUniforms;

/* Push constants for the bake vertex shader (slot 0) — one MVP per angle */
typedef struct BakeVertUniforms {
    mat4 mvp;
} BakeVertUniforms;

/* Push constants for the bake fragment shader (slot 0, space3) */
typedef struct BakeFragUniforms {
    float base_color[4]; /* RGBA base color for trunk or crown draw call */
    float light_dir[3];  /* world-space light direction (normalized)     */
    float ambient;       /* ambient light floor [0, 1]                   */
} BakeFragUniforms;

Atlas layout

#define ATLAS_FRAMES      8     /* azimuth angles at 45° intervals */
#define ATLAS_COLS        4     /* frames per row                  */
#define ATLAS_ROWS        2
#define ATLAS_FRAME_SIZE  256   /* pixels per cell                 */
#define ATLAS_WIDTH       (ATLAS_COLS * ATLAS_FRAME_SIZE)  /* 1024 */
#define ATLAS_HEIGHT      (ATLAS_ROWS * ATLAS_FRAME_SIZE)  /* 512  */

Frames are laid out row-major: [0][1][2][3] / [4][5][6][7].

Frame 0 is at azimuth 0, each subsequent frame adds TAU / ATLAS_FRAMES.

Atlas baking procedure

Baking is a one-shot startup operation. Create and destroy the bake pipeline

inside the bake function — only the atlas texture and sampler persist.

/* 1. Create atlas texture: COLOR_TARGET + SAMPLER usage */
tex_info.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
tex_info.width  = ATLAS_WIDTH;
tex_info.height = ATLAS_HEIGHT;
tex_info.usage  = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;

/* 2. Create depth texture: D32_FLOAT, DEPTH_STENCIL_TARGET usage only */

/* 3. Create bake pipeline */
/*    - Color target: R8G8B8A8_UNORM, blending disabled               */
/*    - Depth: D32_FLOAT, write + test with LESS                      */
/*    - Vertex input: ForgeSceneVertex (FLOAT3 pos at 0, FLOAT3 normal at 12) */
/*    - Back-face cull: BACK (tree mesh is solid)                     */

/* 4. One render pass covers all 8 frames — viewport + scissor change per frame */
SDL_GPUColorTargetInfo ct = { .load_op = SDL_GPU_LOADOP_CLEAR,
                               .clear_color = {0,0,0,0} }; /* transparent black */

for (int i = 0; i < ATLAS_FRAMES; i++) {
    float angle = (float)i * (FORGE_TAU / (float)ATLAS_FRAMES);
    vec3 eye = vec3_create(SDL_sinf(angle) * view_dist, slight_elevation,
                           SDL_cosf(angle) * view_dist);
    mat4 view = mat4_look_at(eye, tree_center, world_up);
    mat4 mvp  = mat4_multiply(ortho_proj, view);

    /* Set viewport and scissor to the atlas cell for this frame */
    int cell_x = (i % ATLAS_COLS) * ATLAS_FRAME_SIZE;
    int cell_y = (i / ATLAS_COLS) * ATLAS_FRAME_SIZE;
    /* SDL_SetGPUViewport + SDL_SetGPUScissor ... */

    /* Push BakeVertUniforms with mvp, then draw trunk and crown as separate
     * calls with different BakeFragUniforms base_color values. */
}

/* 5. Submit, SDL_WaitForGPUIdle, then release bake depth + bake pipeline */

/* 6. Create atlas sampler: LINEAR filter, CLAMP_TO_EDGE on U and V
 *    Clamping prevents bleeding between adjacent atlas cells. */

Use mat4_orthographic sized to the model's bounding volume. A slight Y

elevation on the camera (≈ 15% of model height) avoids flat top-down angles.

Billboard quad

/* Unit quad in XY plane: X from -0.5..+0.5, Y from 0..1, normal +Z */
/* Two CCW triangles: (0,1,2) and (0,2,3) */
verts[0].position = vec3_create(-0.5f, 0.0f, 0.0f);
verts[1].position = vec3_create( 0.5f, 0.0f, 0.0f);
verts[2].position = vec3_create( 0.5f, 1.0f, 0.0f);
verts[3].position = vec3_create(-0.5f, 1.0f, 0.0f);

The vertex shader expands the quad using billboard basis vectors derived from

the pivot-to-camera direction projected onto the XZ plane (cylindrical

billboard — no vertical tilt).

Imposter pipeline

Two vertex buffer slots are required:

/* Slot 0: per-vertex quad geometry */
vb_descs[0].pitch      = sizeof(ForgeSceneVertex); /* 24 bytes */
vb_descs[0].input_rate = SDL_GPU_VERTEXINPUTRATE_VERTEX;
vb_descs[0].instance_step_rate = 0;  /* MUST be 0 in SDL3 GPU */

/* Slot 1: per-instance imposter data */
vb_descs[1].pitch      = sizeof(ImposterInstance); /* 96 bytes */
vb_descs[1].input_rate = SDL_GPU_VERTEXINPUTRATE_INSTANCE;
vb_descs[1].instance_step_rate = 0;

Eight vertex attributes (TEXCOORD0–7):

| Location | Slot | Type | Offset | Purpose |

|----------|------|--------|--------|---------------------------|

| 0 | 0 | FLOAT3 | 0 | Quad position |

| 1 | 0 | FLOAT3 | 12 | Quad normal (unused) |

| 2 | 1 | FLOAT4 | 0 | Transform column 0 |

| 3 | 1 | FLOAT4 | 16 | Transform column 1 |

| 4 | 1 | FLOAT4 | 32 | Transform column 2 |

| 5 | 1 | FLOAT4 | 48 | Transform column 3 |

| 6 | 1 | FLOAT4 | 64 | Atlas UV rect |

| 7 | 1 | FLOAT4 | 80 | Alpha (x) + RGB tint (yzw) |

Alpha blending: SRC_ALPHA / ONE_MINUS_SRC_ALPHA (standard over-compositing).

Disable back-face culling (CULLMODE_NONE) — precision at edge-on angles can

flip winding. Depth test and write both enabled.

Per-frame LOD classification

float cell_u = 1.0f / (float)ATLAS_COLS;
float cell_v = 1.0f / (float)ATLAS_ROWS;

for each tree {
    float dist = vec3_length(vec3_sub(cam_pos, tree_pos));

    if (dist < lod_far)  /* near or transition — add to near_cpu */
    if (dist > lod_near) /* transition or far — add to far_cpu   */

    /* Azimuth frame selection */
    float angle = SDL_atan2f(diff.x, diff.z);
    if (angle < 0.0f) angle += FORGE_TAU;
    int frame = ((int)(angle / FORGE_TAU * ATLAS_FRAMES + 0.5f)) % ATLAS_FRAMES;

    fi->atlas_uv[0] = (float)(frame % ATLAS_COLS) * cell_u;  /* u offset */
    fi->atlas_uv[1] = (float)(frame / ATLAS_COLS) * cell_v;  /* v offset */
    fi->atlas_uv[2] = cell_u;   /* u scale */
    fi->atlas_uv[3] = cell_v;   /* v scale */

    /* Imposter fades in during transition; mesh stays fully opaque */
    fi->alpha = (dist < lod_far) ? (dist - lod_near) / (lod_far - lod_near) : 1.0f;
}

Trees in the transition zone appear in both arrays — the full mesh renders

at full opacity and the imposter fades in on top with increasing alpha.

At the far boundary the mesh stops rendering and the imposter takes over.

Rendering order

/* 1. Classify instances into near_cpu / far_cpu arrays */
classify_instances(state, cam_pos);

/* 2. Upload both arrays via deferred copy pass */
forge_scene_begin_deferred_uploads(s);
near_buf = forge_scene_upload_buffer_deferred(s, SDL_GPU_BUFFERUSAGE_VERTEX,
               near_cpu, near_count * sizeof(ForgeSceneColoredInstance));
far_buf  = forge_scene_upload_buffer_deferred(s, SDL_GPU_BUFFERUSAGE_VERTEX,
               far_cpu, far_count * sizeof(ImposterInstance));
forge_scene_end_deferred_uploads(s);

/* 3. Shadow pass — terrain + near mesh only (imposters skip shadow casting) */
forge_scene_begin_shadow_pass(s);
forge_scene_draw_terrain_shadow(s);
forge_scene_draw_shadow_mesh_instanced_colored(s, tree_vb, tree_ib,
    tree_index_count, near_buf, near_count);
forge_scene_end_shadow_pass(s);

/* 4. Main pass — terrain, near mesh, then imposter draw */
forge_scene_begin_main_pass(s);
forge_scene_draw_terrain(s);
forge_scene_draw_mesh_instanced_colored(s, tree_vb, tree_ib,
    tree_index_count, near_buf, near_count, white);

/* Switch to imposter pipeline for billboard draw */
SDL_BindGPUGraphicsPipeline(forge_scene_main_pass(s), imposter_pipeline);
SDL_PushGPUVertexUniformData(forge_scene_cmd(s), 0, &ivu, sizeof(ivu));
SDL_BindGPUFragmentSamplers(pass, 0, &atlas_bind, 1);
/* Bind slot 0 = quad_vb, slot 1 = far_buf */
SDL_DrawGPUIndexedPrimitives(pass, 6, far_count, 0, 0, 0);
forge_scene_end_main_pass(s);

/* 5. UI pass */

Heightmap from asset pipeline

/* Load pipeline-generated BMP; fall back to procedural fBm if absent */
float *hmap = forge_scene_load_heightmap_image(path, &w, &h);
if (!hmap) {
    /* generate with forge_noise_fbm2d, normalize to [0,1] */
}
forge_scene_set_terrain(&scene, hmap, w, h);

forge_scene_load_heightmap_image reads an 8-bit or 16-bit grayscale BMP and

returns a float[] normalized to [0, 1]. The caller owns the allocation and

must SDL_free it when done.

Common mistakes

VERTEXINPUTRATE_INSTANCE alone controls per-instance advancement.

sampler; REPEAT causes adjacent frame pixels to bleed into each other.

one-shot. Release them after SDL_WaitForGPUIdle to free GPU memory.

diff.x)). The bake orbit uses (sin(angle), y, cos(angle))`, so

atan2(x, z) measures from +Z to match frame 0. Swapping the arguments

produces a 90-degree offset between bake and selection.

pass. At typical LOD distances the shadow error is imperceptible and avoids

a matching shadow billboard pipeline.

Reference

and imposter_bake.vert/frag.hlsl

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.