Skip to content
XaviFortesPublic

About

A Metal-backend Fabric mod for Minecraft with Iris/OptiFine shader-pack support

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

MetalMC

CI Latest release

A Fabric mod that renders Minecraft through a native Apple Metal backend on Apple Silicon, replacing macOS's deprecated, CPU-bound OpenGL translation layer. Java 22 FFM (java.lang.foreign) drives a thin Objective-C++ dylib; Apple's unified memory architecture makes the Java→GPU vertex path a single write into memory the GPU samples directly.

It is not a wrapper over GL calls. Terrain is GPU-driven — culled by a compute kernel and drawn from an indirect command buffer the CPU never walks — and the whole frame, including the GUI, is composited in Metal. On top of that sits a from-scratch implementation of the Iris/OptiFine shader-pack format: pack GLSL is transpiled to Metal Shading Language at load time and executed as a real deferred pipeline.

Target: Minecraft 1.20.4 / Fabric, Apple Silicon (developed on an M4), Java 22.

Contents

What works today

Area State
Terrain (solid, cutout, translucent) GPU-driven: compute cull → indirect command buffer
Mesh memory Shared-slab arena, zero-copy from BufferBuilder
Entities, block entities, held item Ported
Sky, clouds, sunrise/sunset glow, stars Ported
Particles, weather Ported
Sun shadows Compute-culled depth-only pass, normal-offset bias
GUI / HUD Composited from a shared IOSurface
Block atlas + animated sprites Mirrored into Metal with GPU-generated mips
Shader packs (Iris/OptiFine) Loaded, transpiled to MSL, executed — see below
Pack settings menu The pack's own screen tree, sliders and lang files
Upscaling MetalFX spatial

Verified against Complementary — Reimagined and Unbound r5: 21 gbuffers programs, a 9-pass deferred/composite chain, its shadow program, 405 configurable settings, and its 7 quality profiles. The two are not interchangeable even within one family: Unbound ships no clouds=off where Reimagined does, which is the kind of difference a second pack surfaces and a single one hides.

Architecture & data flow

Vertex batch memory lifecycle

 Chunk meshing worker thread                Render thread (= macOS main thread)
 ───────────────────────────                ────────────────────────────────────────────
 BufferBuilder writes 32-byte               VertexBuffer.upload(BuiltBuffer)
 block vertices into a direct   ─────────▶  │
 ByteBuffer (off-heap)                      ▼ [VertexBufferMixin]
                                            MetalWorldRenderer.uploadMesh
                                            │  mtlmc_mesh_create(vertexCount)   (FFM)
                                            │    └─ MTLBuffer, StorageModeShared
                                            │       + CPUCacheModeWriteCombined
                                            │  mtlmc_mesh_contents(handle)      (FFM)
                                            │    └─ MemorySegment over the MTLBuffer's
                                            │       own pages (UMA — not a staging copy)
                                            │  MemorySegment.copy(src → dst)
                                            │    └─ THE upload: one memcpy into memory
                                            │       the GPU samples directly
                                            ▼
 Per frame:                                 WorldRenderer.render
                                            │ [WorldRendererMixin HEAD]
                                            │ mtlmc_begin_frame(viewProj)
                                            │   ├─ dispatch_semaphore_wait (≤3 in flight)
                                            │   ├─ CAMetalLayer nextDrawable
                                            │   └─ render pass begins (clear color+depth)
                                            │ vanilla renderLayer per terrain layer
                                            │   ├─ chunkOffset uniform captured (@Redirect)
                                            │   └─ VertexBuffer.draw() diverted per chunk:
                                            │      mtlmc_draw_mesh(handle, layer, offset)
                                            │        └─ encode drawIndexedPrimitives with
                                            │           shared quad index buffer
                                            │ [WorldRendererMixin RETURN]
                                            │ mtlmc_end_frame
                                            │   ├─ endEncoding, presentDrawable
                                            │   └─ commit + completion handler → semaphore
                                            ▼
                                            GPU consumes the same physical pages Java wrote

