39 min read

Squeezing Every Microsecond Out of a Modern Minecraft Renderer

A ground-up deep dive into every GPU and CPU optimization we made to Mirror — from registers, Early-Z, Hi-Z pyramids, LDS shared memory, and 3D froxel grids to BVHs, zero-alloc JVM render threads, hunting a 198 → 380 FPS Vulkan barrier storm, and first-class Vulkan Mesh Shaders & Meshlets.

On this page
  1. 1. Mental Model: How a Modern GPU Actually Works
  2. 2. Killing Overdraw: Reverse-Z, Early-Z & the Cutout Terrain Prepass
  3. 3. Screen-Space Tile Classification: Decals (10×) & Lighting (3.5×)
  4. 4. Hierarchical Data Structures on the GPU: Hi-Z Pyramids, LDS & textureGather
  5. 5. The Bandwidth Diet: 3D Froxel Grids, Ping-Pong Post, OIT & Half-Res DoF
  6. 6. Deep Dive: What Even Is a BVH? (And Making It 373× Faster on the CPU)
  7. 7. The JVM Render-Thread Diet: Zero-Alloc Encoding, LUTs & Graph Fast Paths
  8. 8. Live Profiling War Story: 198 → 122 → 380 FPS at 1440p (32 Chunks)
  9. 9. Deep Dive: Vulkan Mesh Shaders (VK_EXT_mesh_shader) & Meshlets
  10. 10. Trust, But Hash: How We Verified Everything
  11. 11. Principles You Can Steal for Your Own Engine

Over the past two weeks, we took Mirror — our dual-backend Vulkan 1.2 & OpenGL 4.5 rendering engine for Minecraft — and put every render pass, every synchronization barrier, every geometry front-end, and every Java render-thread hot path under a microscope.

The goal wasn’t “tweak a few constants.” The goal was to find the hardware architectural floor of each stage: stop shading pixels that get thrown away, respect GPU register files and cache lines, fuse memory-bound volumetric passes, stop churning hundreds of kilobytes of Java heap objects every frame, hunt down a live 198 → 122 → 380 FPS Vulkan barrier storm at 1440p (32-chunk render distance), and architect a first-class optional Vulkan Mesh Shader (VK_EXT_mesh_shader) & Meshlet geometry pipeline on supported GPUs.

This writeup is intentionally written as a self-contained learning reference. Every time we introduce a graphics or systems concept — warps, occupancy, local memory spill, Reverse-Z, Early-Z, indirect dispatch, Hi-Z DDA, LDS shared memory, 3D froxel grids, Beer–Lambert transmittance, stackless BVHs, Vulkan dynamic rendering & pipeline barriers, Task/Mesh shaders, and meshlet normal-cone culling — we explain what the silicon is actually doing from first principles before showing the exact code we changed in Mirror.

Let’s start with the micro-benchmark scoreboard, before we dive into the architecture, the live 380 FPS profiling war story, and the Mesh Shader deep dive.

Measured results across 12 core GPU pass benchmarks (RTX 3080, 1920×1080) and 5 CPU render-thread hot paths (JBR 25), before our live 1440p Vulkan sync fix (198 → 380 FPS) and Vulkan Mesh Shader work (1.12–1.35×).

Every GPU timing in this post is a median hardware timestamp (vkCmdWriteTimestamp) on an NVIDIA GeForce RTX 3080 (Ampere GA102), cross-checked with NVIDIA’s VK_KHR_pipeline_executable_properties (driver register count, local spill bytes, SASS binary size), Vulkan Validation Layers (0 errors), and pixel-level output equivalence. Every CPU timing and allocation number comes from System.nanoTime(), ThreadMXBean.getThreadAllocatedBytes(), and live Java Flight Recorder (JFR) + nvidia-smi captures on JetBrains Runtime 25 (JBR 25).


1. Mental Model: How a Modern GPU Actually Works

Before optimizing a single line of GLSL, you need an accurate mental model of what GPU silicon is physically doing when your shader executes. Almost every performance surprise in graphics programming comes from treating a GPU like “a CPU with 10,000 tiny cores.” It isn’t.

Inside one Streaming Multiprocessor (SM) on an RTX 3080, and why cutting Mirror's decal shader from 128 to 80 registers jumped occupancy by 50% and eliminated VRAM spills.

A Quick Hardware Glossary

If you are newer to GPU internals, keep this cheat sheet handy — every term below comes up repeatedly throughout the rest of this post:

TermPlain-English MeaningHardware Reality (RTX 3080 / Ampere)
SMStreaming Multiprocessor — one independent compute/graphics unit on the GPU die.68 SMs on an RTX 3080, each with 4 warp schedulers.
WarpThe smallest group of threads the GPU can schedule (AMD calls it a wavefront).32 threads executing in lockstep (SIMT).
Branch DivergenceWhen threads inside the same 32-thread warp take different sides of an if / else.The SM runs both paths serially with lane masks turned on/off.
Register FileUltra-fast private storage (~1 cycle) holding every live shader variable (vec3, mat4, loop index).65,536 × 32-bit registers shared across all resident warps on an SM.
OccupancyHow many warps fit on an SM simultaneously (resident / hardware max).Max 48 warps/SM. Higher occupancy lets the SM hide 400-cycle VRAM stalls.
Local SpillVariables that don’t fit in registers get evicted to “Local Memory.”Not local! It lives in slow GDDR6X VRAM (cached in L1/L2).
LDS (shared)Local Data Share — tiny programmable on-chip SRAM shared by one workgroup.~20–30 cycle latency (up to 100 KB/SM), ~15–20× faster than VRAM.
SASSFinal hardware machine code compiled by the NVIDIA driver from SPIR-V / GLSL.Smaller SASS = fewer instructions & better instruction-cache hit rate.
Pipeline BarrierA synchronization fence telling the GPU to wait for stage A’s writes before starting stage B.Unnecessary barriers drain all 68 SMs to 0% (pipeline bubbles).

Here are the four hardware realities that governed every GPU change we made:

  1. Warps & SIMT Lockstep. An SM never schedules a single pixel; it schedules warps of 32 threads that all execute the exact same instruction on the exact same clock cycle. If 1 thread in a warp enters a heavy if branch and the other 31 take the else, all 32 threads wait while both branches run back-to-back.
  2. Registers & Occupancy. If your shader needs 128 registers per thread, one 32-thread warp consumes 32×128=4,09632 \times 128 = 4{,}096 registers, so at most 65,536/4,096=1665{,}536 / 4{,}096 = 16 warps can live on an SM at once (33% of its 48-warp ceiling). Why does that matter? Because GPUs don’t have giant out-of-order CPU caches to hide ~400-cycle GDDR6X VRAM fetches — instead, the instant warp #1 requests a texture from VRAM, the scheduler switches in zero cycles to warp #2, then #3, then #4. Too few resident warps (low occupancy) means the SM runs out of ready warps and sits completely idle waiting on memory.
  3. Register Spill (“Local Memory” Is a Lie). When a shader keeps too many live variables at once, the compiler spills them into Local Memory. Despite the cozy name, “local” means thread-private memory in GDDR6X VRAM. Our original fragment decal shader hit 128 registers and spilled 48 bytes per thread to local memory — turning ordinary variable reads into memory traffic.
  4. Bandwidth Beats ALU. Modern GPUs perform tens of trillions of floating-point ops per second, but GDDR6X VRAM bandwidth is finite. Reading or writing a single full-screen 1920 × 1080 × RGBA16F (8 bytes/pixel) render target moves 16.6 MB per pass. Doing that 5 extra times in post-processing wastes 83 MB of VRAM bandwidth every frame — nearly 10 GB/s at 120 FPS — just copying pixels from A to B.

Here is how Mirror’s entire frame graph evolved from start to finish:

Mirror's frame pipeline before and after our GPU optimization tracks.

2. Killing Overdraw: Reverse-Z, Early-Z & the Cutout Terrain Prepass

What Are a G-Buffer, Reverse-Z, Overdraw, and Early-Z?

When Minecraft renders a dense forest or village, the camera looks through overlapping layers of cliffs, stone castle walls, cabins, and oak foliage. Because chunk meshes aren’t sorted perfectly front-to-back per triangle, the GPU often draws a distant mountain first, then a stone wall in front of it, then a wooden house, then oak leaves right in front of your face.

Mirror is a deferred renderer: instead of computing every torch and sun shadow while drawing triangles, the terrain pass writes raw surface properties into a G-Buffer — a stack of Multiple Render Targets (MRT) storing albedo color, surface normal, roughness/metalness material IDs, emissive glow, and baked Minecraft skylight (up to 5 render targets written per pixel).

If you render straight into that 5-MRT G-Buffer without pre-populating depth, the GPU runs the entire expensive terrain fragment shader — 4-tap Rotated Grid Supersampling (RGSS), PBR material decode, tangent-space normal encoding — on every single hidden layer, only for the next closer wall to overwrite it 2 microseconds later. That wasted shading work is overdraw.

To know which triangle is closest at every pixel, the GPU maintains a Z-Buffer (Depth Buffer) storing one floating-point depth value per pixel. Mirror uses Reverse-Z (near → 1.0, far → 0.0, compare op GREATER / GREATER_EQUAL). Why flip it backwards? Because IEEE-754 floating-point numbers pack exponentially more representable values near 0.0 than near 1.0! Perspective projection naturally bunches distant depths near the far plane — so mapping the far plane to 0.0 lets float precision cancel out perspective compression, completely eliminating distant Z-fighting across 32+ chunks and kilometers of LOD terrain.

Modern GPUs also include a fixed-function circuit called Early-Z (Early Depth Testing). Before a pixel ever launches the fragment shader, the rasterizer compares its interpolated depth against the Z-Buffer. If a closer surface is already recorded there, the pixel is killed in hardware for free — zero fragment shader runs, zero texture fetches, zero 5-MRT writes.

Why discard Quietly Breaks Early-Z

Here is the hardware trap that hit our cutout terrain (leaves, tall grass, flowers, vines):

In GLSL, alpha-cutout geometry samples the block atlas’s alpha channel and executes discard; if the pixel falls inside a transparent hole between leaves. The instant a fragment shader contains a discard instruction, the GPU is legally forbidden from performing Early-Z depth writes — because the hardware cannot know whether the pixel even exists until after the entire heavy fragment shader finishes!

So with single-pass rendering:

  • Opaque terrain suffered up to 4× overdraw on heavy 5-MRT shaders.
  • Cutout foliage suffered even worse overdraw, running 4-tap RGSS and full PBR decoding even on transparent leaf holes that immediately got discarded!

Our Fix: 0-MRT Depth Prepass + EQUAL Early-Z

We split opaque AND cutout terrain into two passes:

  1. world.opaque_depth_prepass: Draw solid terrain first, then cutout terrain second, into the depth buffer only (0 color attachments).
    • Solid prepass uses an empty fragment shader (pure fixed-function rasterization at maximum hardware throughput).
    • Cutout prepass runs terrain_depth.frag — just 16 registers, 512 bytes of SASS, 0 MRT writes:
GLSL
// terrain_depth.frag (16 registers, 512 B SASS, 0 color attachments)
void main() {
#ifdef ALPHA_CUTOUT
    if (texture(WorldBaseSampler, depthTexCoord).a * depthAlpha < ALPHA_CUTOUT) {
        discard;
    }
#endif
}
  1. world.opaque_materials: Now the Z-Buffer already holds the exact closest surviving surface at every pixel — including every single leaf edge! So we switch the depth test to GpuCompareOp.EQUAL, disable depth writes (depthWrite = false), compile cutout terrain with MIRROR_TERRAIN_PREPASSED, remove discard completely, and force hardware Early-Z on:
GLSL
// include/terrain_surface.glsl
#ifdef MIRROR_TERRAIN_PREPASSED
layout(early_fragment_tests) in;
#endif

One crucial floating-point rule: if your prepass vertex shader computes gl_Position with slightly different instruction reordering than your G-Buffer vertex shader, the resulting depth can differ by 1 ULP (Unit in the Last Place — the smallest representable float increment) and fail the EQUAL test, causing sparkling pinhole cracks! Declaring invariant gl_Position; forces the compiler to emit bit-identical clip-space math in both passes.

Explore the layered voxel scene below — switch between Split Scene / Heat, Overdraw Heat, and the Z-Buffer, toggle Z-Prepass + EQUAL and Cutout Foliage, and hover any pixel to watch the hardware kill occluded layers before they ever touch the G-Buffer:

Interactive Layered Overdraw & Early-Z Simulator. Compare Single-Pass vs Z-Prepass + EQUAL across distant mountains, castle battlements, timber cabin, and cutout oak foliage.

Measured RTX 3080 results (bit-exact verified against baseline hashes):

  • terrain_lumen_opaque_rgss: 1,836.0 → 473.1 μs (3.88× faster)
  • terrain_core_opaque_rgss: 1,689.6 → 462.9 μs (3.65× faster)
  • terrain_lumen_cutout_rgss: 2,256.9 → 581.6 μs (3.88× faster)
  • terrain_core_cutout_rgss: 1,868.8 → 566.3 μs (3.30× faster)

We applied the same rule to distant LOD terrain (lod_visibility.frag): only the innermost LOD ring needs a discard cutout where it meets near vanilla chunks; all far LOD rings compile with MIRROR_LOD_NO_NEAR_CUTOUT and layout(early_fragment_tests) in;.


3. Screen-Space Tile Classification: Decals (10×) & Lighting (3.5×)

A 1080p screen has 2,073,600 pixels (and 1440p has 3,686,400). Running one monolithic full-screen fragment shader over all 2–3.7 million pixels forces every sky pixel, every sunlit dirt block, and every blank stone wall to pay the worst-case register footprint of the heaviest feature in the shader.

Instead, we partition the screen into 8×8 pixel tiles (240 × 135 = 32,400 tiles at 1080p) and run a tiny classification compute shader first.

What Are Compute Workgroups, Atomic Counters & Indirect Dispatch?

Unlike a fragment shader (which only runs where triangles land), a compute shader launches a 3D grid of workgroups — here layout(local_size_x = 8, local_size_y = 8), so one 64-thread workgroup covers one 8×8 screen tile.

When the classification compute shader inspects a tile and decides “yes, this 8×8 tile needs full clustered lighting”, you must never read that tile list back to the CPU — a GPU-to-CPU readback stalls the entire pipeline for milliseconds. Instead:

  1. One thread per active tile calls uint slot = atomicAdd(dispatchCmd.groupCountX, 1u); — a hardware atomic counter inside a tiny GPU Indirect Dispatch Buffer ({groupCountX, groupCountY, groupCountZ}).
  2. That thread writes its packed (tileX, tileY) coordinate into activeTiles[slot].
  3. Later in the same command buffer, the CPU simply records pass.dispatchIndirect(indirectBuffer). The GPU reads its own groupCountX straight out of VRAM and launches the exact number of 8×8 workgroups that actually have work — zero CPU sync, zero wasted warps on empty tiles!

Deferred Decals: 10.0× Faster & 40 MB Saved

Previously, decals copied the entire G-Buffer (~40 MB of VRAM) into scratch textures so a fragment shader could read old surface data and write blended output back. Worse, the monolithic shader handled every possible PBR material channel, exploding to 128 registers/thread and 48 B of VRAM stack spill (36.4 KB of SASS).

We rebuilt decals around in-place read/write 8×8 compute:

  • An 8×8 classifier bins tiles with decals into SIMPLE (albedo/roughness/normal only — 95% of decals) vs FULL (full material overwrite). Empty tiles (65–90% of the screen!) are never dispatched at all.
  • Compute shaders read and write the G-Buffer storage images in place — deleting the entire ~40 MB scratch copy.
  • Register pressure dropped from 128 → 80 (0 B local spill, 36.4 KB → 8.3 KB SASS, -77%), jumping SM occupancy from 33% to 50%.
  • RTX 3080: Sparse (10% coverage) 174.1 → 17.4 μs (10.0×); Medium (35% coverage) 548.9 → 65.5 μs (8.38×).

Outdoor Deferred Lighting: 3.50× Faster

In a daytime outdoor Minecraft scene, ~40% of the screen is sky and another ~40–50% is sunlit terrain with zero nearby torches or lanterns. Our 8×8 lighting classifier inspects each tile’s depth and light cluster list:

  • Sky tiles → skipped entirely.
  • Sun-only tiles (0 local lights) → dispatched to a specialized low-register sun-only compute variant (-44% SASS) with 2-stage PCF (Percentage-Closer Filtering) shadows: it takes 4 cheap corner shadow taps first, and if all 4 agree the pixel is 100% lit or 100% in shadow, it exits immediately — only soft shadow penumbra edges pay for the full multi-tap filter!
  • Clustered tiles → dispatched to the full local-light shader.
  • RTX 3080: 464.9 → 132.7 μs (3.50× faster).

Drag the lights and decals across the dusk Minecraft landscape below to watch the 8×8 indirect dispatch buckets update live:

Interactive 8×8 Screen-Space Tile Classifier over a dusk voxel scene. Switch between Deferred Lighting and Deferred Decals and drag items to see sky, sun-only, and empty tiles skip heavy shaders.

4. Hierarchical Data Structures on the GPU: Hi-Z Pyramids, LDS & textureGather

What Is a Hi-Z (Hierarchical-Z) Depth Pyramid?

Suppose you are tracing a Screen-Space Reflection (SSR) ray across 300 pixels of empty air before it hits a mountain, or sampling Screen-Space Ambient Occlusion (SSAO) over a 64-pixel radius.

If you march one pixel at a time through the full-resolution depth buffer:

  • You perform dozens of texture fetches across completely empty air.
  • Sampling 64 pixels away at full resolution thrashes the L1 texture cache because neighboring lanes in a 32-thread warp land in scattered memory pages.

A Hierarchical-Z (Hi-Z) Depth Pyramid solves both problems. Just like a color mipmap repeatedly halves width and height (1920×1080 → 960×540 → 480×270 → 240×135 → ...), a depth pyramid stores the conservative closest depth (min in standard-Z, max in Reverse-Z) of every 2×2 block of pixels:

  • Mip 0: 1920 × 1080 (1×1 pixels)
  • Mip 1: 960 × 540 (closest depth of each 2×2 block)
  • Mip 2: 480 × 270 (closest depth of each 4×4 block)
  • Mip 3: 240 × 135 (closest depth of each 8×8 block)

Why conservative? Because if your reflection ray is closer to the camera than the closest single surface anywhere inside an 8×8 block (Mip 3), it is mathematically impossible for the ray to hit anything inside all 64 pixels of that block! Using a DDA (Digital Differential Analyzer) grid stepper, the ray leaps across all 8 pixels in one step, climbing up a mip level whenever it clears a cell and only dropping down toward Mip 0 when it touches a cell’s depth ceiling.

Drag the ray origin (amber) or target (blue) in the voxel canyon below, and hit Race to watch Hi-Z DDA leap across the canyon in a handful of steps while Linear March plods pixel-by-pixel:

Interactive Hi-Z Depth Pyramid & DDA Ray Race. Watch Hi-Z leap across empty canyon air at Mips 1–3 and drop to Mip 0 only at the exact terrain impact.

Building 4 Mip Levels in One Dispatch with LDS Shared Memory

Building a 9-level depth pyramid naively takes 9 separate compute dispatches and 9 pipeline barriers, writing each mip out to VRAM only to immediately read it back in the next dispatch.

Enter LDS (Local Data Share — GLSL shared memory) — tiny, programmable on-chip SRAM sitting directly inside each SM (~20–30 cycles latency vs ~400 cycles for VRAM), shared by every thread in a workgroup.

In depth_pyramid_multi.comp, a single 16×16 workgroup loads a 32×32 block of source depth, computes Mip +0 (16×16) into shared float ldsDepth[16][16], calls barrier() (a workgroup-local fence ensuring all 256 threads finished writing LDS), and then reduces inside on-chip SRAM with zero VRAM reads to emit Mip +1 (8×8), Mip +2 (4×4), and Mip +3 (2×2) all in one dispatch:

GLSL
// depth_pyramid_multi.comp — 4 mips in 1 dispatch via 16x16 on-chip LDS
shared float ldsDepth[16][16];

// Mip +0: 16x16 threads write to output[0] and populate LDS
float d0 = reduce2x2(srcCoord);
ldsDepth[lid.y][lid.x] = d0;
imageStore(DepthPyramidOut0, dstCoord, vec4(d0));
barrier();

// Mip +1: 8x8 threads reduce straight from LDS (zero VRAM reads!)
if ((lid.x & 1u) == 0u && (lid.y & 1u) == 0u) {
    float d1 = combineDepth(
        combineDepth(ldsDepth[lid.y][lid.x],      ldsDepth[lid.y][lid.x + 1u]),
        combineDepth(ldsDepth[lid.y + 1u][lid.x], ldsDepth[lid.y + 1u][lid.x + 1u])
    );
    ldsDepth[lid.y][lid.x] = d1;
    imageStore(DepthPyramidOut1, dstCoord >> 1u, vec4(d1));
}
barrier();
// ...same pattern continues for Mip +2 (4x4) and Mip +3 (2x2)!

Three More Places Hierarchical Pyramids & Hardware Instructions Paid Off Huge

  • Lumen SSAO (961.5 → 271.4 μs, 3.54× faster): Sampling far-radius occlusion taps from higher mips of the nearest-depth pyramid keeps all 32 lanes of a warp inside L1 cache instead of thrashing VRAM!
  • Vectorized textureGather Occlusion Blur (-14.3% SASS, bit-exact): Normally, reading a 4×4 pixel neighborhood takes 16 texelFetch calls. The GPU’s Texture Unit has a dedicated hardware instruction — textureGather(sampler, uv, channel) — that fetches a 2×2 block of raw texels in a single instruction as a vec4 (.w top-left, .z top-right, .x bottom-left, .y bottom-right). Replacing 16 texelFetch calls with 8 textureGather pairs in occlusion_blur.frag produced the exact same output hash (9040512b796e6b83) with 14.3% smaller SASS!
  • 3D Raymarch Light Grid (187.4 → 76.8 μs, 2.44× faster): Built a 3D R8 density mip pyramid (64³ → 32³ → 16³ → 8³) so 10-direction volumetric light cones step through coarser 3D mips as the cone widens — skipping empty air in 3D just like Hi-Z does in 2D!
  • Lumen SSR Reverse-Z (198.7 → 145.4 μs, 1.37× faster): Replaced fixed linear marching with a 16-step texel-space Hi-Z DDA reaching 96 meters.

5. The Bandwidth Diet: 3D Froxel Grids, Ping-Pong Post, OIT & Half-Res DoF

What Actually Is a Froxel Grid? (And Why Volumetric Fog Needs One)

Volumetric fog makes Minecraft feel alive — god-rays slicing through oak trees, warm amber halos blooming around a hanging lantern, and misty blue haze softening distant mountains. To render that physically, the GPU needs to know how much light scatters into the camera at every point in 3D air between your eye and the solid wall behind it.

Wait — why not just store fog in a regular Minecraft-style world-space 3D voxel grid (say, one 1×1×1 meter cube per block)?

  • Out to 256 meters in every direction, a 1-meter cube grid would be 512×256×512=67 million voxels512 \times 256 \times 512 = \mathbf{67\text{ million voxels}} (~536 MB of RGBA16F VRAM!) — AND it would still look blocky and blurry 2 meters in front of your face!
  • Make the cubes smaller (25 cm) so nearby lantern fog looks smooth, and memory explodes by 64×64\times to 34 GB.

The solution invented for modern AAA engines (Frostbite, Unreal, and Mirror) is the Froxel Grid — short for Frustum-Aligned Voxel Grid.

First, picture the camera’s view frustum: a truncated 3D pyramid starting at the camera’s near plane (znearz_{\text{near}}) and expanding outward to the far plane (zfarz_{\text{far}}). Everything visible on your monitor sits inside that pyramid. Now slice that pyramid into a 3D grid of 160×90×64=921,600160 \times 90 \times 64 = 921{,}600 cells (RGBA16F = just 7.4 MB):

  1. Screen-Aligned (x, y) Columns: Every (x, y) column aligns directly with a 12×12 block of screen pixels at 1080p! You never waste a single byte on air outside the camera’s field of view, and every column naturally expands in world width as it gets farther away — matching perspective projection automatically!
  2. Exponential Depth Slices (z = 0..63): Instead of spacing the 64 depth planes evenly in meters, we space them exponentially:

zk=znear⋅(zfarznear)k/N,k∈{0,1,…,64}z_k = z_{\text{near}} \cdot \left(\frac{z_{\text{far}}}{z_{\text{near}}}\right)^{k / N}, \qquad k \in \{0, 1, \dots, 64\}

With znear=0.25 mz_{\text{near}} = 0.25\text{ m} and zfar=128 mz_{\text{far}} = 128\text{ m}, slice 0 is only ~3 cm thick right in front of your face — giving razor-sharp fog silhouettes around a nearby oak tree and glowing lantern — while slice 63 out by the distant cliff is ~12 meters deep, where your eye could never resolve centimeter fog details anyway.

Angled 3/4 side profile of Mirror's 3D Froxel frustum with real scene geometry inside it. Notice how exponential slice planes pack tightly around the nearby oak tree and lantern (amber lit cells) and stretch gently across the watchtower and distant cliff, while a single view ray integrates front-to-back.

How Froxel Fog Renders in 4 Stages (And Why Fusing Passes Saves 7.4 MB/Frame)

Once the 3D frustum grid is defined, Mirror renders volumetric fog by computing two quantities per froxel cell:

  • In-scattering LscatterL_{\text{scatter}} (RGB): How much sun + local torch/lantern light bounces off fog particles inside that cell toward the camera.
  • Extinction σt\sigma_t (Alpha): How dense the fog is in that cell (how strongly it absorbs/blocks light coming from behind it).

Then, in the final Front-to-Back Integration pass, a single compute thread walks along one (x, y) column from slice z = 0 to z = 63 applying Beer–Lambert transmittance over each slice’s physical thickness Δsk=zk+1−zk\Delta s_k = z_{k+1} - z_k:

Tslice=e−σt⋅Δsk,Laccum←Laccum+Taccum⋅Lscatter,Taccum←Taccum⋅TsliceT_{\text{slice}} = e^{-\sigma_t \cdot \Delta s_k}, \qquad L_{\text{accum}} \leftarrow L_{\text{accum}} + T_{\text{accum}} \cdot L_{\text{scatter}}, \qquad T_{\text{accum}} \leftarrow T_{\text{accum}} \cdot T_{\text{slice}}

When a pixel in the final deferred lighting pass wants the exact fog sitting between the camera and a block at depth zz, it performs one single hardware trilinear texture lookup at (screenUV.x, screenUV.y, depthToSlice(z))!

Previously, Mirror ran 4 separate compute passes every frame:

  1. froxel.inject — write fog density & emission into 3D volumes
  2. froxel.light — evaluate sun shadows + clustered local lights → write 7.4 MB transient lightVolume (160×90×64 RGBA16F)
  3. froxel.temporal — read lightVolume back, reproject and blend with last frame’s history to kill jitter → write scatterVolume
  4. froxel.integrate — march front-to-back along Z using Beer–Lambert transmittance

Spot the wasted round-trip between steps 2 and 3? froxel.light computed each froxel’s lighting, flushed 7.4 MB out to VRAM, hit a full pipeline barrier, and froxel.temporal immediately read those exact 7.4 MB right back!

By defining MIRROR_FROXEL_FUSED_TEMPORAL in froxel_light.comp and deleting lightVolume in FroxelVolume.java, the lighting shader blends temporal history while the lit value is still sitting in registers — eliminating a 7.4 MB 3D texture, an entire compute pass + barrier, and cutting 117.8 → 103.4 μs on the RTX 3080.

Orbit the 3D frustum below (drag anywhere to rotate the angled side profile, or drag the glowing amber lantern right through the voxel tree and watchtower) and toggle Exponential vs Linear slices and Fused vs Unfused passes:

Interactive 3D Angled Froxel Frustum. Drag to orbit the 3D view, drag the amber lantern to light nearby froxel cells, and compare Exponential vs Linear slices and Fused vs Unfused memory traffic.

Post-Processing Ping-Pong & DONT_CARE Load Ops

In ShaderPackGraphBuilder and ScenePost, every post-processing pass used to render into a scratch texture and then blit the entire 1080p RGBA16F image back onto sceneColor before the next pass. Worse, fullscreen passes used GpuAttachmentLoadOp.LOAD even though they overwrite 100% of pixels — forcing the GPU to decompress and load the previous frame’s color buffer from VRAM for no reason.

By ping-ponging two color targets (A → B → A → B), switching fullscreen passes to GpuAttachmentLoadOp.DONT_CARE (telling the driver “we’re overwriting every pixel — don’t fetch old VRAM or decompress DCC metadata”), threading the final ping-pong target directly into DepthOfFieldPass, and gating scene.transmission_copy + requestSceneDepth() behind hasTranslucent, we eliminated up to 5 full-resolution RGBA16F blits per frame.

Half-Res Depth of Field (2.62×)

Full-resolution bokeh blur is brutally expensive (704.5 μs at 1080p). Every pixel’s blur size is governed by its Circle of Confusion (CoC) — how far out of focus it is from the focal plane. Our new DoF pipeline computes CoC and color at half resolution (¼ the pixels!), runs a 16×16 tile dilation pass (depth_of_field_tile_dilate.comp) to find the maximum blur radius affecting each tile, and skips the bokeh gather entirely on tiles where maxCoC is sharp. Worst-case 1080p DoF dropped 704.5 → 269.3 μs (-60% SASS).

Translucent Water & Particle OIT Coverage Fast Paths

Transparent water, stained glass, and particles use Binned Order-Independent Transparency (OIT), which splits translucency into two passes: a coverage prepass (which only needs alpha/opacity to partition depth bins) and a shading pass (which evaluates final lighting).

Previously, water and particles ran their entire heavy shader — 6-octave animated Gerstner waves, sky reflections, sun glints, screen-space reflections, tangent-space PBR — during the coverage prepass and immediately threw the RGB color away! Adding #ifdef MIRROR_OIT_COVERAGE fast paths in pack.glsl, terrain_surface.glsl, and particle_surface_fragment.glsl trims coverage down to a cheap opacity-only check.

And in the actual water shading pass, lumenScreenReflection used to call mirrorProjectUv(viewPos) — a full 4×4 matrix multiply + perspective divide — inside every single raymarch loop iteration (up to 48 mat4 multiplies per water pixel!). Because a straight line in 3D view space projects to a straight line in (uv, windowDepth) screen space, projecting just the ray’s start and end points once lets the loop step linearly in screen space with a 3-step binary bisection — cutting 48 → 2 mat4 multiplies per pixel!

Shadow Maps: Backface Culling & Staggered Cascades

Finally, solid terrain and solid entities in shadow maps were drawing with GpuCullMode.NONE (rasterizing both front and back faces of every opaque cube!). Switching solid casters to GpuCullMode.BACK, shrinking the CPU sun shadow gather radius to only the cascades actually redrawn this frame, and staggering directional cascade turn thresholds in DirectionalCascadeCache.java stops all 4 cascades from invalidating simultaneously when you slowly turn the camera.


6. Deep Dive: What Even Is a BVH? (And Making It 373× Faster on the CPU)

Now let’s switch to the CPU / Java side — and start with the biggest single CPU bottleneck we found, which also happens to be one of the most fundamental acceleration structures in all of computer graphics: the Bounding Volume Hierarchy (BVH).

What Is a BVH, From Scratch?

In Minecraft, thousands of block and item textures are stitched onto one big 2D image called a texture atlas. When a shader shades a block, it receives a (u, v) texture coordinate like (0.64, 0.86). Mirror lets resource packs and mods assign custom PBR materials (roughness, metalness, emissive glow, water routing) to individual sprites inside that atlas.

So the fragment shader has a question to answer on every pixel:

“Given (u, v), which sprite rectangle in this 512-sprite atlas am I standing inside?”

  • Naive approach (Linear Scan, O(N)O(N)): Loop through all 512 sprite rectangles and check u >= minU && u <= maxU && v >= minV && v <= maxV. Checking 512 boxes per pixel at 1080p is 1 billion box tests per frame — completely unviable.
  • BVH approach (O(log⁡N)O(\log N)): Wrap all 512 sprites inside one giant Axis-Aligned Bounding Box (AABB) — the root node. Now split the sprites in half along the longest axis (left vs right, or top vs bottom), and wrap each half in its own tight AABB. Keep splitting recursively until each box holds a single sprite (a leaf node).

Now when a pixel asks “am I inside (0.64, 0.86)?”:

  1. Test the root box. Inside? Keep going.
  2. Test the Left Half box. Outside? You just eliminated 256 sprites in one if statement!
  3. Jump straight to the Right Half box. Repeat ~9 times (log⁡2512=9\log_2 512 = 9) and you’ve found the exact sprite!

Why GPUs Use Flat Stackless BVHs with escape Pointers

On a CPU, you might store a tree as Java objects with Node left; Node right; pointers and recurse. GPUs hate recursion and pointer chasing — shaders have no call stack, and jumping randomly around memory ruins cache lines and burns registers.

So Mirror lays the entire BVH out in pre-order inside a flat, contiguous array of 32-byte nodes:

  • If you are inside an internal node at index i, its first child is always right next door at i + 1!
  • If you miss node i, where do you go? Straight to node.escape — the exact array index of the next sibling subtree!
GLSL
// GPU stackless BVH traversal — ZERO stack, ZERO recursion, ONE integer cursor!
int idx = spriteRoot;
while (idx < endIdx) {
    SpriteNode n = SpriteNodes[idx];
    if (uv.x < n.minU || uv.x > n.maxU || uv.y < n.minV || uv.y > n.maxV) {
        idx = n.escape;       // Missed! Skip this entire subtree in 1 instruction
    } else if (n.material >= 0) {
        return n.material;    // Hit a leaf!
    } else {
        idx++;                // Inside internal node: step into left child
    }
}
How a 2D sprite atlas becomes a pre-order binary tree with escape links and finally a contiguous 32-byte-per-node GPU buffer.

Move your cursor over the atlas below to watch the BVH test boxes and skip entire subtrees via escape live, and toggle Linear Scan to compare:

Interactive Stackless BVH Explorer. Move your cursor across the UV atlas to see live AABB tests, tree traversal, and flat SSBO escape jumps.

The 373× CPU Fix in WorldSpriteMaterials

Mirror’s GPU BVH traversal was already clever. The problem was how the CPU was building it:

Java
// BEFORE: WorldGeometryRenderer.java — ran EVERY SINGLE FRAME!
var sprites = new WorldSpriteMaterials(); // threw everything away last frame

On every single frame, even when you were standing completely still:

  1. It copied WorldMaterials.sprites(atlas) into an ArrayList and sorted it by entry.getKey().toString().
  2. Its recursive build(List<Leaf>) allocated two new ArrayList<>(leaves.subList(...)) copies and re-sorted with Comparator.comparingDouble at every single internal tree node — 511 list copies + 511 Node + 511 Region objects = 294.6 KB of garbage and 224 μs every frame!

Wait — there was one subtle constraint in MaterialTable.java: MaterialTable uses frame-scoped reference counting, so each sprite’s materialId offset must still be refreshed via table.intern(...) every frame (an O(1)O(1) identity-map hit).

The tree topology, bounds, escape links, and routes, however, only change when WorldMaterials.revision() or WorldTextureCatalog.revision() changes (resource reloads)!

So in WorldSpriteMaterials.java, we:

  1. Rewrote the builder to partition in place on a single Leaf[] array (zero subList copies!) and pack directly into a flat int[] packedNodes (8 ints = 32 bytes/node).
  2. Cached each atlas’s AtlasTree keyed by (WorldMaterials.revision(), WorldTextureCatalog.revision()).
  3. On steady frames, we ONLY patch the leaf materialId slots (packedNodes[leafNodeIndices[i] * 8 + 4] = offset) and upload the entire buffer with one bulk IntBuffer.put(packedNodes):
  • Measured JBR 25 (512 sprites/frame): 224.0 → 0.6 μs (373× faster), 294.6 KB → 56 B/frame (-99.98% allocation)!

7. The JVM Render-Thread Diet: Zero-Alloc Encoding, LUTs & Graph Fast Paths

At 120–380 FPS, your entire CPU + GPU frame budget is only 2.6 to 8.3 milliseconds. Even when individual Java allocations look “tiny” (a 32-byte GpuRect, a 16-byte long[0], a boxed Integer), multiplying them by 2,000 draw calls and 256 lights per frame turns into ~45–140 MB/s of short-lived garbage on the render thread — evicting hot data from the CPU’s L1/L2 cache and triggering Young-Generation Garbage Collection (GC) pauses that freeze the render thread for several milliseconds right in the middle of frame pacing, even if you have 32 GB of free RAM.

Per-frame render-thread heap churn before and after our 5 CPU optimization tracks (measured on JBR 25).

Here are the exact hidden Java traps we eliminated across Mirror’s CPU hot paths:

Trap 1: Empty Varargs (long...) Allocate new long[0] Every Call

Every call to pass.setBindGroup(0, group) invoked void setBindGroup(int, GpuBindGroup, long... dynamicOffsets). In Java bytecode, calling a varargs method with zero trailing arguments compiles to new long[0] on every single call!

Fix (GpuRenderPass.java, EngineRenderPass.java): Add explicit 2-arg overloads setBindGroup(int, GpuBindGroup) and setBindGroup(int, GpuBindGroupBuilder) delegating to a shared static final long[] NO_DYNAMIC_OFFSETS = new long[0]. Zero source changes at call sites, zero allocation.

Trap 2: Per-Draw new GpuRect, dynamicOffsets.clone(), Boxing & Capturing Lambdas

Inside the deepest Vulkan and OpenGL draw loops (running thousands of times per frame):

  • VkGraphicsCommandState.java: intersect(scissor, renderArea) allocated a brand-new new GpuRect(...) record on every single Vulkan draw just to read its 4 int fields and throw it away! Computing the 4 intersected int locals directly eliminated 100% of them.
  • VkBoundDescriptorSets.java & GlBindGroupBindingState.java: Every dynamic offset update called dynamicOffsets.clone(). Now we reuse the existing long[] via System.arraycopy when lengths match (and share NO_DYNAMIC_OFFSETS when empty).
  • VkGpuCommandEncoder.java & GlGpuCommandEncoder.java: Map<Integer, GpuBufferSlice> activeVertexBuffers boxed vertex slot 0 into Integer on every bind and allocated a HashMap$ValueIterator on every GL draw. Replaced with a tiny GpuBufferSlice[4] array.
  • VkDescriptorSetState.java: Passing this::markDescriptorDirty to VkDescriptorWriteState allocated a capturing lambda object on every texture/buffer write! Storing private final IntConsumer markDescriptorDirty = this::markDescriptorDirty; once on the pooled state made it zero-alloc.
  • GlGpuBackend.java & GlPushConstantState.java: OpenGL was calling new GlGpuCommandEncoder(...) and throwing away all off-heap direct push-constant ByteBuffers at the end of every frame! Now the GL encoder and its push-constant staging buffers persist across frames just like Vulkan’s, GL resource unit caches persist per GpuPipelineLayout, and GlBindGroupState.java inlines UBO upload metadata plus precomputes an O(1)O(1) int[] dynamicOffsetStarts lookup table.

Measured JBR 25 (2,000 draws/frame): 27.4 → 13.3 μs (2.06× faster), 48.0 KB → 0 B/frame (-100% alloc).

Trap 3: Transcendental Math & Scratch Churn in LightClusters & DynamicLights

In LightClusters.java, computing each light’s frustum coverage called NEAR * (float) Math.exp(slice * logStep) twice per slice (up to 64 Math.exp calls per light!), allocated 4 int[] arrays (columns, rows, low, high) per light, and packed records via write(int record, float... values) (allocating a float[12] varargs array per light!).

Because NEAR, FAR, and SLICES = 32 are compile-time constants, precomputing a 32-float SLICE_DEPTHS[] lookup table once in a static initializer replaces all 64 Math.exp calls with an array load! Combined with local int bounds, a reusable int[4] scratch, fixed-arity 12-float write(...), and reusing LightClusters.Builder + MemoryUtil.memSet in LightingPreparer.java:

  • Measured JBR 25 (256 lights/frame): 29.9 → 16.4 μs (1.82× faster), 32.8 KB → 0 B/frame (-100% alloc).

Meanwhile, DynamicLights.java was looking up BuiltInRegistries.ITEM.getKey(item).getPath() and running 8 .contains("torch" / "soul" / ...) checks per held item per frame, plus boxing every entity ID via LIGHTS.keySet().removeIf(...). Caching Item → ItemLightSpec in a Reference2ObjectOpenHashMap and iterating with fastutil’s primitive IntIterator eliminated both completely.

Trap 4: Render Graph Whole-Buffer Sorting & SurfaceTextureTable Repacking

Two final sneaky wins in the core engine:

  1. Render Graph (4.2 → 0.9 μs, 4.67× faster):

    • On every frame, GpuRenderGraphBuilder.java ran rankBufferRanges() across every buffer in the graph — appending (0, size) for every pass, calling Arrays.sort(), deduplicating, and binary-searching ranks even though 95% of buffers are only ever read/written as [0, declaredSize]. Adding an O(1)O(1) fast path for [0, declaredSize] skips sorting and binary search completely.
    • In CompiledRenderGraph.java, every subresource view (shadow cascade layers, depth pyramid mips) built a fresh GpuTextureViewDescriptor.builder()...build(). Packing (dimension, format, aspect, baseMip, levelCount, baseLayer, layerCount) into a 56-bit primitive long inside a ThreadLocal<Long2ObjectOpenHashMap<GpuTextureViewDescriptor>> makes subresource view lookup 0 bytes allocated, lock-free, O(1)O(1).
  2. MaterialTable & SurfaceTextureTable (16.7 → 0.4 μs, 41.7× faster):

    • Replaced boxed List<Integer> materialSetEntries in MaterialTable.java with fastutil IntArrayList (bulk uploaded via IntBuffer.put(entries.elements(), 0, size)), and reused the expired hold ArrayList instead of allocating a new one every frame.
    • In SurfaceTextureTable.java, instead of iterating a HashMap and repacking 12 floats per texture every frame, we cache a packed float[] keyed by (structureRevision, textures.textureBindingRevision()), update only animated UVs when animationTick advances, preserve texture usage tracking in 1–4 CPU instructions via BitSet.or(), and copy the entire table in one FloatBuffer.put().

8. Live Profiling War Story: 198 → 122 → 380 FPS at 1440p (32 Chunks)

Micro-benchmarks are essential, but real games have a hilarious habit of humbling you the second you boot them up.

Right after finishing Sections 1–7, we launched live Minecraft on Vulkan at 1440p, 32-chunk render distance on the RTX 3080 — expecting huge numbers. Instead, the frame counter sat at ~198 FPS, and nvidia-smi showed something bizarre: the RTX 3080 was only at 80% utilization and drawing 135 W (on a 320 W GPU!).

Something was starving the GPU. So we attached Java Flight Recorder (jcmd JFR.start) for 10-second live captures and traced it step by step.

Act I: The Silently Broken Z-Prepass (198 → 122 FPS?!)

Run 1’s JFR capture lit up an immediate alarm: 2,631 exceptions thrown on the render thread in 10 seconds, and vkCmdPipelineBarrier eating 8.0% of total render-thread CPU time.

Opening the stack trace exposed a sneaky bug: our brand-new terrain_depth prepass shader was missing the WorldTransforms uniform block define! Every frame, binding the prepass shader threw an exception that got caught and skipped the entire Z-prepass — meaning we had been benchmarking without Early-Z at all!

We added the missing WorldTransforms define, relaunched the game, and watched FPS…

CRASH from 198 FPS down to 122 FPS.

Wait — what?! How on earth did fixing a 3.88× faster optimization cut live framerate nearly in half, while GPU power rose from 135 W to 196 W and utilization dropped to 78%?

First-Principles Detour: Vulkan Dynamic Rendering & Pipeline Barriers

To understand why Run 2 fell off a cliff, you need to know two core Vulkan rules:

  1. Dynamic Render Passes (vkCmdBeginRenderingKHR / vkCmdEndRenderingKHR). When you draw 400 terrain chunks into the G-Buffer or Depth Buffer, you wrap all 400 draws inside one single Render Pass. That keeps the color and depth tiles hot in on-chip caches so the GPU’s 68 SMs stay completely saturated back-to-back.
  2. Pipeline Barriers (vkCmdPipelineBarrier2KHR) Cannot Run Inside a Render Pass. A Vulkan pipeline barrier tells the hardware: “Stop launching Stage B until Stage A has finished writing and flushed its L2 cache.” Critically, the Vulkan spec forbids inserting a general memory/buffer barrier in the middle of an active Dynamic Render Pass. So if your engine’s automatic state tracker believes an indirect terrain draw needs a buffer barrier, it has to:
    • Call vkCmdEndRenderingKHR (flush the render pass)
    • Emit vkCmdPipelineBarrier2KHR (drain all 68 SMs down to 0% occupancy — a GPU pipeline bubble!)
    • Call vkCmdBeginRenderingKHR (reload attachments with LOAD_OP_LOAD and start over!)

Act II: The Smoking Gun (collapsedAccess + GpuBufferUseHistory)

Now look at what Run 2’s JFR capture caught:

  • 24.2 MB of BufferTransition objects allocated in 10 seconds!
  • vkCmdPipelineBarrier still burning 5.1% of render-thread CPU, and vkCmdBegin/EndRenderingKHR burning 2.7%!

When the Z-prepass finally started working, Mirror’s terrain indirect buffers and geometry buffers were read across multiple read-only access masks (for example, VERTEX_ATTRIBUTE_READ | INDEX_READ, or INDIRECT_COMMAND_READ | SHADER_READ). We traced the barrier generator straight into two files:

  1. VkSynchronizationCommands.collapsedAccess(...): Whenever two or more read-only access bits were combined on a buffer, the helper collapsed them into VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT — accidentally setting writes = true on a pure read-only draw!
  2. GpuBufferUseHistory: Because the tracker now thought every read-only draw was a write, and didn’t prune superseded wider write ranges across overlapping buffer slices, every single indirect terrain draw looked like a Read-After-Write hazard!

Mirror was literally ending the dynamic render pass, firing a full GPU pipeline barrier, and restarting the render pass between indirect terrain draws — starving 68 Ampere SMs into tiny sawtooth bursts!

Real 1440p (32-chunk) RTX 3080 telemetry across all three profiling runs. Fixing the read-only collapsedAccess bug turned a shattered stop-and-go render pass into an unbroken 294 W wall of GPU work.

Act III: The Fix — Unbroken Dynamic Render Passes (122 → 380 FPS!)

Preserving exact read-only access masks in VkSynchronizationCommands.collapsedAccess(...) (never promoting read-only bits to MEMORY_WRITE) and cleanly pruning superseded write records in GpuBufferUseHistory eliminated 100% of the bogus mid-pass barriers and BufferTransition allocations.

Here is the live 1440p @ 32-chunk scoreboard across all three JFR + nvidia-smi captures on the exact same world and camera view:

Metric (1440p, 32 Chunks, RTX 3080)Run 1: Broken Z-PrepassRun 2: Prepass Fixed, VK Barrier StormRun 3: VK Sync Fixed
Live Framerate195–198 FPS121–122 FPS356–365 FPS (380 peak)
GPU Utilization / Power80% / 135 W78% / 196 W95% / 294 W
Render-Thread GC Pauses (10s)3 pauses2 pauses0 pauses
vkCmdPipelineBarrier CPU %8.0%5.1%3.0%
vkCmdBegin/EndRendering CPU %2.8%2.7%0.9%
BufferTransition Allocs (10s)—24.2 MB0 MB
Render-Thread Exceptions (10s)2,63100

Switch between Run 1, Run 2, and Run 3 in the interactive GPU queue simulator below to watch the 68 Ampere SMs drop into pipeline bubbles during Run 2’s barrier storm and then peg at 95% / 294 W in Run 3:

Interactive Vulkan Queue & 68-SM Occupancy Simulator based on our live 1440p 32-chunk JFR + nvidia-smi captures. Compare Run 1, Run 2 (barrier storm), and Run 3 (380 FPS unbroken render pass).

The Post-380 FPS CPU & LOD Sweep

Once the RTX 3080 was finally fed at 95% / 294 W, we audited the remaining top CPU frames in Run 3’s JFR profile and swept up six more sneaky overhead sources:

  • LodNearTerrain column caching & O(1)O(1) LOD skip: When near vanilla terrain already covers every resident LOD node (e.g., inside a 32-chunk world with no distant LODs generated beyond it), skip LOD work in O(1)O(1) instead of scanning empty rings, and cache near-terrain column coverage.
  • WorldLodResidency.retier hoisting: Hoisted invariant chunk-tier bounds checks out of the inner residency loop.
  • PipelineService.tryPreload identity cache: Avoided repeated map lookups and key builds when preloading already-warm pipelines.
  • EngineGpuBuffer graph descriptor caching: Cached immutable buffer descriptors directly on the buffer object instead of rebuilding them during every frame-graph compile.
  • WorldGeometryRenderer scratch-set reuse & lazy FrameModels/FrameSkinning: Eliminated per-frame temporary set allocations and deferred skinning/model frame tables on frames with no animated custom models.

9. Deep Dive: Vulkan Mesh Shaders (VK_EXT_mesh_shader) & Meshlets

At 380 FPS, we asked a fun, ambitious question: can we go even faster by replacing the traditional 30-year-old vertex pipeline with hardware Vulkan Mesh Shaders (VK_EXT_mesh_shader) and Meshlets on supported GPUs?

Because Mesh Shaders are still unfamiliar to a lot of graphics programmers, let’s build the entire concept from scratch — what the old pipeline does, why it bottlenecks, how Task & Mesh shaders work on the silicon, what a Meshlet actually is, how Mirror architected them cleanly as an optional Vulkan fast path, and the honest RTX 3080 benchmarks showing both where they crush it (1.20–1.35×) and where they don’t!

9.1 Why the Classic Vertex Pipeline Hits a Wall

Every 3D engine since the 1990s has pushed triangles through the same rigid front-end:

Compute Cull⟶Indirect Buffer (VRAM)⟶Barrier⟶Input Assembler (IA)⟶Vertex Shader (VS)⟶Rasterizer\text{Compute Cull} \longrightarrow \text{Indirect Buffer (VRAM)} \longrightarrow \text{Barrier} \longrightarrow \text{Input Assembler (IA)} \longrightarrow \text{Vertex Shader (VS)} \longrightarrow \text{Rasterizer}

Even with modern GPU-driven Multi-Draw Indirect (MDI), this fixed-function front-end has three structural limitations:

  1. Two Passes + a VRAM Barrier for GPU Culling. If you want the GPU to frustum-cull or occlusion-cull geometry, you run a Compute Shader that writes surviving draw commands out to an indirect buffer in VRAM, fire a pipeline barrier (COMPUTE → DRAW_INDIRECT), and then let the graphics pipeline read those commands right back.
  2. Blinded Per-Vertex Execution. A Vertex Shader runs on one single vertex in isolation. It has no idea which other two vertices form its triangle, which way that triangle is facing, or whether the whole cluster of 100 triangles is facing away from the sun! You have to load and transform every vertex of every backfacing triangle before the fixed-function clipper finally throws the triangle in the trash.
  3. The Fixed-Function Input Assembler (IA) Bottleneck. The Input Assembler is fixed silicon that fetches 32-bit vertex indices, looks up a small post-transform vertex cache, and assembles triangles serially. When you throw 10 million shadow-casting triangles or millions of distant LOD quads at it, the IA and index-buffer bandwidth become a real ceiling.

9.2 Enter VK_EXT_mesh_shader: Compute-Like Graphics Stages

Mesh Shaders delete the Input Assembler, Vertex Shader, Tessellation, and Geometry Shader completely, and replace the entire geometry front-end with two programmable, compute-like graphics stages that feed triangles straight into the hardware rasterizer:

  1. The Task Shader (*.task, optional Amplification stage).

    • Just like a compute shader, you dispatch a grid of workgroups (vkCmdDrawMeshTasksEXT or vkCmdDrawMeshTasksIndirectEXT), typically 32 threads per workgroup (layout(local_size_x = 32) — one exact Ampere warp!).
    • Each of the 32 threads inspects one coarse cluster (one LOD node or one 124-triangle meshlet). It performs a cheap bounding-sphere frustum test and a backface normal-cone test.
    • Instead of writing to VRAM or using slow atomics, the 32 threads compact the surviving IDs entirely inside warp registers using subgroupBallot / subgroupInclusiveAdd, write the surviving IDs into a tiny on-chip taskPayloadSharedEXT struct, and call EmitMeshTasksEXT(survivingCount, 1, 1).
    • Zero VRAM indirect buffers. Zero compute-to-graphics barriers. Dead clusters never even launch a Mesh Shader!
  2. The Mesh Shader (*.mesh).

    • Each launched Mesh workgroup owns one surviving meshlet (or one LOD chunk slice).
    • It declares its exact output size once with SetMeshOutputsEXT(vertexCount, primitiveCount).
    • All threads in the workgroup cooperate in parallel: they transform unique vertices into gl_MeshVerticesEXT[v].gl_Position, unpack 1-byte triangle indices into gl_PrimitiveTriangleIndicesEXT[t] = uvec3(a, b, c), and hand the finished triangles directly to the hardware rasterizer!
    • Bonus superpower — perprimitiveEXT: In classic shaders, if a flat Minecraft voxel face has a material ID and face normal, you have to output and interpolate it on all 4 vertices. Mesh shaders support perprimitiveEXT, letting you write flat face/material attributes once per triangle instead of duplicating them across vertices!

9.3 What Exactly Is a Meshlet? (And Backface Normal-Cone Culling)

You can’t hand a 20,000-triangle custom 3D model to one Mesh Shader workgroup — on-chip vertex/primitive output memory is small (typically up to 64–256 vertices/primitives per workgroup). So at asset bake time, we chop large meshes into tiny, spatially tight sub-meshes called meshlets.

In Mirror’s new ModelMeshletizer.java:

  • Target Size: Each meshlet holds at most 64 unique vertices and 124 triangles (tuned to NVIDIA Ampere’s 128-primitive allocation granularity and shared-memory footprint).
  • Greedy Vertex-Reuse Clustering: Starting from a spatially coherent seed triangle, the builder greedily pulls in adjacent triangles that reuse already-loaded vertices — achieving ~1.94 triangles per vertex (nearly 2× vertex reuse inside every meshlet!).
  • 4× Smaller uint8 Local Indices: Because a meshlet has at most 64 local vertices (0..63), every triangle index fits in a single byte (uint8) instead of a 32-bit uint32 — slashing index memory bandwidth by 75%!
  • 48-Byte ModelMeshlet Descriptor: Alongside the local vertex/index streams, the baker stores a compact 48-byte descriptor per meshlet containing its offsets, a Ritter bounding sphere (c,r)(\mathbf{c}, r), and a conservative backface normal cone (a^,sin⁡θ)(\hat{a}, \sin\theta):

How Backface Normal-Cone Culling Works

Imagine every triangle in a 124-triangle meshlet has a unit normal arrow sticking straight out of its front face. Now wrap the tightest possible cone around all 124 arrows — centered on their average axis a^\hat{a} with half-angle θ\theta (the widest angle between a^\hat{a} and any triangle’s normal in that meshlet).

Now look at an orthographic directional sun shadow map with light direction v^\hat{v} (pointing from the scene toward the sun). Every single triangle in that meshlet is mathematically guaranteed to face away from the sun whenever:

dot(−v^,a^)≥sin⁡(θ)\text{dot}(-\hat{v}, \hat{a}) \ge \sin(\theta)

Why sin⁡(θ)\sin(\theta)? Because the worst-case triangle inside the cone can tilt at most θ\theta radians away from a^\hat{a}, so the boundary where any triangle could still face the light is 90∘−θ90^\circ - \theta away from −a^-\hat{a} — and cos⁡(90∘−θ)=sin⁡(θ)\cos(90^\circ - \theta) = \sin(\theta)! For a perspective camera at position pcam\mathbf{p}_{\text{cam}}, we conservatively account for the sphere’s finite radius rr around center c\mathbf{c}:

dot ⁣(c−pcam∥c−pcam∥,  a^)≥sin⁡(θ)+r∥c−pcam∥\text{dot}\!\left(\frac{\mathbf{c} - \mathbf{p}_{\text{cam}}}{\|\mathbf{c} - \mathbf{p}_{\text{cam}}\|}, \;\hat{a}\right) \ge \sin(\theta) + \frac{r}{\|\mathbf{c} - \mathbf{p}_{\text{cam}}\|}

When that one single dot product succeeds in 1 thread of the Task Shader, all 124 triangles and 64 vertices vanish immediately — zero vertex fetches, zero matrix transforms, zero rasterizer setup!

Left: Classic Compute + Indirect + Input Assembler pipeline vs Vulkan VK_EXT_mesh_shader. Right: Mirror's 48-byte ModelMeshlet layout, 1-byte uint8 local indices, and how one dot product against a conservative normal cone culls up to 124 backfacing triangles at once.

Drag to rotate the 3D meshlet-partitioned sphere below! Watch the 48 color-coded meshlets light up green (visible), fade to red (culled by backface normal cone in the Task Shader), or turn slate (culled by the frustum edge), and toggle between Mesh Shaders and the Traditional IA+VS pipeline:

Interactive 3D Meshlet & Backface Normal-Cone Visualizer. Drag to orbit the meshlet-partitioned model, toggle Normal-Cone Culling and Frustum Culling, and switch between VK_EXT_mesh_shader and Traditional IA+VS.

9.4 Architecting Mesh Shaders Cleanly (Not as an Afterthought)

We didn’t want Mesh Shaders bolted on as a fragile Vulkan hack. Instead, we integrated them as a first-class optional Vulkan-only fast path right through Mirror’s core GPU abstraction:

  • First-Class GPU API (mirror-core): Added GpuShaderStage.TASK and GpuShaderStage.MESH, GpuMeshShaderCapabilities, and drawMeshTasks / drawMeshTasksIndirect on GpuRenderPass and EngineRenderPass.
  • Automatic Hardware Gating & A/B Toggle: On Vulkan GPUs advertising VK_EXT_mesh_shader (NVIDIA Turing/Ampere/Ada/Blackwell, AMD RDNA 2+, Intel Arc), Mirror enables the mesh shader pipelines automatically; on OpenGL or older GPUs (or when launched with -Dmirror.meshShaders=false), it falls back seamlessly to the Compute + MDI path.
  • VUID-Safe Synchronization: Pipeline stage masks (VK_PIPELINE_STAGE_2_TASK_SHADER_BIT_EXT, VK_PIPELINE_STAGE_2_MESH_SHADER_BIT_EXT) are strictly gated on capabilities.meshShaders() so Vulkan Validation Layers stay 100% clean on non-mesh-shader devices too.
  • Three Integrated Workloads:
    1. LOD Terrain Shadows (lod_shadow_mesh) — Task shader frustum-culls LOD nodes; Mesh shader emits voxel quads directly into shadow cascades.
    2. LOD Camera Visibility & Terrain (lod_visibility_mesh, lod_terrain_mesh) — Uses perprimitiveEXT flat face attributes and #ifndef MIRROR_LOD_NO_NEAR_CUTOUT Early-Z on far rings.
    3. Custom Model Shadows (model_shadow_instanced_mesh in ShadowCommandBuilder) — Uses bake-time ModelMeshletizer (64v/124t, uint8 indices, Ritter sphere + normal cone) to cull and rasterize dense instanced models straight into shadow maps.

Three Ampere Tuning Lessons Learned Along the Way

  1. local_size_x = 128 vs 32 in Mesh Shaders: Expanding 64 LOD quads (256 vertices, 128 triangles) with only 32 threads (1 warp) per Mesh workgroup stalled on SSBO loads. Bumping LOD mesh workgroups to 128 threads (4 warps) let the SM hide memory latency cleanly.
  2. Subgroup Compaction in Task Shaders: Using subgroupBallot + subgroupInclusiveAdd inside 32-thread Task warps compacted surviving meshlets/nodes in ~2 cycles with zero shared-memory atomics.
  3. perprimitiveEXT Cuts Attribute Bandwidth: Sending flat LOD face metadata once per primitive instead of repeating it on every vertex cut Mesh-to-Rasterizer output traffic substantially.

9.5 Honest RTX 3080 Hardware Benchmarks (Wins and Tradeoffs!)

Every number below comes from MeshShaderBenchmarkTest on the RTX 3080 (25 warmup frames + 75 timed frames, Vulkan validation off, GpuProfiler gpuSpanMillis), after verifying pixel-exact depth equivalence (6,801 / 6,801 LOD shadow pixels, 8,735 / 8,735 LOD visibility pixels, 580 / 580 custom model shadow pixels) and 0 Vulkan validation errors:

Benchmark Scenario (RTX 3080 Hardware Timestamps)Compute + MDIVK_EXT_mesh_shaderSpeedup
LOD Shadow 2048² (4,096 nodes, 590k quads)0.178 ms0.159 ms1.12×
LOD Shadow 2048² (16,384 nodes, 2.36M quads)0.413 ms0.346–0.360 ms1.14–1.19×
LOD Visibility 1080p (4,096 nodes, 590k quads)0.108 ms0.123 ms0.88×
LOD Visibility 1080p (16,384 nodes, 2.36M quads)0.197 ms0.201 ms0.98×
Custom Model Shadow 2048² (128× 20k-tri = 2.58M tris)0.187 ms0.157 ms1.20×
Custom Model Shadow 2048² (512× 20k-tri = 10.3M tris)0.815 ms0.632 ms1.29×
Custom Model Surface 1080p (128× 20k-tri, cone cull OFF → ON)0.220 ms0.163 ms1.35×

That’s why engineering beats hype: keep Mesh Shaders enabled where the silicon genuinely rewards them (dense meshletized custom models and massive LOD shadow cascades), and measure every pass instead of assuming a shiny Vulkan extension automatically wins everywhere.


10. Trust, But Hash: How We Verified Everything

Speedups that subtly corrupt pixels, leak Vulkan validation errors, or only work on one graphics API are worthless. Every optimization across this entire post was gated on five checks:

  1. Dual-Target Native Compilation: Every shared shader compiles cleanly through both Vulkan 1.2 SPIR-V (glslang + spirv-val) and OpenGL 4.5, while Vulkan-only VK_EXT_mesh_shader stages compile to SPIR-V 1.4 (GL_EXT_mesh_shader) with clean non-mesh-shader fallbacks.
  2. Pixel-Exact Output Verification: Opaque terrain, cutout terrain, deferred decals, vectorized textureGather occlusion blur (9040512b796e6b83), LOD shadow mesh shaders (6,801/6,801), LOD visibility mesh shaders (8,735/8,735), and custom model shadow meshlets (580/580) all verified against baseline outputs.
  3. Zero Vulkan Validation Errors: Every Vulkan change — including collapsedAccess, GpuBufferUseHistory, and VK_EXT_mesh_shader — ran cleanly under Khronos Vulkan Validation Layers with 0 VUID errors.
  4. Hardware Shader & Live Telemetry: VK_KHR_pipeline_executable_properties (register counts, local spill 48 B → 0 B, SASS reductions), vkCmdWriteTimestamp micro-benchmarks, and live 1440p JFR + nvidia-smi captures (198 → 122 → 380 FPS, 294 W, 0 GC pauses).
  5. Full Regression Suite: Every change ran cleanly against both :mirror-core:test and :mirror-fabric:test (4,450+ tests, 0 failures).

11. Principles You Can Steal for Your Own Engine

If you take away just eight habits from this entire journey, make them these:

  1. Never guess — measure on real hardware. GPU timestamp queries, driver register/spill reports, ThreadMXBean.getThreadAllocatedBytes(), JFR, and nvidia-smi turn optimization from folklore into engineering.
  2. Kill work before optimizing it. Skipping 90% of empty tiles (10×), avoiding 4× overdraw with Early-Z (3.88×), or culling 45% of backfacing meshlets in a Task Shader (1.35×) beats hand-tuning arithmetic every single time.
  3. Watch out for discard and LOAD_OP_LOAD. Both silently sabotage fixed-function GPU hardware (Early-Z and lossless framebuffer compression) unless you structure prepasses and load ops around them.
  4. Guard your Vulkan render passes like gold. One accidental writes = true bit on a read-only buffer can shatter a dynamic render pass into hundreds of pipeline barriers and chop live framerate in half (380 → 122 FPS).
  5. Keep data on-chip whenever possible. LDS shared memory (depth_pyramid_multi.comp), pass fusion (froxel_light_fused), and warp-level subgroup compaction (subgroupInclusiveAdd) turn 400-cycle VRAM round-trips into 0-to-20-cycle register/SRAM operations.
  6. Match the geometry front-end to your mesh topology. Mesh Shaders shine on connected, high-vertex-reuse meshlets with tight normal cones (1.20–1.35×) and massive shadow cascades (1.19×), while disconnected quads in fragment-bound views stay near parity with Compute+MDI.
  7. Flatten trees and cache by revision. Pointer-heavy trees and per-frame rebuilds wreck both GPUs and the JVM. A flat int[] with escape links cached behind an integer revision counter turns 224 μs of GC churn into a 0.6 μs memcpy.
  8. Zero-allocation render threads are a choice. Non-varargs overloads, primitive fastutil collections, ThreadLocal scratch buffers, and precomputed LUTs keep 380 FPS frame pacing completely free of GC pauses.