There is exactly one copy on the whole path (BufferBuilder's ByteBuffer → MTLBuffer contents), which is the theoretical minimum while vanilla still owns mesh building. There is exactly one CPU/GPU sync point (the frame semaphore); no per-buffer locks or fences exist anywhere.

How UMA is exploited

  • All vertex memory is MTLResourceStorageModeShared — on Apple Silicon CPU and GPU address the same DRAM, so buffer.contents handed to Java as a MemorySegment is the GPU-visible allocation. "Upload" = write.
  • MTLResourceCPUCacheModeWriteCombined on vertex buffers: the CPU streams vertices once and never reads back, so bypassing the cache hierarchy wins.
  • The depth attachment is MTLStorageModeMemoryless: on TBDR GPUs it lives in tile memory only — zero DRAM footprint and bandwidth.
  • Dynamic per-frame geometry uses a triple-buffered bump-allocator arena (16 MiB × 3, 64-byte-aligned slices). Slot reuse is gated purely by the frame semaphore, so writes never race in-flight GPU reads.
  • Small per-draw data (chunkOffset, alphaCutoff) goes through setVertexBytes — allocation-free, and vertex/uniform structs are 16-byte-aligned SIMD types (simd_float4x4, simd_float3) matching MSL constant-buffer layout exactly.

One machine. Everything measured in this README was measured on a single M4 MacBook Air (base chip, 10 GPU cores, 24 GB, fanless, 60 Hz panel). Apple Silicon spans ~10x that GPU throughput and 8 GB to 192 GB of unified memory. docs/apple-silicon.md is the audit of what that single data point costs us: the real memory footprint per component and per shader pack, every device capability the renderer assumes versus detects, why newTextureWithDescriptor: returning nil is not the out-of-memory failure mode on this platform, and why "upscale when the frame is slow" is measurably the wrong heuristic here. It also documents what -Dmetalmc.novsync does and does not do, and how to measure a frame that finishes well inside the refresh interval.

Project structure

MinecraftMetal/
├── native/
│   ├── build.sh                     clang++ build; stages both dylibs
│   ├── include/metalmc/bridge.h     the exported C ABI
│   ├── src/
│   │   ├── Bridge.mm                C ABI impl, autoreleasepool discipline
│   │   ├── MetalContext.{h,mm}      device, queue, CAMetalLayer, frame lifecycle,
│   │   │                            MetalFX spatial upscale, present
│   │   ├── PipelineManager.{h,mm}   MSL compile, PSOs, depth-stencil states
│   │   ├── BufferManager.{h,mm}     mesh arena, quad IBO, dynamic arenas
│   │   ├── GpuTerrain.mm            cull kernel + ICB encoding
│   │   ├── IndirectCommandManager.* the ICB itself
│   │   ├── SectionRegistry.*        GPU-resident chunk bounds
│   │   ├── ShadowPass.mm            light-frustum cull + depth-only pass
│   │   ├── FrameMetrics.h           lock-free counters behind the F3 line
│   │   │
│   │   ├── ShaderPackHook.h         the C hook table between the two dylibs
│   │   ├── ShaderPackBridge.mm      the optional dylib's exported ABI
│   │   ├── ShaderPackRuntime.{h,mm} one loaded pack, across the frame
│   │   ├── ShaderPackGeometry.mm    the 21 gbuffers programs + union layout
│   │   ├── ShaderPackChain.mm       deferred/composite/final schedule
│   │   ├── ShaderPackShadow.mm      the pack's own shadow program
│   │   ├── ShaderPackTargets.mm     the colortex ring and its ping-pong
│   │   ├── ShaderPackFrameGraph.mm  pass ordering over the ring
│   │   ├── GlslPatcher.cpp          step-① patcher + include resolver
│   │   ├── ShaderTranspiler.cpp     glslang + SPIRV-Cross driver
│   │   ├── IrisUniforms.mm          the uniform block a pack expects
│   │   ├── CustomUniforms.cpp       shaders.properties expression evaluator
│   │   ├── PackOptions.cpp          settings: parse and rewrite declarations
│   │   ├── PackScreens.cpp          settings: menu tree and lang files
│   │   ├── PackFeatures.cpp         host-draw switches and their #if guards
│   │   ├── PackConstants.cpp        const declarations OptiFine reads back
│   │   ├── PackExternals.cpp        noisetex/shadowtex sampler classification
│   │   └── PackNoise.mm             the generated noise texture
│   └── test/                        28 headless suites; see Testing
└── src/main/
    ├── java/dev/fortes/metalmc/
    │   ├── ffi/
    │   │   ├── MetalBridge.java          FFM downcalls to the core dylib
    │   │   └── MetalShaderBridge.java    FFM downcalls to the shader dylib
    │   ├── render/
    │   │   ├── MetalWorldRenderer.java   render-thread orchestrator
    │   │   ├── ImmediateCapture.java     sky/entity/particle draw funnel
    │   │   ├── GuiCompositor.java        IOSurface FBO ring, HUD capture
    │   │   ├── AtlasCapture.java         GL atlas readback
    │   │   ├── BlockIdCapture.java       mc_Entity block ids, thread-confined
    │   │   ├── ShaderPackFrameState.java the 189-float per-frame block
    │   │   └── PackFeatures.java         host-draw switches, Java side
    │   ├── shaderpack/
    │   │   ├── ShaderPackManager.java    scan, extract, load, reload
    │   │   ├── PackIdentity.java         what to call a pack
    │   │   ├── PackSettings.java         the settings model + persistence
    │   │   └── BlockPropertiesParser.java block.properties → ids
    │   ├── gui/
    │   │   ├── MetalUi.java              shared palette, metrics, header/footer
    │   │   ├── MetalSettingsScreen.java  the renderer's own settings
    │   │   ├── ShaderPackListScreen.java the pack picker
    │   │   └── PackSettingsScreen.java   the pack's own settings tree
    │   └── mixin/                        24 mixins; the interception surface
    └── resources/natives/macos-arm64/
        ├── libmetalmc.dylib              the renderer (no transpiler deps)
        └── libmetalmc-shaders.dylib      optional: glslang + SPIRV-Cross

Two dylibs, deliberately. The core renderer has no dependency on glslang or SPIRV-Cross, so a machine without them still gets the Metal backend — only shader packs go dark. MetalShaderBridge loads the optional one defensively and mtlmc_shaders_available() is the probe.

Building

Native library only (no CMake required):

native/build.sh

Or with CMake: cmake -B native/build -S native && cmake --build native/build.

Full mod (fetches Minecraft/Yarn; needs network). Uses the Gradle wrapper — compileNative runs native/build.sh automatically and stages the dylib into resources, and the Java 22 toolchain the mod needs (FFM is final in 22) is auto-provisioned by the foojay resolver, so only JDK 17+ need be installed to bootstrap:

./gradlew build

Verified building with Gradle 9.6.1 + Fabric Loom 1.17.16, producing build/libs/metalmc-<version>.jar with the dylib bundled at natives/macos-arm64/. Run the dev client with ./gradlew runClient. Outside dev, the launcher's JVM must be Java 22+ with --enable-native-access=ALL-UNNAMED.

CI

.github/workflows/ci.yml runs on every push to main and every PR: the 28 headless suites in native/test/ first (native code is the actual regression risk here — see Testing below), then a build matrix over all three supported Minecraft targets, gated on the suites passing so a broken native change fails in one ~2-minute macOS leg instead of three. Every macOS runner minute here is billed at 10x Linux, which is what the gating buys back. PR builds upload the mod jar as a workflow artifact (14-day retention) for manual testing — that is a convenience, not a release.

Releasing

gradle.properties' mod_version is the single source of truth for the version; a git tag only triggers publishing it. To cut a release:

# bump mod_version in gradle.properties, commit it, then:
git tag v$(grep '^mod_version=' gradle.properties | cut -d= -f2)
git push origin v$(grep '^mod_version=' gradle.properties | cut -d= -f2)

.github/workflows/release.yml takes it from there: refuses to publish if the tag and mod_version disagree, reruns the native suites on the exact tagged commit rather than trusting a prior CI run (a tag can point at a commit CI never saw), then builds one jar per Minecraft target with Fabric's own +mc<version> build-metadata suffix — the convention Sodium and friends use so three genuinely different builds don't all claim to be the same artifact — and attaches all of them to a GitHub Release. Release notes are the commit subjects since the previous tag: this repo has no pull requests, so GitHub's own --generate-notes would find nothing to summarize.

Interception strategy

Vanilla keeps driving chunk scheduling, frustum culling, layer ordering and translucency sorting. The mod taps three narrow, name-stable seams:

  1. WorldRenderer.render HEAD/RETURN — Metal frame begin/present.
  2. WorldRenderer.renderLayer — tracks the active terrain layer and @Redirects the GlUniform.set(FFF) writing chunkOffset, so Metal draws position each chunk with the exact camera-relative offset vanilla computed.
  3. VertexBuffer.upload/draw()/close — any buffer in POSITION_COLOR_TEXTURE_LIGHT_NORMAL quads format is mirrored into a Metal mesh; during an active terrain layer its draw() is cancelled and re-issued through Metal. All other VertexBuffer users (sky, clouds, text) are untouched.

This means no fragile access to WorldRenderer private fields, and mods that add chunk geometry through the vanilla path are captured automatically.

Immediate-mode geometry (block outline, and the path for entities/sky)

Chunk terrain lives in persistent VertexBuffers and is captured on upload. Everything dynamic — block outline, crumbling, entities, particles — is rebuilt every frame and submitted through a different funnel:

RenderLayer.draw(BufferBuilder, VertexSorter)      <- knows the LAYER
  ├─ builder.end() -> BuiltBuffer
  ├─ startDrawing()
  └─ BufferRenderer.drawWithGlobalProgram(buffer)  <- knows the GEOMETRY

Neither half knows both, so the two are paired: RenderLayerMixin publishes the layer into ImmediateCapture on the way in, and BufferRendererMixin intercepts the funnel and asks whether the geometry now arriving should go to Metal. Anything taken is cancelled so vanilla does not also submit it to the hidden GL context; anything declined falls through untouched.

This costs nothing in the terms that matter: the "current layer" is a plain field on the render thread (no locking), and the vertices are copied into the existing per-frame bump-allocated dynamic arena rather than allocating. Adding a future pass means classifying one more layer, not a new interception.

Cancelling a draw means inheriting vanilla's buffer lifecycle, which is the sharp edge of this hook. Three things about it are non-obvious and each one has already cost a bug:

Cancelling requires releasing the buffer yourself

drawWithGlobalProgram → drawWithGlobalProgramInternal → upload() releases the BuiltBuffer on every branch — directly when empty, otherwise inside VertexBuffer.upload's finally block. BuiltBuffer.release decrements BufferBuilder.builtBufferCount and only calls clear()/reset() once it reaches zero. Skip a single release and that count never returns to zero, so elementOffset and batchOffset advance for the rest of the session until the builder's absolute write cursor runs off the end of its own ByteBuffer: IndexOutOfBoundsException in putFloat. BufferRendererMixin therefore calls buffer.release() before ci.cancel(). Capture is synchronous — the vertices are already in the Metal arena — so the ordering is safe.

Capture is fenced to the 3D world pass, not to "frame active"

The Metal frame stays open across the whole 2D phase so the HUD can composite into it, so isFrameActive() says nothing about which pass is running. MetalWorldRenderer.isWorldPassActive() brackets WorldRenderer.render specifically, and capture is gated on that. The 2D phase submits plenty of immediate geometry on the very same entity_* layers — every 3D block item in the hotbar, inventory and creative menus. Capturing those routes them into the 3D pass, where they are depth-tested against terrain and then painted over by the GUI composite: the items simply vanish. Declined, they take vanilla's GL path into the shared GUI surface, which is where 2D geometry belongs.

Immediate geometry uses a different matrix than terrain

This is the single easiest thing to get wrong here. Terrain and immediate-mode geometry live in different spaces:

vertices are in transform applied
Chunk terrain camera-relative world space projection × MatrixStack.peek() (+ per-chunk offset)
Immediate (entities, outline, crumbling) already fully transformed — the VertexConsumer bakes the world MatrixStack into each vertex as it is built vanilla's global RenderSystem matrices only

drawWithGlobalProgramInternal is literally vb.draw(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix(), …), so reusing the terrain view-projection here applies the camera rotation a second time — entities render skewed, as if viewed off-axis. Each immediate draw therefore carries its own MVP, computed from the same globals vanilla is about to use, in a dedicated uniform slot (vertex buffer index 3). The separate slot is deliberate: vanilla draws translucent terrain after entities, so sharing the terrain's slot would corrupt it mid-frame. Crumbling gets its own vertex function for the same reason — the chunk one reads the terrain slot.

Layers are classified by RenderPhase.name ("lines", "crumbling", "entity_solid", …), cached per layer instance in an IdentityHashMap: vanilla memoizes a distinct RenderLayer per entity texture, so there is no singleton to compare by reference, but the name only has to be inspected once per layer.

pass layer format pipeline
Block outline lines LINES (20B) screen-space ribbon, alpha blend
Crumbling crumbling chunk (32B) multiply blend (DstColor, SrcColor), 0.1 discard
Entities entity_solid, entity_cutout*, entity_translucent* entity (36B) alpha blend, 0.1 cutout discard
Eyes eyes entity (36B) additive (One, One), no depth write
Text text, text_intensity, *_polygon_offset, *_see_through text (28B) alpha blend, 0.1 discard

lines is not line primitives

The single most misleading name in the render stack. VertexFormat.DrawMode.LINES is GL_TRIANGLES with a 4-vertices-to-6-indices expansion, and BufferBuilder.next() duplicates every vertex when the draw mode is LINES/LINE_STRIP — so one edge arrives as start, start, end, end. rendertype_lines then builds a screen-space ribbon from each group, offsetting by ±half the line width perpendicular to the segment and picking the side by vertex-id parity.

Drawing that buffer as MTLPrimitiveTypeLine produces zero-length degenerate lines between the duplicate pairs, and nothing rasterizes at all. That, not z-fighting, is why the block outline was invisible; a depth bias would not have helped. The Metal shader now reproduces the expansion step for step, which also means the outline finally has vanilla's thickness rather than being 1px.

Two details matter for correctness:

  • The index pattern is 0,1,2, 3,2,1, not the quad buffer's 0,1,2, 2,3,0. The four corners are start+, start-, end+, end-, so the shared edge has to be the 1–2 diagonal. The quad pattern's shared 0–2 edge is a side of the ribbon, and its two triangles overlap and leave a notch uncovered. atlas_test asserts on a pixel inside that notch.
  • The two matrices cannot be premultiplied. Vanilla applies its shrink between them (ProjMat * VIEW_SCALE * ModelViewMat), and that shrink is what lifts the outline off the block face it traces, so LineUniforms carries model-view and projection separately.

The first-person hand needs the mid-frame depth clear

GameRenderer.renderWorld calls RenderSystem.clear(GL_DEPTH_BUFFER_BIT) immediately before renderHand — the hand is drawn at point-blank range with a fresh projection and would otherwise be depth-culled by the world it is held in front of. (The clear is in renderWorld, not in renderHand.)

Metal can only clear an attachment at load time, so mirroring it means ending the encoder and starting another over the same drawable with colour Load and depth Clear. On a TBDR GPU that is a real tile flush, which is why it is driven by one explicit redirect at that known seam rather than by tracking GL clear state. The new encoder starts blank, so winding, cull, the frame uniform block and every cached binding are re-established afterwards.

The hand also needs the capture fence widened: it is drawn from renderWorld after WorldRenderer.render returns, so handPass brackets it alongside worldPass.

Entity layers are an allowlist, not an entity_ prefix test: the glint, decal, shadow and outline layers depend on blend/depth tricks this pipeline does not reproduce, and drawing them with straight alpha would look worse than leaving them on the (invisible) GL path.

Read vanilla's shader before porting a layer. The .fsh/.vsh/.json files in assets/minecraft/shaders/core/ are the ground truth for what each layer does, and three of these passes were wrong in ways only the source made obvious:

  • rendertype_crumbling.fsh discards below alpha 0.1. Without it the transparent parts of destroy_stage_N still run through the multiply blend, and since those texels are near-white the block is doubled toward white rather than darkened by the cracks. Its .json also declares only Sampler0, and its vertex shader passes Color straight through — so crumbling must not apply the lightmap either, or the already-lit block underneath gets lit twice.
  • rendertype_eyes applies no lightmap and no discard: the whole point is that eyes glow at full brightness in the dark.
  • rendertype_text_intensity samples .rrrr, not .rgba: those font pages store coverage in red alone, so reading rgba gives black text with no alpha and nothing survives the discard.

bindLayer restores what the immediate passes dirty

Vanilla runs entities between the cutout and translucent terrain layers, so terrain state has to survive an immediate pass. Two pieces of encoder state are otherwise established only once per frame and are exactly what the immediate binds overwrite:

state normally set overwritten by
cull mode MetalContext::beginFrame, when the encoder is created bindEntity/bindCrumbling/bindLines → MTLCullModeNone
fragment texture 0 bindFrameResources, once per frame mtlmc_draw_textured, with the mirrored entity texture

Left alone, the translucent pass inherits both and water draws its back faces while sampling a mob skin — the symptom is water going transparent up close and black at distance, varying with view angle. bindLayer therefore re-establishes cull mode and the atlas on every layer change (never per chunk draw, so it is free). atlas_test covers this through the rasterizer rather than by inspection, since Metal exposes no encoder-state getters: it dirties the encoder via bindEntity, calls bindLayer, and asserts the quad both samples the atlas and gets culled when wound backwards.

A related robustness note: if a Java render hook throws mid-frame, the native frame is never ended, and an open MTLRenderCommandEncoder that gets deallocated aborts the process ("Command encoder released without endEncoding") — burying the exception that actually caused it. MetalContext::beginFrame detects a still-open encoder and abandons that frame cleanly (end, commit unpresented, return the in-flight permit), so the Java stack trace is what reaches the crash report.

The dynamic texture mirror

Everything outside the stitched block atlas — entity skins, destroy_stage_N, item textures — is an independent GL texture vanilla binds per draw, so immediate-mode passes need a Metal texture matching whatever GL had bound at that moment. TextureMirror resolves it by GL texture id: the id is read once via glGetTexImage (restoring the previous binding), uploaded to a native cache, and thereafter costs a contains check. RenderSystem.getShaderTexture(0) supplies the id, and is valid at the funnel because RenderLayer.startDrawing() has already run.

Eviction is mandatory, not housekeeping. GL recycles texture ids after deletion, so a stale entry would silently serve one texture's pixels for a completely different one. GlStateManagerMixin hooks _deleteTexture / _deleteTextures — the lowest-level primitives, so every path is caught whatever triggered it. The cache also tracks its byte total, and the F3 overlay reports the mirrored-texture count.

Known limits: a texture is mirrored once, so if vanilla re-uploads pixels into an existing id (an animated entity texture, or a skin arriving after a placeholder) the mirror goes stale until that id is deleted; the entity vertex format's overlay pair (hurt flash) is carried through but not sampled.

Caveat on lines: Metal has no line width, so these are true 1px primitives — vanilla expands each segment into a screen-space quad in rendertype_lines using the Normal attribute and a LineWidth uniform. The topology is identical (consecutive vertex pairs); only thickness differs.

Chunk upload edge cases

VertexBuffer.upload is fed three different shapes of buffer during chunk streaming, and the FFM boundary throws (or reads out of bounds) rather than tolerating the odd ones, so each is classified explicitly:

Case Signal Handling
Translucency re-sort DrawParameters.indexOnly() Keep the existing mesh. getVertexBuffer() returns null by contract here (if (parameters.indexOnly()) return null) — feeding that to MemorySegment.ofBuffer is an NPE.
Section rebuilt to all air vertexCount() == 0 Release the mesh and clear the handle, so no stale geometry stays allocated or drawable.
Normal rebuild otherwise Mirror into a fresh Metal mesh and swap.

uploadMesh additionally rejects a null, zero-capacity, or truncated buffer before touching MemorySegment, so a modded chunk pipeline cannot crash the bridge. The animated-sprite mirror likewise bounds-checks its source rectangle against the sprite sheet before handing a raw pointer to native.

Note: because Metal draws with its own shared quad index buffer, a translucency re-sort's new index order is not reflected — translucent sorting artifacts are a known gap (roadmap).

Threading: chunk uploads look asynchronous (CompletableFuture$AsyncRun in stack traces) but ChunkBuilder.scheduleUpload queues into uploadQueue, which ChunkBuilder.upload() drains on the render thread. The native layer's single-threaded, lock-free contract therefore holds.

GUI / HUD compositing (Strategy A: shared IOSurface)

The HUD, chat, inventory, and menus render through GL, which the CAMetalLayer would otherwise hide. They are composited back on top of the Metal terrain via a zero-copy shared-memory bridge:

 GameRenderer.render HEAD  ── onGameRenderStart (the only between-frames seam)
   │  init / resize / atlas flush / GUI ring (re)configure
   │  mtlmc_gui_configure(w,h) → ring of N IOSurfaces + MTLTextures
   │    Java aliases each IOSurfaceRef to a GL_TEXTURE_RECTANGLE via
   │    CGLTexImageIOSurface2D and wraps it in a GL FBO (+depth renderbuffer)
   │  if no world: open a bare Metal frame (so menus still composite)
   ▼
 renderWorld → WorldRenderer.render  ── Metal terrain pass opens, draws, stays open
   ▼
 InGameHud.render / Screen.render HEAD  ── GuiCompositor.beginCaptureIfNeeded:
   │  bind GL FBO[frameIndex], clear to (0,0,0,0) once/frame; vanilla 2D draws
   │  land in the shared surface (GL writes the same DRAM Metal will sample)
   ▼
 GameRenderer.render RETURN  ── finishFrame:
   │  glFlush (publish GL writes) → mtlmc_composite_gui:
   │    full-screen triangle, alpha blend (srcAlpha, oneMinusSrcAlpha),
   │    depth Always/no-write, drawn as the LAST draw of the terrain encoder
   │    (stays in tile memory — no Load pass, no bandwidth on TBDR)
   │  mtlmc_end_frame → present

Key properties:

  • Ring of kMaxFramesInFlight IOSurfaces. GL writes surface[i] while Metal may still sample surface[i-1] from an in-flight frame — no cross-frame read/write hazard, so triple buffering and frame pacing are preserved. The frame semaphore is still the only CPU/GPU sync point; mtlmc_gui_configure is the only new GPU drain and it runs only on resize.
  • Composite in the terrain encoder, not a second render pass. A loadAction = Load pass would force a tile reload; issuing the GUI draw at the end of the existing pass keeps the color attachment in tile memory (free on Apple TBDR).
  • GL_TEXTURE_RECTANGLE is required by CGLTexImageIOSurface2D; Metal samples the same IOSurface as an ordinary 2D texture. The composite shader flips V to reconcile GL's bottom-left origin with Metal's top-left.
  • The IOSurface→GL alias is done natively. Minecraft's bundled LWJGL (3.3.2) binds CGLGetCurrentContext but not CGLTexImageIOSurface2D, so Java generates and binds the GL_TEXTURE_RECTANGLE and then calls mtlmc_gui_bind_gl_texture, which performs the alias on the render thread's current CGL context (-framework OpenGL). This was found by building, not assumed.
  • Capture starts at the 2D phase boundary, not at individual draw sites. GameRendererMixin binds and clears the surface immediately after GameRenderer.render constructs its DrawContext, which precedes every 2D draw site in that method — the nausea overlay, InGameHud.render, Overlay.render (the loading screen), Screen.renderWithTooltip and ToastManager.draw. Hooking those individually is a trap: the capture used to begin at Screen.render, but TitleScreen overrides render and draws the panorama, logo, splash and copyright before delegating to super.render, so all of it went to the hidden GL framebuffer and only the widgets survived. InGameHudMixin and ScreenMixin remain as defensive re-binds (the latter on renderWithTooltip, which is final and therefore cannot be pre-empted by a subclass); the per-frame guard keeps them idempotent so they never clear away what was already drawn.

DEBUG_GUI_COLOR_TINT=1 (macro in PipelineManager.mm) washes the overlay faint green and forces a minimum alpha so the quad's extent and alignment are visible even where the HUD is transparent — isolates compositing/scale bugs from GL capture bugs.

Current status & known limitations

The whole visible frame is Metal: terrain, entities, block entities, the held item, sky, clouds, particles, weather and the GUI. The honest gaps, as a user would hit them:

  • renderStage and .csh compute passes are unimplemented. Both are inert for Complementary (gated behind IS_IRIS / COLORED_LIGHTING_INTERNAL), so nothing is visibly missing there today — but packs that do use them will shade wrongly rather than partially.
  • 13 Iris uniforms the pack declares are still unfed and shade as zero. The count is logged at load; the names come out of mtlmc_shaders_runtime_unfed.
  • Non-en_US pack lang files are ignored.
  • The settings screen's own rendering is not automatically tested. The model behind it is (28 suites), but a human has to look at the pixels.

Why each of those is open, what it would take to close, and where it sits relative to everything else is tracked on the roadmap board — the first four under #9. This list stays deliberately short so the board remains the single place plans are updated.

  • Block atlas is mirrored into Metal with GPU-generated mips: at reload end, SpriteAtlasTextureMixin flags the composed GL atlas, and the next frame boundary reads it back (glGetTexImage into an off-heap MemorySegment) and hands it to mtlmc_upload_atlas. Since 1.19.3 the atlas never exists as one CPU-side NativeImage — sprites upload their regions separately — so GL readback is the version-stable capture point.
  • The lightmap is mirrored every frame from LightmapTextureManager's 16×16 NativeImage, straight off its pointer — no GL readback, no staging, 1 KiB per frame. The shaders read it exactly as vanilla's do, texelFetch(Sampler2, UV2 / 16, 0), bound to the vertex stage at texture index 1. See below for why approximating it is not survivable.

The lightmap is not optional, and the failure mode is not "slightly wrong light"

The packed light in each vertex is (block << 4, sky << 4). It is tempting to derive brightness from it directly — max(block, sky) / 240 looks reasonable. It is not: the sky-light value stays at 15 outdoors all night. Nothing about the geometry changes at dusk. The 16×16 lightmap texture, which vanilla rebuilds every frame from time of day, weather, dimension, night vision and torch flicker, is the only thing that darkens the world.

So the approximation does not produce "slightly off" lighting — it pins the entire world at noon forever, and that hid a bug that looked nothing like a lighting bug. The Enderman's eyes are an emissive overlay that adds purple on top of the base skin, and the base skin's texels underneath the eyes are pure white (verified by decoding enderman.png: (255,255,255) at exactly the six texels enderman_eyes.png covers). Additive blending onto saturated white is a no-op, so the eyes could never appear. Vanilla escapes it because the lightmap darkens the face first, letting the additive purple dominate.

Every link in that chain was individually correct — layer classification, texture mirroring (byte-for-byte: the palettised 2-bit PNG expands to exactly 22 non-zero RGBA bytes, which is what the client reported), the additive pipeline, and the depth test against coincident body geometry. The bug was two passes away from the symptom.

Why cutout samples the atlas without mipmaps

Vanilla keeps two atlas render phases (verified in RenderLayer's <clinit>):

MIPMAP_BLOCK_ATLAS_TEXTURE = Texture(atlas, blur=false, mipmap=true)
BLOCK_ATLAS_TEXTURE        = Texture(atlas, blur=false, mipmap=false)
layer phase
solid, cutout_mipped, translucent, tripwire mipmapped
cutout (cross models: short grass, flowers, saplings) not mipmapped

That asymmetry is deliberate. Minifying a cutout sprite blends its edge texels with the fully transparent ones surrounding it; wherever the blended alpha still clears the 0.1 discard threshold, a darkened texel survives — so grass fringes black at distance. Vanilla avoids it by never sampling a mip on that layer.

The renderer therefore keeps two samplers (both Nearest min/mag, so texels are never blended within a level) differing only in mip filter, and bindLayer selects per layer. This is why mirroring vanilla's mip chain did not fix the fringe on its own: on this layer vanilla does not sample those mips at all.

Why the mip chain is mirrored, not generated

Every mip level is read back from vanilla's GL atlas and written into the Metal texture, rather than kept from Metal's generateMipmapsForTexture. That matters for correctness, not just fidelity:

  • Vanilla builds mips with MipmapHelper, which weights RGB by alpha (and averages in linear space), so fully transparent texels never drag colour toward black.
  • generateMipmapsForTexture is a plain box filter. Transparent atlas texels have RGB (0,0,0), so it averages black straight into the edges.

On cutout sprites like short grass that darkens the edge texels, and viewing them at an angle selects exactly those lower mips — producing a faint black fringe wherever the blended alpha still clears the 0.1 discard threshold. The discard itself was never the problem: chunk_fragment has always discarded below alphaCutoff, which is 0.1 for cutout/cutout_mipped/tripwire, matching vanilla's rendertype_cutout.fsh and applied to texel × vertexColor the same way.

The GPU-generated chain is still produced by mtlmc_upload_atlas and left in place as a seed, so a level that fails to read back retains usable data. (The animated-sprite path already mirrored vanilla's per-level images, so it was correct from the start — only the initial capture was generating its own.)

Animated textures (water, lava, fire, …)

Vanilla ticks animated block sprites once per client tick, uploading the current frame into a sub-region of the GL atlas. Those updates are mirrored into the Metal atlas so animations play:

  • SpriteAtlasTextureMixin brackets tickAnimatedSprites() and flags the block atlas; SpriteContentsMixin injects the tail of upload(int x, int y, int frameX, int frameY, NativeImage[] images) and, for each mip level i, mirrors images[i]'s (frameX>>i, frameY>>i) region into the Metal atlas at (x>>i, y>>i) — byte-for-byte the same mapping vanilla feeds NativeImage.upload (verified from bytecode).
  • The read is zero-copy and strided: NativeImageAccessor exposes the NativeImage's off-heap pointer, and mtlmc_update_atlas_region does a replaceRegion:…bytesPerRow: straight from a sub-rectangle of the sprite sheet into the shared-storage Metal atlas — no per-pixel reads, no staging.
  • All mip levels are updated, so distant animated blocks stay consistent.
  • Scoped to the block atlas via the tick bracket, so initial stitch and other atlases (which are captured wholesale) are ignored.

Tradeoff: the update writes into the same atlas an in-flight GPU frame may be sampling (shared storage), so a torn sprite is theoretically possible for one frame. It is imperceptible at 20 Hz animation vs 60+ Hz render and avoids a per-tick GPU drain; the alternative (an in-frame blit from a staging ring) is noted for later hardening.

Guarding the GUI surface's alpha channel

Compositing only works if the HUD surface's alpha means "how much of this pixel is GUI". Vanilla never has to care — it renders into an opaque framebuffer — so several draws treat the alpha channel as scratch space. Two defences:

  1. The clear must actually reach alpha. glClear is gated by the colour mask, the depth mask and the scissor test, and MC's Framebuffer.drawInternal runs _colorMask(true, true, true, false) every frame. GuiCompositor therefore forces all three open before clearing, via GlStateManager so MC's state cache agrees with the driver (clearing behind the cache also makes MC skip its own later _clearColor and inherit ours).
  2. Full-screen overlays must not rewrite alpha. InGameHud.renderVignetteOverlay draws full-screen with blendFuncSeparate(ZERO, ONE_MINUS_SRC_COLOR, ONE, ZERO) — the alpha half is dst_a = src_a, and vignette.png is opaque, so it stamps alpha 1 over the whole surface and turns the HUD layer into an opaque black sheet. InGameHudMixin masks alpha writes for the duration, keeping the RGB darkening and leaving alpha alone.

renderCrosshair uses the same (ONE, ZERO) alpha pattern but is a few pixels wide, and should end up opaque, so it is deliberately left alone.

Consequence of (2): the vignette no longer tints the 3D world, since a screen-space multiply in the GUI layer cannot reach the separate Metal layer. Applying it during the Metal composite is the correct fix (roadmap).

  • Mapping pins — audited against the Yarn 1.20.4+build.3 jar via javap, not guessed. Verified descriptors: WorldRenderer.render(MatrixStack;FJZCamera;GameRenderer;LightmapTextureManager;Matrix4f)V (one Matrix4f = projection; model-view from the MatrixStack), renderLayer(RenderLayer;MatrixStack;DDD Matrix4f)V, GlUniform.set(FFF)V (2 call sites in renderLayer, both chunkOffset), VertexBuffer.upload(BuiltBuffer)V/draw()V/close()V, SpriteAtlasTexture.upload(SpriteLoader$StitchResult)V/getId()V/tickAnimatedSprites()V, SpriteContents.upload(IIII[NativeImage)V, NativeImage.pointer (long), GameRenderer.render(FJZ)V + client field, InGameHud.render(DrawContext;F)V, Screen.render(DrawContext;IIF)V, BuiltBuffer.getParameters()/getVertexBuffer(), DrawParameters.format()/mode()/vertexCount()/indexCount(). After a build, every one of these is confirmed remapped to its intermediary name in the jar (e.g. render→method_22710, NativeImage.pointer→field_4988), which is the proof they resolve — an unresolved ref would remain a literal Yarn string. defaultRequire: 1 still fails loudly at launch on any future drift.
  • The whole project compiles with ./gradlew build (Gradle 9.6.1 / Loom 1.17.16 / auto-provisioned JDK 22). The WorldRenderer.render crash (InvalidInjectionException — missing MatrixStack param, extra Matrix4f) is fixed. Mixin application still isn't exercised against a live client here (no display), but every target is descriptor-verified and confirmed remapped.
  • GUI compositing — still-unexercised runtime bits: a GL 3.2 core context accepts GL_TEXTURE_RECTANGLE IOSurface attachments, and the GL→Metal ordering holds with a single glFlush before the Metal commit. The V-flip in gui_vertex is validated by an X-split in the GPU test (flip-agnostic); its up/down correctness only shows against real GL output. Semi-transparent HUD edges (text AA) may show a faint halo because the composite uses straight srcAlpha rather than premultiplied alpha — the refinement is per-draw blend control on the GL side. (The earlier worry that LWJGL exposes CGLTexImageIOSurface2D proved false — it does not — so that call is now native; see the compositing section.)
  • Mixin compatibilityLevel JAVA_21 with Java 22 bytecode relies on Fabric's sponge-mixin fork (loader ≥0.15.10) accepting class version 66.
  • Double vsync: both the CAMetalLayer (displaySyncEnabled) and the invisible GL swap throttle. If pacing stutters, disable vsync in-game or set displaySyncEnabled = NO and let GL pace.
  • Sodium replaces the vanilla chunk pipeline entirely; this foundation hooks vanilla. A Sodium backend would target ChunkShaderInterface/render lists instead.

Optimizations, and how each was achieved

Every number here was measured on this machine (M4, 1708×960 unless stated), not estimated. Where a figure is a range it is because it genuinely varies.

1. Zero-copy vertex upload (UMA)

What. One memcpy on the entire Java→GPU path, and no staging buffer.

How. MTLResourceStorageModeShared means CPU and GPU address the same DRAM on Apple Silicon, so MTLBuffer.contents handed back to Java as a MemorySegment is the GPU-visible allocation. MemorySegment.copy out of vanilla's BufferBuilder is the upload — there is no second step. CPUCacheModeWriteCombined keeps those streaming writes out of the cache the CPU never reads back.

Cost avoided. The GL path copied Java → GL driver staging → VRAM, and on macOS also crossed the GL translation layer per draw.

2. GPU-driven terrain: compute cull + indirect command buffers

What. The CPU no longer walks the visible-chunk list to encode draws. A compute kernel frustum-culls the section registry and writes an MTLIndirectCommandBuffer the GPU then executes.

How. Every uploaded chunk section registers its bounds and mesh handle in a GPU-resident registry. Per frame one kernel dispatch tests each section against the frustum planes and, for survivors, encodes drawIndexedPrimitives directly into the ICB. The render thread encodes one executeCommandsInBuffer.

Verified by gpu_terrain_test, which asserts the kernel-encoded output is byte-identical to the CPU-encoded path — the only way to be sure a reordering optimization is not quietly dropping geometry.

3. Mesh arena with shared slabs

What. Chunk meshes are suballocated from a few large MTLBuffer slabs instead of one buffer per section.

How. A free-list allocator hands out byte ranges; a mesh handle is (slab, offset, length). Section churn recycles ranges without ever asking Metal for a new allocation, which matters because newBuffer is a kernel round trip and Minecraft rebuilds sections constantly.

Why it also enables the ICB. Draws from one slab share a vertex buffer bind, so the indirect path only varies the offsets — the reason a GPU-encoded draw can be expressed at all.

4. Sun shadows without a CPU pass

What. Real-time sun shadows whose casters are selected on the GPU.

How. The same cull kernel runs a second time against the light frustum and encodes a depth-only ICB; the shadow map is rendered in one pass with no fragment shader bound. Receivers sample it in the terrain fragment shader.

Bias. Normal-offset rather than constant or slope-scaled depth bias: the receiver is displaced along its normal by a distance scaled to the shadow-map texel footprint. Constant bias produced either acne at 1024 or peter-panning at 4096, and no single constant worked across the resolution range the menu offers.

Measured. 16384 / 16384 shadow texels covered in daylight; correctly falls to 0 near the horizon, because ShadowMatrices fades the light frustum out as the sun sets — skipping the pass instead would leave stale daylight shadows.

5. One render pass for all world geometry (union pass)

What. With a shader pack loaded, all 21 gbuffers programs draw into a single render pass.

How. The pass's colour attachments are the union of every program's declared DRAWBUFFERS targets. Each program's fragment outputs are remapped at translation time into that union layout, and attachments a program does not write are masked off — which is what preserves the other programs' g-buffer data underneath.

Cost avoided. The obvious implementation is one pass per program, which on a tile-based GPU means storing and reloading the whole g-buffer 21 times per frame. This keeps it resident in tile memory.

6. Parallel shader transpilation

What. Pack load time 31.3 s → ~11.5 s, and since then to ~6.3 s cold / ~3.1 s warm (#20) once the patcher's output was cached too — see below for why that mattered so much more than caching the transpiler.

How. Translating a program (patch → glslang → SPIR-V → SPIRV-Cross → MSL) is a pure function of that program's source, so the 21 gbuffers programs and the composite chain are translated under dispatch_apply(DISPATCH_APPLY_AUTO, …) and merged serially. glslang is safe here because InitializeProcess sits behind std::call_once and every thread builds its own TShader/TProgram.

What stayed serial. Include resolution and preprocessing, because they scrape the pack's const settings and live DRAWBUFFERS into shared state.

Where the time actually goes. Measured against Complementary Unbound r5, timing the patcher and the transpiler separately (#14). Per-job CPU time across the 17 geometry programs:

patch glslang + SPIRV-Cross
cold 17 026 ms 341 ms
warm 16 828 ms 20 ms

Translation is roughly 2 % of the phase that used to be reported as "translate" — the patcher's regex work over megabyte sources is essentially all of it. (Those are CPU times summed over concurrent jobs, so they do not add up to the ~2.2 s wall the phase takes; the parallelism is about 7.7×.)

Metal pipeline compilation was 3.3 s on a cold load and then ~5 ms forever after, because macOS caches it independently of anything here.

Both caches, in series. The translation cache keys on the patcher's OUTPUT, so the patcher had to run to produce the key — which is why caching translation alone only ever recovered ~1 s. patchStepOne now carries its own cache keyed on its input, and the two compose:

translate (wall) patch (CPU) glslang (CPU) total load
cold 1 926 ms 14 523 ms 341 ms 6 251 ms
warm 4 ms 24 ms 11 ms 3 085 ms

What remains on a warm load is include resolution, ~2.3 s of the 3.1 s — now the largest single item, and cacheable by the same argument if anyone wants it.

Note also that load time on this machine drifts +47 % across six consecutive runs from thermal and background load, so load-time claims have to come from paired or interleaved runs, never a sequential A-then-B.

7. Frame pacing and metrics

What. Three frames in flight, one semaphore, no per-buffer fences.

How. A single dispatch_semaphore gates beginFrame; the command buffer's completion handler signals it. Because the wait is isolated, the F3 overlay can report wait separately from CPU — wait > CPU is a direct GPU-bound signal without a trace.

8. GUI compositing through a shared IOSurface

What. The HUD is drawn by vanilla into GL and composited in Metal with no readback.

How. A ring of IOSurfaces is imported as MTLTexture on the Metal side and bound as an FBO colour attachment on the GL side. The same pages back both, so "transferring" the HUD is a texture bind.

9. Honouring the pack's host-draw switches

What. clouds=off, underwaterOverlay=false, vignette=false are obeyed.

Why it is an optimization as well as a fix. A suppressed program is never resolved, so it is never transpiled either. Ignoring clouds=off also cost correctness: vanilla's cloud plane went through the pack's gbuffers_clouds and landed in colortex0 as a hard-edged black slab.

Measured. Pure-black pixels in the frame: 6.52 % → 0.03 %.

10. MetalFX spatial upscaling

What. Render below native resolution and upscale on the GPU.

How. MTLFXSpatialScaler between the world pass and present. Temporal upscaling would be better but needs motion vectors the g-buffer does not carry — see the roadmap.

Shader packs (Iris / OptiFine)

A from-scratch implementation of the format, targeting Metal rather than GL.

The translation chain

pack GLSL 130 (+ #include, OptiFine extensions)
   │  resolveIncludes        — include closure, pack-relative
   │  applyPackOptions       — the user's settings baked in
   │  patchStepOne           — ftransform(), gl_* compat, DRAWBUFFERS remap,
   │                           attribute rewrites, alpha-test injection
   ▼  glslang                — GLSL → SPIR-V
   ▼  SPIRV-Cross CompilerMSL — SPIR-V → Metal Shading Language
   ▼  newLibraryWithSource   — MSL → MTLLibrary → MTLRenderPipelineState

Both dylibs are built from one header (ShaderPackHook.h) and talk through a plain C function-pointer table. That is deliberate: glslang and SPIRV-Cross live in the optional libmetalmc-shaders.dylib, so a missing transpiler makes shader packs unavailable without stopping the renderer from loading.

Frame structure with a pack loaded

shadow pass          the pack's shadow program, depth-only
   ▼
union world pass     all 21 gbuffers programs, one pass, union attachments
   ▼
deferred1            reads the g-buffer
   ▼
composite … composite7   ping-ponging over the colortex ring
   ▼
final                → the drawable

Things that were not obvious

  • The colortex ring is stored GL-side-up. Pack programs rasterize with clip Y negated, so texture row 0 is the screen bottom. Forgetting this made a depth probe read the ground and "confirm" a bug that did not exist.
  • Negating Y reverses apparent winding. The world pass therefore sets MTLWindingClockwise; leaving it CCW culls exactly the geometry that should be drawn, with no error anywhere.
  • An encoder crossing the C ABI as a bare void* carries no ownership. ARC destroys it before the caller uses it and the process aborts with "Command encoder released without endEncoding" — which looks like a product crash, not a lifetime bug. Passes hold a strong reference for the pass's lifetime.
  • gl_MultiTexCoord1 is the lightmap in raw vanilla units — the packed pair (block << 4, sky << 4), 0..240 — while the legacy texcoord is 0..1. The /256 is the normalization vanilla performs with gl_TextureMatrix[1]. Missing it makes every block near a light source blow out.
  • mc_Entity is not in the vertex stream. Block ids have to be captured while the chunk is being built, by bracketing BlockRenderManager.renderBlock and renderFluid — fluids never touch BlockModelRenderer, and water is exactly what block.32000 names.
  • BlockRenderManager is a singleton shared by every chunk worker. Per-call state in mixin instance fields raced into a hard crash from a worker thread. The bracket is thread-confined.

Pack settings

The pack declares its own settings as annotated defines (#define NIGHT_STAR_AMOUNT 2 //[0 1 2 3 4]), lays its menu out in shaders.properties screen.*, and names everything in lang/*.lang. MetalMC parses all three and renders the pack's own layout — for Complementary that is 405 options across 51 screens with 160 sliders.

Changing a setting rewrites the GLSL and reloads the pack, because that is how the format works; Iris pays the same cost. The screen therefore applies once on leaving, not per click.

Values are kept as text end to end. A pack's value list mixes 1.00, -96 and 99999.0; the value is substituted back into GLSL verbatim and the lang key is the exact spelling, so a round trip through a double would rewrite 1.00 to 1 and break both the shader and its label.

Coordinate-space conventions (GPU-probed, not assumed)

The usual "OpenGL → Metal" folklore (flip Y, invert winding) is wrong for this renderer, and applying it breaks things. Both facts below are verified by probes in native/test/atlas_test.mm that render to an offscreen target and read the pixels back, so they can be re-checked on any machine:

Question Probe result Consequence
Where does NDC y=+1 land? memory row 0 (image top) — same as GL No Y-flip in the projection. Adding one renders the world upside down.
Is a CCW (y-up NDC) triangle front-facing? yes, under MTLWindingCounterClockwise — same as GL Keep GL's winding. Inverting it culls all terrain.

Only the Z range actually differs (GL [-1,1] vs Metal [0,1]), handled once in MetalContext::beginFrame via z' = 0.5z + 0.5w.

The GUI composite likewise needs no V-flip: its uv is derived from the y-up clip position, which already reconciles the origins — screen bottom = NDC y=-1 → uv.y=0 → surface memory row 0, and GL renders bottom-up so row 0 is GL's bottom. The classic V-flip applies when uv comes from a top-left-origin screen coordinate, which is not the case here.

Metrics (F3 overlay)

Two lines are appended to the right-hand F3 column:

[MetalMC] FPS: 240 | CPU: 0.42ms | GPU: 3.10ms | VRAM: 412MB
[MetalMC] wait: 4.85ms (GPU-bound) | frames: 51234
Metric Source
CPU ms std::chrono::steady_clock around encode → commit, excluding the semaphore wait
GPU ms MTLCommandBuffer.GPUEndTime − GPUStartTime, read in the completion handler
wait ms time blocked on the in-flight frame semaphore
VRAM MTLDevice.currentAllocatedSize

Separating wait from CPU is the point of the split: the render thread blocking on the frame semaphore means it is waiting on the GPU, so wait > CPU is the clearest GPU-bound signal available without a full trace — the overlay labels it directly. A high CPU figure with near-zero wait means the opposite: encoding is the bottleneck.

Implementation notes:

  • FrameMetrics (native/src/FrameMetrics.h) is deliberately free of any Metal/Objective-C dependency, so its smoothing and export contract are unit-tested headlessly (undersized/null buffers, first-sample seeding, convergence, NaN rejection, reset).
  • The GPU sample arrives on an arbitrary thread (Metal chooses the completion handler's thread), so every field is std::atomic with relaxed ordering — these are advisory counters, never used to make rendering decisions.
  • Values are exponentially smoothed (α = 0.1) so the overlay is readable, but the first sample seeds the average exactly rather than ramping from zero.
  • mtlmc_get_render_metrics is pure atomic loads (no Objective-C, no pool), and the Java side reuses one global-arena buffer, so polling per frame allocates nothing.

Diagnostics

  • -Dmetalmc.debug=true — logs a terrain pipeline summary every 300 frames: uploads seen / how many matched the block vertex format, meshes created, draws issued, and why draws were skipped (skipNoMesh / skipNoLayer), plus the last chunk offset and last rejected vertex format. The single most useful signal: draws=0 means the break is upstream (capture, format, or layer classification); draws>0 with a blank screen means it is downstream (matrices, culling, depth, or compositing).
  • -Dmetalmc.gui.disable=true — skips HUD capture/compositing entirely, leaving a terrain-only frame. Isolates "the GUI layer covers the 3D scene" from "the 3D scene never drew".
  • The same stats line reports guiCorner=0xAARRGGBB — the HUD surface's texel at (2,2), a spot nothing draws on. Corner alpha 00 means the transparent clear survived; FF means something is still stamping alpha over the whole surface (look for another full-screen draw with an alpha-writing blend).
  • DEBUG_TEXTURE_CHECKERBOARD / DEBUG_GUI_COLOR_TINT — native macros in PipelineManager.mm (see Testing).
  • METALMC_VERIFY_PACK_STATE=1 — switches off the sticky-state memo in packBind (the mirror's bookkeeping is kept, every value is re-fed), giving a one-relaunch A/B for an optimisation that shades wrongly rather than failing when it is stale. Driven by tools/pack_state_ab/, which also supplies a world exercising all five terrain layers — MetricsWorld has no water or tripwire, so gbuffers_water never binds there.
  • METALMC_LOG_RENDER_STAGE=1 — reports each distinct (program, stage) pair once. A wrong stage is invisible otherwise: the pack branches confidently and incorrectly rather than erroring.
  • METALMC_PROFILE_PACK_TERRAIN=1 — per-draw phase timing of the pack-routed terrain path. The phase split is an attribution hint (each phase is smaller than the clock reads that measure it); the medians are what to compare, and they resolve differences the live frame time cannot.

Testing

native/test/run_tests.sh builds and runs 28 headless suites (no window, no Minecraft — they link the production classes directly) and exits non-zero on the first failure. They cover, roughly in dependency order:

Suite What it proves
arena_test Mesh-arena suballocation and churn
registry_test GPU section registry lifetimes
atlas_test Atlas upload, mip chain readback, rejection paths
gui_test (×2) IOSurface import and straight-alpha composite, plus the debug tint
gpu_terrain_test Kernel-encoded terrain byte-identical to the CPU path
sort_test Translucency ordering via custom index buffers
upscale_test MetalFX spatial scaler at production shapes
shadow_test Cull → depth ICB → chunk receive, end to end
customuniforms_test shaders.properties expression evaluator
packfeatures_test Host-draw switches and their #if guards
packoptions_test Pack settings: parse, rewrite, menu tree, lang
targets_test / framegraph_test colortex ring, ping-pong, pass schedule
transpiler_test / pipeline_test GLSL → SPIR-V → MSL, in-process
render_pack_test A translated program rendering to a colortex MRT
geometry_test Vanilla vertices bound to a pack's attribute layout
packshadow_test The pack's own shadow program producing a real depth map
worldpass_test The union world pass: all geometry, one pass
framestate_test Java's flat float array → a pack's uniform blocks
packinstall_test Install sequence against the real MetalContext
terrain_gbuffer_test A chunk mesh through the pack's g-buffer
runtime_test / gbuffers_test / uniforms_test / chain_test A loaded pack across the frame lifecycle
gpu_cull_test Compute-encoded ICB + GPU frustum culling
icb_bench Encode cost (informational — asserts nothing)

Several assert against the real shader pack on disk rather than fixtures, so they cannot drift from what the pack actually ships.

gui_test.mm (same harness) validates the compositing path end to end on the GPU: PipelineManager GUI pipeline + sampler, IOSurface creation, zero-copy MTLTexture-from-IOSurface import, and a composite over a terrain-colored target with pixel-exact readback — the transparent HUD region must leave the terrain intact while the opaque region overwrites it. It is built and run twice, once normally and once with -DDEBUG_GUI_COLOR_TINT=1, so the debug toggle is exercised too.

Native-side diagnostics on every atlas upload: dimensions, mip levels, bytes-per-row, total bytes, texture pointer, plus an FNV-1a checksum and non-zero count over the top-left 16×16 region — proof that real pixels crossed the FFM boundary. Setting DEBUG_TEXTURE_CHECKERBOARD=1 (macro in PipelineManager.mm, overridable via -D) freezes a 64×64 magenta/black checkerboard as the atlas and ignores uploads, isolating shader/sampler bugs from Java capture bugs.

Roadmap

Done

Kept here because the README used to promise them, and because each is now a section above: lightmap mirroring, sky/cloud/particle ports, native frustum culling with indirect command buffers, entities and the held item, sun shadows, the MetalFX upscaler, and the whole Iris/OptiFine shader-pack pipeline including its settings menu and the MSL transpile cache (native/src/TranspileCache.h).

Open work

Planned work lives on the MetalMC Roadmap board, not in this file — one place to update, so the two cannot drift apart.

Every item there is a tracked issue with scope, acceptance criteria, dependencies and the traps worth knowing before starting. Beyond status, the board carries two fields:

Field Values
Bucket Now (committed) · Next (planned, roughly 1–3 months) · Later (directional)
Effort S (days) · M (1–2 weeks) · L (3–6 weeks) · XL (multi-month)

Current priority is performance and architecture, and two things about that ordering are worth stating here because they are easy to misread from the board alone:

  • Measurement comes first. Every performance number quoted in this README was taken on the vanilla path, before the shader-pack chain existed. A pack-loaded frame also runs a shadow pass, 21 gbuffers programs and a 9-pass deferred/composite chain, none of which those numbers represent.
  • The remaining shader-pack compatibility items — unfed Iris uniforms, BSL end to end, renderStage, and .csh compute passes — are parked deliberately as a single card rather than four. They are the difference between "works with Complementary" and "works with the ecosystem"; flipping the project's priority should promote that whole card as a unit. Pack profiles were the fifth and are now done.

About

A Metal-backend Fabric mod for Minecraft with Iris/OptiFine shader-pack support

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages