ソースを参照

Initial commit: N64 Node Shader Studio in pure Rust

Vasily 6 日 前
コミット
8a91239edc

+ 3 - 0
.gitignore

@@ -0,0 +1,3 @@
+/target/
+crates/*/target/
+**/*.rs.bk

+ 49 - 0
Cargo.lock

@@ -0,0 +1,49 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "byteorder"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+
+[[package]]
+name = "hash32"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
+dependencies = [
+ "byteorder",
+]
+
+[[package]]
+name = "heapless"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
+dependencies = [
+ "hash32",
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "n64-rom"
+version = "0.1.0"
+dependencies = [
+ "heapless",
+ "shader-core",
+]
+
+[[package]]
+name = "shader-core"
+version = "0.1.0"
+dependencies = [
+ "heapless",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"

+ 11 - 0
Cargo.toml

@@ -0,0 +1,11 @@
+[workspace]
+resolver = "2"
+members = ["crates/shader-core", "crates/n64-rom"]
+default-members = ["crates/shader-core"]
+
+[profile.release]
+opt-level = 3
+lto = true
+codegen-units = 1
+panic = "abort"
+

+ 38 - 0
README.md

@@ -0,0 +1,38 @@
+# N64 Node Shader Studio
+
+A pure `#[no_std]` Rust interactive node-based shader studio for real Nintendo 64 hardware (zero C dependencies), compiling node graphs directly into 64-bit N64 Reality Display Processor (`G_SETCOMBINE`) hardware commands with a live 3D hardware-rasterized preview viewport.
+
+## Workspace Layout
+
+- [`crates/shader-core`](crates/shader-core): Pure `#![no_std]` engine (no `alloc`) containing the zero-heap `NodeGraph`, Graph-to-RDP compiler + software reference evaluator, 6 shader presets, procedural 32×32 RGBA5551 textures, 4 procedural 3D meshes (`Sphere`, `Torus`, `Cube`, `Teapot`), SGI-style split-screen UI + 4×6 bitmap font, and CRC-16 EEPROM graph serializer.
+- [`crates/n64-rom`](crates/n64-rom): Bare-metal `#![no_std]` `#![no_main]` MIPS III (`mips-nintendo64-none`) ROM using VR4300 cache ops, VI (`320×240p` / `640×480i` with Expansion Pak), direct RDP triangle/combiner/TMEM command lists, SI/PIF Joybus Controller + N64 Mouse + 4K/16K EEPROM drivers, and CP0/DPC silicon performance counters.
+
+## Building & Testing
+
+Run host PC unit tests:
+```powershell
+cargo test
+```
+
+Build the bootable `.z64` ROM into `dist/n64-shader-studio.z64` (requires `nightly-2025-01-12` with `rust-src` and `nust64`):
+```powershell
+.\build-rom.ps1
+```
+
+Copy `dist/n64-shader-studio.z64` onto your EverDrive-64 / SummerCart64 SD card and boot on real N64 hardware.
+
+## Controls
+
+| Input | Action |
+| :--- | :--- |
+| **Analog Stick / N64 Mouse** | Move cursor across the Left 65% Node Canvas |
+| **D-Pad** | Snap cursor directly to nearest pin or node title bar (or navigate menus) |
+| **A Button** (or Mouse Left) | Start/complete wire between pins, unplug connected input, drag node title bar, or edit node parameters |
+| **B Button** (or Mouse Right) | Cancel drag, close popup, or unplug hovered input pin |
+| **Z Button** | Open Add-Node menu at cursor |
+| **Z + B** | Delete hovered node (Output node is protected) |
+| **Start** | Open Studio Menu (6 Presets, Auto-Spin, Perf HUD, 320p/480i toggle, EEPROM Save/Load) |
+| **L Button** | Cycle 3D preview mesh (`Sphere`, `Torus`, `Cube`, `Teapot`) |
+| **R Button** | Cycle lighting preset (`Studio`, `Rim`, `Toon`, `Sunset`) |
+| **Z + R** | Toggle wireframe overlay |
+| **C-Buttons** | Orbit 3D preview camera |

+ 32 - 0
build-rom.ps1

@@ -0,0 +1,32 @@
+param(
+    [switch]$SkipTests
+)
+
+$ErrorActionPreference = "Stop"
+$Root = $PSScriptRoot
+
+if (-not $SkipTests) {
+    Write-Host "Running shader-core host unit tests..." -ForegroundColor Cyan
+    cargo test --manifest-path "$Root\Cargo.toml"
+    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+}
+
+Write-Host "Building N64 ROM (mips-nintendo64-none, release)..." -ForegroundColor Cyan
+Push-Location "$Root\crates\n64-rom"
+try {
+    cargo +nightly-2025-01-12 run --release
+    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+} finally {
+    Pop-Location
+}
+
+$SrcRom = "$Root\target\mips-nintendo64-none\release\n64-rom.z64"
+$AltRom = "$Root\crates\n64-rom\target\mips-nintendo64-none\release\n64-rom.z64"
+$BuiltRom = if (Test-Path $SrcRom) { $SrcRom } elseif (Test-Path $AltRom) { $AltRom } else { throw "Could not find generated .z64 ROM!" }
+
+New-Item -ItemType Directory -Force -Path "$Root\dist" | Out-Null
+$DistRom = "$Root\dist\n64-shader-studio.z64"
+Copy-Item -Force $BuiltRom $DistRom
+
+$Size = (Get-Item $DistRom).Length
+Write-Host "Ready for flashcart: $DistRom ($Size bytes)" -ForegroundColor Green

+ 15 - 0
crates/n64-rom/.cargo/config.toml

@@ -0,0 +1,15 @@
+[build]
+target = "mips-nintendo64-none.json"
+
+[unstable]
+build-std = ["core"]
+
+[target."mips-nintendo64-none"]
+rustflags = ["-Clto", "-Cembed-bitcode"]
+
+runner = [
+    "nust64",
+    "--libdragon", "release",
+    "--name", "N64 SHADER STUDIO",
+    "--elf"
+]

+ 10 - 0
crates/n64-rom/Cargo.toml

@@ -0,0 +1,10 @@
+[package]
+name = "n64-rom"
+version = "0.1.0"
+edition = "2021"
+license = "MIT OR Apache-2.0"
+
+[dependencies]
+shader-core = { path = "../shader-core" }
+heapless = "0.8"
+

+ 45 - 0
crates/n64-rom/linker.ld

@@ -0,0 +1,45 @@
+ENTRY(_entrypoint)
+
+SECTIONS {
+    . = 0x80000400;
+    __boot_start = .;
+
+    .boot : {
+        *(.boot)
+        . = ALIGN(16);
+    }
+
+    .text : {
+        *(.text .text.*)
+        . = ALIGN(16);
+    }
+
+    .rodata : {
+        *(.rodata .rodata.*)
+        . = ALIGN(16);
+    }
+
+    .data : {
+        *(.data .data.*)
+        . = ALIGN(16);
+    }
+
+    .bss : {
+        __bss_start = .;
+        *(.bss .bss.*)
+        *(COMMON)
+        . = ALIGN(16);
+        __bss_end = .;
+    }
+
+    __rom_end = . - __boot_start + 0xB0001000;
+
+    /DISCARD/ : {
+        *(.MIPS.*)
+        *(.comment)
+        *(.mdebug.*)
+        *(.pdr)
+        *(.reginfo)
+        *(.got)
+    }
+}

+ 25 - 0
crates/n64-rom/mips-nintendo64-none.json

@@ -0,0 +1,25 @@
+{
+  "arch": "mips",
+  "cpu": "mips3",
+  "data-layout": "E-m:e-p:32:32-i8:8:32-i16:16:32-i64:64-n32:64-S128",
+  "disable-redzone": true,
+  "env": "unknown",
+  "executables": true,
+  "features": "+mips3",
+  "linker": "rust-lld",
+  "linker-flavor": "ld.lld",
+  "llvm-abiname": "n32",
+  "llvm-target": "mips-unknown-unknown",
+  "os": "none",
+  "panic-strategy": "abort",
+  "pre-link-args": {
+    "ld.lld": [
+      "--script=crates/n64-rom/linker.ld"
+    ]
+  },
+  "relocation-model": "static",
+  "target-c-int-width": "32",
+  "target-endian": "big",
+  "target-pointer-width": "32",
+  "vendor": "nintendo64"
+}

+ 3 - 0
crates/n64-rom/rust-toolchain.toml

@@ -0,0 +1,3 @@
+[toolchain]
+channel = "nightly-2025-01-12"
+components = ["rust-src"]

+ 66 - 0
crates/n64-rom/src/cache.rs

@@ -0,0 +1,66 @@
+//! MIPS VR4300 Data Cache & Address Translation Helpers.
+
+use core::arch::asm;
+
+const DCACHE_LINE: usize = 16;
+
+#[inline(always)]
+pub fn phys_addr(addr: usize) -> u32 {
+    (addr as u32) & 0x1FFF_FFFF
+}
+
+#[inline(always)]
+pub const fn kseg0(phys: u32) -> usize {
+    (phys as usize) | 0x8000_0000
+}
+
+#[inline(always)]
+pub const fn kseg1(phys: u32) -> usize {
+    (phys as usize) | 0xA000_0000
+}
+
+/// Write back dirty D-cache lines covering `[addr, addr + len)` to RDRAM (Hit Writeback D-Cache).
+#[inline]
+pub fn dcache_writeback(addr: usize, len: usize) {
+    if len == 0 {
+        return;
+    }
+    let start = addr & !(DCACHE_LINE - 1);
+    let end = (addr + len + DCACHE_LINE - 1) & !(DCACHE_LINE - 1);
+    let mut p = start;
+    while p < end {
+        unsafe {
+            asm!(
+                ".set noat",
+                "cache 0x19, 0({0})",
+                ".set at",
+                in(reg) p,
+                options(nostack, preserves_flags)
+            );
+        }
+        p += DCACHE_LINE;
+    }
+}
+
+/// Invalidate D-cache lines covering `[addr, addr + len)` so CPU reads fresh RDP/DMA data.
+#[inline]
+pub fn dcache_invalidate(addr: usize, len: usize) {
+    if len == 0 {
+        return;
+    }
+    let start = addr & !(DCACHE_LINE - 1);
+    let end = (addr + len + DCACHE_LINE - 1) & !(DCACHE_LINE - 1);
+    let mut p = start;
+    while p < end {
+        unsafe {
+            asm!(
+                ".set noat",
+                "cache 0x11, 0({0})",
+                ".set at",
+                in(reg) p,
+                options(nostack, preserves_flags)
+            );
+        }
+        p += DCACHE_LINE;
+    }
+}

+ 270 - 0
crates/n64-rom/src/joybus.rs

@@ -0,0 +1,270 @@
+//! Bare-metal Serial Interface (SI) + PIF-RAM Joybus driver:
+//! Supports N64 Standard Controller, N64 Mouse, and 4K/16K Cartridge EEPROM.
+
+use core::ptr::addr_of_mut;
+
+use crate::cache::{kseg1, phys_addr};
+use shader_core::storage::SLOT_BYTES;
+use shader_core::ui::InputState;
+
+const SI_BASE: usize = 0xA480_0000;
+const SI_DRAM_ADDR: *mut u32 = (SI_BASE + 0x00) as *mut u32;
+const SI_PIF_ADDR_RD64B: *mut u32 = (SI_BASE + 0x04) as *mut u32;
+const SI_PIF_ADDR_WR64B: *mut u32 = (SI_BASE + 0x10) as *mut u32;
+const SI_STATUS: *mut u32 = (SI_BASE + 0x18) as *mut u32;
+
+const SI_BUSY_MASK: u32 = 0x3; // DMA_BUSY | IO_BUSY
+const PIF_RAM_PHYS: u32 = 0x1FC0_07C0;
+
+#[repr(align(16))]
+#[allow(dead_code)]
+struct AlignedPif([u8; 64]);
+
+static mut PIF_TX: AlignedPif = AlignedPif([0; 64]);
+static mut PIF_RX: AlignedPif = AlignedPif([0; 64]);
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum DeviceType {
+    None,
+    Controller,
+    Mouse,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum EepromType {
+    None,
+    Eeprom4K,
+    Eeprom16K,
+}
+
+impl EepromType {
+    pub const fn kb(self) -> u8 {
+        match self {
+            Self::None => 0,
+            Self::Eeprom4K => 4,
+            Self::Eeprom16K => 16,
+        }
+    }
+}
+
+#[inline]
+fn wait_si_idle() {
+    unsafe {
+        while (SI_STATUS.read_volatile() & SI_BUSY_MASK) != 0 {}
+    }
+}
+
+fn joybus_exec(tx_setup: impl FnOnce(&mut [u8; 64])) -> [u8; 64] {
+    wait_si_idle();
+    unsafe {
+        let tx_k1 = kseg1(phys_addr(addr_of_mut!(PIF_TX) as usize)) as *mut [u8; 64];
+        let rx_k1 = kseg1(phys_addr(addr_of_mut!(PIF_RX) as usize)) as *mut [u8; 64];
+        let tx = &mut *tx_k1;
+        tx.fill(0);
+        tx_setup(tx);
+        tx[63] = 0x01;
+
+        SI_STATUS.write_volatile(0); // Ack any SI interrupt
+        SI_DRAM_ADDR.write_volatile(phys_addr(addr_of_mut!(PIF_TX) as usize));
+        SI_PIF_ADDR_WR64B.write_volatile(PIF_RAM_PHYS);
+        wait_si_idle();
+
+        SI_STATUS.write_volatile(0);
+        SI_DRAM_ADDR.write_volatile(phys_addr(addr_of_mut!(PIF_RX) as usize));
+        SI_PIF_ADDR_RD64B.write_volatile(PIF_RAM_PHYS);
+        wait_si_idle();
+
+        *rx_k1
+    }
+}
+
+pub fn identify_port(port: u8) -> DeviceType {
+    let rx = joybus_exec(|tx| {
+        let mut i = 0usize;
+        for _ in 0..port {
+            tx[i] = 0x00;
+            i += 1;
+        }
+        tx[i] = 0x01;
+        tx[i + 1] = 0x03;
+        tx[i + 2] = 0x00; // Identify
+        tx[i + 3] = 0xFF;
+        tx[i + 4] = 0xFF;
+        tx[i + 5] = 0xFF;
+        tx[i + 6] = 0xFE;
+    });
+    let base = port as usize;
+    if (rx[base + 1] & 0xC0) != 0 {
+        return DeviceType::None;
+    }
+    let id = ((rx[base + 3] as u16) << 8) | (rx[base + 4] as u16);
+    match id {
+        0x0500 => DeviceType::Controller,
+        0x0200 => DeviceType::Mouse,
+        _ => DeviceType::None,
+    }
+}
+
+/// Poll Port 0 (Controller or Mouse) and optionally Port 1 if a Mouse is plugged there.
+pub fn poll_input(port0: DeviceType, port1: DeviceType) -> InputState {
+    let rx = joybus_exec(|tx| {
+        let mut i = 0usize;
+        if port0 != DeviceType::None {
+            tx[i] = 0x01;
+            tx[i + 1] = 0x04;
+            tx[i + 2] = 0x01; // Read controller/mouse state
+            tx[i + 3] = 0xFF;
+            tx[i + 4] = 0xFF;
+            tx[i + 5] = 0xFF;
+            tx[i + 6] = 0xFF;
+            i += 7;
+        } else {
+            tx[i] = 0x00;
+            i += 1;
+        }
+        if port1 == DeviceType::Mouse {
+            tx[i] = 0x01;
+            tx[i + 1] = 0x04;
+            tx[i + 2] = 0x01;
+            tx[i + 3] = 0xFF;
+            tx[i + 4] = 0xFF;
+            tx[i + 5] = 0xFF;
+            tx[i + 6] = 0xFF;
+            i += 7;
+        }
+        tx[i] = 0xFE;
+    });
+
+    let mut out = InputState::default();
+    let mut off = 0usize;
+    if port0 != DeviceType::None {
+        if (rx[off + 1] & 0xC0) == 0 {
+            let btns = ((rx[off + 3] as u16) << 8) | (rx[off + 4] as u16);
+            let ax = rx[off + 5] as i8;
+            let ay = rx[off + 6] as i8;
+            out.buttons |= btns;
+            if port0 == DeviceType::Mouse {
+                out.is_mouse = true;
+                out.mouse_dx = ax;
+                out.mouse_dy = ay;
+            } else {
+                out.stick_x = ax;
+                out.stick_y = ay;
+            }
+        }
+        off += 7;
+    } else {
+        off += 1;
+    }
+
+    if port1 == DeviceType::Mouse && (rx[off + 1] & 0xC0) == 0 {
+        let btns = ((rx[off + 3] as u16) << 8) | (rx[off + 4] as u16);
+        out.buttons |= btns;
+        out.is_mouse = true;
+        out.mouse_dx = rx[off + 5] as i8;
+        out.mouse_dy = rx[off + 6] as i8;
+    }
+
+    out
+}
+
+pub fn detect_eeprom() -> EepromType {
+    let rx = joybus_exec(|tx| {
+        // Skip Ports 0..3 -> Cartridge EEPROM on Channel 4
+        tx[0] = 0x00;
+        tx[1] = 0x00;
+        tx[2] = 0x00;
+        tx[3] = 0x00;
+        tx[4] = 0x01;
+        tx[5] = 0x03;
+        tx[6] = 0x00; // Identify
+        tx[7] = 0xFF;
+        tx[8] = 0xFF;
+        tx[9] = 0xFF;
+        tx[10] = 0xFE;
+    });
+    if (rx[5] & 0xC0) != 0 {
+        return EepromType::None;
+    }
+    let id = ((rx[7] as u16) << 8) | (rx[8] as u16);
+    match id {
+        0x0080 => EepromType::Eeprom4K,
+        0x00C0 => EepromType::Eeprom16K,
+        _ => EepromType::None,
+    }
+}
+
+fn eeprom_wait_ready() {
+    for _ in 0..4096 {
+        let rx = joybus_exec(|tx| {
+            tx[0] = 0x00;
+            tx[1] = 0x00;
+            tx[2] = 0x00;
+            tx[3] = 0x00;
+            tx[4] = 0x01;
+            tx[5] = 0x03;
+            tx[6] = 0x00;
+            tx[7] = 0xFF;
+            tx[8] = 0xFF;
+            tx[9] = 0xFF;
+            tx[10] = 0xFE;
+        });
+        if (rx[9] & 0x80) == 0 {
+            break;
+        }
+    }
+}
+
+pub fn eeprom_read_slot(slot: u8, out: &mut [u8; SLOT_BYTES]) -> bool {
+    let start_block = slot * 64;
+    for b in 0..64u8 {
+        let block = start_block + b;
+        let rx = joybus_exec(|tx| {
+            tx[0] = 0x00;
+            tx[1] = 0x00;
+            tx[2] = 0x00;
+            tx[3] = 0x00;
+            tx[4] = 0x02; // send len: cmd + block
+            tx[5] = 0x08; // recv len: 8 bytes
+            tx[6] = 0x04; // EEPROM Read Block
+            tx[7] = block;
+            for k in 8..16 {
+                tx[k] = 0xFF;
+            }
+            tx[16] = 0xFE;
+        });
+        if (rx[5] & 0xC0) != 0 {
+            return false;
+        }
+        let off = (b as usize) * 8;
+        out[off..off + 8].copy_from_slice(&rx[8..16]);
+    }
+    true
+}
+
+pub fn eeprom_write_slot(slot: u8, data: &[u8; SLOT_BYTES]) -> bool {
+    let start_block = slot * 64;
+    for b in 0..64u8 {
+        eeprom_wait_ready();
+        let block = start_block + b;
+        let off = (b as usize) * 8;
+        let rx = joybus_exec(|tx| {
+            tx[0] = 0x00;
+            tx[1] = 0x00;
+            tx[2] = 0x00;
+            tx[3] = 0x00;
+            tx[4] = 0x0A; // send len: cmd + block + 8 bytes
+            tx[5] = 0x01; // recv len: status byte
+            tx[6] = 0x05; // EEPROM Write Block
+            tx[7] = block;
+            tx[8..16].copy_from_slice(&data[off..off + 8]);
+            tx[16] = 0xFF;
+            tx[17] = 0xFE;
+        });
+        if (rx[5] & 0xC0) != 0 || rx[16] != 0x00 {
+            return false;
+        }
+    }
+    eeprom_wait_ready();
+    true
+}

+ 345 - 0
crates/n64-rom/src/main.rs

@@ -0,0 +1,345 @@
+//! N64 Node Shader Studio — Pure Rust Bare-Metal Hardware Entrypoint.
+
+#![no_std]
+#![no_main]
+#![feature(asm_experimental_arch)]
+
+mod cache;
+mod joybus;
+mod perf;
+mod rdp;
+mod vi;
+
+use core::arch::asm;
+use core::panic::PanicInfo;
+use core::slice;
+
+use cache::{dcache_invalidate, dcache_writeback, kseg0};
+use joybus::{
+    detect_eeprom, eeprom_read_slot, eeprom_write_slot, identify_port, poll_input,
+};
+use perf::{cp0_ticks_to_us, read_cp0_count};
+use rdp::{other_modes_fill, other_modes_for_shader, RdpList};
+use shader_core::graph::TexPattern;
+use shader_core::math::rgb5551;
+use shader_core::mesh::{generate_mesh, project_mesh, MeshBuffer, MeshKind, ProjectParams};
+use shader_core::storage::{deserialize_graph, serialize_graph, SLOT_BYTES};
+use shader_core::textures::{generate_texture, TEX_PIXELS};
+use shader_core::ui::{InputState, PerfStats, StorageAction, StudioApp, VP_H, VP_W, VP_X, VP_Y};
+
+#[panic_handler]
+fn panic(_info: &PanicInfo) -> ! {
+    loop {
+        unsafe {
+            asm!("nop");
+        }
+    }
+}
+
+#[inline(always)]
+unsafe fn enable_fpu_flush_to_zero() {
+    let mut status: u32;
+    asm!(".set noat", "mfc0 {0}, $12", ".set at", out(reg) status, options(nomem, nostack));
+    status |= 1 << 29; // CP0 Status.CU1 = enable FPU
+    asm!(".set noat", "mtc0 {0}, $12", ".set at", in(reg) status, options(nomem, nostack));
+    asm!("nop; nop; nop", options(nomem, nostack));
+    // FCSR ($31): FS = 1 (bit 24) flush denormals to zero, no traps enabled
+    let fcsr: u32 = 1 << 24;
+    asm!(".set noat", "ctc1 {0}, $31", ".set at", in(reg) fcsr, options(nomem, nostack));
+}
+
+#[no_mangle]
+pub extern "C" fn _entrypoint() -> ! {
+    extern "C" {
+        static mut __bss_start: u32;
+        static mut __bss_end: u32;
+    }
+
+    unsafe {
+        let mut p = &raw mut __bss_start;
+        let end = &raw mut __bss_end;
+        while p < end {
+            p.write_volatile(0);
+            p = p.add(1);
+        }
+        enable_fpu_flush_to_zero();
+    }
+
+    main_loop()
+}
+
+fn detect_rdram_size() -> usize {
+    let raw = unsafe { (0xA400_0000 as *const u32).read_volatile() } as usize;
+    if raw >= 0x40_0000 && raw <= 0x80_0000 {
+        raw
+    } else {
+        0x40_0000
+    }
+}
+
+fn main_loop() -> ! {
+    let rdram_bytes = detect_rdram_size();
+    let rdram_mb = (rdram_bytes / (1024 * 1024)) as u8;
+    let has_exp_pak = rdram_bytes >= 0x80_0000;
+
+    // Reserve 192 KB at top of RDRAM for stack; place framebuffers, Z-buffer, and textures below it.
+    let stack_reserve = 192 * 1024;
+    let max_fb_w = if has_exp_pak { 640usize } else { 320usize };
+    let max_fb_h = if has_exp_pak { 480usize } else { 240usize };
+    let fb_stride_bytes = (max_fb_w * max_fb_h * 2 + 63) & !63;
+    let tex_bytes = (TEX_PIXELS * 2 + 63) & !63;
+
+    let mut top = (rdram_bytes - stack_reserve) & !63;
+    top -= tex_bytes;
+    let tex1_phys = top as u32;
+    top -= tex_bytes;
+    let tex0_phys = top as u32;
+    top -= fb_stride_bytes;
+    let zbuf_phys = top as u32;
+    top -= fb_stride_bytes;
+    let fb1_phys = top as u32;
+    top -= fb_stride_bytes;
+    let fb0_phys = top as u32;
+
+    let mut hi_res = false;
+    let mut fb_w = 320usize;
+    let mut fb_h = 240usize;
+    let mut back_idx = 1usize;
+    let fb_phys = [fb0_phys, fb1_phys];
+
+    vi::init_vi(fb_phys[0], fb_w as u32, fb_h as u32, false);
+
+    let port0 = identify_port(0);
+    let port1 = identify_port(1);
+    let eeprom = detect_eeprom();
+
+    let mut app = StudioApp::new();
+    let mut mesh_buf = MeshBuffer::new();
+    let mut cur_mesh_kind = MeshKind::Sphere;
+    generate_mesh(cur_mesh_kind, &mut mesh_buf);
+
+    let mut cur_pat0: Option<TexPattern> = None;
+    let mut cur_pat1: Option<TexPattern> = None;
+
+    let mut prev_input = InputState::default();
+    let mut slot_buf = [0u8; SLOT_BYTES];
+    let mut perf = PerfStats {
+        rdram_mb,
+        eeprom_kb: eeprom.kb(),
+        ..Default::default()
+    };
+
+    loop {
+        let t_frame_start = read_cp0_count();
+
+        let input = poll_input(port0, port1);
+        app.update(&input, &prev_input);
+        prev_input = input;
+
+        // Handle pending EEPROM / Expansion Pak Hi-Res actions
+        if let Some(action) = app.pending_action.take() {
+            match action {
+                StorageAction::ToggleHiRes => {
+                    if has_exp_pak {
+                        hi_res = !hi_res;
+                        fb_w = if hi_res { 640 } else { 320 };
+                        fb_h = if hi_res { 480 } else { 240 };
+                        vi::init_vi(fb_phys[back_idx ^ 1], fb_w as u32, fb_h as u32, hi_res);
+                        app.set_toast(if hi_res { "640X480 INTERLACED" } else { "320X240 PROGRESSIVE" });
+                    } else {
+                        app.set_toast("NEED 8MB EXP PAK");
+                    }
+                }
+                StorageAction::SaveEeprom(slot) => {
+                    if eeprom.kb() == 0 {
+                        app.set_toast("NO EEPROM DETECTED");
+                    } else if serialize_graph(&app.graph, &mut slot_buf).is_ok()
+                        && eeprom_write_slot(slot, &slot_buf)
+                    {
+                        app.set_toast("SAVED TO EEPROM!");
+                    } else {
+                        app.set_toast("EEPROM WRITE ERR");
+                    }
+                }
+                StorageAction::LoadEeprom(slot) => {
+                    if eeprom.kb() == 0 {
+                        app.set_toast("NO EEPROM DETECTED");
+                    } else if eeprom_read_slot(slot, &mut slot_buf) {
+                        match deserialize_graph(&slot_buf) {
+                            Ok(g) => app.replace_graph(g, "LOADED FROM EEPROM!"),
+                            Err(_) => app.set_toast("EMPTY/BAD EEPROM"),
+                        }
+                    } else {
+                        app.set_toast("EEPROM READ ERR");
+                    }
+                }
+            }
+        }
+
+        if app.mesh_kind != cur_mesh_kind {
+            cur_mesh_kind = app.mesh_kind;
+            generate_mesh(cur_mesh_kind, &mut mesh_buf);
+        }
+
+        // Update 32x32 textures in RDRAM whenever pattern changes
+        let pat0_need = app
+            .compiled
+            .as_ref()
+            .ok()
+            .and_then(|s| s.tex0.map(|t| t.pattern))
+            .unwrap_or(TexPattern::ChromeEnv);
+        if cur_pat0 != Some(pat0_need) {
+            let t0_ptr = kseg0(tex0_phys) as *mut [u16; TEX_PIXELS];
+            unsafe {
+                generate_texture(pat0_need, &mut *t0_ptr);
+            }
+            dcache_writeback(t0_ptr as usize, TEX_PIXELS * 2);
+            cur_pat0 = Some(pat0_need);
+        }
+
+        let pat1_need = app
+            .compiled
+            .as_ref()
+            .ok()
+            .and_then(|s| s.tex1.map(|t| t.pattern))
+            .unwrap_or(TexPattern::WaterCaustics);
+        if cur_pat1 != Some(pat1_need) {
+            let t1_ptr = kseg0(tex1_phys) as *mut [u16; TEX_PIXELS];
+            unsafe {
+                generate_texture(pat1_need, &mut *t1_ptr);
+            }
+            dcache_writeback(t1_ptr as usize, TEX_PIXELS * 2);
+            cur_pat1 = Some(pat1_need);
+        }
+
+        let back_phys = fb_phys[back_idx];
+        let back_k0 = kseg0(back_phys);
+        let fb_slice = unsafe { slice::from_raw_parts_mut(back_k0 as *mut u16, fb_w * fb_h) };
+
+        // 1. CPU renders Left 65% Node Canvas & UI chrome into cached backbuffer
+        app.render_canvas(fb_slice, fb_w, fb_h);
+        dcache_writeback(back_k0, fb_w * fb_h * 2);
+
+        // 2. Transform & project 3D mesh into Right 35% Viewport
+        let sc = if hi_res { 2.0f32 } else { 1.0f32 };
+        let vp_x0 = (VP_X as f32) * sc;
+        let vp_y0 = (VP_Y as f32) * sc;
+        let vp_w = (VP_W as f32) * sc;
+        let vp_h = (VP_H as f32) * sc;
+
+        let (env_map, scroll_x, scroll_y, uses_fresnel, fresnel_power, fresnel_bias) =
+            match &app.compiled {
+                Ok(s) => {
+                    let tcfg = s.tex0.or(s.tex1);
+                    (
+                        tcfg.map(|t| t.env_map).unwrap_or(false),
+                        tcfg.map(|t| t.scroll_x).unwrap_or(0),
+                        tcfg.map(|t| t.scroll_y).unwrap_or(0),
+                        s.uses_fresnel,
+                        s.fresnel_power,
+                        s.fresnel_bias,
+                    )
+                }
+                Err(_) => (false, 0, 0, false, 2, 0),
+            };
+
+        let proj_tris = project_mesh(
+            &mesh_buf,
+            &ProjectParams {
+                vp_x0,
+                vp_y0,
+                vp_w,
+                vp_h,
+                yaw: app.yaw,
+                pitch: app.pitch,
+                frame: app.frame,
+                light: app.light_preset,
+                env_map,
+                scroll_x,
+                scroll_y,
+                uses_fresnel,
+                fresnel_power,
+                fresnel_bias,
+            },
+        );
+
+        let t_cpu_end = read_cp0_count();
+
+        // 3. Build Hardware RDP Display List for Right 35% Viewport
+        let mut dl = RdpList::new();
+        let vx0 = vp_x0 as i32;
+        let vy0 = vp_y0 as i32;
+        let vx1 = (vp_x0 + vp_w) as i32;
+        let vy1 = (vp_y0 + vp_h) as i32;
+
+        dl.set_scissor(vx0, vy0, vx1, vy1);
+        dl.set_other_modes(other_modes_fill());
+
+        // Clear Z-buffer in viewport
+        dl.sync_pipe();
+        dl.set_color_image_rgba16(zbuf_phys, fb_w as u32);
+        dl.set_fill_color_16(0xFFFC);
+        dl.fill_rectangle_fill_mode(vx0, vy0, vx1, vy1);
+
+        // Clear color viewport background
+        dl.sync_pipe();
+        dl.set_color_image_rgba16(back_phys, fb_w as u32);
+        dl.set_z_image(zbuf_phys);
+        dl.set_fill_color_16(rgb5551(14, 18, 28));
+        dl.fill_rectangle_fill_mode(vx0, vy0, vx1, vy1);
+
+        if let Ok(shader) = &app.compiled {
+            // Load active textures into TMEM (TEX0 @ 0x000, TEX1 @ 0x100 64-bit words)
+            if shader.tex0.is_some() {
+                dl.load_texture_32x32(0, tex0_phys, 0x000, 0, 0);
+            }
+            if let Some(t1) = shader.tex1 {
+                let s_off = (((app.frame as i32 * t1.scroll_x as i32) >> 1) & 31) as u32 * 4;
+                let t_off = (((app.frame as i32 * t1.scroll_y as i32) >> 1) & 31) as u32 * 4;
+                dl.load_texture_32x32(1, tex1_phys, 0x100, s_off, t_off);
+            }
+
+            dl.sync_pipe();
+            dl.set_other_modes(other_modes_for_shader(shader));
+            dl.set_combine_raw(shader.combine_cmd);
+            dl.set_prim_color(shader.prim_color, shader.prim_lod_frac);
+            dl.set_env_color(shader.env_color);
+
+            for tri in &proj_tris {
+                dl.triangle_shade_tex_zbuf(tri, 0);
+            }
+        }
+
+        dl.sync_full();
+
+        let t_rdp_start = read_cp0_count();
+        let dpc = dl.submit_and_wait();
+        let t_rdp_end = read_cp0_count();
+
+        // 4. Invalidate CPU D-cache over framebuffer before drawing wireframe + Perf HUD overlay
+        dcache_invalidate(back_k0, fb_w * fb_h * 2);
+
+        perf.cpu_us = cp0_ticks_to_us(t_cpu_end.wrapping_sub(t_frame_start));
+        perf.rdp_us = cp0_ticks_to_us(t_rdp_end.wrapping_sub(t_rdp_start));
+        perf.rdp_clock = dpc.clock;
+        perf.rdp_pipe_busy = dpc.pipe_busy;
+        perf.rdp_tmem_busy = dpc.tmem_busy;
+        perf.is_mouse = input.is_mouse;
+        perf.hi_res = hi_res;
+
+        app.render_viewport_overlay(fb_slice, fb_w, fb_h, &proj_tris, &perf);
+        dcache_writeback(back_k0, fb_w * fb_h * 2);
+
+        let t_frame_end = read_cp0_count();
+        perf.frame_us = cp0_ticks_to_us(t_frame_end.wrapping_sub(t_frame_start));
+        perf.fps = if perf.frame_us > 0 {
+            (1_000_000 / perf.frame_us).min(60) as u16
+        } else {
+            60
+        };
+
+        // 5. Wait vertical blank and flip Video Interface framebuffer
+        vi::wait_vblank_and_swap(back_phys, fb_w as u32, hi_res);
+        back_idx ^= 1;
+    }
+}

+ 60 - 0
crates/n64-rom/src/perf.rs

@@ -0,0 +1,60 @@
+//! VR4300 CP0 Count & Reality Display Processor (DPC) hardware performance counters.
+
+use core::arch::asm;
+
+const DPC_STATUS: *mut u32 = 0xA410_000C as *mut u32;
+const DPC_CLOCK: *const u32 = 0xA410_0010 as *const u32;
+const DPC_BUFBUSY: *const u32 = 0xA410_0014 as *const u32;
+const DPC_PIPEBUSY: *const u32 = 0xA410_0018 as *const u32;
+const DPC_TMEM: *const u32 = 0xA410_001C as *const u32;
+
+#[derive(Copy, Clone, Debug, Default)]
+pub struct DpcCounters {
+    pub clock: u32,
+    #[allow(dead_code)]
+    pub buf_busy: u32,
+    pub pipe_busy: u32,
+    pub tmem_busy: u32,
+}
+
+#[inline(always)]
+pub fn read_cp0_count() -> u32 {
+    let count: u32;
+    unsafe {
+        asm!(
+            ".set noat",
+            "mfc0 {0}, $9",
+            ".set at",
+            out(reg) count,
+            options(nomem, nostack, preserves_flags)
+        );
+    }
+    count
+}
+
+/// Convert CP0 Count delta (46.875 MHz) to microseconds.
+#[inline(always)]
+pub fn cp0_ticks_to_us(delta: u32) -> u32 {
+    ((delta as u64 * 16) / 750) as u32
+}
+
+/// Clear DPC clock, bufbusy, pipebusy, and tmem counters (and clear XBUS mode).
+#[inline]
+pub fn dpc_reset_counters() {
+    unsafe {
+        // Bit 0: clear XBUS_DMEM_DMA; Bits 6..9: clear TMEM, PIPE, CMD/BUF, CLOCK counters
+        DPC_STATUS.write_volatile(0x03C1);
+    }
+}
+
+#[inline]
+pub fn dpc_read_counters() -> DpcCounters {
+    unsafe {
+        DpcCounters {
+            clock: DPC_CLOCK.read_volatile(),
+            buf_busy: DPC_BUFBUSY.read_volatile(),
+            pipe_busy: DPC_PIPEBUSY.read_volatile(),
+            tmem_busy: DPC_TMEM.read_volatile(),
+        }
+    }
+}

+ 406 - 0
crates/n64-rom/src/rdp.rs

@@ -0,0 +1,406 @@
+//! Bare-metal Nintendo 64 Reality Display Processor (RDP) command builder & triangle rasterizer.
+
+use core::ptr::addr_of_mut;
+
+use crate::cache::{dcache_writeback, kseg0, phys_addr};
+use crate::perf::{dpc_read_counters, dpc_reset_counters, DpcCounters};
+use shader_core::compiler::{CompiledShader, CycleCount};
+use shader_core::graph::BlendMode;
+use shader_core::math::{abs_f32, clamp_f32, floor_f32};
+use shader_core::mesh::ProjectedTri;
+use shader_core::textures::TEX_SIZE;
+
+const DPC_START: *mut u32 = 0xA410_0000 as *mut u32;
+const DPC_END: *mut u32 = 0xA410_0004 as *mut u32;
+const MI_INTR: *const u32 = 0xA430_0008 as *const u32;
+const MI_INIT_MODE: *mut u32 = 0xA430_0000 as *mut u32;
+
+const MI_INTR_DP: u32 = 1 << 5;
+const MI_CLR_DP_INTR: u32 = 1 << 11;
+
+const DL_CAP_WORDS: usize = 32768; // 256 KB display list buffer
+
+#[repr(align(16))]
+#[allow(dead_code)]
+struct AlignedDl([u64; DL_CAP_WORDS]);
+
+static mut DL_BUF: AlignedDl = AlignedDl([0; DL_CAP_WORDS]);
+
+// SET_OTHER_MODES bits
+const SOM_CYCLE_1: u64 = 0 << 52;
+const SOM_CYCLE_2: u64 = 1 << 52;
+const SOM_CYCLE_FILL: u64 = 3 << 52;
+const SOM_TEXTURE_PERSP: u64 = 1 << 51;
+const SOM_SAMPLE_BILINEAR: u64 = 2 << 44;
+const SOM_TF0_RGB: u64 = 1 << 43;
+const SOM_TF1_RGB: u64 = 2 << 41;
+const SOM_RGBDITHER_BAYER: u64 = 1 << 38;
+const SOM_RGBDITHER_NONE: u64 = 3 << 38;
+const SOM_ALPHADITHER_NONE: u64 = 3 << 36;
+const SOM_BLENDING: u64 = 1 << 14;
+const SOM_ZMODE_OPAQUE: u64 = 0 << 10;
+const SOM_ZMODE_TRANSPARENT: u64 = 2 << 10;
+const SOM_COVERAGE_DEST_CLAMP: u64 = 0 << 8;
+const SOM_READ_ENABLE: u64 = 1 << 6;
+const SOM_Z_WRITE: u64 = 1 << 5;
+const SOM_Z_COMPARE: u64 = 1 << 4;
+
+pub struct RdpList {
+    len: usize,
+}
+
+impl RdpList {
+    pub fn new() -> Self {
+        Self { len: 0 }
+    }
+
+    #[inline(always)]
+    fn push(&mut self, word: u64) {
+        if self.len < DL_CAP_WORDS {
+            unsafe {
+                let buf = kseg0(phys_addr(addr_of_mut!(DL_BUF) as usize)) as *mut u64;
+                buf.add(self.len).write(word);
+            }
+            self.len += 1;
+        }
+    }
+
+    #[inline(always)]
+    fn push_words(&mut self, w0: u32, w1: u32) {
+        self.push(((w0 as u64) << 32) | (w1 as u64));
+    }
+
+    pub fn sync_load(&mut self) {
+        self.push(0xE600_0000_0000_0000);
+    }
+
+    pub fn sync_pipe(&mut self) {
+        self.push(0xE700_0000_0000_0000);
+    }
+
+    pub fn sync_tile(&mut self) {
+        self.push(0xE800_0000_0000_0000);
+    }
+
+    pub fn sync_full(&mut self) {
+        self.push(0xE900_0000_0000_0000);
+    }
+
+    pub fn set_scissor(&mut self, x0: i32, y0: i32, x1: i32, y1: i32) {
+        let x0f = (x0.max(0) * 4) as u32 & 0xFFF;
+        let y0f = (y0.max(0) * 4) as u32 & 0xFFF;
+        let x1f = (x1.max(0) * 4) as u32 & 0xFFF;
+        let y1f = (y1.max(0) * 4) as u32 & 0xFFF;
+        let w0 = 0xED00_0000 | (x0f << 12) | y0f;
+        let w1 = (x1f << 12) | y1f;
+        self.push_words(w0, w1);
+    }
+
+    /// Set Color Image: RGBA16 (`fmt = 0`, `size = 2` -> 16-bit).
+    pub fn set_color_image_rgba16(&mut self, phys: u32, width: u32) {
+        let w0 = 0xFF00_0000 | (0 << 21) | (2 << 19) | ((width - 1) & 0x3FF);
+        let w1 = phys & 0x00FF_FFFF;
+        self.push_words(w0, w1);
+    }
+
+    pub fn set_z_image(&mut self, phys: u32) {
+        self.push_words(0xFE00_0000, phys & 0x00FF_FFFF);
+    }
+
+    pub fn set_texture_image_rgba16(&mut self, phys: u32, width: u32) {
+        let w0 = 0xFD00_0000 | (0 << 21) | (2 << 19) | ((width - 1) & 0x3FF);
+        let w1 = phys & 0x00FF_FFFF;
+        self.push_words(w0, w1);
+    }
+
+    pub fn set_fill_color_16(&mut self, color5551: u16) {
+        let c = color5551 as u32;
+        self.push_words(0xF700_0000, (c << 16) | c);
+    }
+
+    pub fn set_env_color(&mut self, rgba: [u8; 4]) {
+        let c = ((rgba[0] as u32) << 24)
+            | ((rgba[1] as u32) << 16)
+            | ((rgba[2] as u32) << 8)
+            | (rgba[3] as u32);
+        self.push_words(0xFB00_0000, c);
+    }
+
+    pub fn set_prim_color(&mut self, rgba: [u8; 4], prim_lod_frac: u8) {
+        let w0 = 0xFA00_0000 | (prim_lod_frac as u32);
+        let c = ((rgba[0] as u32) << 24)
+            | ((rgba[1] as u32) << 16)
+            | ((rgba[2] as u32) << 8)
+            | (rgba[3] as u32);
+        self.push_words(w0, c);
+    }
+
+    pub fn set_combine_raw(&mut self, combine_cmd: u64) {
+        self.push(combine_cmd);
+    }
+
+    pub fn set_other_modes(&mut self, som: u64) {
+        self.push((0xEFu64 << 56) | (som & 0x00FF_FFFF_FFFF_FFFF));
+    }
+
+    /// Fill rectangle in Fill Mode (`x1, y1` are exclusive; hardware expects inclusive `x1-1, y1-1`).
+    pub fn fill_rectangle_fill_mode(&mut self, x0: i32, y0: i32, x1: i32, y1: i32) {
+        if x1 <= x0 || y1 <= y0 {
+            return;
+        }
+        let fx0 = (x0 * 4) as u32 & 0xFFF;
+        let fy0 = (y0 * 4) as u32 & 0xFFF;
+        let fx1 = ((x1 - 1) * 4) as u32 & 0xFFF;
+        let fy1 = ((y1 - 1) * 4) as u32 & 0xFFF;
+        let w0 = 0xF600_0000 | (fx1 << 12) | fy1;
+        let w1 = (fx0 << 12) | fy0;
+        self.push_words(w0, w1);
+    }
+
+    /// Configure an RGBA16 32x32 wrapping tile in TMEM.
+    pub fn set_tile_rgba16_32x32(&mut self, tile: u8, tmem_words: u16) {
+        // fmt=0 (RGBA), size=2 (16-bit), line = (32 * 2)/8 = 8 64-bit words
+        let line: u32 = 8;
+        let w0 = 0xF500_0000
+            | (0 << 21)
+            | (2 << 19)
+            | ((line & 0x1FF) << 9)
+            | ((tmem_words as u32) & 0x1FF);
+        // mask_t = 5 (32), mask_s = 5 (32)
+        let w1 = (((tile as u32) & 7) << 24) | (5 << 14) | (5 << 4);
+        self.push_words(w0, w1);
+    }
+
+    pub fn load_tile_32x32(&mut self, tile: u8) {
+        let s1 = (TEX_SIZE as u32 - 1) * 4;
+        let t1 = (TEX_SIZE as u32 - 1) * 4;
+        let w0 = 0xF400_0000;
+        let w1 = (((tile as u32) & 7) << 24) | (s1 << 12) | t1;
+        self.push_words(w0, w1);
+    }
+
+    pub fn set_tile_size_32x32(&mut self, tile: u8, s_off_fx: u32, t_off_fx: u32) {
+        let s0 = s_off_fx & 0xFFF;
+        let t0 = t_off_fx & 0xFFF;
+        let s1 = (s0 + (TEX_SIZE as u32 - 1) * 4) & 0xFFF;
+        let t1 = (t0 + (TEX_SIZE as u32 - 1) * 4) & 0xFFF;
+        let w0 = 0xF200_0000 | (s0 << 12) | t0;
+        let w1 = (((tile as u32) & 7) << 24) | (s1 << 12) | t1;
+        self.push_words(w0, w1);
+    }
+
+    pub fn load_texture_32x32(&mut self, tile: u8, phys: u32, tmem_words: u16, s_off_fx: u32, t_off_fx: u32) {
+        self.sync_tile();
+        self.set_texture_image_rgba16(phys, TEX_SIZE as u32);
+        self.set_tile_rgba16_32x32(tile, tmem_words);
+        self.sync_load();
+        self.load_tile_32x32(tile);
+        self.set_tile_size_32x32(tile, s_off_fx, t_off_fx);
+    }
+
+    /// Emit `0xCF` (Shade + Texture + Z-Buffer Triangle, 22 x 64-bit words = 176 bytes).
+    pub fn triangle_shade_tex_zbuf(&mut self, tri: &ProjectedTri, tile: u8) {
+        if self.len + 22 > DL_CAP_WORDS {
+            return;
+        }
+        let mut v1 = tri.v[0];
+        let mut v2 = tri.v[1];
+        let mut v3 = tri.v[2];
+        if v1.y > v2.y {
+            core::mem::swap(&mut v1, &mut v2);
+        }
+        if v2.y > v3.y {
+            core::mem::swap(&mut v2, &mut v3);
+        }
+        if v1.y > v2.y {
+            core::mem::swap(&mut v1, &mut v2);
+        }
+
+        let x1 = v1.x;
+        let x2 = v2.x;
+        let x3 = v3.x;
+        let y1 = floor_f32(v1.y * 4.0) * 0.25;
+        let y2 = floor_f32(v2.y * 4.0) * 0.25;
+        let y3 = floor_f32(v3.y * 4.0) * 0.25;
+
+        let y1f = clamp_f32(floor_f32(v1.y * 4.0), -16384.0, 16380.0) as i32;
+        let y2f = clamp_f32(floor_f32(v2.y * 4.0), -16384.0, 16380.0) as i32;
+        let y3f = clamp_f32(floor_f32(v3.y * 4.0), -16384.0, 16380.0) as i32;
+
+        let hx = x3 - x1;
+        let hy = y3 - y1;
+        let mx = x2 - x1;
+        let my = y2 - y1;
+        let lx = x3 - x2;
+        let ly = y3 - y2;
+
+        let nz = hx * my - hy * mx;
+        if abs_f32(nz) < 1e-4 {
+            return;
+        }
+        let attr_factor = -1.0 / nz;
+        let lft: u32 = if nz < 0.0 { 1 } else { 0 };
+
+        let ish = if abs_f32(hy) > 1e-5 { hx / hy } else { 0.0 };
+        let ism = if abs_f32(my) > 1e-5 { mx / my } else { 0.0 };
+        let isl = if abs_f32(ly) > 1e-5 { lx / ly } else { 0.0 };
+        let fy = floor_f32(y1) - y1;
+
+        let xh = x1 + fy * ish;
+        let xm = x1 + fy * ism;
+        let xl = x2;
+
+        // 1. Edge Coefficients (4 x 64-bit words)
+        self.push_words(
+            0xCF00_0000 | (lft << 23) | (((tile as u32) & 7) << 16) | ((y3f as u32) & 0x3FFF),
+            (((y2f as u32) & 0x3FFF) << 16) | ((y1f as u32) & 0x3FFF),
+        );
+        self.push_words(float_to_s16_16(xl) as u32, float_to_s16_16(isl) as u32);
+        self.push_words(float_to_s16_16(xh) as u32, float_to_s16_16(ish) as u32);
+        self.push_words(float_to_s16_16(xm) as u32, float_to_s16_16(ism) as u32);
+
+        // 2. Shade Coefficients (8 x 64-bit words)
+        let write_attr = |val1: f32, val2: f32, val3: f32| -> (i32, i32, i32, i32) {
+            let m = val2 - val1;
+            let h = val3 - val1;
+            let nx = hy * m - my * h;
+            let ny = mx * h - hx * m;
+            let dx = nx * attr_factor;
+            let dy = ny * attr_factor;
+            let de = dy + dx * ish;
+            (
+                float_to_s16_16(val1 + fy * de),
+                float_to_s16_16(dx),
+                float_to_s16_16(de),
+                float_to_s16_16(dy),
+            )
+        };
+
+        let (r0, drx, dre, dry) = write_attr(v1.r * 255.0, v2.r * 255.0, v3.r * 255.0);
+        let (g0, dgx, dge, dgy) = write_attr(v1.g * 255.0, v2.g * 255.0, v3.g * 255.0);
+        let (b0, dbx, dbe, dby) = write_attr(v1.b * 255.0, v2.b * 255.0, v3.b * 255.0);
+        let (a0, dax, dae, day) = write_attr(v1.a * 255.0, v2.a * 255.0, v3.a * 255.0);
+
+        self.push_words(hi16(r0, g0), hi16(b0, a0));
+        self.push_words(hi16(drx, dgx), hi16(dbx, dax));
+        self.push_words(lo16(r0, g0), lo16(b0, a0));
+        self.push_words(lo16(drx, dgx), lo16(dbx, dax));
+        self.push_words(hi16(dre, dge), hi16(dbe, dae));
+        self.push_words(hi16(dry, dgy), hi16(dby, day));
+        self.push_words(lo16(dre, dge), lo16(dbe, dae));
+        self.push_words(lo16(dry, dgy), lo16(dby, day));
+
+        // 3. Texture Coefficients (8 x 64-bit words, perspective-correct S/W, T/W, 1/W)
+        let max_inv_w = v1.inv_w.max(v2.inv_w).max(v3.inv_w).max(1e-5);
+        let min_w = 1.0 / max_inv_w;
+        let iw1 = v1.inv_w * min_w;
+        let iw2 = v2.inv_w * min_w;
+        let iw3 = v3.inv_w * min_w;
+
+        let s1 = v1.s * 32.0 * iw1;
+        let t1 = v1.t * 32.0 * iw1;
+        let s2 = v2.s * 32.0 * iw2;
+        let t2 = v2.t * 32.0 * iw2;
+        let s3 = v3.s * 32.0 * iw3;
+        let t3 = v3.t * 32.0 * iw3;
+
+        let (ss0, dsx, dse, dsy) = write_attr(s1, s2, s3);
+        let (tt0, dtx, dte, dty) = write_attr(t1, t2, t3);
+        let (ww0, dwx, dwe, dwy) = write_attr(iw1 * 32767.0, iw2 * 32767.0, iw3 * 32767.0);
+
+        self.push_words(hi16(ss0, tt0), (ww0 as u32) & 0xFFFF_0000);
+        self.push_words(hi16(dsx, dtx), (dwx as u32) & 0xFFFF_0000);
+        self.push_words(lo16(ss0, tt0), (ww0 as u32) << 16);
+        self.push_words(lo16(dsx, dtx), (dwx as u32) << 16);
+        self.push_words(hi16(dse, dte), (dwe as u32) & 0xFFFF_0000);
+        self.push_words(hi16(dsy, dty), (dwy as u32) & 0xFFFF_0000);
+        self.push_words(lo16(dse, dte), (dwe as u32) << 16);
+        self.push_words(lo16(dsy, dty), (dwy as u32) << 16);
+
+        // 4. Z-Buffer Coefficients (2 x 64-bit words)
+        let (zz0, dzx, dze, dzy) = write_attr(v1.z * 32767.0, v2.z * 32767.0, v3.z * 32767.0);
+        self.push_words(zz0 as u32, dzx as u32);
+        self.push_words(dze as u32, dzy as u32);
+    }
+
+    pub fn submit_and_wait(&self) -> DpcCounters {
+        if self.len == 0 {
+            return DpcCounters::default();
+        }
+        let start_k0 = kseg0(phys_addr(addr_of_mut!(DL_BUF) as usize));
+        let byte_len = self.len * 8;
+        dcache_writeback(start_k0, byte_len);
+
+        let start_phys = phys_addr(start_k0);
+        let end_phys = start_phys + (byte_len as u32);
+
+        dpc_reset_counters();
+        unsafe {
+            MI_INIT_MODE.write_volatile(MI_CLR_DP_INTR);
+            DPC_START.write_volatile(start_phys);
+            DPC_END.write_volatile(end_phys);
+            while (MI_INTR.read_volatile() & MI_INTR_DP) == 0 {}
+            MI_INIT_MODE.write_volatile(MI_CLR_DP_INTR);
+        }
+        dpc_read_counters()
+    }
+}
+
+/// Build the `SET_OTHER_MODES` word for a compiled shader's cycle count & blend mode.
+pub fn other_modes_for_shader(shader: &CompiledShader) -> u64 {
+    let cyc = match shader.cycles {
+        CycleCount::OneCycle => SOM_CYCLE_1,
+        CycleCount::TwoCycle => SOM_CYCLE_2,
+    };
+    let base = cyc
+        | SOM_TEXTURE_PERSP
+        | SOM_SAMPLE_BILINEAR
+        | SOM_TF0_RGB
+        | SOM_TF1_RGB
+        | SOM_RGBDITHER_BAYER
+        | SOM_ALPHADITHER_NONE
+        | SOM_COVERAGE_DEST_CLAMP;
+
+    match shader.blend_mode {
+        BlendMode::Opaque => base | SOM_ZMODE_OPAQUE | SOM_Z_WRITE | SOM_Z_COMPARE,
+        BlendMode::Translucent => {
+            let blend = match shader.cycles {
+                CycleCount::OneCycle => 0x0050_0000u64, // IN_RGB*IN_ALPHA + MEM_RGB*(1-IN_ALPHA)
+                CycleCount::TwoCycle => 0x0C10_0000u64, // Pass0: IN_RGB*1, Pass1: CYC1*IN_ALPHA + MEM_RGB*(1-IN_ALPHA)
+            };
+            base | blend | SOM_BLENDING | SOM_READ_ENABLE | SOM_ZMODE_TRANSPARENT | SOM_Z_COMPARE
+        }
+        BlendMode::Additive => {
+            let blend = match shader.cycles {
+                CycleCount::OneCycle => 0x0048_0000u64, // IN_RGB*IN_ALPHA + MEM_RGB*1
+                CycleCount::TwoCycle => 0x0C12_0000u64, // Pass0: IN_RGB*1, Pass1: CYC1*IN_ALPHA + MEM_RGB*1
+            };
+            base | blend | SOM_BLENDING | SOM_READ_ENABLE | SOM_ZMODE_TRANSPARENT | SOM_Z_COMPARE
+        }
+    }
+}
+
+pub fn other_modes_fill() -> u64 {
+    SOM_CYCLE_FILL | SOM_RGBDITHER_NONE | SOM_ALPHADITHER_NONE
+}
+
+#[inline(always)]
+fn float_to_s16_16(f: f32) -> i32 {
+    if f >= 32767.0 {
+        return 0x7FFF_0000;
+    }
+    if f < -32768.0 {
+        return i32::MIN;
+    }
+    (floor_f32(f * 65536.0)) as i32
+}
+
+#[inline(always)]
+fn hi16(a: i32, b: i32) -> u32 {
+    ((a as u32) & 0xFFFF_0000) | (((b as u32) >> 16) & 0xFFFF)
+}
+
+#[inline(always)]
+fn lo16(a: i32, b: i32) -> u32 {
+    (((a as u32) & 0xFFFF) << 16) | ((b as u32) & 0xFFFF)
+}

+ 158 - 0
crates/n64-rom/src/vi.rs

@@ -0,0 +1,158 @@
+//! Bare-metal Nintendo 64 Video Interface (VI) driver for 320x240p and 640x480i.
+
+const VI_BASE: usize = 0xA440_0000;
+const VI_CTRL: *mut u32 = (VI_BASE + 0x00) as *mut u32;
+const VI_ORIGIN: *mut u32 = (VI_BASE + 0x04) as *mut u32;
+const VI_WIDTH: *mut u32 = (VI_BASE + 0x08) as *mut u32;
+const VI_V_INTR: *mut u32 = (VI_BASE + 0x0C) as *mut u32;
+const VI_V_CURRENT: *const u32 = (VI_BASE + 0x10) as *const u32;
+const VI_BURST: *mut u32 = (VI_BASE + 0x14) as *mut u32;
+const VI_V_SYNC: *mut u32 = (VI_BASE + 0x18) as *mut u32;
+const VI_H_SYNC: *mut u32 = (VI_BASE + 0x1C) as *mut u32;
+const VI_H_SYNC_LEAP: *mut u32 = (VI_BASE + 0x20) as *mut u32;
+const VI_H_VIDEO: *mut u32 = (VI_BASE + 0x24) as *mut u32;
+const VI_V_VIDEO: *mut u32 = (VI_BASE + 0x28) as *mut u32;
+const VI_V_BURST: *mut u32 = (VI_BASE + 0x2C) as *mut u32;
+const VI_X_SCALE: *mut u32 = (VI_BASE + 0x30) as *mut u32;
+const VI_Y_SCALE: *mut u32 = (VI_BASE + 0x34) as *mut u32;
+
+// TV type written by IPL3 into low RDRAM (0 = PAL, 1 = NTSC, 2 = MPAL)
+const OS_TV_TYPE: *const u32 = 0x8000_0300 as *const u32;
+
+const VI_PIXEL_ADVANCE_DEFAULT: u32 = 0b0011 << 12;
+const VI_AA_MODE_NONE: u32 = 0b11 << 8;
+const VI_CTRL_SERRATE: u32 = 1 << 6;
+const VI_CTRL_TYPE_16_BPP: u32 = 0b10;
+
+#[derive(Copy, Clone)]
+struct ViPreset {
+    burst: u32,
+    v_sync: u32,
+    h_sync: u32,
+    h_sync_leap: u32,
+    h_video: u32,
+    v_video: u32,
+    v_burst: u32,
+}
+
+const PRESET_PAL_P: ViPreset = ViPreset {
+    burst: 0x0404_233A,
+    v_sync: 0x0000_0271,
+    h_sync: 0x0015_0C69,
+    h_sync_leap: 0x0C6F_0C6E,
+    h_video: 0x0080_0300,
+    v_video: 0x005F_0239,
+    v_burst: 0x0009_026B,
+};
+
+const PRESET_NTSC_P: ViPreset = ViPreset {
+    burst: 0x03E5_2239,
+    v_sync: 0x0000_020D,
+    h_sync: 0x0000_0C15,
+    h_sync_leap: 0x0C15_0C15,
+    h_video: 0x006C_02EC,
+    v_video: 0x0025_01FF,
+    v_burst: 0x000E_0204,
+};
+
+const PRESET_MPAL_P: ViPreset = ViPreset {
+    burst: 0x0465_1E39,
+    v_sync: 0x0000_020D,
+    h_sync: 0x0004_0C11,
+    h_sync_leap: 0x0C19_0C1A,
+    h_video: 0x006C_02EC,
+    v_video: 0x0025_01FF,
+    v_burst: 0x000E_0204,
+};
+
+const PRESET_PAL_I: ViPreset = ViPreset {
+    burst: 0x0404_233A,
+    v_sync: 0x0000_0270,
+    h_sync: 0x0015_0C69,
+    h_sync_leap: 0x0C6F_0C6E,
+    h_video: 0x0080_0300,
+    v_video: 0x005D_0237,
+    v_burst: 0x0009_026B,
+};
+
+const PRESET_NTSC_I: ViPreset = ViPreset {
+    burst: 0x03E5_2239,
+    v_sync: 0x0000_020C,
+    h_sync: 0x0000_0C15,
+    h_sync_leap: 0x0C15_0C15,
+    h_video: 0x006C_02EC,
+    v_video: 0x0023_01FD,
+    v_burst: 0x000E_0204,
+};
+
+const PRESET_MPAL_I: ViPreset = ViPreset {
+    burst: 0x0465_1E39,
+    v_sync: 0x0000_020C,
+    h_sync: 0x0000_0C10,
+    h_sync_leap: 0x0C1C_0C1C,
+    h_video: 0x006C_02EC,
+    v_video: 0x0023_01FD,
+    v_burst: 0x000B_0202,
+};
+
+pub fn tv_type() -> u32 {
+    unsafe { OS_TV_TYPE.read_volatile() }
+}
+
+pub fn init_vi(fb_phys: u32, width: u32, height: u32, interlaced: bool) {
+    let preset = match (tv_type(), interlaced) {
+        (0, false) => PRESET_PAL_P,
+        (0, true) => PRESET_PAL_I,
+        (2, false) => PRESET_MPAL_P,
+        (2, true) => PRESET_MPAL_I,
+        (_, false) => PRESET_NTSC_P,
+        (_, true) => PRESET_NTSC_I,
+    };
+
+    let mut ctrl = VI_PIXEL_ADVANCE_DEFAULT | VI_AA_MODE_NONE | VI_CTRL_TYPE_16_BPP;
+    if interlaced {
+        ctrl |= VI_CTRL_SERRATE;
+    }
+
+    let x_scale = (1024 * width + 320) / 640;
+    let y_scale = (1024 * height + 120) / 240;
+
+    unsafe {
+        VI_CTRL.write_volatile(0);
+        VI_ORIGIN.write_volatile(fb_phys & 0x00FF_FFFF);
+        VI_WIDTH.write_volatile(width);
+        VI_V_INTR.write_volatile(2);
+        VI_BURST.write_volatile(preset.burst);
+        VI_V_SYNC.write_volatile(preset.v_sync);
+        VI_H_SYNC.write_volatile(preset.h_sync);
+        VI_H_SYNC_LEAP.write_volatile(preset.h_sync_leap);
+        VI_H_VIDEO.write_volatile(preset.h_video);
+        VI_V_VIDEO.write_volatile(preset.v_video);
+        VI_V_BURST.write_volatile(preset.v_burst);
+        VI_X_SCALE.write_volatile(x_scale);
+        VI_Y_SCALE.write_volatile(y_scale);
+        VI_CTRL.write_volatile(ctrl);
+    }
+}
+
+#[inline(always)]
+pub fn v_current() -> u32 {
+    unsafe { VI_V_CURRENT.read_volatile() }
+}
+
+/// Wait for the top vertical blanking interval and swap framebuffer origin.
+pub fn wait_vblank_and_swap(fb_phys: u32, width: u32, interlaced: bool) {
+    // If currently in top blank (< 32), wait out until active scanout begins so we don't double-flip.
+    while v_current() < 32 {}
+    // Wait until active scanout ends and top blanking (< 32) begins.
+    while v_current() >= 32 {}
+
+    let field_offset = if interlaced && (v_current() & 1) == 0 {
+        width * 2
+    } else {
+        0
+    };
+    unsafe {
+        VI_ORIGIN.write_volatile((fb_phys + field_offset) & 0x00FF_FFFF);
+    }
+}

+ 8 - 0
crates/shader-core/Cargo.toml

@@ -0,0 +1,8 @@
+[package]
+name = "shader-core"
+version = "0.1.0"
+edition = "2021"
+license = "MIT OR Apache-2.0"
+
+[dependencies]
+heapless = "0.8"

+ 1671 - 0
crates/shader-core/src/compiler.rs

@@ -0,0 +1,1671 @@
+//! Graph-to-RDP Compiler & Software Reference Combiner Evaluator.
+//!
+//! Compiles a `NodeGraph` into a real 64-bit Nintendo 64 `G_SETCOMBINE` (`0xFC`)
+//! command word plus pipeline state (Cycle 1 vs Cycle 2, PRIM/ENV colors,
+//! texture configurations, Fresnel vertex alpha, and blender mode).
+
+use crate::graph::{BlendMode, NodeGraph, NodeId, NodeType, PinId, TexPattern};
+use heapless::{String, Vec};
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum CycleCount {
+    OneCycle,
+    TwoCycle,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub struct TexConfig {
+    pub pattern: TexPattern,
+    pub scroll_x: i8,
+    pub scroll_y: i8,
+    pub env_map: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CompiledShader {
+    pub combine_cmd: u64,
+    pub cycles: CycleCount,
+    pub prim_color: [u8; 4],
+    pub prim_lod_frac: u8,
+    pub env_color: [u8; 4],
+    pub tex0: Option<TexConfig>,
+    pub tex1: Option<TexConfig>,
+    pub uses_shade: bool,
+    pub uses_fresnel: bool,
+    pub fresnel_power: u8,
+    pub fresnel_bias: u8,
+    pub blend_mode: BlendMode,
+    pub cycle1_text: String<40>,
+    pub cycle2_text: String<40>,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum CompileError {
+    MissingOutput,
+    UnconnectedOutput(NodeId),
+    CycleDetected(NodeId),
+    ExceedsTwoCycles(NodeId),
+    Cycle2Tex0Quirk(NodeId),
+    InvalidSlot { node: NodeId, reason: &'static str },
+}
+
+impl CompileError {
+    pub fn offending_node(&self) -> Option<NodeId> {
+        match *self {
+            Self::MissingOutput => None,
+            Self::UnconnectedOutput(n)
+            | Self::CycleDetected(n)
+            | Self::ExceedsTwoCycles(n)
+            | Self::Cycle2Tex0Quirk(n)
+            | Self::InvalidSlot { node: n, .. } => Some(n),
+        }
+    }
+
+    pub const fn summary(&self) -> &'static str {
+        match self {
+            Self::MissingOutput => "MISSING OUTPUT NODE",
+            Self::UnconnectedOutput(_) => "OUTPUT COL NOT WIRED",
+            Self::CycleDetected(_) => "GRAPH CYCLE DETECTED",
+            Self::ExceedsTwoCycles(_) => "EXCEEDS 2 RDP CYCLES",
+            Self::Cycle2Tex0Quirk(_) => "CYC2 TEX0 HW QUIRK",
+            Self::InvalidSlot { reason, .. } => reason,
+        }
+    }
+}
+
+/// Hardware mux source tokens (abstracted before Cycle-1 vs Cycle-2 code encoding).
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+enum RgbSrc {
+    Combined,
+    Tex0,
+    Tex1,
+    Prim,
+    Shade,
+    Env,
+    One,
+    Noise,
+    Zero,
+    Tex0Alpha,
+    Tex1Alpha,
+    PrimAlpha,
+    ShadeAlpha,
+    EnvAlpha,
+    PrimLodFrac,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+enum AlphaSrc {
+    Combined,
+    Tex0,
+    Tex1,
+    Prim,
+    Shade,
+    Env,
+    One,
+    Zero,
+    PrimLodFrac,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+struct RgbStage {
+    a: RgbSrc,
+    b: RgbSrc,
+    c: RgbSrc,
+    d: RgbSrc,
+}
+
+impl RgbStage {
+    const fn pass_combined() -> Self {
+        Self {
+            a: RgbSrc::Zero,
+            b: RgbSrc::Zero,
+            c: RgbSrc::Zero,
+            d: RgbSrc::Combined,
+        }
+    }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+struct AlphaStage {
+    a: AlphaSrc,
+    b: AlphaSrc,
+    c: AlphaSrc,
+    d: AlphaSrc,
+}
+
+impl AlphaStage {
+    const fn pass_one() -> Self {
+        Self {
+            a: AlphaSrc::Zero,
+            b: AlphaSrc::Zero,
+            c: AlphaSrc::Zero,
+            d: AlphaSrc::One,
+        }
+    }
+
+    const fn pass_combined() -> Self {
+        Self {
+            a: AlphaSrc::Zero,
+            b: AlphaSrc::Zero,
+            c: AlphaSrc::Zero,
+            d: AlphaSrc::Combined,
+        }
+    }
+}
+
+impl RgbSrc {
+    fn is_alpha_only(self) -> bool {
+        matches!(
+            self,
+            Self::Tex0Alpha
+                | Self::Tex1Alpha
+                | Self::PrimAlpha
+                | Self::ShadeAlpha
+                | Self::EnvAlpha
+                | Self::PrimLodFrac
+        )
+    }
+
+    fn label(self) -> &'static str {
+        match self {
+            Self::Combined => "CMB",
+            Self::Tex0 => "T0",
+            Self::Tex1 => "T1",
+            Self::Prim => "PRM",
+            Self::Shade => "SHD",
+            Self::Env => "ENV",
+            Self::One => "1",
+            Self::Noise => "NSE",
+            Self::Zero => "0",
+            Self::Tex0Alpha => "T0a",
+            Self::Tex1Alpha => "T1a",
+            Self::PrimAlpha => "PRMa",
+            Self::ShadeAlpha => "SHDa",
+            Self::EnvAlpha => "ENVa",
+            Self::PrimLodFrac => "PLOD",
+        }
+    }
+
+    fn encode_a(self, cyc2: bool, node: NodeId) -> Result<u64, CompileError> {
+        match (cyc2, self) {
+            (false, Self::Combined) => Err(CompileError::InvalidSlot {
+                node,
+                reason: "COMBINED ONLY IN CYC2",
+            }),
+            (true, Self::Tex0) | (true, Self::Tex0Alpha) => Err(CompileError::Cycle2Tex0Quirk(node)),
+            (_, Self::Combined) => Ok(0),
+            (false, Self::Tex0) => Ok(1),
+            (false, Self::Tex1) => Ok(2),
+            (true, Self::Tex1) => Ok(1),
+            (_, Self::Prim) => Ok(3),
+            (_, Self::Shade) => Ok(4),
+            (_, Self::Env) => Ok(5),
+            (_, Self::One) => Ok(6),
+            (_, Self::Noise) => Ok(7),
+            (_, Self::Zero) => Ok(8),
+            _ => Err(CompileError::InvalidSlot {
+                node,
+                reason: "BAD SLOT A INPUT",
+            }),
+        }
+    }
+
+    fn encode_b(self, cyc2: bool, node: NodeId) -> Result<u64, CompileError> {
+        match (cyc2, self) {
+            (false, Self::Combined) => Err(CompileError::InvalidSlot {
+                node,
+                reason: "COMBINED ONLY IN CYC2",
+            }),
+            (true, Self::Tex0) | (true, Self::Tex0Alpha) => Err(CompileError::Cycle2Tex0Quirk(node)),
+            (_, Self::Combined) => Ok(0),
+            (false, Self::Tex0) => Ok(1),
+            (false, Self::Tex1) => Ok(2),
+            (true, Self::Tex1) => Ok(1),
+            (_, Self::Prim) => Ok(3),
+            (_, Self::Shade) => Ok(4),
+            (_, Self::Env) => Ok(5),
+            (_, Self::Zero) => Ok(8),
+            _ => Err(CompileError::InvalidSlot {
+                node,
+                reason: "BAD SLOT B INPUT",
+            }),
+        }
+    }
+
+    fn encode_c(self, cyc2: bool, node: NodeId) -> Result<u64, CompileError> {
+        match (cyc2, self) {
+            (false, Self::Combined) => Err(CompileError::InvalidSlot {
+                node,
+                reason: "COMBINED ONLY IN CYC2",
+            }),
+            (true, Self::Tex0) | (true, Self::Tex0Alpha) => Err(CompileError::Cycle2Tex0Quirk(node)),
+            (_, Self::Combined) => Ok(0),
+            (false, Self::Tex0) => Ok(1),
+            (false, Self::Tex1) => Ok(2),
+            (true, Self::Tex1) => Ok(1),
+            (_, Self::Prim) => Ok(3),
+            (_, Self::Shade) => Ok(4),
+            (_, Self::Env) => Ok(5),
+            (false, Self::Tex0Alpha) => Ok(8),
+            (false, Self::Tex1Alpha) => Ok(9),
+            (true, Self::Tex1Alpha) => Ok(8),
+            (_, Self::PrimAlpha) => Ok(10),
+            (_, Self::ShadeAlpha) => Ok(11),
+            (_, Self::EnvAlpha) => Ok(12),
+            (_, Self::PrimLodFrac) => Ok(14),
+            (_, Self::Zero) => Ok(16),
+            _ => Err(CompileError::InvalidSlot {
+                node,
+                reason: "BAD SLOT C INPUT",
+            }),
+        }
+    }
+
+    fn encode_d(self, cyc2: bool, node: NodeId) -> Result<u64, CompileError> {
+        match (cyc2, self) {
+            (false, Self::Combined) => Err(CompileError::InvalidSlot {
+                node,
+                reason: "COMBINED ONLY IN CYC2",
+            }),
+            (true, Self::Tex0) | (true, Self::Tex0Alpha) => Err(CompileError::Cycle2Tex0Quirk(node)),
+            (_, Self::Combined) => Ok(0),
+            (false, Self::Tex0) => Ok(1),
+            (false, Self::Tex1) => Ok(2),
+            (true, Self::Tex1) => Ok(1),
+            (_, Self::Prim) => Ok(3),
+            (_, Self::Shade) => Ok(4),
+            (_, Self::Env) => Ok(5),
+            (_, Self::One) => Ok(6),
+            (_, Self::Zero) => Ok(7),
+            _ => Err(CompileError::InvalidSlot {
+                node,
+                reason: "BAD SLOT D INPUT",
+            }),
+        }
+    }
+}
+
+impl AlphaSrc {
+    fn encode_abd(self, cyc2: bool, node: NodeId) -> Result<u64, CompileError> {
+        match (cyc2, self) {
+            (false, Self::Combined) => Err(CompileError::InvalidSlot {
+                node,
+                reason: "COMBINED ONLY IN CYC2",
+            }),
+            (true, Self::Tex0) => Err(CompileError::Cycle2Tex0Quirk(node)),
+            (_, Self::Combined) => Ok(0),
+            (false, Self::Tex0) => Ok(1),
+            (false, Self::Tex1) => Ok(2),
+            (true, Self::Tex1) => Ok(1),
+            (_, Self::Prim) => Ok(3),
+            (_, Self::Shade) => Ok(4),
+            (_, Self::Env) => Ok(5),
+            (_, Self::One) => Ok(6),
+            (_, Self::Zero) => Ok(7),
+            (_, Self::PrimLodFrac) => Err(CompileError::InvalidSlot {
+                node,
+                reason: "PLOD ONLY IN ALPHA C",
+            }),
+        }
+    }
+
+    fn encode_c(self, cyc2: bool, node: NodeId) -> Result<u64, CompileError> {
+        match (cyc2, self) {
+            (true, Self::Tex0) => Err(CompileError::Cycle2Tex0Quirk(node)),
+            (false, Self::Tex0) => Ok(1),
+            (false, Self::Tex1) => Ok(2),
+            (true, Self::Tex1) => Ok(1),
+            (_, Self::Prim) => Ok(3),
+            (_, Self::Shade) => Ok(4),
+            (_, Self::Env) => Ok(5),
+            (_, Self::PrimLodFrac) => Ok(6),
+            (_, Self::Zero) => Ok(7),
+            _ => Err(CompileError::InvalidSlot {
+                node,
+                reason: "BAD ALPHA C INPUT",
+            }),
+        }
+    }
+}
+
+struct CompileCtx {
+    prim_color: Option<[u8; 4]>,
+    prim_lod_frac: Option<u8>,
+    env_color: Option<[u8; 4]>,
+    tex0: Option<TexConfig>,
+    tex1: Option<TexConfig>,
+    uses_shade: bool,
+    fresnel: Option<(u8, u8)>,
+    visiting: Vec<NodeId, 32>,
+}
+
+impl CompileCtx {
+    fn new() -> Self {
+        Self {
+            prim_color: None,
+            prim_lod_frac: None,
+            env_color: None,
+            tex0: None,
+            tex1: None,
+            uses_shade: false,
+            fresnel: None,
+            visiting: Vec::new(),
+        }
+    }
+
+    fn set_prim(&mut self, rgba: [u8; 4], node: NodeId) -> Result<(), CompileError> {
+        if let Some(prev) = self.prim_color {
+            if prev != rgba {
+                return Err(CompileError::InvalidSlot {
+                    node,
+                    reason: "CONFLICTING PRIM COLOR",
+                });
+            }
+        }
+        self.prim_color = Some(rgba);
+        Ok(())
+    }
+
+    fn set_env(&mut self, rgba: [u8; 4], node: NodeId) -> Result<(), CompileError> {
+        if let Some(prev) = self.env_color {
+            if prev != rgba {
+                return Err(CompileError::InvalidSlot {
+                    node,
+                    reason: "CONFLICTING ENV COLOR",
+                });
+            }
+        }
+        self.env_color = Some(rgba);
+        Ok(())
+    }
+
+    fn set_lod_frac(&mut self, val: u8, node: NodeId) -> Result<(), CompileError> {
+        if let Some(prev) = self.prim_lod_frac {
+            if prev != val {
+                return Err(CompileError::InvalidSlot {
+                    node,
+                    reason: "TWO MIX FACTORS USED",
+                });
+            }
+        }
+        self.prim_lod_frac = Some(val);
+        Ok(())
+    }
+}
+
+#[derive(Copy, Clone, Debug)]
+enum Expr {
+    Leaf(RgbSrc, NodeId),
+    Stage {
+        node: NodeId,
+        stage: RgbStage,
+        child: Option<(NodeId, RgbStage)>,
+    },
+}
+
+#[derive(Copy, Clone, Debug)]
+enum AlphaExpr {
+    Leaf(AlphaSrc, NodeId),
+    Stage {
+        node: NodeId,
+        stage: AlphaStage,
+        child: Option<(NodeId, AlphaStage)>,
+    },
+}
+
+fn pin_to_rgb_leaf(graph: &NodeGraph, pin: PinId, ctx: &mut CompileCtx) -> Result<RgbSrc, CompileError> {
+    let node = graph.node(pin.node).ok_or(CompileError::MissingOutput)?;
+    match node.kind {
+        NodeType::Texture0 {
+            pattern,
+            scroll_x,
+            scroll_y,
+            env_map,
+        } => {
+            ctx.tex0 = Some(TexConfig {
+                pattern,
+                scroll_x,
+                scroll_y,
+                env_map,
+            });
+            Ok(if pin.slot == 1 {
+                RgbSrc::Tex0Alpha
+            } else {
+                RgbSrc::Tex0
+            })
+        }
+        NodeType::Texture1 {
+            pattern,
+            scroll_x,
+            scroll_y,
+            env_map,
+        } => {
+            ctx.tex1 = Some(TexConfig {
+                pattern,
+                scroll_x,
+                scroll_y,
+                env_map,
+            });
+            Ok(if pin.slot == 1 {
+                RgbSrc::Tex1Alpha
+            } else {
+                RgbSrc::Tex1
+            })
+        }
+        NodeType::VertexColor => {
+            ctx.uses_shade = true;
+            Ok(if pin.slot == 1 {
+                RgbSrc::ShadeAlpha
+            } else {
+                RgbSrc::Shade
+            })
+        }
+        NodeType::PrimColor { rgba } => {
+            ctx.set_prim(rgba, node.id)?;
+            Ok(if pin.slot == 1 {
+                RgbSrc::PrimAlpha
+            } else {
+                RgbSrc::Prim
+            })
+        }
+        NodeType::EnvColor { rgba } => {
+            ctx.set_env(rgba, node.id)?;
+            Ok(if pin.slot == 1 {
+                RgbSrc::EnvAlpha
+            } else {
+                RgbSrc::Env
+            })
+        }
+        NodeType::Noise => Ok(RgbSrc::Noise),
+        NodeType::Fresnel { power, bias } => {
+            ctx.uses_shade = true;
+            ctx.fresnel = Some((power, bias));
+            Ok(RgbSrc::ShadeAlpha)
+        }
+        _ => Err(CompileError::InvalidSlot {
+            node: node.id,
+            reason: "UNEXPECTED LEAF NODE",
+        }),
+    }
+}
+
+fn pin_to_alpha_leaf(graph: &NodeGraph, pin: PinId, ctx: &mut CompileCtx) -> Result<AlphaSrc, CompileError> {
+    let node = graph.node(pin.node).ok_or(CompileError::MissingOutput)?;
+    match node.kind {
+        NodeType::Texture0 {
+            pattern,
+            scroll_x,
+            scroll_y,
+            env_map,
+        } => {
+            ctx.tex0 = Some(TexConfig {
+                pattern,
+                scroll_x,
+                scroll_y,
+                env_map,
+            });
+            Ok(AlphaSrc::Tex0)
+        }
+        NodeType::Texture1 {
+            pattern,
+            scroll_x,
+            scroll_y,
+            env_map,
+        } => {
+            ctx.tex1 = Some(TexConfig {
+                pattern,
+                scroll_x,
+                scroll_y,
+                env_map,
+            });
+            Ok(AlphaSrc::Tex1)
+        }
+        NodeType::VertexColor => {
+            ctx.uses_shade = true;
+            Ok(AlphaSrc::Shade)
+        }
+        NodeType::PrimColor { rgba } => {
+            ctx.set_prim(rgba, node.id)?;
+            Ok(AlphaSrc::Prim)
+        }
+        NodeType::EnvColor { rgba } => {
+            ctx.set_env(rgba, node.id)?;
+            Ok(AlphaSrc::Env)
+        }
+        NodeType::Fresnel { power, bias } => {
+            ctx.uses_shade = true;
+            ctx.fresnel = Some((power, bias));
+            Ok(AlphaSrc::Shade)
+        }
+        _ => Err(CompileError::InvalidSlot {
+            node: node.id,
+            reason: "INVALID ALPHA INPUT",
+        }),
+    }
+}
+
+fn stage_mul_rgb(x: RgbSrc, y: RgbSrc, node: NodeId) -> Result<RgbStage, CompileError> {
+    // `(A - 0) * C + 0`: Noise and normal colors prefer `A`; alpha-only sources MUST go in `C`.
+    let (a, c) = if x.is_alpha_only() && !y.is_alpha_only() {
+        (y, x)
+    } else if y == RgbSrc::Noise && x != RgbSrc::Noise && !x.is_alpha_only() {
+        (y, x)
+    } else if x.is_alpha_only() && y.is_alpha_only() {
+        return Err(CompileError::InvalidSlot {
+            node,
+            reason: "CANNOT MUL TWO ALPHAS",
+        });
+    } else if x == RgbSrc::Noise && y == RgbSrc::Noise {
+        return Err(CompileError::InvalidSlot {
+            node,
+            reason: "CANNOT MUL NOISE*NOISE",
+        });
+    } else {
+        (x, y)
+    };
+    Ok(RgbStage {
+        a,
+        b: RgbSrc::Zero,
+        c,
+        d: RgbSrc::Zero,
+    })
+}
+
+fn stage_add_rgb(x: RgbSrc, y: RgbSrc, node: NodeId) -> Result<RgbStage, CompileError> {
+    // `(1 - 0) * C + D`: `C` can hold alpha sources or colors (not Noise), `D` can hold colors (not Noise or alpha-only).
+    let (c, d) = if (y.is_alpha_only() || x == RgbSrc::Noise) && !x.is_alpha_only() && y != RgbSrc::Noise {
+        (y, x)
+    } else if x == RgbSrc::Noise && y == RgbSrc::Noise {
+        return Err(CompileError::InvalidSlot {
+            node,
+            reason: "CANNOT ADD NOISE+NOISE",
+        });
+    } else if x.is_alpha_only() && y.is_alpha_only() {
+        return Err(CompileError::InvalidSlot {
+            node,
+            reason: "CANNOT ADD TWO ALPHAS",
+        });
+    } else {
+        (x, y)
+    };
+    if c == RgbSrc::Noise || d == RgbSrc::Noise || d.is_alpha_only() {
+        return Err(CompileError::InvalidSlot {
+            node,
+            reason: "INVALID ADD OPERANDS",
+        });
+    }
+    Ok(RgbStage {
+        a: RgbSrc::One,
+        b: RgbSrc::Zero,
+        c,
+        d,
+    })
+}
+
+fn stage_fma_rgb(
+    mul_x: RgbSrc,
+    mul_y: RgbSrc,
+    add_z: RgbSrc,
+    node: NodeId,
+) -> Result<RgbStage, CompileError> {
+    let mul = stage_mul_rgb(mul_x, mul_y, node)?;
+    if add_z == RgbSrc::Noise || add_z.is_alpha_only() {
+        return Err(CompileError::InvalidSlot {
+            node,
+            reason: "INVALID FMA ADDEND",
+        });
+    }
+    Ok(RgbStage {
+        a: mul.a,
+        b: RgbSrc::Zero,
+        c: mul.c,
+        d: add_z,
+    })
+}
+
+fn stage_mix_rgb(
+    a_val: RgbSrc,
+    b_val: RgbSrc,
+    t_val: RgbSrc,
+    const_factor: Option<u8>,
+    ctx: &mut CompileCtx,
+    node: NodeId,
+) -> Result<RgbStage, CompileError> {
+    // Standard lerp: `(B - A) * T + A`.
+    // If `A == Noise` (only valid in slot A) and `T` is constant, swap to `(Noise - B) * (1 - T) + B`.
+    if a_val == RgbSrc::Noise {
+        if let Some(f) = const_factor {
+            ctx.set_lod_frac(255u8.saturating_sub(f), node)?;
+            return Ok(RgbStage {
+                a: RgbSrc::Noise,
+                b: b_val,
+                c: RgbSrc::PrimLodFrac,
+                d: b_val,
+            });
+        }
+        return Err(CompileError::InvalidSlot {
+            node,
+            reason: "NOISE INVALID IN MIX A",
+        });
+    }
+    if a_val.is_alpha_only() || b_val.is_alpha_only() {
+        return Err(CompileError::InvalidSlot {
+            node,
+            reason: "ALPHA ONLY IN MIX INPUT",
+        });
+    }
+    if let Some(f) = const_factor {
+        ctx.set_lod_frac(f, node)?;
+    }
+    Ok(RgbStage {
+        a: b_val,
+        b: a_val,
+        c: t_val,
+        d: a_val,
+    })
+}
+
+fn compile_rgb_expr(
+    graph: &NodeGraph,
+    pin: PinId,
+    ctx: &mut CompileCtx,
+) -> Result<Expr, CompileError> {
+    if ctx.visiting.contains(&pin.node) {
+        return Err(CompileError::CycleDetected(pin.node));
+    }
+    let node = graph.node(pin.node).ok_or(CompileError::MissingOutput)?;
+    ctx.visiting
+        .push(node.id)
+        .map_err(|_| CompileError::ExceedsTwoCycles(node.id))?;
+
+    let res = match node.kind {
+        NodeType::Texture0 { .. }
+        | NodeType::Texture1 { .. }
+        | NodeType::VertexColor
+        | NodeType::PrimColor { .. }
+        | NodeType::EnvColor { .. }
+        | NodeType::Noise
+        | NodeType::Fresnel { .. } => {
+            let src = pin_to_rgb_leaf(graph, pin, ctx)?;
+            Ok(Expr::Leaf(src, node.id))
+        }
+        NodeType::Multiply => {
+            let p0 = graph
+                .input_source(node.id, 0)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "MUL INPUT A UNWIRED",
+                })?;
+            let p1 = graph
+                .input_source(node.id, 1)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "MUL INPUT B UNWIRED",
+                })?;
+            let e0 = compile_rgb_expr(graph, p0, ctx)?;
+            let e1 = compile_rgb_expr(graph, p1, ctx)?;
+            match (e0, e1) {
+                (Expr::Leaf(x, _), Expr::Leaf(y, _)) => Ok(Expr::Stage {
+                    node: node.id,
+                    stage: stage_mul_rgb(x, y, node.id)?,
+                    child: None,
+                }),
+                (
+                    Expr::Stage {
+                        node: cnode,
+                        stage: cstage,
+                        child: None,
+                    },
+                    Expr::Leaf(y, _),
+                ) => Ok(Expr::Stage {
+                    node: node.id,
+                    stage: stage_mul_rgb(RgbSrc::Combined, y, node.id)?,
+                    child: Some((cnode, cstage)),
+                }),
+                (
+                    Expr::Leaf(x, _),
+                    Expr::Stage {
+                        node: cnode,
+                        stage: cstage,
+                        child: None,
+                    },
+                ) => Ok(Expr::Stage {
+                    node: node.id,
+                    stage: stage_mul_rgb(x, RgbSrc::Combined, node.id)?,
+                    child: Some((cnode, cstage)),
+                }),
+                _ => Err(CompileError::ExceedsTwoCycles(node.id)),
+            }
+        }
+        NodeType::Add => {
+            let p0 = graph
+                .input_source(node.id, 0)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "ADD INPUT A UNWIRED",
+                })?;
+            let p1 = graph
+                .input_source(node.id, 1)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "ADD INPUT B UNWIRED",
+                })?;
+            let e0 = compile_rgb_expr(graph, p0, ctx)?;
+            let e1 = compile_rgb_expr(graph, p1, ctx)?;
+            match (e0, e1) {
+                (Expr::Leaf(x, _), Expr::Leaf(y, _)) => Ok(Expr::Stage {
+                    node: node.id,
+                    stage: stage_add_rgb(x, y, node.id)?,
+                    child: None,
+                }),
+                // Fuse `Add(Multiply(x, y), z)` into 1 cycle if `Multiply` has no child!
+                (
+                    Expr::Stage {
+                        node: cnode,
+                        stage: cstage,
+                        child: None,
+                    },
+                    Expr::Leaf(z, _),
+                ) => {
+                    let cnode_ref = graph.node(cnode).ok_or(CompileError::MissingOutput)?;
+                    if matches!(cnode_ref.kind, NodeType::Multiply)
+                        && cstage.d == RgbSrc::Zero
+                        && cstage.b == RgbSrc::Zero
+                    {
+                        if let Ok(fma) = stage_fma_rgb(cstage.a, cstage.c, z, node.id) {
+                            return {
+                                ctx.visiting.pop();
+                                Ok(Expr::Stage {
+                                    node: node.id,
+                                    stage: fma,
+                                    child: None,
+                                })
+                            };
+                        }
+                    }
+                    Ok(Expr::Stage {
+                        node: node.id,
+                        stage: stage_add_rgb(RgbSrc::Combined, z, node.id)?,
+                        child: Some((cnode, cstage)),
+                    })
+                }
+                (
+                    Expr::Leaf(z, _),
+                    Expr::Stage {
+                        node: cnode,
+                        stage: cstage,
+                        child: None,
+                    },
+                ) => {
+                    let cnode_ref = graph.node(cnode).ok_or(CompileError::MissingOutput)?;
+                    if matches!(cnode_ref.kind, NodeType::Multiply)
+                        && cstage.d == RgbSrc::Zero
+                        && cstage.b == RgbSrc::Zero
+                    {
+                        if let Ok(fma) = stage_fma_rgb(cstage.a, cstage.c, z, node.id) {
+                            return {
+                                ctx.visiting.pop();
+                                Ok(Expr::Stage {
+                                    node: node.id,
+                                    stage: fma,
+                                    child: None,
+                                })
+                            };
+                        }
+                    }
+                    Ok(Expr::Stage {
+                        node: node.id,
+                        stage: stage_add_rgb(z, RgbSrc::Combined, node.id)?,
+                        child: Some((cnode, cstage)),
+                    })
+                }
+                _ => Err(CompileError::ExceedsTwoCycles(node.id)),
+            }
+        }
+        NodeType::Mix { factor } => {
+            let p0 = graph
+                .input_source(node.id, 0)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "MIX INPUT A UNWIRED",
+                })?;
+            let p1 = graph
+                .input_source(node.id, 1)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "MIX INPUT B UNWIRED",
+                })?;
+            let e0 = compile_rgb_expr(graph, p0, ctx)?;
+            let e1 = compile_rgb_expr(graph, p1, ctx)?;
+
+            let (t_src, const_fac) = if let Some(pt) = graph.input_source(node.id, 2) {
+                match compile_rgb_expr(graph, pt, ctx)? {
+                    Expr::Leaf(t, _) => (t, None),
+                    Expr::Stage { .. } => return Err(CompileError::ExceedsTwoCycles(node.id)),
+                }
+            } else {
+                (RgbSrc::PrimLodFrac, Some(factor))
+            };
+
+            match (e0, e1) {
+                (Expr::Leaf(a_val, _), Expr::Leaf(b_val, _)) => Ok(Expr::Stage {
+                    node: node.id,
+                    stage: stage_mix_rgb(a_val, b_val, t_src, const_fac, ctx, node.id)?,
+                    child: None,
+                }),
+                (
+                    Expr::Stage {
+                        node: cnode,
+                        stage: cstage,
+                        child: None,
+                    },
+                    Expr::Leaf(b_val, _),
+                ) => Ok(Expr::Stage {
+                    node: node.id,
+                    stage: stage_mix_rgb(RgbSrc::Combined, b_val, t_src, const_fac, ctx, node.id)?,
+                    child: Some((cnode, cstage)),
+                }),
+                (
+                    Expr::Leaf(a_val, _),
+                    Expr::Stage {
+                        node: cnode,
+                        stage: cstage,
+                        child: None,
+                    },
+                ) => Ok(Expr::Stage {
+                    node: node.id,
+                    stage: stage_mix_rgb(a_val, RgbSrc::Combined, t_src, const_fac, ctx, node.id)?,
+                    child: Some((cnode, cstage)),
+                }),
+                _ => Err(CompileError::ExceedsTwoCycles(node.id)),
+            }
+        }
+        NodeType::Output { .. } => Err(CompileError::CycleDetected(node.id)),
+    };
+
+    ctx.visiting.pop();
+    res
+}
+
+fn compile_alpha_expr(
+    graph: &NodeGraph,
+    pin: PinId,
+    ctx: &mut CompileCtx,
+) -> Result<AlphaExpr, CompileError> {
+    if ctx.visiting.contains(&pin.node) {
+        return Err(CompileError::CycleDetected(pin.node));
+    }
+    let node = graph.node(pin.node).ok_or(CompileError::MissingOutput)?;
+    ctx.visiting
+        .push(node.id)
+        .map_err(|_| CompileError::ExceedsTwoCycles(node.id))?;
+
+    let res = match node.kind {
+        NodeType::Texture0 { .. }
+        | NodeType::Texture1 { .. }
+        | NodeType::VertexColor
+        | NodeType::PrimColor { .. }
+        | NodeType::EnvColor { .. }
+        | NodeType::Fresnel { .. } => Ok(AlphaExpr::Leaf(pin_to_alpha_leaf(graph, pin, ctx)?, node.id)),
+        NodeType::Multiply => {
+            let p0 = graph
+                .input_source(node.id, 0)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "ALPHA MUL A UNWIRED",
+                })?;
+            let p1 = graph
+                .input_source(node.id, 1)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "ALPHA MUL B UNWIRED",
+                })?;
+            let e0 = compile_alpha_expr(graph, p0, ctx)?;
+            let e1 = compile_alpha_expr(graph, p1, ctx)?;
+            match (e0, e1) {
+                (AlphaExpr::Leaf(x, _), AlphaExpr::Leaf(y, _)) => Ok(AlphaExpr::Stage {
+                    node: node.id,
+                    stage: AlphaStage {
+                        a: x,
+                        b: AlphaSrc::Zero,
+                        c: y,
+                        d: AlphaSrc::Zero,
+                    },
+                    child: None,
+                }),
+                (
+                    AlphaExpr::Stage {
+                        node: cnode,
+                        stage: cstage,
+                        child: None,
+                    },
+                    AlphaExpr::Leaf(y, _),
+                ) => Ok(AlphaExpr::Stage {
+                    node: node.id,
+                    stage: AlphaStage {
+                        a: AlphaSrc::Combined,
+                        b: AlphaSrc::Zero,
+                        c: y,
+                        d: AlphaSrc::Zero,
+                    },
+                    child: Some((cnode, cstage)),
+                }),
+                _ => Err(CompileError::ExceedsTwoCycles(node.id)),
+            }
+        }
+        NodeType::Add => {
+            let p0 = graph
+                .input_source(node.id, 0)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "ALPHA ADD A UNWIRED",
+                })?;
+            let p1 = graph
+                .input_source(node.id, 1)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "ALPHA ADD B UNWIRED",
+                })?;
+            let e0 = compile_alpha_expr(graph, p0, ctx)?;
+            let e1 = compile_alpha_expr(graph, p1, ctx)?;
+            match (e0, e1) {
+                (AlphaExpr::Leaf(x, _), AlphaExpr::Leaf(y, _)) => Ok(AlphaExpr::Stage {
+                    node: node.id,
+                    stage: AlphaStage {
+                        a: AlphaSrc::One,
+                        b: AlphaSrc::Zero,
+                        c: x,
+                        d: y,
+                    },
+                    child: None,
+                }),
+                _ => Err(CompileError::ExceedsTwoCycles(node.id)),
+            }
+        }
+        NodeType::Mix { factor } => {
+            let p0 = graph
+                .input_source(node.id, 0)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "ALPHA MIX A UNWIRED",
+                })?;
+            let p1 = graph
+                .input_source(node.id, 1)
+                .ok_or(CompileError::InvalidSlot {
+                    node: node.id,
+                    reason: "ALPHA MIX B UNWIRED",
+                })?;
+            let e0 = compile_alpha_expr(graph, p0, ctx)?;
+            let e1 = compile_alpha_expr(graph, p1, ctx)?;
+            ctx.set_lod_frac(factor, node.id)?;
+            match (e0, e1) {
+                (AlphaExpr::Leaf(a_val, _), AlphaExpr::Leaf(b_val, _)) => Ok(AlphaExpr::Stage {
+                    node: node.id,
+                    stage: AlphaStage {
+                        a: b_val,
+                        b: a_val,
+                        c: AlphaSrc::PrimLodFrac,
+                        d: a_val,
+                    },
+                    child: None,
+                }),
+                _ => Err(CompileError::ExceedsTwoCycles(node.id)),
+            }
+        }
+        _ => Err(CompileError::InvalidSlot {
+            node: node.id,
+            reason: "INVALID ALPHA NODE",
+        }),
+    };
+
+    ctx.visiting.pop();
+    res
+}
+
+fn format_stage(stage: RgbStage) -> String<40> {
+    use core::fmt::Write;
+    let mut s = String::new();
+    let _ = write!(
+        s,
+        "({}-{})*{}+{}",
+        stage.a.label(),
+        stage.b.label(),
+        stage.c.label(),
+        stage.d.label()
+    );
+    s
+}
+
+#[allow(clippy::too_many_arguments)]
+fn pack_set_combine(
+    rgb0: RgbStage,
+    n_rgb0: NodeId,
+    alp0: AlphaStage,
+    n_alp0: NodeId,
+    rgb1: RgbStage,
+    n_rgb1: NodeId,
+    alp1: AlphaStage,
+    n_alp1: NodeId,
+    two_cycle: bool,
+) -> Result<u64, CompileError> {
+    let a0 = rgb0.a.encode_a(false, n_rgb0)?;
+    let b0 = rgb0.b.encode_b(false, n_rgb0)?;
+    let c0 = rgb0.c.encode_c(false, n_rgb0)?;
+    let d0 = rgb0.d.encode_d(false, n_rgb0)?;
+    let aa0 = alp0.a.encode_abd(false, n_alp0)?;
+    let ba0 = alp0.b.encode_abd(false, n_alp0)?;
+    let ca0 = alp0.c.encode_c(false, n_alp0)?;
+    let da0 = alp0.d.encode_abd(false, n_alp0)?;
+
+    let (a1, b1, c1, d1, aa1, ba1, ca1, da1) = if two_cycle {
+        (
+            rgb1.a.encode_a(true, n_rgb1)?,
+            rgb1.b.encode_b(true, n_rgb1)?,
+            rgb1.c.encode_c(true, n_rgb1)?,
+            rgb1.d.encode_d(true, n_rgb1)?,
+            alp1.a.encode_abd(true, n_alp1)?,
+            alp1.b.encode_abd(true, n_alp1)?,
+            alp1.c.encode_c(true, n_alp1)?,
+            alp1.d.encode_abd(true, n_alp1)?,
+        )
+    } else {
+        // Real hardware requires Cycle 2 fields to mirror Cycle 1 in 1-cycle mode.
+        (a0, b0, c0, d0, aa0, ba0, ca0, da0)
+    };
+
+    Ok((0xFCu64 << 56)
+        | (a0 << 52)
+        | (c0 << 47)
+        | (aa0 << 44)
+        | (ca0 << 41)
+        | (a1 << 37)
+        | (c1 << 32)
+        | (b0 << 28)
+        | (b1 << 24)
+        | (aa1 << 21)
+        | (ca1 << 18)
+        | (d0 << 15)
+        | (ba0 << 12)
+        | (da0 << 9)
+        | (d1 << 6)
+        | (ba1 << 3)
+        | da1)
+}
+
+/// Compile a `NodeGraph` into a hardware N64 RDP shader configuration.
+pub fn compile(graph: &NodeGraph) -> Result<CompiledShader, CompileError> {
+    let out_id = graph.find_output().ok_or(CompileError::MissingOutput)?;
+    let out_node = graph.node(out_id).ok_or(CompileError::MissingOutput)?;
+    let blend_mode = match out_node.kind {
+        NodeType::Output { blend_mode } => blend_mode,
+        _ => BlendMode::Opaque,
+    };
+
+    let col_pin = graph
+        .input_source(out_id, 0)
+        .ok_or(CompileError::UnconnectedOutput(out_id))?;
+
+    let mut ctx = CompileCtx::new();
+    let rgb_expr = compile_rgb_expr(graph, col_pin, &mut ctx)?;
+
+    let alpha_expr = if let Some(alp_pin) = graph.input_source(out_id, 1) {
+        Some(compile_alpha_expr(graph, alp_pin, &mut ctx)?)
+    } else {
+        None
+    };
+
+    // Determine whether 2-cycle mode is required.
+    let rgb_needs_2cyc = matches!(
+        rgb_expr,
+        Expr::Stage {
+            child: Some(_),
+            ..
+        }
+    );
+    let alpha_needs_2cyc = matches!(
+        alpha_expr,
+        Some(AlphaExpr::Stage {
+            child: Some(_),
+            ..
+        })
+    );
+    let two_cycle = rgb_needs_2cyc || alpha_needs_2cyc;
+
+    // Lower RGB stages.
+    let (rgb0, n_rgb0, rgb1, n_rgb1) = match rgb_expr {
+        Expr::Leaf(src, n) => {
+            let st = if src == RgbSrc::Noise {
+                // Noise is only in A; if PrimColor unused, set Prim=white to multiply by 1.0.
+                if ctx.prim_color.is_none() {
+                    ctx.prim_color = Some([255, 255, 255, 255]);
+                }
+                RgbStage {
+                    a: RgbSrc::Noise,
+                    b: RgbSrc::Zero,
+                    c: RgbSrc::Prim,
+                    d: RgbSrc::Zero,
+                }
+            } else if src.is_alpha_only() {
+                RgbStage {
+                    a: RgbSrc::One,
+                    b: RgbSrc::Zero,
+                    c: src,
+                    d: RgbSrc::Zero,
+                }
+            } else {
+                RgbStage {
+                    a: RgbSrc::Zero,
+                    b: RgbSrc::Zero,
+                    c: RgbSrc::Zero,
+                    d: src,
+                }
+            };
+            if two_cycle {
+                // Put leaf in Cycle 1 and pass Combined in Cycle 2 (avoids TEX0 bug in Cyc2!).
+                (st, n, RgbStage::pass_combined(), out_id)
+            } else {
+                (st, n, st, n)
+            }
+        }
+        Expr::Stage {
+            node,
+            stage,
+            child: None,
+        } => {
+            if two_cycle {
+                (stage, node, RgbStage::pass_combined(), out_id)
+            } else {
+                (stage, node, stage, node)
+            }
+        }
+        Expr::Stage {
+            node,
+            stage,
+            child: Some((cnode, cstage)),
+        } => (cstage, cnode, stage, node),
+    };
+
+    // Lower Alpha stages.
+    let (alp0, n_alp0, alp1, n_alp1) = match alpha_expr {
+        None => {
+            let st = AlphaStage::pass_one();
+            (st, out_id, st, out_id)
+        }
+        Some(AlphaExpr::Leaf(src, n)) => {
+            let st = AlphaStage {
+                a: AlphaSrc::Zero,
+                b: AlphaSrc::Zero,
+                c: AlphaSrc::Zero,
+                d: src,
+            };
+            if two_cycle {
+                (st, n, AlphaStage::pass_combined(), out_id)
+            } else {
+                (st, n, st, n)
+            }
+        }
+        Some(AlphaExpr::Stage {
+            node,
+            stage,
+            child: None,
+        }) => {
+            if two_cycle {
+                (stage, node, AlphaStage::pass_combined(), out_id)
+            } else {
+                (stage, node, stage, node)
+            }
+        }
+        Some(AlphaExpr::Stage {
+            node,
+            stage,
+            child: Some((cnode, cstage)),
+        }) => (cstage, cnode, stage, node),
+    };
+
+    let combine_cmd = pack_set_combine(
+        rgb0, n_rgb0, alp0, n_alp0, rgb1, n_rgb1, alp1, n_alp1, two_cycle,
+    )?;
+
+    let cycle1_text = format_stage(rgb0);
+    let mut cycle2_text = String::new();
+    if two_cycle {
+        cycle2_text = format_stage(rgb1);
+    } else {
+        let _ = cycle2_text.push_str("1-CYC PASS");
+    }
+
+    let (fresnel_power, fresnel_bias) = ctx.fresnel.unwrap_or((2, 0));
+
+    Ok(CompiledShader {
+        combine_cmd,
+        cycles: if two_cycle {
+            CycleCount::TwoCycle
+        } else {
+            CycleCount::OneCycle
+        },
+        prim_color: ctx.prim_color.unwrap_or([255, 255, 255, 255]),
+        prim_lod_frac: ctx.prim_lod_frac.unwrap_or(128),
+        env_color: ctx.env_color.unwrap_or([255, 255, 255, 255]),
+        tex0: ctx.tex0,
+        tex1: ctx.tex1,
+        uses_shade: ctx.uses_shade,
+        uses_fresnel: ctx.fresnel.is_some(),
+        fresnel_power,
+        fresnel_bias,
+        blend_mode,
+        cycle1_text,
+        cycle2_text,
+    })
+}
+
+/// Software reference evaluator for raw 64-bit `G_SETCOMBINE` (`0xFC`) words.
+/// Used by unit tests to verify the packed hardware bitfields end-to-end.
+#[derive(Copy, Clone, Debug)]
+pub struct CombinerInputs {
+    pub tex0: [u8; 4],
+    pub tex1: [u8; 4],
+    pub prim: [u8; 4],
+    pub env: [u8; 4],
+    pub shade: [u8; 4],
+    pub noise: [u8; 4],
+    pub prim_lod_frac: u8,
+}
+
+pub fn eval_combine_word(combine_cmd: u64, two_cycle: bool, inp: &CombinerInputs) -> [u8; 4] {
+    let a0 = ((combine_cmd >> 52) & 0xF) as u8;
+    let c0 = ((combine_cmd >> 47) & 0x1F) as u8;
+    let aa0 = ((combine_cmd >> 44) & 0x7) as u8;
+    let ca0 = ((combine_cmd >> 41) & 0x7) as u8;
+    let a1 = ((combine_cmd >> 37) & 0xF) as u8;
+    let c1 = ((combine_cmd >> 32) & 0x1F) as u8;
+    let b0 = ((combine_cmd >> 28) & 0xF) as u8;
+    let b1 = ((combine_cmd >> 24) & 0xF) as u8;
+    let aa1 = ((combine_cmd >> 21) & 0x7) as u8;
+    let ca1 = ((combine_cmd >> 18) & 0x7) as u8;
+    let d0 = ((combine_cmd >> 15) & 0x7) as u8;
+    let ba0 = ((combine_cmd >> 12) & 0x7) as u8;
+    let da0 = ((combine_cmd >> 9) & 0x7) as u8;
+    let d1 = ((combine_cmd >> 6) & 0x7) as u8;
+    let ba1 = ((combine_cmd >> 3) & 0x7) as u8;
+    let da1 = (combine_cmd & 0x7) as u8;
+
+    let eval_rgb_code = |code: u8, cyc2: bool, comb: [i32; 4]| -> [i32; 3] {
+        match (cyc2, code) {
+            (true, 0) => [comb[0], comb[1], comb[2]],
+            (false, 1) => [inp.tex0[0] as i32, inp.tex0[1] as i32, inp.tex0[2] as i32],
+            (false, 2) | (true, 1) => [inp.tex1[0] as i32, inp.tex1[1] as i32, inp.tex1[2] as i32],
+            (_, 3) => [inp.prim[0] as i32, inp.prim[1] as i32, inp.prim[2] as i32],
+            (_, 4) => [inp.shade[0] as i32, inp.shade[1] as i32, inp.shade[2] as i32],
+            (_, 5) => [inp.env[0] as i32, inp.env[1] as i32, inp.env[2] as i32],
+            (_, 6) => [255, 255, 255],
+            (_, 7) if !cyc2 => [inp.noise[0] as i32, inp.noise[1] as i32, inp.noise[2] as i32],
+            (true, 7) => [comb[3], comb[3], comb[3]], // COMBINED_ALPHA in C
+            (false, 8) => [inp.tex0[3] as i32; 3],
+            (false, 9) | (true, 8) => [inp.tex1[3] as i32; 3],
+            (_, 10) => [inp.prim[3] as i32; 3],
+            (_, 11) => [inp.shade[3] as i32; 3],
+            (_, 12) => [inp.env[3] as i32; 3],
+            (_, 14) => [inp.prim_lod_frac as i32; 3],
+            _ => [0, 0, 0],
+        }
+    };
+
+    let eval_rgb_ab = |code: u8, cyc2: bool, comb: [i32; 4]| -> [i32; 3] {
+        match (cyc2, code) {
+            (_, 7) => [inp.noise[0] as i32, inp.noise[1] as i32, inp.noise[2] as i32],
+            (_, 8) => [0, 0, 0],
+            _ => eval_rgb_code(code, cyc2, comb),
+        }
+    };
+
+    let eval_rgb_d = |code: u8, cyc2: bool, comb: [i32; 4]| -> [i32; 3] {
+        if code == 7 {
+            [0, 0, 0]
+        } else {
+            eval_rgb_code(code, cyc2, comb)
+        }
+    };
+
+    let eval_alp = |code: u8, is_c: bool, cyc2: bool, comb: [i32; 4]| -> i32 {
+        match (cyc2, is_c, code) {
+            (true, false, 0) => comb[3],
+            (false, _, 1) => inp.tex0[3] as i32,
+            (false, _, 2) | (true, _, 1) => inp.tex1[3] as i32,
+            (_, _, 3) => inp.prim[3] as i32,
+            (_, _, 4) => inp.shade[3] as i32,
+            (_, _, 5) => inp.env[3] as i32,
+            (_, false, 6) => 255,
+            (_, true, 6) => inp.prim_lod_frac as i32,
+            (_, _, 7) => 0,
+            _ => 0,
+        }
+    };
+
+    let step = |cyc2: bool,
+                a: u8,
+                b: u8,
+                c: u8,
+                d: u8,
+                aa: u8,
+                ba: u8,
+                ca: u8,
+                da: u8,
+                comb: [i32; 4]|
+     -> [i32; 4] {
+        let va = eval_rgb_ab(a, cyc2, comb);
+        let vb = eval_rgb_ab(b, cyc2, comb);
+        let vc = eval_rgb_code(c, cyc2, comb);
+        let vd = eval_rgb_d(d, cyc2, comb);
+        let mut out = [0i32; 4];
+        for i in 0..3 {
+            let v = ((va[i] - vb[i]) * vc[i]) / 255 + vd[i];
+            out[i] = v.clamp(0, 255);
+        }
+        let vaa = eval_alp(aa, false, cyc2, comb);
+        let vba = eval_alp(ba, false, cyc2, comb);
+        let vca = eval_alp(ca, true, cyc2, comb);
+        let vda = eval_alp(da, false, cyc2, comb);
+        out[3] = (((vaa - vba) * vca) / 255 + vda).clamp(0, 255);
+        out
+    };
+
+    let cyc1_out = step(false, a0, b0, c0, d0, aa0, ba0, ca0, da0, [0; 4]);
+    let fin = if two_cycle {
+        step(true, a1, b1, c1, d1, aa1, ba1, ca1, da1, cyc1_out)
+    } else {
+        cyc1_out
+    };
+    [fin[0] as u8, fin[1] as u8, fin[2] as u8, fin[3] as u8]
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::graph::PinDir;
+
+    fn test_inputs() -> CombinerInputs {
+        CombinerInputs {
+            tex0: [200, 100, 50, 255],
+            tex1: [40, 80, 160, 200],
+            prim: [128, 255, 64, 180],
+            env: [10, 20, 240, 100],
+            shade: [200, 200, 200, 128],
+            noise: [90, 90, 90, 255],
+            prim_lod_frac: 128,
+        }
+    }
+
+    #[test]
+    fn compile_one_cycle_mul_and_eval() {
+        let mut g = NodeGraph::new();
+        let t0 = g
+            .add_node(
+                NodeType::Texture0 {
+                    pattern: TexPattern::ChromeEnv,
+                    scroll_x: 0,
+                    scroll_y: 0,
+                    env_map: false,
+                },
+                10,
+                20,
+            )
+            .unwrap();
+        let prim = g
+            .add_node(
+                NodeType::PrimColor {
+                    rgba: [128, 255, 64, 180],
+                },
+                10,
+                70,
+            )
+            .unwrap();
+        let mul = g.add_node(NodeType::Multiply, 70, 40).unwrap();
+        let out = g
+            .add_node(
+                NodeType::Output {
+                    blend_mode: BlendMode::Opaque,
+                },
+                140,
+                40,
+            )
+            .unwrap();
+
+        g.connect(
+            PinId { node: t0, slot: 0, dir: PinDir::Output },
+            PinId { node: mul, slot: 0, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: prim, slot: 0, dir: PinDir::Output },
+            PinId { node: mul, slot: 1, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: mul, slot: 0, dir: PinDir::Output },
+            PinId { node: out, slot: 0, dir: PinDir::Input },
+        );
+
+        let compiled = compile(&g).expect("should compile");
+        assert_eq!(compiled.cycles, CycleCount::OneCycle);
+        assert_eq!(compiled.combine_cmd >> 56, 0xFC);
+
+        let px = eval_combine_word(compiled.combine_cmd, false, &test_inputs());
+        // (200 * 128)/255 = 100, (100 * 255)/255 = 100, (50 * 64)/255 = 12
+        assert!((px[0] as i32 - 100).abs() <= 1);
+        assert!((px[1] as i32 - 100).abs() <= 1);
+        assert!((px[2] as i32 - 12).abs() <= 1);
+        assert_eq!(px[3], 255);
+    }
+
+    #[test]
+    fn compile_two_cycle_chrome_fresnel_mix() {
+        let mut g = NodeGraph::new();
+        let t0 = g
+            .add_node(
+                NodeType::Texture0 {
+                    pattern: TexPattern::ChromeEnv,
+                    scroll_x: 0,
+                    scroll_y: 0,
+                    env_map: true,
+                },
+                10,
+                20,
+            )
+            .unwrap();
+        let vtx = g.add_node(NodeType::VertexColor, 10, 60).unwrap();
+        let env = g
+            .add_node(
+                NodeType::EnvColor {
+                    rgba: [10, 20, 240, 255],
+                },
+                10,
+                100,
+            )
+            .unwrap();
+        let frs = g
+            .add_node(NodeType::Fresnel { power: 2, bias: 16 }, 10, 140)
+            .unwrap();
+        let mul = g.add_node(NodeType::Multiply, 70, 40).unwrap();
+        let mix = g.add_node(NodeType::Mix { factor: 128 }, 120, 80).unwrap();
+        let out = g
+            .add_node(
+                NodeType::Output {
+                    blend_mode: BlendMode::Opaque,
+                },
+                170,
+                80,
+            )
+            .unwrap();
+
+        g.connect(
+            PinId { node: t0, slot: 0, dir: PinDir::Output },
+            PinId { node: mul, slot: 0, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: vtx, slot: 0, dir: PinDir::Output },
+            PinId { node: mul, slot: 1, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: mul, slot: 0, dir: PinDir::Output },
+            PinId { node: mix, slot: 0, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: env, slot: 0, dir: PinDir::Output },
+            PinId { node: mix, slot: 1, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: frs, slot: 0, dir: PinDir::Output },
+            PinId { node: mix, slot: 2, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: mix, slot: 0, dir: PinDir::Output },
+            PinId { node: out, slot: 0, dir: PinDir::Input },
+        );
+
+        let compiled = compile(&g).expect("should compile");
+        assert_eq!(compiled.cycles, CycleCount::TwoCycle);
+        assert!(compiled.uses_fresnel);
+
+        let px = eval_combine_word(compiled.combine_cmd, true, &test_inputs());
+        // Cycle 1: tex0 * shade = (200*200/255, 100*200/255, 50*200/255) ~ (156, 78, 39)
+        // Cycle 2: lerp((156,78,39), (10,20,240), 128/255) ~ (83, 49, 139)
+        assert!((px[0] as i32 - 83).abs() <= 2);
+        assert!((px[1] as i32 - 49).abs() <= 2);
+        assert!((px[2] as i32 - 139).abs() <= 2);
+    }
+
+    #[test]
+    fn rejects_three_cycle_chain_with_exact_node() {
+        let mut g = NodeGraph::new();
+        let t0 = g
+            .add_node(
+                NodeType::Texture0 {
+                    pattern: TexPattern::ChromeEnv,
+                    scroll_x: 0,
+                    scroll_y: 0,
+                    env_map: false,
+                },
+                0,
+                0,
+            )
+            .unwrap();
+        let t1 = g
+            .add_node(
+                NodeType::Texture1 {
+                    pattern: TexPattern::LavaMagma,
+                    scroll_x: 0,
+                    scroll_y: 0,
+                    env_map: false,
+                },
+                0,
+                40,
+            )
+            .unwrap();
+        let p = g
+            .add_node(NodeType::PrimColor { rgba: [255; 4] }, 0, 80)
+            .unwrap();
+        let e = g
+            .add_node(NodeType::EnvColor { rgba: [255; 4] }, 0, 120)
+            .unwrap();
+        let m1 = g.add_node(NodeType::Multiply, 50, 20).unwrap();
+        let m2 = g.add_node(NodeType::Multiply, 90, 40).unwrap();
+        let m3 = g.add_node(NodeType::Multiply, 130, 60).unwrap();
+        let out = g
+            .add_node(
+                NodeType::Output {
+                    blend_mode: BlendMode::Opaque,
+                },
+                170,
+                60,
+            )
+            .unwrap();
+
+        g.connect(
+            PinId { node: t0, slot: 0, dir: PinDir::Output },
+            PinId { node: m1, slot: 0, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: t1, slot: 0, dir: PinDir::Output },
+            PinId { node: m1, slot: 1, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: m1, slot: 0, dir: PinDir::Output },
+            PinId { node: m2, slot: 0, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: p, slot: 0, dir: PinDir::Output },
+            PinId { node: m2, slot: 1, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: m2, slot: 0, dir: PinDir::Output },
+            PinId { node: m3, slot: 0, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: e, slot: 0, dir: PinDir::Output },
+            PinId { node: m3, slot: 1, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: m3, slot: 0, dir: PinDir::Output },
+            PinId { node: out, slot: 0, dir: PinDir::Input },
+        );
+
+        let err = compile(&g).unwrap_err();
+        assert_eq!(err, CompileError::ExceedsTwoCycles(m3));
+    }
+
+    #[test]
+    fn detects_cycle2_tex0_silicon_quirk() {
+        let mut g = NodeGraph::new();
+        let p = g
+            .add_node(NodeType::PrimColor { rgba: [200; 4] }, 0, 0)
+            .unwrap();
+        let e = g
+            .add_node(NodeType::EnvColor { rgba: [100; 4] }, 0, 40)
+            .unwrap();
+        let t0 = g
+            .add_node(
+                NodeType::Texture0 {
+                    pattern: TexPattern::ChromeEnv,
+                    scroll_x: 0,
+                    scroll_y: 0,
+                    env_map: false,
+                },
+                0,
+                80,
+            )
+            .unwrap();
+        let mix = g.add_node(NodeType::Mix { factor: 128 }, 60, 20).unwrap();
+        let mul = g.add_node(NodeType::Multiply, 110, 50).unwrap();
+        let out = g
+            .add_node(
+                NodeType::Output {
+                    blend_mode: BlendMode::Opaque,
+                },
+                160,
+                50,
+            )
+            .unwrap();
+
+        g.connect(
+            PinId { node: p, slot: 0, dir: PinDir::Output },
+            PinId { node: mix, slot: 0, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: e, slot: 0, dir: PinDir::Output },
+            PinId { node: mix, slot: 1, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: mix, slot: 0, dir: PinDir::Output },
+            PinId { node: mul, slot: 0, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: t0, slot: 0, dir: PinDir::Output },
+            PinId { node: mul, slot: 1, dir: PinDir::Input },
+        );
+        g.connect(
+            PinId { node: mul, slot: 0, dir: PinDir::Output },
+            PinId { node: out, slot: 0, dir: PinDir::Input },
+        );
+
+        let err = compile(&g).unwrap_err();
+        assert_eq!(err, CompileError::Cycle2Tex0Quirk(mul));
+    }
+}

+ 167 - 0
crates/shader-core/src/font.rs

@@ -0,0 +1,167 @@
+//! Crisp pure-Rust 4x6 bitmap font for 320x240 and 640x480 RGBA5551 rendering.
+
+pub const GLYPH_W: usize = 4;
+pub const GLYPH_H: usize = 6;
+pub const GLYPH_ADV: usize = 5;
+
+/// Each glyph is 6 rows x 4 pixels packed as 6 nibbles (`row 0` in bits `23..20`, `row 5` in bits `3..0`).
+#[inline]
+const fn g(r0: u8, r1: u8, r2: u8, r3: u8, r4: u8, r5: u8) -> u32 {
+    ((r0 as u32 & 0xF) << 20)
+        | ((r1 as u32 & 0xF) << 16)
+        | ((r2 as u32 & 0xF) << 12)
+        | ((r3 as u32 & 0xF) << 8)
+        | ((r4 as u32 & 0xF) << 4)
+        | (r5 as u32 & 0xF)
+}
+
+#[rustfmt::skip]
+const FONT_4X6: [u32; 95] = [
+    g(0x0,0x0,0x0,0x0,0x0,0x0), // ' ' 32
+    g(0x4,0x4,0x4,0x4,0x0,0x4), // '!' 33
+    g(0xA,0xA,0x0,0x0,0x0,0x0), // '"' 34
+    g(0xA,0xF,0xA,0xF,0xA,0x0), // '#' 35
+    g(0x4,0xF,0xC,0x6,0xF,0x4), // '$' 36
+    g(0x9,0x2,0x4,0x8,0x9,0x0), // '%' 37
+    g(0x6,0x9,0x6,0x9,0x6,0x0), // '&' 38
+    g(0x4,0x4,0x0,0x0,0x0,0x0), // '\'' 39
+    g(0x2,0x4,0x4,0x4,0x2,0x0), // '(' 40
+    g(0x4,0x2,0x2,0x2,0x4,0x0), // ')' 41
+    g(0xA,0x4,0xE,0x4,0xA,0x0), // '*' 42
+    g(0x0,0x4,0xE,0x4,0x0,0x0), // '+' 43
+    g(0x0,0x0,0x0,0x0,0x4,0x8), // ',' 44
+    g(0x0,0x0,0xE,0x0,0x0,0x0), // '-' 45
+    g(0x0,0x0,0x0,0x0,0x4,0x0), // '.' 46
+    g(0x1,0x2,0x4,0x8,0x0,0x0), // '/' 47
+    g(0x6,0x9,0xB,0xD,0x6,0x0), // '0' 48
+    g(0x4,0xC,0x4,0x4,0xE,0x0), // '1' 49
+    g(0x6,0x9,0x2,0x4,0xF,0x0), // '2' 50
+    g(0xE,0x1,0x6,0x1,0xE,0x0), // '3' 51
+    g(0x9,0x9,0xF,0x1,0x1,0x0), // '4' 52
+    g(0xF,0x8,0xE,0x1,0xE,0x0), // '5' 53
+    g(0x7,0x8,0xE,0x9,0x6,0x0), // '6' 54
+    g(0xF,0x1,0x2,0x4,0x4,0x0), // '7' 55
+    g(0x6,0x9,0x6,0x9,0x6,0x0), // '8' 56
+    g(0x6,0x9,0x7,0x1,0xE,0x0), // '9' 57
+    g(0x0,0x4,0x0,0x4,0x0,0x0), // ':' 58
+    g(0x0,0x4,0x0,0x4,0x8,0x0), // ';' 59
+    g(0x2,0x4,0x8,0x4,0x2,0x0), // '<' 60
+    g(0x0,0xE,0x0,0xE,0x0,0x0), // '=' 61
+    g(0x8,0x4,0x2,0x4,0x8,0x0), // '>' 62
+    g(0x6,0x9,0x2,0x0,0x2,0x0), // '?' 63
+    g(0x6,0xB,0xB,0x8,0x7,0x0), // '@' 64
+    g(0x6,0x9,0xF,0x9,0x9,0x0), // 'A' 65
+    g(0xE,0x9,0xE,0x9,0xE,0x0), // 'B' 66
+    g(0x7,0x8,0x8,0x8,0x7,0x0), // 'C' 67
+    g(0xE,0x9,0x9,0x9,0xE,0x0), // 'D' 68
+    g(0xF,0x8,0xE,0x8,0xF,0x0), // 'E' 69
+    g(0xF,0x8,0xE,0x8,0x8,0x0), // 'F' 70
+    g(0x7,0x8,0xB,0x9,0x7,0x0), // 'G' 71
+    g(0x9,0x9,0xF,0x9,0x9,0x0), // 'H' 72
+    g(0xE,0x4,0x4,0x4,0xE,0x0), // 'I' 73
+    g(0x1,0x1,0x1,0x9,0x6,0x0), // 'J' 74
+    g(0x9,0xA,0xC,0xA,0x9,0x0), // 'K' 75
+    g(0x8,0x8,0x8,0x8,0xF,0x0), // 'L' 76
+    g(0x9,0xF,0x9,0x9,0x9,0x0), // 'M' 77
+    g(0x9,0xD,0xB,0x9,0x9,0x0), // 'N' 78
+    g(0x6,0x9,0x9,0x9,0x6,0x0), // 'O' 79
+    g(0xE,0x9,0xE,0x8,0x8,0x0), // 'P' 80
+    g(0x6,0x9,0x9,0xB,0x7,0x0), // 'Q' 81
+    g(0xE,0x9,0xE,0xA,0x9,0x0), // 'R' 82
+    g(0x7,0x8,0x6,0x1,0xE,0x0), // 'S' 83
+    g(0xE,0x4,0x4,0x4,0x4,0x0), // 'T' 84
+    g(0x9,0x9,0x9,0x9,0x6,0x0), // 'U' 85
+    g(0x9,0x9,0x9,0x6,0x6,0x0), // 'V' 86
+    g(0x9,0x9,0x9,0xF,0x9,0x0), // 'W' 87
+    g(0x9,0x6,0x6,0x6,0x9,0x0), // 'X' 88
+    g(0x9,0x9,0x6,0x4,0x4,0x0), // 'Y' 89
+    g(0xF,0x2,0x4,0x8,0xF,0x0), // 'Z' 90
+    g(0xE,0x8,0x8,0x8,0xE,0x0), // '[' 91
+    g(0x8,0x4,0x2,0x1,0x0,0x0), // '\' 92
+    g(0xE,0x2,0x2,0x2,0xE,0x0), // ']' 93
+    g(0x4,0xA,0x0,0x0,0x0,0x0), // '^' 94
+    g(0x0,0x0,0x0,0x0,0xF,0x0), // '_' 95
+    g(0x4,0x2,0x0,0x0,0x0,0x0), // '`' 96
+    g(0x0,0x6,0xA,0xA,0x7,0x0), // 'a' 97
+    g(0x8,0xE,0x9,0x9,0xE,0x0), // 'b' 98
+    g(0x0,0x7,0x8,0x8,0x7,0x0), // 'c' 99
+    g(0x1,0x7,0x9,0x9,0x7,0x0), // 'd' 100
+    g(0x0,0x6,0xF,0x8,0x7,0x0), // 'e' 101
+    g(0x3,0x4,0xE,0x4,0x4,0x0), // 'f' 102
+    g(0x0,0x7,0x9,0x7,0x1,0xE), // 'g' 103
+    g(0x8,0xE,0x9,0x9,0x9,0x0), // 'h' 104
+    g(0x4,0x0,0x4,0x4,0x4,0x0), // 'i' 105
+    g(0x2,0x0,0x2,0x2,0xA,0x4), // 'j' 106
+    g(0x8,0x9,0xE,0xA,0x9,0x0), // 'k' 107
+    g(0xC,0x4,0x4,0x4,0xE,0x0), // 'l' 108
+    g(0x0,0xF,0xF,0x9,0x9,0x0), // 'm' 109
+    g(0x0,0xE,0x9,0x9,0x9,0x0), // 'n' 110
+    g(0x0,0x6,0x9,0x9,0x6,0x0), // 'o' 111
+    g(0x0,0xE,0x9,0xE,0x8,0x8), // 'p' 112
+    g(0x0,0x7,0x9,0x7,0x1,0x1), // 'q' 113
+    g(0x0,0x6,0x9,0x8,0x8,0x0), // 'r' 114
+    g(0x0,0x7,0xC,0x2,0xE,0x0), // 's' 115
+    g(0x4,0xE,0x4,0x4,0x3,0x0), // 't' 116
+    g(0x0,0x9,0x9,0x9,0x7,0x0), // 'u' 117
+    g(0x0,0x9,0x9,0x6,0x6,0x0), // 'v' 118
+    g(0x0,0x9,0x9,0xF,0x6,0x0), // 'w' 119
+    g(0x0,0x9,0x6,0x6,0x9,0x0), // 'x' 120
+    g(0x0,0x9,0x9,0x7,0x1,0xE), // 'y' 121
+    g(0x0,0xF,0x2,0x4,0xF,0x0), // 'z' 122
+    g(0x3,0x4,0xC,0x4,0x3,0x0), // '{' 123
+    g(0x4,0x4,0x4,0x4,0x4,0x0), // '|' 124
+    g(0xC,0x2,0x3,0x2,0xC,0x0), // '}' 125
+    g(0x5,0xA,0x0,0x0,0x0,0x0), // '~' 126
+];
+
+pub fn draw_text_scaled(
+    fb: &mut [u16],
+    fb_w: usize,
+    fb_h: usize,
+    x: i16,
+    y: i16,
+    text: &str,
+    color: u16,
+    scale: usize,
+) {
+    let scale = scale.max(1);
+    let mut cx = x as i32;
+    let y = y as i32;
+    for b in text.bytes() {
+        let idx = if (32..=126).contains(&b) {
+            (b - 32) as usize
+        } else {
+            0
+        };
+        let glyph = FONT_4X6[idx];
+        for row in 0..GLYPH_H {
+            let nibble = (glyph >> ((5 - row) * 4)) & 0xF;
+            if nibble == 0 {
+                continue;
+            }
+            for col in 0..GLYPH_W {
+                if ((nibble >> (3 - col)) & 1) != 0 {
+                    for sy in 0..scale {
+                        let py = y + (row * scale + sy) as i32;
+                        if py < 0 || py >= fb_h as i32 {
+                            continue;
+                        }
+                        let row_off = (py as usize) * fb_w;
+                        for sx in 0..scale {
+                            let px = cx + (col * scale + sx) as i32;
+                            if px >= 0 && px < fb_w as i32 {
+                                fb[row_off + px as usize] = color;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        cx += (GLYPH_ADV * scale) as i32;
+    }
+}
+
+#[inline]
+pub fn draw_text(fb: &mut [u16], fb_w: usize, fb_h: usize, x: i16, y: i16, text: &str, color: u16) {
+    draw_text_scaled(fb, fb_w, fb_h, x, y, text, color, 1);
+}

+ 411 - 0
crates/shader-core/src/graph.rs

@@ -0,0 +1,411 @@
+//! Zero-heap Node Graph data model for N64 Node Shader Studio.
+
+use heapless::Vec;
+
+pub const MAX_NODES: usize = 32;
+pub const MAX_WIRES: usize = 64;
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub struct NodeId(pub u8);
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum PinDir {
+    Input,
+    Output,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub struct PinId {
+    pub node: NodeId,
+    pub slot: u8,
+    pub dir: PinDir,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum TexPattern {
+    ChromeEnv = 0,
+    LavaMagma = 1,
+    WaterCaustics = 2,
+    HoloScanlines = 3,
+    ToonChecker = 4,
+    BrickDetail = 5,
+}
+
+impl TexPattern {
+    pub const ALL: [TexPattern; 6] = [
+        TexPattern::ChromeEnv,
+        TexPattern::LavaMagma,
+        TexPattern::WaterCaustics,
+        TexPattern::HoloScanlines,
+        TexPattern::ToonChecker,
+        TexPattern::BrickDetail,
+    ];
+
+    pub fn from_u8(v: u8) -> Self {
+        match v % 6 {
+            0 => Self::ChromeEnv,
+            1 => Self::LavaMagma,
+            2 => Self::WaterCaustics,
+            3 => Self::HoloScanlines,
+            4 => Self::ToonChecker,
+            _ => Self::BrickDetail,
+        }
+    }
+
+    pub const fn short_name(self) -> &'static str {
+        match self {
+            Self::ChromeEnv => "CHROME",
+            Self::LavaMagma => "LAVA",
+            Self::WaterCaustics => "CAUSTIC",
+            Self::HoloScanlines => "SCANLN",
+            Self::ToonChecker => "TOON",
+            Self::BrickDetail => "BRICK",
+        }
+    }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum BlendMode {
+    Opaque = 0,
+    Translucent = 1,
+    Additive = 2,
+}
+
+impl BlendMode {
+    pub fn from_u8(v: u8) -> Self {
+        match v % 3 {
+            0 => Self::Opaque,
+            1 => Self::Translucent,
+            _ => Self::Additive,
+        }
+    }
+
+    pub const fn short_name(self) -> &'static str {
+        match self {
+            Self::Opaque => "OPAQUE",
+            Self::Translucent => "ALPHA",
+            Self::Additive => "ADD",
+        }
+    }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum NodeType {
+    Texture0 {
+        pattern: TexPattern,
+        scroll_x: i8,
+        scroll_y: i8,
+        env_map: bool,
+    },
+    Texture1 {
+        pattern: TexPattern,
+        scroll_x: i8,
+        scroll_y: i8,
+        env_map: bool,
+    },
+    VertexColor,
+    PrimColor {
+        rgba: [u8; 4],
+    },
+    EnvColor {
+        rgba: [u8; 4],
+    },
+    Noise,
+    Mix {
+        factor: u8,
+    },
+    Multiply,
+    Add,
+    Fresnel {
+        power: u8,
+        bias: u8,
+    },
+    Output {
+        blend_mode: BlendMode,
+    },
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum NodeCategory {
+    Input,
+    Math,
+    Output,
+}
+
+impl NodeType {
+    pub const fn title(&self) -> &'static str {
+        match self {
+            Self::Texture0 { .. } => "TEX0",
+            Self::Texture1 { .. } => "TEX1",
+            Self::VertexColor => "VTX COL",
+            Self::PrimColor { .. } => "PRIM",
+            Self::EnvColor { .. } => "ENV",
+            Self::Noise => "NOISE",
+            Self::Mix { .. } => "MIX",
+            Self::Multiply => "MUL",
+            Self::Add => "ADD",
+            Self::Fresnel { .. } => "FRESNEL",
+            Self::Output { .. } => "OUTPUT",
+        }
+    }
+
+    pub const fn category(&self) -> NodeCategory {
+        match self {
+            Self::Texture0 { .. }
+            | Self::Texture1 { .. }
+            | Self::VertexColor
+            | Self::PrimColor { .. }
+            | Self::EnvColor { .. }
+            | Self::Noise
+            | Self::Fresnel { .. } => NodeCategory::Input,
+            Self::Mix { .. } | Self::Multiply | Self::Add => NodeCategory::Math,
+            Self::Output { .. } => NodeCategory::Output,
+        }
+    }
+
+    pub const fn input_count(&self) -> u8 {
+        match self {
+            Self::Mix { .. } => 3,
+            Self::Multiply | Self::Add | Self::Output { .. } => 2,
+            _ => 0,
+        }
+    }
+
+    pub const fn output_count(&self) -> u8 {
+        match self {
+            Self::Texture0 { .. }
+            | Self::Texture1 { .. }
+            | Self::VertexColor
+            | Self::PrimColor { .. }
+            | Self::EnvColor { .. } => 2,
+            Self::Noise | Self::Mix { .. } | Self::Multiply | Self::Add | Self::Fresnel { .. } => {
+                1
+            }
+            Self::Output { .. } => 0,
+        }
+    }
+
+    pub const fn input_label(&self, slot: u8) -> &'static str {
+        match (self, slot) {
+            (Self::Mix { .. }, 0) => "A",
+            (Self::Mix { .. }, 1) => "B",
+            (Self::Mix { .. }, 2) => "T",
+            (Self::Multiply, 0) | (Self::Add, 0) => "A",
+            (Self::Multiply, 1) | (Self::Add, 1) => "B",
+            (Self::Output { .. }, 0) => "COL",
+            (Self::Output { .. }, 1) => "ALP",
+            _ => "",
+        }
+    }
+
+    pub const fn output_label(&self, slot: u8) -> &'static str {
+        match (self, slot) {
+            (Self::Texture0 { .. }, 0)
+            | (Self::Texture1 { .. }, 0)
+            | (Self::VertexColor, 0)
+            | (Self::PrimColor { .. }, 0)
+            | (Self::EnvColor { .. }, 0) => "RGB",
+            (Self::Texture0 { .. }, 1)
+            | (Self::Texture1 { .. }, 1)
+            | (Self::VertexColor, 1)
+            | (Self::PrimColor { .. }, 1)
+            | (Self::EnvColor { .. }, 1) => "A",
+            (Self::Fresnel { .. }, 0) => "FAC",
+            (Self::Noise, 0) | (Self::Mix { .. }, 0) | (Self::Multiply, 0) | (Self::Add, 0) => {
+                "OUT"
+            }
+            _ => "",
+        }
+    }
+
+    /// Logical box size `(width, height)` in 320x240 logical coordinates.
+    pub const fn size(&self) -> (i16, i16) {
+        let rows = if self.input_count() > self.output_count() {
+            self.input_count()
+        } else {
+            self.output_count()
+        };
+        let extra = match self {
+            Self::PrimColor { .. }
+            | Self::EnvColor { .. }
+            | Self::Texture0 { .. }
+            | Self::Texture1 { .. }
+            | Self::Mix { .. }
+            | Self::Fresnel { .. }
+            | Self::Output { .. } => 8,
+            _ => 0,
+        };
+        let h = 14 + (rows as i16) * 10 + extra;
+        let w = match self {
+            Self::Texture0 { .. } | Self::Texture1 { .. } | Self::Fresnel { .. } => 56,
+            Self::VertexColor | Self::Output { .. } => 54,
+            _ => 48,
+        };
+        (w, h)
+    }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub struct Node {
+    pub id: NodeId,
+    pub kind: NodeType,
+    pub x: i16,
+    pub y: i16,
+}
+
+impl Node {
+    pub fn pin_pos(&self, slot: u8, dir: PinDir) -> (i16, i16) {
+        let (w, _) = self.kind.size();
+        let px = match dir {
+            PinDir::Input => self.x,
+            PinDir::Output => self.x + w,
+        };
+        let py = self.y + 18 + (slot as i16) * 10;
+        (px, py)
+    }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub struct Wire {
+    pub from: PinId,
+    pub to: PinId,
+}
+
+#[derive(Clone, Debug)]
+pub struct NodeGraph {
+    pub nodes: Vec<Node, MAX_NODES>,
+    pub wires: Vec<Wire, MAX_WIRES>,
+    pub is_dirty: bool,
+    next_id: u8,
+}
+
+impl Default for NodeGraph {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl NodeGraph {
+    pub fn new() -> Self {
+        Self {
+            nodes: Vec::new(),
+            wires: Vec::new(),
+            is_dirty: true,
+            next_id: 1,
+        }
+    }
+
+    pub fn clear(&mut self) {
+        self.nodes.clear();
+        self.wires.clear();
+        self.next_id = 1;
+        self.is_dirty = true;
+    }
+
+    pub fn add_node(&mut self, kind: NodeType, x: i16, y: i16) -> Option<NodeId> {
+        if matches!(kind, NodeType::Output { .. }) && self.find_output().is_some() {
+            return None;
+        }
+        let id = NodeId(self.next_id);
+        self.next_id = self.next_id.wrapping_add(1).max(1);
+        self.nodes
+            .push(Node { id, kind, x, y })
+            .ok()
+            .map(|()| {
+                self.is_dirty = true;
+                id
+            })
+    }
+
+    /// Insert a node with an explicit ID (used by deserialization).
+    pub fn insert_with_id(&mut self, id: NodeId, kind: NodeType, x: i16, y: i16) -> bool {
+        if self.node(id).is_some() {
+            return false;
+        }
+        if self.nodes.push(Node { id, kind, x, y }).is_ok() {
+            if id.0 >= self.next_id {
+                self.next_id = id.0.wrapping_add(1).max(1);
+            }
+            self.is_dirty = true;
+            true
+        } else {
+            false
+        }
+    }
+
+    pub fn remove_node(&mut self, id: NodeId) -> bool {
+        let Some(pos) = self.nodes.iter().position(|n| n.id == id) else {
+            return false;
+        };
+        if matches!(self.nodes[pos].kind, NodeType::Output { .. }) {
+            return false;
+        }
+        self.nodes.swap_remove(pos);
+        self.wires
+            .retain(|w| w.from.node != id && w.to.node != id);
+        self.is_dirty = true;
+        true
+    }
+
+    pub fn connect(&mut self, from: PinId, to: PinId) -> bool {
+        if from.dir != PinDir::Output || to.dir != PinDir::Input {
+            return false;
+        }
+        if from.node == to.node {
+            return false;
+        }
+        let Some(src) = self.node(from.node) else {
+            return false;
+        };
+        let Some(dst) = self.node(to.node) else {
+            return false;
+        };
+        if from.slot >= src.kind.output_count() || to.slot >= dst.kind.input_count() {
+            return false;
+        }
+        // Single driver per input pin: remove any existing wire to `to`.
+        self.wires.retain(|w| w.to != to);
+        if self.wires.push(Wire { from, to }).is_ok() {
+            self.is_dirty = true;
+            true
+        } else {
+            false
+        }
+    }
+
+    pub fn disconnect_input(&mut self, to: PinId) -> bool {
+        let before = self.wires.len();
+        self.wires.retain(|w| w.to != to);
+        if self.wires.len() != before {
+            self.is_dirty = true;
+            true
+        } else {
+            false
+        }
+    }
+
+    pub fn find_output(&self) -> Option<NodeId> {
+        self.nodes
+            .iter()
+            .find(|n| matches!(n.kind, NodeType::Output { .. }))
+            .map(|n| n.id)
+    }
+
+    pub fn node(&self, id: NodeId) -> Option<&Node> {
+        self.nodes.iter().find(|n| n.id == id)
+    }
+
+    pub fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
+        self.is_dirty = true;
+        self.nodes.iter_mut().find(|n| n.id == id)
+    }
+
+    pub fn input_source(&self, node: NodeId, slot: u8) -> Option<PinId> {
+        self.wires
+            .iter()
+            .find(|w| w.to.node == node && w.to.slot == slot)
+            .map(|w| w.from)
+    }
+}

+ 11 - 0
crates/shader-core/src/lib.rs

@@ -0,0 +1,11 @@
+#![cfg_attr(not(test), no_std)]
+
+pub mod compiler;
+pub mod font;
+pub mod graph;
+pub mod math;
+pub mod mesh;
+pub mod presets;
+pub mod storage;
+pub mod textures;
+pub mod ui;

+ 355 - 0
crates/shader-core/src/math.rs

@@ -0,0 +1,355 @@
+//! Pure `#[no_std]` math, vector/matrix operations, and RGBA5551 color helpers.
+
+pub const PI: f32 = 3.141592653589793;
+pub const TAU: f32 = 6.283185307179586;
+pub const HALF_PI: f32 = 1.5707963267948966;
+
+#[inline(always)]
+pub fn abs_f32(x: f32) -> f32 {
+    if x < 0.0 { -x } else { x }
+}
+
+#[inline(always)]
+pub fn min_f32(a: f32, b: f32) -> f32 {
+    if a < b { a } else { b }
+}
+
+#[inline(always)]
+pub fn max_f32(a: f32, b: f32) -> f32 {
+    if a > b { a } else { b }
+}
+
+#[inline(always)]
+pub fn clamp_f32(x: f32, lo: f32, hi: f32) -> f32 {
+    if x < lo {
+        lo
+    } else if x > hi {
+        hi
+    } else {
+        x
+    }
+}
+
+#[inline(always)]
+pub fn floor_f32(x: f32) -> f32 {
+    let i = x as i32;
+    let fi = i as f32;
+    if x < fi { fi - 1.0 } else { fi }
+}
+
+#[inline(always)]
+pub fn ceil_f32(x: f32) -> f32 {
+    let i = x as i32;
+    let fi = i as f32;
+    if x > fi { fi + 1.0 } else { fi }
+}
+
+/// Fast deterministic `sin(x)` using range reduction and a 7th-order polynomial.
+pub fn sin_f32(x: f32) -> f32 {
+    // Wrap to [-PI, PI]
+    let k = floor_f32((x + PI) / TAU);
+    let mut y = x - k * TAU;
+    if y > PI {
+        y -= TAU;
+    } else if y < -PI {
+        y += TAU;
+    }
+    // Fold into [-PI/2, PI/2]
+    if y > HALF_PI {
+        y = PI - y;
+    } else if y < -HALF_PI {
+        y = -PI - y;
+    }
+    let y2 = y * y;
+    // 7th-order Taylor/minimax approximation on [-PI/2, PI/2]
+    y * (1.0 - y2 * (0.16666667 - y2 * (0.008333333 - y2 * 0.0001984127)))
+}
+
+#[inline(always)]
+pub fn cos_f32(x: f32) -> f32 {
+    sin_f32(x + HALF_PI)
+}
+
+#[inline(always)]
+pub fn sin_cos_f32(x: f32) -> (f32, f32) {
+    (sin_f32(x), cos_f32(x))
+}
+
+/// Square root via bit-level initial guess + 3 Newton-Raphson iterations.
+pub fn sqrt_f32(x: f32) -> f32 {
+    if x <= 0.0 {
+        return 0.0;
+    }
+    let half = 0.5 * x;
+    let mut i = x.to_bits();
+    i = 0x5f3759df - (i >> 1);
+    let mut y = f32::from_bits(i);
+    y = y * (1.5 - half * y * y);
+    y = y * (1.5 - half * y * y);
+    y = y * (1.5 - half * y * y);
+    x * y
+}
+
+/// Inverse square root `1 / sqrt(x)`.
+pub fn inv_sqrt_f32(x: f32) -> f32 {
+    if x <= 1e-12 {
+        return 0.0;
+    }
+    let half = 0.5 * x;
+    let mut i = x.to_bits();
+    i = 0x5f3759df - (i >> 1);
+    let mut y = f32::from_bits(i);
+    y = y * (1.5 - half * y * y);
+    y = y * (1.5 - half * y * y);
+    y * (1.5 - half * y * y)
+}
+
+/// Integer power for small exponents (`0..=16`).
+pub fn pow_f32_u8(base: f32, exp: u8) -> f32 {
+    let mut acc = 1.0;
+    let mut b = base;
+    let mut e = exp;
+    while e > 0 {
+        if (e & 1) != 0 {
+            acc *= b;
+        }
+        e >>= 1;
+        if e > 0 {
+            b *= b;
+        }
+    }
+    acc
+}
+
+#[derive(Copy, Clone, Debug, Default, PartialEq)]
+pub struct Vec2 {
+    pub x: f32,
+    pub y: f32,
+}
+
+impl Vec2 {
+    #[inline(always)]
+    pub const fn new(x: f32, y: f32) -> Self {
+        Self { x, y }
+    }
+}
+
+#[derive(Copy, Clone, Debug, Default, PartialEq)]
+pub struct Vec3 {
+    pub x: f32,
+    pub y: f32,
+    pub z: f32,
+}
+
+impl Vec3 {
+    #[inline(always)]
+    pub const fn new(x: f32, y: f32, z: f32) -> Self {
+        Self { x, y, z }
+    }
+
+    #[inline(always)]
+    pub fn add(self, o: Self) -> Self {
+        Self::new(self.x + o.x, self.y + o.y, self.z + o.z)
+    }
+
+    #[inline(always)]
+    pub fn sub(self, o: Self) -> Self {
+        Self::new(self.x - o.x, self.y - o.y, self.z - o.z)
+    }
+
+    #[inline(always)]
+    pub fn scale(self, s: f32) -> Self {
+        Self::new(self.x * s, self.y * s, self.z * s)
+    }
+
+    #[inline(always)]
+    pub fn dot(self, o: Self) -> f32 {
+        self.x * o.x + self.y * o.y + self.z * o.z
+    }
+
+    #[inline(always)]
+    pub fn cross(self, o: Self) -> Self {
+        Self::new(
+            self.y * o.z - self.z * o.y,
+            self.z * o.x - self.x * o.z,
+            self.x * o.y - self.y * o.x,
+        )
+    }
+
+    #[inline(always)]
+    pub fn len_sq(self) -> f32 {
+        self.dot(self)
+    }
+
+    #[inline(always)]
+    pub fn normalize(self) -> Self {
+        let lsq = self.len_sq();
+        if lsq <= 1e-12 {
+            return Self::new(0.0, 1.0, 0.0);
+        }
+        self.scale(inv_sqrt_f32(lsq))
+    }
+}
+
+/// Column-major 4x4 matrix (`m[col][row]`).
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub struct Mat4 {
+    pub m: [[f32; 4]; 4],
+}
+
+impl Mat4 {
+    pub const fn identity() -> Self {
+        Self {
+            m: [
+                [1.0, 0.0, 0.0, 0.0],
+                [0.0, 1.0, 0.0, 0.0],
+                [0.0, 0.0, 1.0, 0.0],
+                [0.0, 0.0, 0.0, 1.0],
+            ],
+        }
+    }
+
+    pub fn mul(&self, rhs: &Self) -> Self {
+        let mut out = [[0.0f32; 4]; 4];
+        for c in 0..4 {
+            for r in 0..4 {
+                out[c][r] = self.m[0][r] * rhs.m[c][0]
+                    + self.m[1][r] * rhs.m[c][1]
+                    + self.m[2][r] * rhs.m[c][2]
+                    + self.m[3][r] * rhs.m[c][3];
+            }
+        }
+        Self { m: out }
+    }
+
+    pub fn rotation_y(angle: f32) -> Self {
+        let (s, c) = sin_cos_f32(angle);
+        Self {
+            m: [
+                [c, 0.0, -s, 0.0],
+                [0.0, 1.0, 0.0, 0.0],
+                [s, 0.0, c, 0.0],
+                [0.0, 0.0, 0.0, 1.0],
+            ],
+        }
+    }
+
+    pub fn rotation_x(angle: f32) -> Self {
+        let (s, c) = sin_cos_f32(angle);
+        Self {
+            m: [
+                [1.0, 0.0, 0.0, 0.0],
+                [0.0, c, s, 0.0],
+                [0.0, -s, c, 0.0],
+                [0.0, 0.0, 0.0, 1.0],
+            ],
+        }
+    }
+
+    pub fn translation(x: f32, y: f32, z: f32) -> Self {
+        Self {
+            m: [
+                [1.0, 0.0, 0.0, 0.0],
+                [0.0, 1.0, 0.0, 0.0],
+                [0.0, 0.0, 1.0, 0.0],
+                [x, y, z, 1.0],
+            ],
+        }
+    }
+
+    /// Standard right-handed perspective projection mapping depth to `[0, 1]`.
+    pub fn perspective(fov_y_rad: f32, aspect: f32, near: f32, far: f32) -> Self {
+        let half = fov_y_rad * 0.5;
+        let (s, c) = sin_cos_f32(half);
+        let f = if abs_f32(s) > 1e-6 { c / s } else { 1.0 };
+        let nf = 1.0 / (near - far);
+        Self {
+            m: [
+                [f / aspect, 0.0, 0.0, 0.0],
+                [0.0, f, 0.0, 0.0],
+                [0.0, 0.0, far * nf, -1.0],
+                [0.0, 0.0, (far * near) * nf, 0.0],
+            ],
+        }
+    }
+
+    #[inline]
+    pub fn transform_point(&self, p: Vec3) -> [f32; 4] {
+        [
+            self.m[0][0] * p.x + self.m[1][0] * p.y + self.m[2][0] * p.z + self.m[3][0],
+            self.m[0][1] * p.x + self.m[1][1] * p.y + self.m[2][1] * p.z + self.m[3][1],
+            self.m[0][2] * p.x + self.m[1][2] * p.y + self.m[2][2] * p.z + self.m[3][2],
+            self.m[0][3] * p.x + self.m[1][3] * p.y + self.m[2][3] * p.z + self.m[3][3],
+        ]
+    }
+
+    #[inline]
+    pub fn transform_dir(&self, d: Vec3) -> Vec3 {
+        Vec3::new(
+            self.m[0][0] * d.x + self.m[1][0] * d.y + self.m[2][0] * d.z,
+            self.m[0][1] * d.x + self.m[1][1] * d.y + self.m[2][1] * d.z,
+            self.m[0][2] * d.x + self.m[1][2] * d.y + self.m[2][2] * d.z,
+        )
+    }
+}
+
+/// Convert 8-bit RGBA to N64 16-bit RGBA5551 (`RRRRR GGGGG BBBBB A`).
+#[inline(always)]
+pub const fn rgba8_to_rgba5551(r: u8, g: u8, b: u8, a: u8) -> u16 {
+    (((r as u16) >> 3) << 11)
+        | (((g as u16) >> 3) << 6)
+        | (((b as u16) >> 3) << 1)
+        | ((a as u16) >> 7)
+}
+
+#[inline(always)]
+pub const fn rgb5551(r: u8, g: u8, b: u8) -> u16 {
+    rgba8_to_rgba5551(r, g, b, 255)
+}
+
+#[inline(always)]
+pub const fn rgba5551_to_rgb8(c: u16) -> [u8; 3] {
+    let r = (((c >> 11) & 0x1F) * 255 / 31) as u8;
+    let g = (((c >> 6) & 0x1F) * 255 / 31) as u8;
+    let b = (((c >> 1) & 0x1F) * 255 / 31) as u8;
+    [r, g, b]
+}
+
+/// Fast integer alpha blend of `fg` over `bg` in RGBA5551 (`alpha` 0..=255).
+#[inline(always)]
+pub fn blend_rgb5551(bg: u16, fg: u16, alpha: u8) -> u16 {
+    let a = alpha as u16;
+    let inv = 255 - a;
+    let br = (bg >> 11) & 0x1F;
+    let bg_c = (bg >> 6) & 0x1F;
+    let bb = (bg >> 1) & 0x1F;
+
+    let fr = (fg >> 11) & 0x1F;
+    let fg_c = (fg >> 6) & 0x1F;
+    let fb = (fg >> 1) & 0x1F;
+
+    let r = (fr * a + br * inv) / 255;
+    let g = (fg_c * a + bg_c * inv) / 255;
+    let b = (fb * a + bb * inv) / 255;
+    (r << 11) | (g << 6) | (b << 1) | 1
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn trig_and_sqrt_accuracy() {
+        for deg in (-360..=360).step_by(15) {
+            let rad = (deg as f32) * PI / 180.0;
+            let s = sin_f32(rad);
+            let c = cos_f32(rad);
+            assert!((s - rad.sin()).abs() < 1e-3, "sin({deg}) = {s}");
+            assert!((c - rad.cos()).abs() < 1e-3, "cos({deg}) = {c}");
+        }
+        for v in [0.25f32, 1.0, 2.0, 9.0, 123.456] {
+            let s = sqrt_f32(v);
+            assert!((s - v.sqrt()).abs() < 1e-4, "sqrt({v}) = {s}");
+        }
+    }
+}

+ 544 - 0
crates/shader-core/src/mesh.rs

@@ -0,0 +1,544 @@
+//! Procedural 3D preview meshes (Sphere, Torus, Cube, Teapot), lighting, and projection.
+
+use crate::math::{
+    clamp_f32, max_f32, pow_f32_u8, sin_cos_f32, Mat4, Vec2, Vec3, PI, TAU,
+};
+use heapless::Vec;
+
+pub const MAX_VERTS: usize = 224;
+pub const MAX_TRIS: usize = 340;
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum MeshKind {
+    Sphere = 0,
+    Torus = 1,
+    Cube = 2,
+    Teapot = 3,
+}
+
+impl MeshKind {
+    pub fn next(self) -> Self {
+        match self {
+            Self::Sphere => Self::Torus,
+            Self::Torus => Self::Cube,
+            Self::Cube => Self::Teapot,
+            Self::Teapot => Self::Sphere,
+        }
+    }
+
+    pub const fn name(self) -> &'static str {
+        match self {
+            Self::Sphere => "SPHERE",
+            Self::Torus => "TORUS",
+            Self::Cube => "CUBE",
+            Self::Teapot => "TEAPOT",
+        }
+    }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum LightPreset {
+    Studio = 0,
+    RimBacklight = 1,
+    ToonHard = 2,
+    Sunset = 3,
+}
+
+impl LightPreset {
+    pub fn next(self) -> Self {
+        match self {
+            Self::Studio => Self::RimBacklight,
+            Self::RimBacklight => Self::ToonHard,
+            Self::ToonHard => Self::Sunset,
+            Self::Sunset => Self::Studio,
+        }
+    }
+
+    pub const fn name(self) -> &'static str {
+        match self {
+            Self::Studio => "STUDIO",
+            Self::RimBacklight => "RIM",
+            Self::ToonHard => "TOON",
+            Self::Sunset => "SUNSET",
+        }
+    }
+}
+
+#[derive(Copy, Clone, Debug)]
+pub struct Vertex3D {
+    pub pos: Vec3,
+    pub normal: Vec3,
+    pub uv: Vec2,
+}
+
+#[derive(Clone, Debug)]
+pub struct MeshBuffer {
+    pub verts: Vec<Vertex3D, MAX_VERTS>,
+    pub tris: Vec<[u16; 3], MAX_TRIS>,
+}
+
+impl Default for MeshBuffer {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl MeshBuffer {
+    pub fn new() -> Self {
+        Self {
+            verts: Vec::new(),
+            tris: Vec::new(),
+        }
+    }
+}
+
+pub fn generate_mesh(kind: MeshKind, out: &mut MeshBuffer) {
+    out.verts.clear();
+    out.tris.clear();
+    match kind {
+        MeshKind::Sphere => gen_sphere(out, 12, 8),
+        MeshKind::Torus => gen_torus(out, 14, 10, 0.72, 0.30),
+        MeshKind::Cube => gen_cube(out),
+        MeshKind::Teapot => gen_teapot(out),
+    }
+}
+
+fn push_lathe_grid(
+    out: &mut MeshBuffer,
+    rings: usize,
+    segs: usize,
+    base_idx: u16,
+    flip_winding: bool,
+) {
+    let stride = (segs + 1) as u16;
+    for r in 0..rings {
+        for s in 0..segs {
+            let i0 = base_idx + (r as u16) * stride + (s as u16);
+            let i1 = i0 + 1;
+            let i2 = i0 + stride;
+            let i3 = i2 + 1;
+            if flip_winding {
+                let _ = out.tris.push([i0, i1, i2]);
+                let _ = out.tris.push([i1, i3, i2]);
+            } else {
+                let _ = out.tris.push([i0, i2, i1]);
+                let _ = out.tris.push([i1, i2, i3]);
+            }
+        }
+    }
+}
+
+fn gen_sphere(out: &mut MeshBuffer, segs: usize, rings: usize) {
+    let radius = 0.95f32;
+    for r in 0..=rings {
+        let v = (r as f32) / (rings as f32);
+        let phi = v * PI;
+        let (sp, cp) = sin_cos_f32(phi);
+        for s in 0..=segs {
+            let u = (s as f32) / (segs as f32);
+            let theta = u * TAU;
+            let (st, ct) = sin_cos_f32(theta);
+            let n = Vec3::new(sp * ct, cp, sp * st).normalize();
+            let _ = out.verts.push(Vertex3D {
+                pos: n.scale(radius),
+                normal: n,
+                uv: Vec2::new(u * 2.0, v),
+            });
+        }
+    }
+    push_lathe_grid(out, rings, segs, 0, true);
+}
+
+fn gen_torus(out: &mut MeshBuffer, major_segs: usize, minor_segs: usize, major_r: f32, minor_r: f32) {
+    for i in 0..=major_segs {
+        let u = (i as f32) / (major_segs as f32);
+        let theta = u * TAU;
+        let (st, ct) = sin_cos_f32(theta);
+        for j in 0..=minor_segs {
+            let v = (j as f32) / (minor_segs as f32);
+            let phi = v * TAU;
+            let (sp, cp) = sin_cos_f32(phi);
+            let r = major_r + minor_r * cp;
+            let pos = Vec3::new(r * ct, minor_r * sp, r * st);
+            let n = Vec3::new(cp * ct, sp, cp * st).normalize();
+            let _ = out.verts.push(Vertex3D {
+                pos,
+                normal: n,
+                uv: Vec2::new(u * 3.0, v),
+            });
+        }
+    }
+    push_lathe_grid(out, major_segs, minor_segs, 0, true);
+}
+
+fn gen_cube(out: &mut MeshBuffer) {
+    // 2x2 subdivided faces (54 verts, 48 tris) for smooth Gouraud & Fresnel shading
+    let faces: [(Vec3, Vec3, Vec3); 6] = [
+        (Vec3::new(0.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)),
+        (Vec3::new(0.0, 0.0, -1.0), Vec3::new(-1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)),
+        (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 1.0, 0.0)),
+        (Vec3::new(-1.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0)),
+        (Vec3::new(0.0, 1.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.0, -1.0)),
+        (Vec3::new(0.0, -1.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0)),
+    ];
+    let half = 0.72f32;
+    for (n, right, up) in faces {
+        let base = out.verts.len() as u16;
+        for iy in 0..=2 {
+            let v = (iy as f32) * 0.5;
+            let fy = (1.0 - v) * 2.0 - 1.0;
+            for ix in 0..=2 {
+                let u = (ix as f32) * 0.5;
+                let fx = u * 2.0 - 1.0;
+                let pos = n
+                    .scale(half)
+                    .add(right.scale(fx * half))
+                    .add(up.scale(fy * half));
+                // Blend slight spherical normal for richer Fresnel rim on cube edges
+                let smooth_n = n.add(pos.normalize().scale(0.25)).normalize();
+                let _ = out.verts.push(Vertex3D {
+                    pos,
+                    normal: smooth_n,
+                    uv: Vec2::new(u, v),
+                });
+            }
+        }
+        push_lathe_grid(out, 2, 2, base, false);
+    }
+}
+
+fn gen_teapot(out: &mut MeshBuffer) {
+    // 1. Lathed teapot body + lid + finial knob (11 profile rings x 12 segs = 156 verts)
+    let profile: [(f32, f32); 11] = [
+        (0.02, -0.60),
+        (0.45, -0.58),
+        (0.70, -0.36),
+        (0.80, -0.05),
+        (0.74, 0.24),
+        (0.54, 0.42),
+        (0.58, 0.48),
+        (0.46, 0.50),
+        (0.36, 0.62),
+        (0.14, 0.72),
+        (0.02, 0.76),
+    ];
+    let segs = 12usize;
+    let base_body = out.verts.len() as u16;
+    for (ri, &(r, y)) in profile.iter().enumerate() {
+        let (dr, dy) = if ri == 0 {
+            (profile[1].0 - r, profile[1].1 - y)
+        } else if ri + 1 == profile.len() {
+            (r - profile[ri - 1].0, y - profile[ri - 1].1)
+        } else {
+            (profile[ri + 1].0 - profile[ri - 1].0, profile[ri + 1].1 - profile[ri - 1].1)
+        };
+        // Outward normal in (r, y) plane is (dy, -dr)
+        let nr = dy;
+        let ny = -dr;
+        let v = (ri as f32) / ((profile.len() - 1) as f32);
+        for s in 0..=segs {
+            let u = (s as f32) / (segs as f32);
+            let (st, ct) = sin_cos_f32(u * TAU);
+            let pos = Vec3::new(r * ct, y, r * st);
+            let normal = Vec3::new(nr * ct, ny, nr * st).normalize();
+            let _ = out.verts.push(Vertex3D {
+                pos,
+                normal,
+                uv: Vec2::new(u * 2.0, v),
+            });
+        }
+    }
+    push_lathe_grid(out, profile.len() - 1, segs, base_body, false);
+
+    // 2. Curved Spout (+X side): 4 rings x 4 segs = 25 verts, 32 tris
+    let spout_spine: [(f32, f32, f32); 4] = [
+        (0.65, -0.06, 0.16),
+        (0.88, 0.08, 0.13),
+        (1.04, 0.30, 0.10),
+        (1.12, 0.48, 0.08),
+    ];
+    let tube_segs = 4usize;
+    let base_spout = out.verts.len() as u16;
+    for (i, &(cx, cy, rad)) in spout_spine.iter().enumerate() {
+        let (tx, ty) = if i + 1 < spout_spine.len() {
+            (spout_spine[i + 1].0 - cx, spout_spine[i + 1].1 - cy)
+        } else {
+            (cx - spout_spine[i - 1].0, cy - spout_spine[i - 1].1)
+        };
+        let tang = Vec3::new(tx, ty, 0.0).normalize();
+        let up_ortho = Vec3::new(-tang.y, tang.x, 0.0);
+        let side = Vec3::new(0.0, 0.0, 1.0);
+        for s in 0..=tube_segs {
+            let u = (s as f32) / (tube_segs as f32);
+            let (sa, ca) = sin_cos_f32(u * TAU);
+            let n = up_ortho.scale(ca).add(side.scale(sa)).normalize();
+            let pos = Vec3::new(cx, cy, 0.0).add(n.scale(rad));
+            let _ = out.verts.push(Vertex3D {
+                pos,
+                normal: n,
+                uv: Vec2::new(u, (i as f32) / 3.0),
+            });
+        }
+    }
+    push_lathe_grid(out, spout_spine.len() - 1, tube_segs, base_spout, true);
+
+    // 3. Curved Handle (-X side): 5 rings x 4 segs = 30 verts, 40 tris
+    let handle_spine: [(f32, f32, f32); 5] = [
+        (-0.62, 0.28, 0.09),
+        (-0.98, 0.32, 0.09),
+        (-1.12, 0.06, 0.09),
+        (-0.98, -0.22, 0.09),
+        (-0.64, -0.26, 0.09),
+    ];
+    let base_handle = out.verts.len() as u16;
+    for (i, &(cx, cy, rad)) in handle_spine.iter().enumerate() {
+        let (tx, ty) = if i + 1 < handle_spine.len() {
+            (handle_spine[i + 1].0 - cx, handle_spine[i + 1].1 - cy)
+        } else {
+            (cx - handle_spine[i - 1].0, cy - handle_spine[i - 1].1)
+        };
+        let tang = Vec3::new(tx, ty, 0.0).normalize();
+        let up_ortho = Vec3::new(-tang.y, tang.x, 0.0);
+        let side = Vec3::new(0.0, 0.0, 1.0);
+        for s in 0..=tube_segs {
+            let u = (s as f32) / (tube_segs as f32);
+            let (sa, ca) = sin_cos_f32(u * TAU);
+            let n = up_ortho.scale(ca).add(side.scale(sa)).normalize();
+            let pos = Vec3::new(cx, cy, 0.0).add(n.scale(rad));
+            let _ = out.verts.push(Vertex3D {
+                pos,
+                normal: n,
+                uv: Vec2::new(u, (i as f32) / 4.0),
+            });
+        }
+    }
+    push_lathe_grid(out, handle_spine.len() - 1, tube_segs, base_handle, true);
+}
+
+#[derive(Copy, Clone, Debug)]
+pub struct ScreenVert {
+    pub x: f32,
+    pub y: f32,
+    /// Depth normalized `[0.0, 1.0]`
+    pub z: f32,
+    /// `1.0 / clip_w`
+    pub inv_w: f32,
+    /// Normalized color `[0.0, 1.0]`
+    pub r: f32,
+    pub g: f32,
+    pub b: f32,
+    pub a: f32,
+    /// Texture coordinates in texels `[0.0, 32.0]` (may scroll outside and wrap in RDP)
+    pub s: f32,
+    pub t: f32,
+}
+
+#[derive(Copy, Clone, Debug)]
+pub struct ProjectedTri {
+    pub v: [ScreenVert; 3],
+}
+
+#[derive(Copy, Clone, Debug)]
+pub struct ProjectParams {
+    pub vp_x0: f32,
+    pub vp_y0: f32,
+    pub vp_w: f32,
+    pub vp_h: f32,
+    pub yaw: f32,
+    pub pitch: f32,
+    pub frame: u32,
+    pub light: LightPreset,
+    pub env_map: bool,
+    pub scroll_x: i8,
+    pub scroll_y: i8,
+    pub uses_fresnel: bool,
+    pub fresnel_power: u8,
+    pub fresnel_bias: u8,
+}
+
+/// Transform, light, backface-cull, and project `mesh` into screen-space RDP triangles.
+pub fn project_mesh(mesh: &MeshBuffer, params: &ProjectParams) -> Vec<ProjectedTri, MAX_TRIS> {
+    let model = Mat4::rotation_y(params.yaw).mul(&Mat4::rotation_x(params.pitch));
+    let view = Mat4::translation(0.0, -0.04, -3.15);
+    let mv = view.mul(&model);
+    let aspect = params.vp_w / max_f32(params.vp_h, 1.0);
+    let proj = Mat4::perspective(0.75, aspect, 0.5, 16.0);
+    let mvp = proj.mul(&mv);
+
+    let (key_dir, key_col, amb_col, toon) = match params.light {
+        LightPreset::Studio => (
+            Vec3::new(0.55, 0.72, 0.42).normalize(),
+            [0.95f32, 0.95, 1.0],
+            [0.24f32, 0.27, 0.34],
+            false,
+        ),
+        LightPreset::RimBacklight => (
+            Vec3::new(-0.65, 0.35, -0.66).normalize(),
+            [0.45f32, 0.78, 1.0],
+            [0.32f32, 0.25, 0.38],
+            false,
+        ),
+        LightPreset::ToonHard => (
+            Vec3::new(0.48, 0.75, 0.45).normalize(),
+            [1.0f32, 1.0, 0.96],
+            [0.32f32, 0.30, 0.35],
+            true,
+        ),
+        LightPreset::Sunset => (
+            Vec3::new(-0.72, 0.45, 0.52).normalize(),
+            [1.0f32, 0.62, 0.28],
+            [0.22f32, 0.16, 0.32],
+            false,
+        ),
+    };
+
+    let t_sec = (params.frame as f32) * (1.0 / 60.0);
+    let scroll_u = (params.scroll_x as f32) * 0.22 * t_sec;
+    let scroll_v = (params.scroll_y as f32) * 0.22 * t_sec;
+    let bias_f = (params.fresnel_bias as f32) / 255.0;
+    let power = params.fresnel_power.clamp(1, 8);
+
+    let mut xformed: Vec<Option<ScreenVert>, MAX_VERTS> = Vec::new();
+    for vert in &mesh.verts {
+        let clip = mvp.transform_point(vert.pos);
+        if clip[3] <= 0.1 {
+            let _ = xformed.push(None);
+            continue;
+        }
+        let inv_w = 1.0 / clip[3];
+        let ndc_x = clip[0] * inv_w;
+        let ndc_y = clip[1] * inv_w;
+        let ndc_z = clamp_f32(clip[2] * inv_w, 0.0, 0.999);
+
+        let sx = params.vp_x0 + (ndc_x * 0.5 + 0.5) * params.vp_w;
+        let sy = params.vp_y0 + (0.5 - ndc_y * 0.5) * params.vp_h;
+
+        let n_view = mv.transform_dir(vert.normal).normalize();
+        let pos_view = mv.transform_point(vert.pos);
+        let view_dir = Vec3::new(-pos_view[0], -pos_view[1], -pos_view[2]).normalize();
+
+        let mut ndl = max_f32(n_view.dot(key_dir), 0.0);
+        if toon {
+            ndl = if ndl > 0.55 {
+                1.0
+            } else if ndl > 0.18 {
+                0.55
+            } else {
+                0.05
+            };
+        }
+
+        let r = clamp_f32(amb_col[0] + key_col[0] * ndl, 0.0, 1.0);
+        let g = clamp_f32(amb_col[1] + key_col[1] * ndl, 0.0, 1.0);
+        let b = clamp_f32(amb_col[2] + key_col[2] * ndl, 0.0, 1.0);
+
+        let a = if params.uses_fresnel {
+            let ndv = clamp_f32(n_view.dot(view_dir), 0.0, 1.0);
+            clamp_f32(pow_f32_u8(1.0 - ndv, power) + bias_f, 0.0, 1.0)
+        } else {
+            1.0
+        };
+
+        let (u, v) = if params.env_map {
+            (n_view.x * 0.5 + 0.5, 0.5 - n_view.y * 0.5)
+        } else {
+            (vert.uv.x, vert.uv.y)
+        };
+
+        let s = (u + scroll_u) * 32.0;
+        let t = (v + scroll_v) * 32.0;
+
+        let _ = xformed.push(Some(ScreenVert {
+            x: sx,
+            y: sy,
+            z: ndc_z,
+            inv_w,
+            r,
+            g,
+            b,
+            a,
+            s,
+            t,
+        }));
+    }
+
+    let mut out = Vec::new();
+    let x0 = params.vp_x0;
+    let y0 = params.vp_y0;
+    let x1 = params.vp_x0 + params.vp_w;
+    let y1 = params.vp_y0 + params.vp_h;
+
+    for &[i0, i1, i2] in &mesh.tris {
+        let Some(Some(v0)) = xformed.get(i0 as usize) else {
+            continue;
+        };
+        let Some(Some(v1)) = xformed.get(i1 as usize) else {
+            continue;
+        };
+        let Some(Some(v2)) = xformed.get(i2 as usize) else {
+            continue;
+        };
+        // Screen-space signed area (Y-down): positive = front-facing CCW in Y-up view
+        let area = (v1.x - v0.x) * (v2.y - v0.y) - (v2.x - v0.x) * (v1.y - v0.y);
+        if area <= 0.25 {
+            continue;
+        }
+        // Quick viewport bounds reject
+        let min_x = v0.x.min(v1.x).min(v2.x);
+        let max_x = v0.x.max(v1.x).max(v2.x);
+        let min_y = v0.y.min(v1.y).min(v2.y);
+        let max_y = v0.y.max(v1.y).max(v2.y);
+        if max_x < x0 || min_x >= x1 || max_y < y0 || min_y >= y1 {
+            continue;
+        }
+        let _ = out.push(ProjectedTri { v: [*v0, *v1, *v2] });
+    }
+
+    out
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn all_meshes_generate_and_project_into_viewport() {
+        let mut buf = MeshBuffer::new();
+        let params = ProjectParams {
+            vp_x0: 208.0,
+            vp_y0: 14.0,
+            vp_w: 112.0,
+            vp_h: 210.0,
+            yaw: 0.5,
+            pitch: 0.25,
+            frame: 12,
+            light: LightPreset::Studio,
+            env_map: true,
+            scroll_x: 1,
+            scroll_y: -1,
+            uses_fresnel: true,
+            fresnel_power: 3,
+            fresnel_bias: 16,
+        };
+        for kind in [
+            MeshKind::Sphere,
+            MeshKind::Torus,
+            MeshKind::Cube,
+            MeshKind::Teapot,
+        ] {
+            generate_mesh(kind, &mut buf);
+            assert!(!buf.verts.is_empty(), "{kind:?} verts empty");
+            assert!(!buf.tris.is_empty(), "{kind:?} tris empty");
+            let proj = project_mesh(&buf, &params);
+            assert!(!proj.is_empty(), "{kind:?} projected 0 front tris");
+            for tri in &proj {
+                for v in &tri.v {
+                    assert!(v.x.is_finite() && v.y.is_finite() && v.z.is_finite());
+                    assert!(v.inv_w.is_finite() && v.inv_w > 0.0);
+                }
+            }
+        }
+    }
+}

+ 362 - 0
crates/shader-core/src/presets.rs

@@ -0,0 +1,362 @@
+//! Six pre-wired N64 shader node graph presets for immediate hardware demos.
+
+use crate::graph::{BlendMode, NodeGraph, NodeType, PinDir, PinId, TexPattern};
+
+pub const PRESET_COUNT: usize = 6;
+
+pub fn preset_name(idx: usize) -> &'static str {
+    match idx % PRESET_COUNT {
+        0 => "METAL CAP CHROME",
+        1 => "LAVA FLOW",
+        2 => "SCI-FI HOLOGRAM",
+        3 => "TOON CEL-SHADER",
+        4 => "WATER CAUSTICS",
+        _ => "HARDWARE NOISE",
+    }
+}
+
+pub fn load_preset(idx: usize) -> NodeGraph {
+    let mut g = NodeGraph::new();
+    match idx % PRESET_COUNT {
+        // 0: Metal Cap Chrome -> (TEX0(env) * VTX) mixed toward ENV rim via FRESNEL
+        0 => {
+            let t0 = g
+                .add_node(
+                    NodeType::Texture0 {
+                        pattern: TexPattern::ChromeEnv,
+                        scroll_x: 0,
+                        scroll_y: 0,
+                        env_map: true,
+                    },
+                    8,
+                    22,
+                )
+                .unwrap();
+            let vtx = g.add_node(NodeType::VertexColor, 8, 66).unwrap();
+            let env = g
+                .add_node(
+                    NodeType::EnvColor {
+                        rgba: [150, 210, 255, 255],
+                    },
+                    8,
+                    108,
+                )
+                .unwrap();
+            let frs = g
+                .add_node(NodeType::Fresnel { power: 3, bias: 12 }, 8, 152)
+                .unwrap();
+            let mul = g.add_node(NodeType::Multiply, 78, 36).unwrap();
+            let mix = g.add_node(NodeType::Mix { factor: 160 }, 84, 100).unwrap();
+            let out = g
+                .add_node(
+                    NodeType::Output {
+                        blend_mode: BlendMode::Opaque,
+                    },
+                    146,
+                    92,
+                )
+                .unwrap();
+
+            wire(&mut g, t0, 0, mul, 0);
+            wire(&mut g, vtx, 0, mul, 1);
+            wire(&mut g, mul, 0, mix, 0);
+            wire(&mut g, env, 0, mix, 1);
+            wire(&mut g, frs, 0, mix, 2);
+            wire(&mut g, mix, 0, out, 0);
+        }
+        // 1: Lava Flow -> Mix(TEX0, TEX1, 0.45) * PRIM incandescent glow
+        1 => {
+            let t0 = g
+                .add_node(
+                    NodeType::Texture0 {
+                        pattern: TexPattern::LavaMagma,
+                        scroll_x: 2,
+                        scroll_y: 1,
+                        env_map: false,
+                    },
+                    8,
+                    22,
+                )
+                .unwrap();
+            let t1 = g
+                .add_node(
+                    NodeType::Texture1 {
+                        pattern: TexPattern::WaterCaustics,
+                        scroll_x: -2,
+                        scroll_y: 2,
+                        env_map: false,
+                    },
+                    8,
+                    70,
+                )
+                .unwrap();
+            let prim = g
+                .add_node(
+                    NodeType::PrimColor {
+                        rgba: [255, 185, 95, 255],
+                    },
+                    8,
+                    124,
+                )
+                .unwrap();
+            let mix = g.add_node(NodeType::Mix { factor: 105 }, 80, 42).unwrap();
+            let mul = g.add_node(NodeType::Multiply, 84, 118).unwrap();
+            let out = g
+                .add_node(
+                    NodeType::Output {
+                        blend_mode: BlendMode::Opaque,
+                    },
+                    146,
+                    108,
+                )
+                .unwrap();
+
+            wire(&mut g, t0, 0, mix, 0);
+            wire(&mut g, t1, 0, mix, 1);
+            wire(&mut g, mix, 0, mul, 0);
+            wire(&mut g, prim, 0, mul, 1);
+            wire(&mut g, mul, 0, out, 0);
+        }
+        // 2: Sci-Fi Hologram -> Mix(TEX0 * PRIM, ENV, FRESNEL) + FRESNEL alpha
+        2 => {
+            let t0 = g
+                .add_node(
+                    NodeType::Texture0 {
+                        pattern: TexPattern::HoloScanlines,
+                        scroll_x: 0,
+                        scroll_y: 3,
+                        env_map: false,
+                    },
+                    8,
+                    22,
+                )
+                .unwrap();
+            let prim = g
+                .add_node(
+                    NodeType::PrimColor {
+                        rgba: [50, 225, 255, 255],
+                    },
+                    8,
+                    68,
+                )
+                .unwrap();
+            let env = g
+                .add_node(
+                    NodeType::EnvColor {
+                        rgba: [180, 255, 255, 255],
+                    },
+                    8,
+                    112,
+                )
+                .unwrap();
+            let frs = g
+                .add_node(NodeType::Fresnel { power: 2, bias: 32 }, 8, 156)
+                .unwrap();
+            let mul = g.add_node(NodeType::Multiply, 78, 36).unwrap();
+            let mix = g.add_node(NodeType::Mix { factor: 160 }, 84, 102).unwrap();
+            let out = g
+                .add_node(
+                    NodeType::Output {
+                        blend_mode: BlendMode::Translucent,
+                    },
+                    146,
+                    102,
+                )
+                .unwrap();
+
+            wire(&mut g, t0, 0, mul, 0);
+            wire(&mut g, prim, 0, mul, 1);
+            wire(&mut g, mul, 0, mix, 0);
+            wire(&mut g, env, 0, mix, 1);
+            wire(&mut g, frs, 0, mix, 2);
+            wire(&mut g, mix, 0, out, 0);
+            wire(&mut g, frs, 0, out, 1);
+        }
+        // 3: Toon Cel-Shader -> Mix(TEX0 * PRIM, ENV, FRESNEL)
+        3 => {
+            let t0 = g
+                .add_node(
+                    NodeType::Texture0 {
+                        pattern: TexPattern::ToonChecker,
+                        scroll_x: 0,
+                        scroll_y: 0,
+                        env_map: true,
+                    },
+                    8,
+                    22,
+                )
+                .unwrap();
+            let prim = g
+                .add_node(
+                    NodeType::PrimColor {
+                        rgba: [240, 72, 64, 255],
+                    },
+                    8,
+                    68,
+                )
+                .unwrap();
+            let env = g
+                .add_node(
+                    NodeType::EnvColor {
+                        rgba: [255, 235, 160, 255],
+                    },
+                    8,
+                    112,
+                )
+                .unwrap();
+            let frs = g
+                .add_node(NodeType::Fresnel { power: 4, bias: 0 }, 8, 156)
+                .unwrap();
+            let mul = g.add_node(NodeType::Multiply, 78, 36).unwrap();
+            let mix = g.add_node(NodeType::Mix { factor: 160 }, 84, 102).unwrap();
+            let out = g
+                .add_node(
+                    NodeType::Output {
+                        blend_mode: BlendMode::Opaque,
+                    },
+                    146,
+                    98,
+                )
+                .unwrap();
+
+            wire(&mut g, t0, 0, mul, 0);
+            wire(&mut g, prim, 0, mul, 1);
+            wire(&mut g, mul, 0, mix, 0);
+            wire(&mut g, env, 0, mix, 1);
+            wire(&mut g, frs, 0, mix, 2);
+            wire(&mut g, mix, 0, out, 0);
+        }
+        // 4: Water Caustics -> Add(Mix(TEX0, TEX1, 0.5), ENV)
+        4 => {
+            let t0 = g
+                .add_node(
+                    NodeType::Texture0 {
+                        pattern: TexPattern::WaterCaustics,
+                        scroll_x: 1,
+                        scroll_y: 2,
+                        env_map: false,
+                    },
+                    8,
+                    22,
+                )
+                .unwrap();
+            let t1 = g
+                .add_node(
+                    NodeType::Texture1 {
+                        pattern: TexPattern::WaterCaustics,
+                        scroll_x: -2,
+                        scroll_y: 1,
+                        env_map: false,
+                    },
+                    8,
+                    70,
+                )
+                .unwrap();
+            let env = g
+                .add_node(
+                    NodeType::EnvColor {
+                        rgba: [12, 48, 96, 255],
+                    },
+                    8,
+                    124,
+                )
+                .unwrap();
+            let mix = g.add_node(NodeType::Mix { factor: 128 }, 80, 42).unwrap();
+            let add = g.add_node(NodeType::Add, 84, 118).unwrap();
+            let out = g
+                .add_node(
+                    NodeType::Output {
+                        blend_mode: BlendMode::Opaque,
+                    },
+                    146,
+                    108,
+                )
+                .unwrap();
+
+            wire(&mut g, t0, 0, mix, 0);
+            wire(&mut g, t1, 0, mix, 1);
+            wire(&mut g, mix, 0, add, 0);
+            wire(&mut g, env, 0, add, 1);
+            wire(&mut g, add, 0, out, 0);
+        }
+        // 5: Hardware Noise -> Mix(NOISE, TEX0 * VTX, 0.7)
+        _ => {
+            let t0 = g
+                .add_node(
+                    NodeType::Texture0 {
+                        pattern: TexPattern::BrickDetail,
+                        scroll_x: 0,
+                        scroll_y: 0,
+                        env_map: false,
+                    },
+                    8,
+                    22,
+                )
+                .unwrap();
+            let vtx = g.add_node(NodeType::VertexColor, 8, 68).unwrap();
+            let noise = g.add_node(NodeType::Noise, 8, 120).unwrap();
+            let mul = g.add_node(NodeType::Multiply, 78, 36).unwrap();
+            let mix = g.add_node(NodeType::Mix { factor: 180 }, 84, 108).unwrap();
+            let out = g
+                .add_node(
+                    NodeType::Output {
+                        blend_mode: BlendMode::Opaque,
+                    },
+                    146,
+                    102,
+                )
+                .unwrap();
+
+            wire(&mut g, t0, 0, mul, 0);
+            wire(&mut g, vtx, 0, mul, 1);
+            wire(&mut g, noise, 0, mix, 0);
+            wire(&mut g, mul, 0, mix, 1);
+            wire(&mut g, mix, 0, out, 0);
+        }
+    }
+    g
+}
+
+fn wire(
+    g: &mut NodeGraph,
+    from_node: crate::graph::NodeId,
+    from_slot: u8,
+    to_node: crate::graph::NodeId,
+    to_slot: u8,
+) {
+    let ok = g.connect(
+        PinId {
+            node: from_node,
+            slot: from_slot,
+            dir: PinDir::Output,
+        },
+        PinId {
+            node: to_node,
+            slot: to_slot,
+            dir: PinDir::Input,
+        },
+    );
+    debug_assert!(ok);
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::compiler::compile;
+
+    #[test]
+    fn all_presets_compile_cleanly() {
+        for i in 0..PRESET_COUNT {
+            let g = load_preset(i);
+            let res = compile(&g);
+            assert!(
+                res.is_ok(),
+                "preset {i} ({}) failed to compile: {:?}",
+                preset_name(i),
+                res.err()
+            );
+            let shader = res.unwrap();
+            assert_eq!(shader.combine_cmd >> 56, 0xFC);
+        }
+    }
+}

+ 224 - 0
crates/shader-core/src/storage.rs

@@ -0,0 +1,224 @@
+//! Compact binary NodeGraph serialization for 4K/16K N64 EEPROM (<= 512 bytes).
+
+use crate::graph::{BlendMode, NodeGraph, NodeId, NodeType, PinDir, PinId, TexPattern};
+
+pub const SLOT_BYTES: usize = 512;
+const MAGIC: [u8; 4] = *b"N64S";
+const VERSION: u8 = 1;
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum StorageError {
+    BadMagic,
+    BadVersion,
+    BadChecksum,
+    Truncated,
+    GraphFull,
+}
+
+fn crc16_ccitt(data: &[u8]) -> u16 {
+    let mut crc = 0xFFFFu16;
+    for &b in data {
+        crc ^= (b as u16) << 8;
+        for _ in 0..8 {
+            if (crc & 0x8000) != 0 {
+                crc = (crc << 1) ^ 0x1021;
+            } else {
+                crc <<= 1;
+            }
+        }
+    }
+    crc
+}
+
+/// Serialize a `NodeGraph` into a 512-byte EEPROM slot.
+///
+/// Layout:
+/// - `[0..4]` magic `"N64S"`
+/// - `[4]` version `1`
+/// - `[5]` node_count (`<= 32`)
+/// - `[6]` wire_count (`<= 64`)
+/// - `[7]` reserved
+/// - Nodes: 9 bytes each (`id`, `tag`, `x: i16`, `y: i16`, `p0..p3`)
+/// - Wires: 4 bytes each (`from_node`, `from_slot`, `to_node`, `to_slot`)
+/// - `[510..512]` CRC-16/CCITT over `[0..510]`
+pub fn serialize_graph(graph: &NodeGraph, out: &mut [u8; SLOT_BYTES]) -> Result<usize, StorageError> {
+    out.fill(0);
+    let header = 8;
+    let node_bytes = graph.nodes.len() * 10;
+    let wire_bytes = graph.wires.len() * 4;
+    let total = header + node_bytes + wire_bytes;
+    if total > SLOT_BYTES - 2 {
+        return Err(StorageError::GraphFull);
+    }
+
+    out[0..4].copy_from_slice(&MAGIC);
+    out[4] = VERSION;
+    out[5] = graph.nodes.len() as u8;
+    out[6] = graph.wires.len() as u8;
+    out[7] = 0;
+
+    let mut off = header;
+    for n in &graph.nodes {
+        let (tag, p) = match n.kind {
+            NodeType::Texture0 {
+                pattern,
+                scroll_x,
+                scroll_y,
+                env_map,
+            } => (
+                0u8,
+                [pattern as u8, scroll_x as u8, scroll_y as u8, env_map as u8],
+            ),
+            NodeType::Texture1 {
+                pattern,
+                scroll_x,
+                scroll_y,
+                env_map,
+            } => (
+                1u8,
+                [pattern as u8, scroll_x as u8, scroll_y as u8, env_map as u8],
+            ),
+            NodeType::VertexColor => (2u8, [0; 4]),
+            NodeType::PrimColor { rgba } => (3u8, rgba),
+            NodeType::EnvColor { rgba } => (4u8, rgba),
+            NodeType::Noise => (5u8, [0; 4]),
+            NodeType::Mix { factor } => (6u8, [factor, 0, 0, 0]),
+            NodeType::Multiply => (7u8, [0; 4]),
+            NodeType::Add => (8u8, [0; 4]),
+            NodeType::Fresnel { power, bias } => (9u8, [power, bias, 0, 0]),
+            NodeType::Output { blend_mode } => (10u8, [blend_mode as u8, 0, 0, 0]),
+        };
+        let xb = n.x.to_be_bytes();
+        let yb = n.y.to_be_bytes();
+        out[off] = n.id.0;
+        out[off + 1] = tag;
+        out[off + 2] = xb[0];
+        out[off + 3] = xb[1];
+        out[off + 4] = yb[0];
+        out[off + 5] = yb[1];
+        out[off + 6..off + 10].copy_from_slice(&p); // Wait: 6 + 4 = 10 -> 10 bytes per node!
+        off += 10;
+    }
+
+    for w in &graph.wires {
+        if off + 4 > SLOT_BYTES - 2 {
+            return Err(StorageError::GraphFull);
+        }
+        out[off] = w.from.node.0;
+        out[off + 1] = w.from.slot;
+        out[off + 2] = w.to.node.0;
+        out[off + 3] = w.to.slot;
+        off += 4;
+    }
+
+    let crc = crc16_ccitt(&out[..SLOT_BYTES - 2]).to_be_bytes();
+    out[SLOT_BYTES - 2] = crc[0];
+    out[SLOT_BYTES - 1] = crc[1];
+    Ok(off + 2)
+}
+
+pub fn deserialize_graph(data: &[u8; SLOT_BYTES]) -> Result<NodeGraph, StorageError> {
+    if data[0..4] != MAGIC {
+        return Err(StorageError::BadMagic);
+    }
+    if data[4] != VERSION {
+        return Err(StorageError::BadVersion);
+    }
+    let expected_crc = u16::from_be_bytes([data[SLOT_BYTES - 2], data[SLOT_BYTES - 1]]);
+    let actual_crc = crc16_ccitt(&data[..SLOT_BYTES - 2]);
+    if expected_crc != actual_crc {
+        return Err(StorageError::BadChecksum);
+    }
+
+    let node_count = data[5] as usize;
+    let wire_count = data[6] as usize;
+    let mut off = 8usize;
+    if off + node_count * 10 + wire_count * 4 > SLOT_BYTES - 2 {
+        return Err(StorageError::Truncated);
+    }
+
+    let mut g = NodeGraph::new();
+    for _ in 0..node_count {
+        let id = NodeId(data[off]);
+        let tag = data[off + 1];
+        let x = i16::from_be_bytes([data[off + 2], data[off + 3]]);
+        let y = i16::from_be_bytes([data[off + 4], data[off + 5]]);
+        let p = [data[off + 6], data[off + 7], data[off + 8], data[off + 9]];
+        let kind = match tag {
+            0 => NodeType::Texture0 {
+                pattern: TexPattern::from_u8(p[0]),
+                scroll_x: p[1] as i8,
+                scroll_y: p[2] as i8,
+                env_map: p[3] != 0,
+            },
+            1 => NodeType::Texture1 {
+                pattern: TexPattern::from_u8(p[0]),
+                scroll_x: p[1] as i8,
+                scroll_y: p[2] as i8,
+                env_map: p[3] != 0,
+            },
+            2 => NodeType::VertexColor,
+            3 => NodeType::PrimColor { rgba: p },
+            4 => NodeType::EnvColor { rgba: p },
+            5 => NodeType::Noise,
+            6 => NodeType::Mix { factor: p[0] },
+            7 => NodeType::Multiply,
+            8 => NodeType::Add,
+            9 => NodeType::Fresnel {
+                power: p[0],
+                bias: p[1],
+            },
+            _ => NodeType::Output {
+                blend_mode: BlendMode::from_u8(p[0]),
+            },
+        };
+        if !g.insert_with_id(id, kind, x, y) {
+            return Err(StorageError::GraphFull);
+        }
+        off += 10;
+    }
+
+    for _ in 0..wire_count {
+        let from = PinId {
+            node: NodeId(data[off]),
+            slot: data[off + 1],
+            dir: PinDir::Output,
+        };
+        let to = PinId {
+            node: NodeId(data[off + 2]),
+            slot: data[off + 3],
+            dir: PinDir::Input,
+        };
+        g.connect(from, to);
+        off += 4;
+    }
+
+    Ok(g)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::compiler::compile;
+    use crate::presets::{load_preset, PRESET_COUNT};
+
+    #[test]
+    fn roundtrip_all_presets_and_detect_corruption() {
+        let mut buf = [0u8; SLOT_BYTES];
+        for i in 0..PRESET_COUNT {
+            let orig = load_preset(i);
+            let used = serialize_graph(&orig, &mut buf).expect("serialize preset");
+            assert!(used <= SLOT_BYTES);
+            let restored = deserialize_graph(&buf).expect("deserialize preset");
+            assert_eq!(orig.nodes.len(), restored.nodes.len());
+            assert_eq!(orig.wires.len(), restored.wires.len());
+            assert_eq!(
+                compile(&orig).unwrap().combine_cmd,
+                compile(&restored).unwrap().combine_cmd
+            );
+        }
+        // Corrupt a payload byte -> must fail CRC check
+        buf[12] ^= 0x55;
+        assert_eq!(deserialize_graph(&buf).unwrap_err(), StorageError::BadChecksum);
+    }
+}

+ 113 - 0
crates/shader-core/src/textures.rs

@@ -0,0 +1,113 @@
+//! Procedural 32x32 RGBA5551 texture generator (2048 bytes each; fits TEX0 + TEX1 in 4 KB TMEM).
+
+use crate::graph::TexPattern;
+use crate::math::{abs_f32, clamp_f32, rgba8_to_rgba5551, sin_f32, sqrt_f32, TAU};
+
+pub const TEX_SIZE: usize = 32;
+pub const TEX_PIXELS: usize = TEX_SIZE * TEX_SIZE;
+
+pub fn generate_texture(pattern: TexPattern, out: &mut [u16; TEX_PIXELS]) {
+    for y in 0..TEX_SIZE {
+        let v = (y as f32 + 0.5) / (TEX_SIZE as f32);
+        for x in 0..TEX_SIZE {
+            let u = (x as f32 + 0.5) / (TEX_SIZE as f32);
+            let [r, g, b, a] = sample_pattern(pattern, x, y, u, v);
+            out[y * TEX_SIZE + x] = rgba8_to_rgba5551(r, g, b, a);
+        }
+    }
+}
+
+fn sample_pattern(pattern: TexPattern, ix: usize, iy: usize, u: f32, v: f32) -> [u8; 4] {
+    match pattern {
+        TexPattern::ChromeEnv => {
+            // Classic SM64 Metal Cap style studio horizon + soft specular spots
+            let dx = u - 0.5;
+            let dy = v - 0.5;
+            let rad = sqrt_f32(dx * dx + dy * dy);
+            let horizon = sin_f32((v - 0.45) * 9.0 + sin_f32(u * TAU * 2.0) * 0.45);
+            let sky = clamp_f32(1.0 - v * 1.1 + horizon * 0.2, 0.0, 1.0);
+            let spot1 = clamp_f32(1.0 - sqrt_f32((u - 0.32) * (u - 0.32) + (v - 0.28) * (v - 0.28)) * 4.5, 0.0, 1.0);
+            let spot2 = clamp_f32(1.0 - sqrt_f32((u - 0.72) * (u - 0.72) + (v - 0.68) * (v - 0.68)) * 4.0, 0.0, 1.0);
+            let band = if abs_f32(v - 0.52) < 0.09 { 0.85 } else { 0.0 };
+            let rim = clamp_f32(1.0 - rad * 1.35, 0.15, 1.0);
+            let lum = clamp_f32(0.18 + sky * 0.45 + spot1 * 0.8 + spot2 * 0.35 + band * 0.35, 0.0, 1.0) * rim;
+            let r = (clamp_f32(lum * 235.0 + spot1 * 45.0, 0.0, 255.0)) as u8;
+            let g = (clamp_f32(lum * 245.0 + spot1 * 40.0, 0.0, 255.0)) as u8;
+            let b = (clamp_f32(lum * 255.0 + 18.0 * sky, 0.0, 255.0)) as u8;
+            [r, g, b, 255]
+        }
+        TexPattern::LavaMagma => {
+            let w1 = sin_f32(u * TAU * 2.0 + sin_f32(v * TAU * 2.0));
+            let w2 = sin_f32(v * TAU * 3.0 - sin_f32(u * TAU * 2.0));
+            let ridge = 1.0 - abs_f32(w1 + w2) * 0.5;
+            let heat = clamp_f32(ridge * ridge * 1.15, 0.0, 1.0);
+            let r = (clamp_f32(75.0 + heat * 180.0, 0.0, 255.0)) as u8;
+            let g = (clamp_f32(heat * heat * 205.0, 0.0, 255.0)) as u8;
+            let b = (clamp_f32(heat * heat * heat * 90.0, 0.0, 255.0)) as u8;
+            [r, g, b, 255]
+        }
+        TexPattern::WaterCaustics => {
+            let s1 = sin_f32((u + v) * TAU * 2.0 + sin_f32(u * TAU * 3.0) * 0.8);
+            let s2 = sin_f32((u - v) * TAU * 2.0 + sin_f32(v * TAU * 3.0) * 0.8);
+            let c = 1.0 - clamp_f32(abs_f32(s1 + s2) * 0.55, 0.0, 1.0);
+            let bright = c * c * c;
+            let r = (clamp_f32(25.0 + bright * 180.0, 0.0, 255.0)) as u8;
+            let g = (clamp_f32(95.0 + bright * 155.0, 0.0, 255.0)) as u8;
+            let b = (clamp_f32(155.0 + bright * 100.0, 0.0, 255.0)) as u8;
+            [r, g, b, 255]
+        }
+        TexPattern::HoloScanlines => {
+            let line = if (iy & 3) < 2 { 255 } else { 70 };
+            let grid = if (ix & 7) == 0 || (iy & 7) == 0 { 255 } else { line };
+            let r = (grid / 3) as u8;
+            let g = grid as u8;
+            let b = grid as u8;
+            let a = if (iy & 3) < 2 || (ix & 7) == 0 { 255 } else { 0 };
+            [r, g, b, a]
+        }
+        TexPattern::ToonChecker => {
+            // Crisp quantized toon step bands + subtle micro-grid
+            let q = ((u * 4.0) as i32 + (v * 4.0) as i32) & 1;
+            let band = if v < 0.28 {
+                245
+            } else if v < 0.68 {
+                if q == 0 { 185 } else { 165 }
+            } else {
+                95
+            };
+            [band, band, band, 255]
+        }
+        TexPattern::BrickDetail => {
+            let row = iy / 8;
+            let bx = (ix + if (row & 1) == 1 { 8 } else { 0 }) & 15;
+            let by = iy & 7;
+            if bx == 0 || by == 0 {
+                [115, 110, 105, 255]
+            } else {
+                let n = (((ix * 37 + iy * 17) & 15) as i16) - 8;
+                let r = (175 + n).clamp(0, 255) as u8;
+                let g = (95 + n / 2).clamp(0, 255) as u8;
+                let b = (75 + n / 2).clamp(0, 255) as u8;
+                [r, g, b, 255]
+            }
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn all_textures_generate_varied_pixels() {
+        let mut buf = [0u16; TEX_PIXELS];
+        for pat in TexPattern::ALL {
+            generate_texture(pat, &mut buf);
+            let first = buf[0];
+            assert!(
+                buf.iter().any(|&px| px != first),
+                "texture {pat:?} should not be uniform"
+            );
+        }
+    }
+}

+ 1284 - 0
crates/shader-core/src/ui.rs

@@ -0,0 +1,1284 @@
+//! Split-screen SGI-style Node Canvas UI, input/pin-snapping, and viewport HUD.
+
+use core::fmt::Write;
+use heapless::{String, Vec};
+
+use crate::compiler::{compile, CompileError, CompiledShader, CycleCount};
+use crate::font::draw_text_scaled;
+use crate::graph::{
+    BlendMode, NodeCategory, NodeGraph, NodeId, NodeType, PinDir, PinId, TexPattern,
+};
+use crate::math::{abs_f32, blend_rgb5551, rgb5551};
+use crate::mesh::{LightPreset, MeshKind, ProjectedTri};
+use crate::presets::{load_preset, preset_name, PRESET_COUNT};
+
+pub const LOGICAL_W: i16 = 320;
+pub const LOGICAL_H: i16 = 240;
+/// Left 65% (`208 / 320 = 65.0%`)
+pub const CANVAS_W: i16 = 208;
+pub const HEADER_H: i16 = 14;
+/// Right 35% (`112 / 320 = 35.0%`)
+pub const VP_X: i16 = 208;
+pub const VP_Y: i16 = 14;
+pub const VP_W: i16 = 112;
+pub const VP_H: i16 = 198;
+
+pub const BTN_A: u16 = 1 << 15;
+pub const BTN_B: u16 = 1 << 14;
+pub const BTN_Z: u16 = 1 << 13;
+pub const BTN_START: u16 = 1 << 12;
+pub const BTN_DUP: u16 = 1 << 11;
+pub const BTN_DDOWN: u16 = 1 << 10;
+pub const BTN_DLEFT: u16 = 1 << 9;
+pub const BTN_DRIGHT: u16 = 1 << 8;
+pub const BTN_L: u16 = 1 << 5;
+pub const BTN_R: u16 = 1 << 4;
+pub const BTN_CUP: u16 = 1 << 3;
+pub const BTN_CDOWN: u16 = 1 << 2;
+pub const BTN_CLEFT: u16 = 1 << 1;
+pub const BTN_CRIGHT: u16 = 1 << 0;
+
+#[derive(Copy, Clone, Debug, Default)]
+pub struct InputState {
+    pub buttons: u16,
+    pub stick_x: i8,
+    pub stick_y: i8,
+    pub is_mouse: bool,
+    pub mouse_dx: i8,
+    pub mouse_dy: i8,
+}
+
+#[derive(Copy, Clone, Debug, Default)]
+pub struct PerfStats {
+    pub frame_us: u32,
+    pub cpu_us: u32,
+    pub rdp_us: u32,
+    pub rdp_clock: u32,
+    pub rdp_pipe_busy: u32,
+    pub rdp_tmem_busy: u32,
+    pub fps: u16,
+    pub rdram_mb: u8,
+    pub eeprom_kb: u8,
+    pub is_mouse: bool,
+    pub hi_res: bool,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum StorageAction {
+    SaveEeprom(u8),
+    LoadEeprom(u8),
+    ToggleHiRes,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+enum DragState {
+    Idle,
+    DraggingNode { node: NodeId, dx: i16, dy: i16 },
+    DraggingWire(PinId),
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+enum OverlayMenu {
+    None,
+    StartMenu { cursor: usize },
+    AddNodeMenu { cursor: usize, spawn_x: i16, spawn_y: i16 },
+    EditParam { node: NodeId, field: usize },
+}
+
+pub struct StudioApp {
+    pub graph: NodeGraph,
+    pub compiled: Result<CompiledShader, CompileError>,
+    pub active_preset: usize,
+    pub cursor_x: i16,
+    pub cursor_y: i16,
+    drag: DragState,
+    menu: OverlayMenu,
+    pub mesh_kind: MeshKind,
+    pub light_preset: LightPreset,
+    pub wireframe: bool,
+    pub auto_spin: bool,
+    pub show_perf: bool,
+    pub yaw: f32,
+    pub pitch: f32,
+    pub frame: u32,
+    pub pending_action: Option<StorageAction>,
+    toast: String<32>,
+    toast_timer: u16,
+}
+
+impl Default for StudioApp {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl StudioApp {
+    pub fn new() -> Self {
+        let mut graph = load_preset(0);
+        let compiled = compile(&graph);
+        graph.is_dirty = false;
+        let mut toast = String::new();
+        let _ = toast.push_str("PRESET: METAL CAP CHROME");
+        Self {
+            graph,
+            compiled,
+            active_preset: 0,
+            cursor_x: 96,
+            cursor_y: 100,
+            drag: DragState::Idle,
+            menu: OverlayMenu::None,
+            mesh_kind: MeshKind::Sphere,
+            light_preset: LightPreset::Studio,
+            wireframe: false,
+            auto_spin: true,
+            show_perf: true,
+            yaw: 0.4,
+            pitch: 0.25,
+            frame: 0,
+            pending_action: None,
+            toast,
+            toast_timer: 180,
+        }
+    }
+
+    pub fn set_toast(&mut self, msg: &str) {
+        self.toast.clear();
+        for c in msg.chars().take(32) {
+            let _ = self.toast.push(c);
+        }
+        self.toast_timer = 150;
+    }
+
+    pub fn load_preset_idx(&mut self, idx: usize) {
+        self.active_preset = idx % PRESET_COUNT;
+        self.graph = load_preset(self.active_preset);
+        self.compiled = compile(&self.graph);
+        self.graph.is_dirty = false;
+        self.drag = DragState::Idle;
+        self.set_toast(preset_name(self.active_preset));
+    }
+
+    pub fn replace_graph(&mut self, g: NodeGraph, msg: &str) {
+        self.graph = g;
+        self.compiled = compile(&self.graph);
+        self.graph.is_dirty = false;
+        self.drag = DragState::Idle;
+        self.set_toast(msg);
+    }
+
+    pub fn update(&mut self, input: &InputState, prev: &InputState) {
+        self.frame = self.frame.wrapping_add(1);
+        if self.toast_timer > 0 {
+            self.toast_timer -= 1;
+        }
+
+        let pressed = input.buttons & !prev.buttons;
+        let held = input.buttons;
+
+        // 3D viewport camera orbit via C-buttons
+        let mut manual_orbit = false;
+        if (held & BTN_CLEFT) != 0 {
+            self.yaw -= 0.045;
+            manual_orbit = true;
+        }
+        if (held & BTN_CRIGHT) != 0 {
+            self.yaw += 0.045;
+            manual_orbit = true;
+        }
+        if (held & BTN_CUP) != 0 {
+            self.pitch = (self.pitch - 0.035).clamp(-1.2, 1.2);
+            manual_orbit = true;
+        }
+        if (held & BTN_CDOWN) != 0 {
+            self.pitch = (self.pitch + 0.035).clamp(-1.2, 1.2);
+            manual_orbit = true;
+        }
+        if self.auto_spin && !manual_orbit {
+            self.yaw += 0.018;
+        }
+
+        // L cycles 3D mesh; R cycles lighting; Z+R toggles wireframe
+        if (pressed & BTN_L) != 0 {
+            self.mesh_kind = self.mesh_kind.next();
+            self.set_toast(self.mesh_kind.name());
+        }
+        if (pressed & BTN_R) != 0 {
+            if (held & BTN_Z) != 0 {
+                self.wireframe = !self.wireframe;
+                self.set_toast(if self.wireframe { "WIREFRAME ON" } else { "WIREFRAME OFF" });
+            } else {
+                self.light_preset = self.light_preset.next();
+                self.set_toast(self.light_preset.name());
+            }
+        }
+
+        // Start button toggles Start Menu
+        if (pressed & BTN_START) != 0 {
+            self.menu = match self.menu {
+                OverlayMenu::StartMenu { .. } => OverlayMenu::None,
+                _ => OverlayMenu::StartMenu { cursor: self.active_preset },
+            };
+            return;
+        }
+
+        // Handle active popup menus first
+        match self.menu {
+            OverlayMenu::StartMenu { cursor } => {
+                self.update_start_menu(cursor, pressed);
+                return;
+            }
+            OverlayMenu::AddNodeMenu { cursor, spawn_x, spawn_y } => {
+                self.update_add_menu(cursor, spawn_x, spawn_y, pressed);
+                return;
+            }
+            OverlayMenu::EditParam { node, field } => {
+                self.update_param_editor(node, field, pressed, held);
+                return;
+            }
+            OverlayMenu::None => {}
+        }
+
+        // Cursor movement: N64 Mouse deltas or Analog Stick with deadzone
+        if input.is_mouse {
+            self.cursor_x = (self.cursor_x + input.mouse_dx as i16).clamp(2, CANVAS_W - 3);
+            self.cursor_y = (self.cursor_y - input.mouse_dy as i16).clamp(HEADER_H + 2, LOGICAL_H - 3);
+        } else {
+            let sx = if abs_f32(input.stick_x as f32) > 10.0 {
+                (input.stick_x as i16) / 22
+            } else {
+                0
+            };
+            let sy = if abs_f32(input.stick_y as f32) > 10.0 {
+                -(input.stick_y as i16) / 22
+            } else {
+                0
+            };
+            self.cursor_x = (self.cursor_x + sx).clamp(2, CANVAS_W - 3);
+            self.cursor_y = (self.cursor_y + sy).clamp(HEADER_H + 2, LOGICAL_H - 3);
+        }
+
+        // D-Pad Pin & Node Snapping
+        if (pressed & (BTN_DUP | BTN_DDOWN | BTN_DLEFT | BTN_DRIGHT)) != 0 {
+            let dir_x = if (pressed & BTN_DRIGHT) != 0 {
+                1
+            } else if (pressed & BTN_DLEFT) != 0 {
+                -1
+            } else {
+                0
+            };
+            let dir_y = if (pressed & BTN_DDOWN) != 0 {
+                1
+            } else if (pressed & BTN_DUP) != 0 {
+                -1
+            } else {
+                0
+            };
+            self.snap_cursor(dir_x, dir_y);
+        }
+
+        // Z + B deletes hovered node; Z opens Add-Node menu
+        if (pressed & BTN_Z) != 0 {
+            if let Some(nid) = self.hit_node(self.cursor_x, self.cursor_y) {
+                if (held & BTN_B) != 0 {
+                    if self.graph.remove_node(nid) {
+                        self.set_toast("NODE REMOVED");
+                    }
+                    return;
+                }
+            }
+            self.menu = OverlayMenu::AddNodeMenu {
+                cursor: 0,
+                spawn_x: (self.cursor_x - 24).clamp(4, CANVAS_W - 60),
+                spawn_y: (self.cursor_y - 12).clamp(HEADER_H + 4, LOGICAL_H - 44),
+            };
+            return;
+        }
+        if (pressed & BTN_B) != 0 && (held & BTN_Z) != 0 {
+            if let Some(nid) = self.hit_node(self.cursor_x, self.cursor_y) {
+                if self.graph.remove_node(nid) {
+                    self.set_toast("NODE REMOVED");
+                }
+                return;
+            }
+        }
+
+        // Dragging node movement
+        if let DragState::DraggingNode { node, dx, dy } = self.drag {
+            let nx = (self.cursor_x - dx).clamp(2, CANVAS_W - 60);
+            let ny = (self.cursor_y - dy).clamp(HEADER_H + 2, LOGICAL_H - 38);
+            if let Some(n) = self.graph.nodes.iter_mut().find(|n| n.id == node) {
+                n.x = nx;
+                n.y = ny;
+            }
+            if (held & BTN_A) == 0 && !input.is_mouse {
+                self.drag = DragState::Idle;
+            }
+        }
+
+        // B cancels drag or disconnects hovered input pin
+        if (pressed & BTN_B) != 0 {
+            if self.drag != DragState::Idle {
+                self.drag = DragState::Idle;
+            } else if let Some(pin) = self.hit_pin(self.cursor_x, self.cursor_y) {
+                if pin.dir == PinDir::Input && self.graph.disconnect_input(pin) {
+                    self.set_toast("WIRE UNPLUGGED");
+                }
+            }
+        }
+
+        // A button interactions
+        if (pressed & BTN_A) != 0 {
+            match self.drag {
+                DragState::DraggingWire(from_pin) => {
+                    if let Some(to_pin) = self.hit_pin(self.cursor_x, self.cursor_y) {
+                        let ok = match (from_pin.dir, to_pin.dir) {
+                            (PinDir::Output, PinDir::Input) => self.graph.connect(from_pin, to_pin),
+                            (PinDir::Input, PinDir::Output) => self.graph.connect(to_pin, from_pin),
+                            _ => false,
+                        };
+                        if ok {
+                            self.set_toast("WIRE CONNECTED");
+                        }
+                    }
+                    self.drag = DragState::Idle;
+                }
+                DragState::DraggingNode { .. } => {
+                    self.drag = DragState::Idle;
+                }
+                DragState::Idle => {
+                    if let Some(pin) = self.hit_pin(self.cursor_x, self.cursor_y) {
+                        if pin.dir == PinDir::Input && self.graph.input_source(pin.node, pin.slot).is_some() {
+                            self.graph.disconnect_input(pin);
+                            self.set_toast("WIRE UNPLUGGED");
+                        } else {
+                            self.drag = DragState::DraggingWire(pin);
+                        }
+                    } else if let Some((nid, is_title, nx, ny)) = self.hit_node_part(self.cursor_x, self.cursor_y) {
+                        if is_title {
+                            self.drag = DragState::DraggingNode {
+                                node: nid,
+                                dx: self.cursor_x - nx,
+                                dy: self.cursor_y - ny,
+                            };
+                        } else {
+                            self.menu = OverlayMenu::EditParam { node: nid, field: 0 };
+                        }
+                    }
+                }
+            }
+        }
+
+        // Recompile ONLY when graph is dirty
+        if self.graph.is_dirty {
+            self.compiled = compile(&self.graph);
+            self.graph.is_dirty = false;
+        }
+    }
+
+    fn update_start_menu(&mut self, mut cursor: usize, pressed: u16) {
+        // Items: 0..6 Presets, 6 Toggle Auto-Spin, 7 Toggle Perf HUD, 8 Toggle 640x480, 9 Save EEPROM, 10 Load EEPROM
+        const ITEMS: usize = 11;
+        if (pressed & BTN_DUP) != 0 {
+            cursor = (cursor + ITEMS - 1) % ITEMS;
+        } else if (pressed & BTN_DDOWN) != 0 {
+            cursor = (cursor + 1) % ITEMS;
+        }
+        if (pressed & BTN_B) != 0 {
+            self.menu = OverlayMenu::None;
+            return;
+        }
+        if (pressed & BTN_A) != 0 {
+            match cursor {
+                0..=5 => self.load_preset_idx(cursor),
+                6 => {
+                    self.auto_spin = !self.auto_spin;
+                    self.set_toast(if self.auto_spin { "AUTO-SPIN ON" } else { "AUTO-SPIN OFF" });
+                }
+                7 => {
+                    self.show_perf = !self.show_perf;
+                    self.set_toast(if self.show_perf { "PERF HUD ON" } else { "PERF HUD OFF" });
+                }
+                8 => {
+                    self.pending_action = Some(StorageAction::ToggleHiRes);
+                }
+                9 => {
+                    self.pending_action = Some(StorageAction::SaveEeprom(0));
+                }
+                10 => {
+                    self.pending_action = Some(StorageAction::LoadEeprom(0));
+                }
+                _ => {}
+            }
+            self.menu = OverlayMenu::None;
+            return;
+        }
+        self.menu = OverlayMenu::StartMenu { cursor };
+    }
+
+    fn update_add_menu(&mut self, mut cursor: usize, spawn_x: i16, spawn_y: i16, pressed: u16) {
+        const KINDS: usize = 10;
+        if (pressed & BTN_DUP) != 0 {
+            cursor = (cursor + KINDS - 1) % KINDS;
+        } else if (pressed & BTN_DDOWN) != 0 {
+            cursor = (cursor + 1) % KINDS;
+        }
+        if (pressed & (BTN_B | BTN_Z)) != 0 {
+            self.menu = OverlayMenu::None;
+            return;
+        }
+        if (pressed & BTN_A) != 0 {
+            let kind = match cursor {
+                0 => NodeType::Texture0 {
+                    pattern: TexPattern::ChromeEnv,
+                    scroll_x: 0,
+                    scroll_y: 0,
+                    env_map: false,
+                },
+                1 => NodeType::Texture1 {
+                    pattern: TexPattern::WaterCaustics,
+                    scroll_x: 1,
+                    scroll_y: 1,
+                    env_map: false,
+                },
+                2 => NodeType::VertexColor,
+                3 => NodeType::PrimColor { rgba: [255, 160, 64, 255] },
+                4 => NodeType::EnvColor { rgba: [90, 210, 255, 255] },
+                5 => NodeType::Noise,
+                6 => NodeType::Fresnel { power: 2, bias: 16 },
+                7 => NodeType::Mix { factor: 128 },
+                8 => NodeType::Multiply,
+                _ => NodeType::Add,
+            };
+            if self.graph.add_node(kind, spawn_x, spawn_y).is_some() {
+                self.compiled = compile(&self.graph);
+                self.graph.is_dirty = false;
+                self.set_toast("NODE ADDED");
+            } else {
+                self.set_toast("GRAPH FULL (32)");
+            }
+            self.menu = OverlayMenu::None;
+            return;
+        }
+        self.menu = OverlayMenu::AddNodeMenu {
+            cursor,
+            spawn_x,
+            spawn_y,
+        };
+    }
+
+    fn update_param_editor(&mut self, node_id: NodeId, mut field: usize, pressed: u16, held: u16) {
+        if (pressed & (BTN_B | BTN_A)) != 0 {
+            self.menu = OverlayMenu::None;
+            return;
+        }
+        let Some(node) = self.graph.node(node_id) else {
+            self.menu = OverlayMenu::None;
+            return;
+        };
+        let field_count = match node.kind {
+            NodeType::Texture0 { .. } | NodeType::Texture1 { .. } => 4,
+            NodeType::PrimColor { .. } | NodeType::EnvColor { .. } => 4,
+            NodeType::Mix { .. } => 1,
+            NodeType::Fresnel { .. } => 2,
+            NodeType::Output { .. } => 1,
+            _ => {
+                self.menu = OverlayMenu::None;
+                return;
+            }
+        };
+        if (pressed & BTN_DUP) != 0 {
+            field = (field + field_count - 1) % field_count;
+        } else if (pressed & BTN_DDOWN) != 0 {
+            field = (field + 1) % field_count;
+        }
+
+        let step_pressed = if (pressed & BTN_DRIGHT) != 0 {
+            1i16
+        } else if (pressed & BTN_DLEFT) != 0 {
+            -1i16
+        } else {
+            0
+        };
+        let step_held = if (held & BTN_DRIGHT) != 0 {
+            4i16
+        } else if (held & BTN_DLEFT) != 0 {
+            -4i16
+        } else {
+            0
+        };
+
+        if step_pressed != 0 || step_held != 0 {
+            if let Some(n) = self.graph.node_mut(node_id) {
+                match &mut n.kind {
+                    NodeType::Texture0 {
+                        pattern,
+                        scroll_x,
+                        scroll_y,
+                        env_map,
+                    }
+                    | NodeType::Texture1 {
+                        pattern,
+                        scroll_x,
+                        scroll_y,
+                        env_map,
+                    } => {
+                        if step_pressed != 0 {
+                            match field {
+                                0 => {
+                                    let idx = (*pattern as i16 + step_pressed).rem_euclid(6) as u8;
+                                    *pattern = TexPattern::from_u8(idx);
+                                }
+                                1 => *scroll_x = (*scroll_x as i16 + step_pressed).clamp(-8, 8) as i8,
+                                2 => *scroll_y = (*scroll_y as i16 + step_pressed).clamp(-8, 8) as i8,
+                                _ => *env_map = !*env_map,
+                            }
+                        }
+                    }
+                    NodeType::PrimColor { rgba } | NodeType::EnvColor { rgba } => {
+                        let d = if step_pressed != 0 { step_pressed * 8 } else { step_held };
+                        rgba[field] = (rgba[field] as i16 + d).clamp(0, 255) as u8;
+                    }
+                    NodeType::Mix { factor } => {
+                        let d = if step_pressed != 0 { step_pressed * 8 } else { step_held };
+                        *factor = (*factor as i16 + d).clamp(0, 255) as u8;
+                    }
+                    NodeType::Fresnel { power, bias } => {
+                        if step_pressed != 0 {
+                            if field == 0 {
+                                *power = (*power as i16 + step_pressed).clamp(1, 8) as u8;
+                            } else {
+                                *bias = (*bias as i16 + step_pressed * 8).clamp(0, 200) as u8;
+                            }
+                        }
+                    }
+                    NodeType::Output { blend_mode } => {
+                        if step_pressed != 0 {
+                            let idx = (*blend_mode as i16 + step_pressed).rem_euclid(3) as u8;
+                            *blend_mode = BlendMode::from_u8(idx);
+                        }
+                    }
+                    _ => {}
+                }
+            }
+            if self.graph.is_dirty {
+                self.compiled = compile(&self.graph);
+                self.graph.is_dirty = false;
+            }
+        }
+        self.menu = OverlayMenu::EditParam { node: node_id, field };
+    }
+
+    pub fn snap_cursor(&mut self, dir_x: i16, dir_y: i16) {
+        let mut best_score = i32::MAX;
+        let mut best_pos: Option<(i16, i16)> = None;
+
+        let mut consider = |tx: i16, ty: i16| {
+            let dx = (tx - self.cursor_x) as i32;
+            let dy = (ty - self.cursor_y) as i32;
+            let proj = dx * (dir_x as i32) + dy * (dir_y as i32);
+            if proj <= 2 {
+                return;
+            }
+            let ortho = if dir_x != 0 { dy.abs() } else { dx.abs() };
+            let score = proj + ortho * 2;
+            if score < best_score {
+                best_score = score;
+                best_pos = Some((tx, ty));
+            }
+        };
+
+        for n in &self.graph.nodes {
+            let (w, _) = n.kind.size();
+            consider(n.x + w / 2, n.y + 5); // node title bar
+            for s in 0..n.kind.input_count() {
+                let (px, py) = n.pin_pos(s, PinDir::Input);
+                consider(px, py);
+            }
+            for s in 0..n.kind.output_count() {
+                let (px, py) = n.pin_pos(s, PinDir::Output);
+                consider(px, py);
+            }
+        }
+
+        if let Some((bx, by)) = best_pos {
+            self.cursor_x = bx.clamp(2, CANVAS_W - 3);
+            self.cursor_y = by.clamp(HEADER_H + 2, LOGICAL_H - 3);
+        }
+    }
+
+    fn hit_pin(&self, x: i16, y: i16) -> Option<PinId> {
+        let mut best = None;
+        let mut best_d2 = 36i32; // radius 6 px
+        for n in &self.graph.nodes {
+            for s in 0..n.kind.input_count() {
+                let (px, py) = n.pin_pos(s, PinDir::Input);
+                let d2 = ((x - px) as i32).pow(2) + ((y - py) as i32).pow(2);
+                if d2 <= best_d2 {
+                    best_d2 = d2;
+                    best = Some(PinId {
+                        node: n.id,
+                        slot: s,
+                        dir: PinDir::Input,
+                    });
+                }
+            }
+            for s in 0..n.kind.output_count() {
+                let (px, py) = n.pin_pos(s, PinDir::Output);
+                let d2 = ((x - px) as i32).pow(2) + ((y - py) as i32).pow(2);
+                if d2 <= best_d2 {
+                    best_d2 = d2;
+                    best = Some(PinId {
+                        node: n.id,
+                        slot: s,
+                        dir: PinDir::Output,
+                    });
+                }
+            }
+        }
+        best
+    }
+
+    fn hit_node(&self, x: i16, y: i16) -> Option<NodeId> {
+        self.hit_node_part(x, y).map(|(id, _, _, _)| id)
+    }
+
+    fn hit_node_part(&self, x: i16, y: i16) -> Option<(NodeId, bool, i16, i16)> {
+        for n in self.graph.nodes.iter().rev() {
+            let (w, h) = n.kind.size();
+            if x >= n.x && x <= n.x + w && y >= n.y && y <= n.y + h {
+                let is_title = y <= n.y + 11;
+                return Some((n.id, is_title, n.x, n.y));
+            }
+        }
+        None
+    }
+
+    /// Render the Left 65% SGI-style node editor canvas + header/footer bars into `fb`.
+    pub fn render_canvas(&self, fb: &mut [u16], fb_w: usize, fb_h: usize) {
+        let sc = if fb_w >= 640 { 2 } else { 1 };
+        let cw = (CANVAS_W as usize) * sc;
+
+        // 1. SGI-style dark grid background on Left 65%
+        let bg_base = rgb5551(22, 27, 36);
+        let grid_minor = rgb5551(30, 38, 50);
+        let grid_major = rgb5551(42, 54, 72);
+        for py in (HEADER_H as usize * sc)..fb_h {
+            let ly = py / sc;
+            let row = py * fb_w;
+            let is_ymaj = (ly & 31) == 0;
+            let is_ymin = (ly & 15) == 0;
+            for px in 0..cw.min(fb_w) {
+                let lx = px / sc;
+                let col = if is_ymaj || (lx & 31) == 0 {
+                    grid_major
+                } else if is_ymin || (lx & 15) == 0 {
+                    grid_minor
+                } else {
+                    bg_base
+                };
+                fb[row + px] = col;
+            }
+        }
+
+        // 2. Top header bar across full width (320px) + bottom viewport chrome
+        fill_rect(fb, fb_w, fb_h, 0, 0, LOGICAL_W, HEADER_H, rgb5551(32, 46, 74), sc);
+        draw_line(
+            fb,
+            fb_w,
+            fb_h,
+            0,
+            HEADER_H - 1,
+            LOGICAL_W - 1,
+            HEADER_H - 1,
+            rgb5551(72, 108, 168),
+            sc,
+        );
+        draw_text_scaled(fb, fb_w, fb_h, 4, 4, "N64 NODE SHADER STUDIO", rgb5551(235, 244, 255), sc);
+
+        let mut hdr_right: String<24> = String::new();
+        let _ = write!(hdr_right, "P{}:{}", self.active_preset + 1, self.mesh_kind.name());
+        draw_text_scaled(fb, fb_w, fb_h, VP_X + 4, 4, &hdr_right, rgb5551(160, 220, 255), sc);
+
+        // Right 35% divider & footer background (viewport interior itself is filled by RDP!)
+        fill_rect(
+            fb,
+            fb_w,
+            fb_h,
+            VP_X,
+            VP_Y + VP_H,
+            VP_W,
+            LOGICAL_H - (VP_Y + VP_H),
+            rgb5551(20, 24, 34),
+            sc,
+        );
+        draw_line(
+            fb,
+            fb_w,
+            fb_h,
+            VP_X,
+            HEADER_H,
+            VP_X,
+            LOGICAL_H - 1,
+            rgb5551(84, 112, 164),
+            sc,
+        );
+
+        // 3. Draw Bezier wires
+        let wire_col = match &self.compiled {
+            Ok(_) => rgb5551(80, 220, 255),
+            Err(_) => rgb5551(240, 120, 70),
+        };
+        for w in &self.graph.wires {
+            if let (Some(n_from), Some(n_to)) =
+                (self.graph.node(w.from.node), self.graph.node(w.to.node))
+            {
+                let p0 = n_from.pin_pos(w.from.slot, PinDir::Output);
+                let p1 = n_to.pin_pos(w.to.slot, PinDir::Input);
+                draw_bezier_wire(fb, fb_w, fb_h, p0, p1, wire_col, sc);
+            }
+        }
+        if let DragState::DraggingWire(pin) = self.drag {
+            if let Some(n) = self.graph.node(pin.node) {
+                let p0 = n.pin_pos(pin.slot, pin.dir);
+                draw_bezier_wire(
+                    fb,
+                    fb_w,
+                    fb_h,
+                    p0,
+                    (self.cursor_x, self.cursor_y),
+                    rgb5551(255, 225, 90),
+                    sc,
+                );
+            }
+        }
+
+        // 4. Draw Node Boxes
+        let err_node = self.compiled.as_ref().err().and_then(|e| e.offending_node());
+        let flash_red = (self.frame & 16) != 0;
+        let hovered_pin = self.hit_pin(self.cursor_x, self.cursor_y);
+
+        for n in &self.graph.nodes {
+            let (w, h) = n.kind.size();
+            let is_err = err_node == Some(n.id);
+            let body_col = rgb5551(36, 42, 54);
+            let hdr_col = match n.kind.category() {
+                NodeCategory::Input => rgb5551(26, 108, 122),
+                NodeCategory::Math => rgb5551(74, 62, 142),
+                NodeCategory::Output => rgb5551(158, 104, 30),
+            };
+            let border_col = if is_err {
+                if flash_red {
+                    rgb5551(255, 48, 48)
+                } else {
+                    rgb5551(190, 28, 28)
+                }
+            } else {
+                rgb5551(96, 114, 146)
+            };
+
+            fill_rect(fb, fb_w, fb_h, n.x, n.y, w, h, body_col, sc);
+            fill_rect(fb, fb_w, fb_h, n.x, n.y, w, 10, hdr_col, sc);
+            draw_rect_outline(fb, fb_w, fb_h, n.x, n.y, w, h, border_col, sc);
+            draw_text_scaled(fb, fb_w, fb_h, n.x + 3, n.y + 2, n.kind.title(), rgb5551(245, 248, 255), sc);
+            if is_err {
+                draw_text_scaled(fb, fb_w, fb_h, n.x + w - 16, n.y + 2, "!", rgb5551(255, 80, 80), sc);
+            }
+
+            // Input & Output pins
+            for s in 0..n.kind.input_count() {
+                let (px, py) = n.pin_pos(s, PinDir::Input);
+                let is_hov = hovered_pin
+                    == Some(PinId {
+                        node: n.id,
+                        slot: s,
+                        dir: PinDir::Input,
+                    });
+                let pcol = if is_hov {
+                    rgb5551(255, 240, 96)
+                } else if self.graph.input_source(n.id, s).is_some() {
+                    rgb5551(90, 235, 255)
+                } else {
+                    rgb5551(150, 165, 190)
+                };
+                fill_rect(fb, fb_w, fb_h, px - 2, py - 2, 5, 5, pcol, sc);
+                draw_text_scaled(fb, fb_w, fb_h, px + 4, py - 2, n.kind.input_label(s), rgb5551(195, 205, 220), sc);
+            }
+            for s in 0..n.kind.output_count() {
+                let (px, py) = n.pin_pos(s, PinDir::Output);
+                let is_hov = hovered_pin
+                    == Some(PinId {
+                        node: n.id,
+                        slot: s,
+                        dir: PinDir::Output,
+                    });
+                let pcol = if is_hov {
+                    rgb5551(255, 240, 96)
+                } else {
+                    rgb5551(110, 245, 175)
+                };
+                fill_rect(fb, fb_w, fb_h, px - 2, py - 2, 5, 5, pcol, sc);
+                let lbl = n.kind.output_label(s);
+                let lx = px - 4 - (lbl.len() as i16) * 5;
+                draw_text_scaled(fb, fb_w, fb_h, lx, py - 2, lbl, rgb5551(195, 225, 205), sc);
+            }
+
+            // Compact parameter swatch/label at bottom of node
+            match n.kind {
+                NodeType::PrimColor { rgba } | NodeType::EnvColor { rgba } => {
+                    fill_rect(
+                        fb,
+                        fb_w,
+                        fb_h,
+                        n.x + 4,
+                        n.y + h - 7,
+                        w - 8,
+                        4,
+                        rgb5551(rgba[0], rgba[1], rgba[2]),
+                        sc,
+                    );
+                }
+                NodeType::Texture0 { pattern, .. } | NodeType::Texture1 { pattern, .. } => {
+                    draw_text_scaled(
+                        fb,
+                        fb_w,
+                        fb_h,
+                        n.x + 4,
+                        n.y + h - 8,
+                        pattern.short_name(),
+                        rgb5551(170, 220, 235),
+                        sc,
+                    );
+                }
+                NodeType::Mix { factor } => {
+                    let mut s: String<8> = String::new();
+                    let pct = ((factor as u16) * 100) / 255;
+                    let _ = write!(s, "T:{pct}%");
+                    draw_text_scaled(fb, fb_w, fb_h, n.x + 4, n.y + h - 8, &s, rgb5551(210, 200, 255), sc);
+                }
+                NodeType::Fresnel { power, .. } => {
+                    let mut s: String<8> = String::new();
+                    let _ = write!(s, "POW:{power}");
+                    draw_text_scaled(fb, fb_w, fb_h, n.x + 4, n.y + h - 8, &s, rgb5551(170, 240, 210), sc);
+                }
+                NodeType::Output { blend_mode } => {
+                    draw_text_scaled(
+                        fb,
+                        fb_w,
+                        fb_h,
+                        n.x + 4,
+                        n.y + h - 8,
+                        blend_mode.short_name(),
+                        rgb5551(255, 210, 120),
+                        sc,
+                    );
+                }
+                _ => {}
+            }
+        }
+
+        // 5. Canvas footer controls / toast hint
+        fill_rect(fb, fb_w, fb_h, 0, LOGICAL_H - 11, CANVAS_W, 11, rgb5551(18, 22, 30), sc);
+        if self.toast_timer > 0 {
+            draw_text_scaled(fb, fb_w, fb_h, 4, LOGICAL_H - 9, &self.toast, rgb5551(255, 224, 110), sc);
+        } else {
+            draw_text_scaled(
+                fb,
+                fb_w,
+                fb_h,
+                4,
+                LOGICAL_H - 9,
+                "A:WIRE/EDIT Z:ADD START:MENU L/R:3D",
+                rgb5551(140, 158, 184),
+                sc,
+            );
+        }
+
+        // 6. Popup Menus (if open)
+        self.render_menu(fb, fb_w, fb_h, sc);
+
+        // 7. Crisp crosshair cursor
+        draw_cursor(fb, fb_w, fb_h, self.cursor_x, self.cursor_y, sc);
+    }
+
+    fn render_menu(&self, fb: &mut [u16], fb_w: usize, fb_h: usize, sc: usize) {
+        match self.menu {
+            OverlayMenu::None => {}
+            OverlayMenu::StartMenu { cursor } => {
+                let (mx, my, mw, mh) = (18, 28, 172, 134);
+                fill_rect(fb, fb_w, fb_h, mx, my, mw, mh, rgb5551(20, 26, 40), sc);
+                draw_rect_outline(fb, fb_w, fb_h, mx, my, mw, mh, rgb5551(120, 170, 255), sc);
+                fill_rect(fb, fb_w, fb_h, mx, my, mw, 11, rgb5551(42, 68, 118), sc);
+                draw_text_scaled(fb, fb_w, fb_h, mx + 4, my + 3, "STUDIO MENU (START)", rgb5551(255, 255, 255), sc);
+
+                let labels = [
+                    "1: METAL CAP CHROME",
+                    "2: LAVA FLOW",
+                    "3: SCI-FI HOLOGRAM",
+                    "4: TOON CEL-SHADER",
+                    "5: WATER CAUSTICS",
+                    "6: HARDWARE NOISE",
+                    "TOGGLE AUTO-SPIN",
+                    "TOGGLE PERF HUD",
+                    "TOGGLE 320P / 480I",
+                    "SAVE TO EEPROM SLOT 0",
+                    "LOAD FROM EEPROM SLOT 0",
+                ];
+                for (i, lbl) in labels.iter().enumerate() {
+                    let iy = my + 14 + (i as i16) * 10;
+                    if i == cursor {
+                        fill_rect(fb, fb_w, fb_h, mx + 2, iy - 1, mw - 4, 9, rgb5551(58, 92, 152), sc);
+                    }
+                    let col = if i == cursor { rgb5551(255, 240, 120) } else { rgb5551(205, 215, 232) };
+                    draw_text_scaled(fb, fb_w, fb_h, mx + 6, iy + 1, lbl, col, sc);
+                }
+            }
+            OverlayMenu::AddNodeMenu { cursor, .. } => {
+                let (mx, my, mw, mh) = (32, 36, 136, 120);
+                fill_rect(fb, fb_w, fb_h, mx, my, mw, mh, rgb5551(22, 28, 42), sc);
+                draw_rect_outline(fb, fb_w, fb_h, mx, my, mw, mh, rgb5551(110, 230, 190), sc);
+                fill_rect(fb, fb_w, fb_h, mx, my, mw, 11, rgb5551(28, 92, 92), sc);
+                draw_text_scaled(fb, fb_w, fb_h, mx + 4, my + 3, "ADD NODE (A:OK B:ESC)", rgb5551(255, 255, 255), sc);
+
+                let items = [
+                    "TEX0 (TEXTURE 0)",
+                    "TEX1 (TEXTURE 1)",
+                    "VERTEX COLOR",
+                    "PRIM COLOR",
+                    "ENV COLOR",
+                    "RDP NOISE",
+                    "FRESNEL RIM",
+                    "MIX (LERP)",
+                    "MULTIPLY",
+                    "ADD",
+                ];
+                for (i, lbl) in items.iter().enumerate() {
+                    let iy = my + 14 + (i as i16) * 10;
+                    if i == cursor {
+                        fill_rect(fb, fb_w, fb_h, mx + 2, iy - 1, mw - 4, 9, rgb5551(45, 118, 120), sc);
+                    }
+                    let col = if i == cursor { rgb5551(255, 245, 130) } else { rgb5551(210, 224, 236) };
+                    draw_text_scaled(fb, fb_w, fb_h, mx + 6, iy + 1, lbl, col, sc);
+                }
+            }
+            OverlayMenu::EditParam { node, field } => {
+                let Some(n) = self.graph.node(node) else {
+                    return;
+                };
+                let (mx, my, mw, mh) = (26, 62, 152, 68);
+                fill_rect(fb, fb_w, fb_h, mx, my, mw, mh, rgb5551(22, 26, 38), sc);
+                draw_rect_outline(fb, fb_w, fb_h, mx, my, mw, mh, rgb5551(240, 195, 90), sc);
+                fill_rect(fb, fb_w, fb_h, mx, my, mw, 11, rgb5551(110, 80, 32), sc);
+                draw_text_scaled(fb, fb_w, fb_h, mx + 4, my + 3, "EDIT NODE (D-PAD)", rgb5551(255, 255, 255), sc);
+
+                let mut lines: Vec<String<28>, 4> = Vec::new();
+                match n.kind {
+                    NodeType::Texture0 { pattern, scroll_x, scroll_y, env_map }
+                    | NodeType::Texture1 { pattern, scroll_x, scroll_y, env_map } => {
+                        let mut s0 = String::new();
+                        let _ = write!(s0, "PATTERN: {}", pattern.short_name());
+                        let mut s1 = String::new();
+                        let _ = write!(s1, "SCROLL X: {scroll_x}");
+                        let mut s2 = String::new();
+                        let _ = write!(s2, "SCROLL Y: {scroll_y}");
+                        let mut s3 = String::new();
+                        let _ = write!(s3, "ENV MAP: {}", if env_map { "ON" } else { "OFF" });
+                        let _ = lines.push(s0);
+                        let _ = lines.push(s1);
+                        let _ = lines.push(s2);
+                        let _ = lines.push(s3);
+                    }
+                    NodeType::PrimColor { rgba } | NodeType::EnvColor { rgba } => {
+                        for (ci, ch) in ["R", "G", "B", "A"].iter().enumerate() {
+                            let mut s = String::new();
+                            let _ = write!(s, "{ch}: {}", rgba[ci]);
+                            let _ = lines.push(s);
+                        }
+                    }
+                    NodeType::Mix { factor } => {
+                        let mut s = String::new();
+                        let _ = write!(s, "FACTOR: {factor}");
+                        let _ = lines.push(s);
+                    }
+                    NodeType::Fresnel { power, bias } => {
+                        let mut s0 = String::new();
+                        let _ = write!(s0, "POWER: {power}");
+                        let mut s1 = String::new();
+                        let _ = write!(s1, "BIAS: {bias}");
+                        let _ = lines.push(s0);
+                        let _ = lines.push(s1);
+                    }
+                    NodeType::Output { blend_mode } => {
+                        let mut s = String::new();
+                        let _ = write!(s, "BLEND: {}", blend_mode.short_name());
+                        let _ = lines.push(s);
+                    }
+                    _ => {}
+                }
+                for (i, line) in lines.iter().enumerate() {
+                    let iy = my + 16 + (i as i16) * 11;
+                    if i == field {
+                        fill_rect(fb, fb_w, fb_h, mx + 3, iy - 1, mw - 6, 9, rgb5551(88, 72, 42), sc);
+                    }
+                    let col = if i == field { rgb5551(255, 240, 120) } else { rgb5551(210, 218, 232) };
+                    draw_text_scaled(fb, fb_w, fb_h, mx + 6, iy + 1, line, col, sc);
+                }
+            }
+        }
+    }
+
+    /// Draw wireframe (if enabled), compiler error notice, and hardware Perf HUD in the Right 35% Viewport.
+    pub fn render_viewport_overlay(
+        &self,
+        fb: &mut [u16],
+        fb_w: usize,
+        fb_h: usize,
+        tris: &[ProjectedTri],
+        perf: &PerfStats,
+    ) {
+        let sc = if fb_w >= 640 { 2 } else { 1 };
+
+        // Optional wireframe overlay clipped to viewport
+        if self.wireframe {
+            let wf_col = rgb5551(160, 255, 190);
+            for tri in tris {
+                let p0 = (tri.v[0].x as i16, tri.v[0].y as i16);
+                let p1 = (tri.v[1].x as i16, tri.v[1].y as i16);
+                let p2 = (tri.v[2].x as i16, tri.v[2].y as i16);
+                draw_line_clipped(fb, fb_w, fb_h, p0.0, p0.1, p1.0, p1.1, wf_col, VP_X * (sc as i16), VP_Y * (sc as i16), (VP_X + VP_W) * (sc as i16), (VP_Y + VP_H) * (sc as i16));
+                draw_line_clipped(fb, fb_w, fb_h, p1.0, p1.1, p2.0, p2.1, wf_col, VP_X * (sc as i16), VP_Y * (sc as i16), (VP_X + VP_W) * (sc as i16), (VP_Y + VP_H) * (sc as i16));
+                draw_line_clipped(fb, fb_w, fb_h, p2.0, p2.1, p0.0, p0.1, wf_col, VP_X * (sc as i16), VP_Y * (sc as i16), (VP_X + VP_W) * (sc as i16), (VP_Y + VP_H) * (sc as i16));
+            }
+        }
+
+        // Compiler error banner inside viewport if graph is invalid
+        if let Err(err) = &self.compiled {
+            fill_rect(fb, fb_w, fb_h, VP_X + 4, VP_Y + 76, VP_W - 8, 28, rgb5551(92, 16, 16), sc);
+            draw_rect_outline(fb, fb_w, fb_h, VP_X + 4, VP_Y + 76, VP_W - 8, 28, rgb5551(255, 72, 72), sc);
+            draw_text_scaled(fb, fb_w, fb_h, VP_X + 8, VP_Y + 80, "COMPILE ERROR:", rgb5551(255, 190, 190), sc);
+            draw_text_scaled(fb, fb_w, fb_h, VP_X + 8, VP_Y + 90, err.summary(), rgb5551(255, 255, 255), sc);
+        }
+
+        // Top-right Perf Overlay inside viewport
+        if self.show_perf {
+            let mut s1: String<24> = String::new();
+            let _ = write!(s1, "{}FPS {}us", perf.fps, perf.frame_us);
+            draw_text_scaled(fb, fb_w, fb_h, VP_X + 4, VP_Y + 4, &s1, rgb5551(140, 255, 175), sc);
+
+            let mut s2: String<24> = String::new();
+            let _ = write!(s2, "RDP:{}clk", perf.rdp_clock);
+            draw_text_scaled(fb, fb_w, fb_h, VP_X + 4, VP_Y + 12, &s2, rgb5551(170, 225, 255), sc);
+
+            let mut s3: String<24> = String::new();
+            let cyc = match &self.compiled {
+                Ok(c) => match c.cycles {
+                    CycleCount::OneCycle => "1CYC",
+                    CycleCount::TwoCycle => "2CYC",
+                },
+                Err(_) => "ERR ",
+            };
+            let inp_lbl = if perf.is_mouse { "MSE" } else { "PAD" };
+            let _ = write!(s3, "{cyc} {}M {inp_lbl}", perf.rdram_mb);
+            draw_text_scaled(fb, fb_w, fb_h, VP_X + 4, VP_Y + 20, &s3, rgb5551(225, 215, 145), sc);
+        }
+
+        // Bottom viewport shader/combiner summary
+        let fy = VP_Y + VP_H + 3;
+        match &self.compiled {
+            Ok(c) => {
+                let mut l1: String<24> = String::new();
+                let _ = write!(l1, "C1:{}", &c.cycle1_text);
+                draw_text_scaled(fb, fb_w, fb_h, VP_X + 3, fy, &l1, rgb5551(160, 230, 255), sc);
+                let mut l2: String<24> = String::new();
+                let _ = write!(l2, "C2:{}", &c.cycle2_text);
+                draw_text_scaled(fb, fb_w, fb_h, VP_X + 3, fy + 8, &l2, rgb5551(190, 200, 225), sc);
+                let mut l3: String<24> = String::new();
+                let _ = write!(l3, "CC:{:016X}", c.combine_cmd);
+                draw_text_scaled(fb, fb_w, fb_h, VP_X + 3, fy + 16, &l3, rgb5551(135, 160, 190), sc);
+            }
+            Err(e) => {
+                draw_text_scaled(fb, fb_w, fb_h, VP_X + 3, fy + 4, e.summary(), rgb5551(255, 110, 110), sc);
+            }
+        }
+    }
+}
+
+fn fill_rect(fb: &mut [u16], fb_w: usize, fb_h: usize, x: i16, y: i16, w: i16, h: i16, col: u16, sc: usize) {
+    let x0 = ((x as i32) * (sc as i32)).clamp(0, fb_w as i32) as usize;
+    let y0 = ((y as i32) * (sc as i32)).clamp(0, fb_h as i32) as usize;
+    let x1 = (((x + w) as i32) * (sc as i32)).clamp(0, fb_w as i32) as usize;
+    let y1 = (((y + h) as i32) * (sc as i32)).clamp(0, fb_h as i32) as usize;
+    for py in y0..y1 {
+        let row = py * fb_w;
+        for px in x0..x1 {
+            fb[row + px] = col;
+        }
+    }
+}
+
+fn draw_rect_outline(fb: &mut [u16], fb_w: usize, fb_h: usize, x: i16, y: i16, w: i16, h: i16, col: u16, sc: usize) {
+    draw_line(fb, fb_w, fb_h, x, y, x + w - 1, y, col, sc);
+    draw_line(fb, fb_w, fb_h, x, y + h - 1, x + w - 1, y + h - 1, col, sc);
+    draw_line(fb, fb_w, fb_h, x, y, x, y + h - 1, col, sc);
+    draw_line(fb, fb_w, fb_h, x + w - 1, y, x + w - 1, y + h - 1, col, sc);
+}
+
+fn draw_line(fb: &mut [u16], fb_w: usize, fb_h: usize, x0: i16, y0: i16, x1: i16, y1: i16, col: u16, sc: usize) {
+    draw_line_clipped(
+        fb,
+        fb_w,
+        fb_h,
+        x0 * (sc as i16),
+        y0 * (sc as i16),
+        x1 * (sc as i16),
+        y1 * (sc as i16),
+        col,
+        0,
+        0,
+        fb_w as i16,
+        fb_h as i16,
+    );
+}
+
+#[allow(clippy::too_many_arguments)]
+fn draw_line_clipped(
+    fb: &mut [u16],
+    fb_w: usize,
+    fb_h: usize,
+    mut x0: i16,
+    mut y0: i16,
+    x1: i16,
+    y1: i16,
+    col: u16,
+    cx0: i16,
+    cy0: i16,
+    cx1: i16,
+    cy1: i16,
+) {
+    let dx = (x1 - x0).abs();
+    let sx = if x0 < x1 { 1 } else { -1 };
+    let dy = -(y1 - y0).abs();
+    let sy = if y0 < y1 { 1 } else { -1 };
+    let mut err = dx + dy;
+
+    loop {
+        if x0 >= cx0 && x0 < cx1 && y0 >= cy0 && y0 < cy1 && (y0 as usize) < fb_h && (x0 as usize) < fb_w {
+            fb[(y0 as usize) * fb_w + (x0 as usize)] = col;
+        }
+        if x0 == x1 && y0 == y1 {
+            break;
+        }
+        let e2 = 2 * err;
+        if e2 >= dy {
+            err += dy;
+            x0 += sx;
+        }
+        if e2 <= dx {
+            err += dx;
+            y0 += sy;
+        }
+    }
+}
+
+fn draw_bezier_wire(
+    fb: &mut [u16],
+    fb_w: usize,
+    fb_h: usize,
+    p0: (i16, i16),
+    p3: (i16, i16),
+    col: u16,
+    sc: usize,
+) {
+    let dx = ((p3.0 - p0.0).abs() / 2).max(16);
+    let p1 = (p0.0 + dx, p0.1);
+    let p2 = (p3.0 - dx, p3.1);
+    let mut prev = p0;
+    const SEGS: i32 = 8;
+    for i in 1..=SEGS {
+        let t = (i as f32) / (SEGS as f32);
+        let u = 1.0 - t;
+        let b0 = u * u * u;
+        let b1 = 3.0 * u * u * t;
+        let b2 = 3.0 * u * t * t;
+        let b3 = t * t * t;
+        let bx = (b0 * p0.0 as f32 + b1 * p1.0 as f32 + b2 * p2.0 as f32 + b3 * p3.0 as f32) as i16;
+        let by = (b0 * p0.1 as f32 + b1 * p1.1 as f32 + b2 * p2.1 as f32 + b3 * p3.1 as f32) as i16;
+        draw_line_clipped(
+            fb,
+            fb_w,
+            fb_h,
+            prev.0 * (sc as i16),
+            prev.1 * (sc as i16),
+            bx * (sc as i16),
+            by * (sc as i16),
+            col,
+            0,
+            HEADER_H * sc as i16,
+            CANVAS_W * sc as i16,
+            fb_h as i16,
+        );
+        prev = (bx, by);
+    }
+}
+
+fn draw_cursor(fb: &mut [u16], fb_w: usize, fb_h: usize, cx: i16, cy: i16, sc: usize) {
+    let white = rgb5551(255, 255, 255);
+    let dark = rgb5551(16, 20, 28);
+    // Subtle dark shadow + bright white crosshair
+    draw_line(fb, fb_w, fb_h, cx - 4, cy + 1, cx + 4, cy + 1, dark, sc);
+    draw_line(fb, fb_w, fb_h, cx + 1, cy - 4, cx + 1, cy + 4, dark, sc);
+    draw_line(fb, fb_w, fb_h, cx - 4, cy, cx + 4, cy, white, sc);
+    draw_line(fb, fb_w, fb_h, cx, cy - 4, cx, cy + 4, white, sc);
+    let px = (cx as usize) * sc;
+    let py = (cy as usize) * sc;
+    if py < fb_h && px < fb_w {
+        fb[py * fb_w + px] = blend_rgb5551(fb[py * fb_w + px], rgb5551(255, 220, 80), 220);
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn dpad_snaps_to_pins_and_canvas_renders() {
+        let mut app = StudioApp::new();
+        app.cursor_x = 40;
+        app.cursor_y = 30;
+        app.snap_cursor(1, 0);
+        assert!(app.cursor_x > 40);
+
+        // Verify rendering at both 320x240 and 640x480 without panic
+        let mut fb320 = vec![0u16; 320 * 240];
+        app.render_canvas(&mut fb320, 320, 240);
+        assert!(fb320.iter().any(|&p| p != 0));
+
+        let mut fb640 = vec![0u16; 640 * 480];
+        app.render_canvas(&mut fb640, 640, 480);
+        assert!(fb640.iter().any(|&p| p != 0));
+    }
+
+    #[test]
+    fn disconnect_and_reconnect_updates_dirty_and_compiles() {
+        let mut app = StudioApp::new();
+        let out_id = app.graph.find_output().unwrap();
+        let orig_src = app.graph.input_source(out_id, 0).unwrap();
+        assert!(app.graph.disconnect_input(PinId {
+            node: out_id,
+            slot: 0,
+            dir: PinDir::Input,
+        }));
+        app.update(&InputState::default(), &InputState::default());
+        assert_eq!(app.compiled.as_ref().unwrap_err(), &CompileError::UnconnectedOutput(out_id));
+
+        assert!(app.graph.connect(
+            orig_src,
+            PinId {
+                node: out_id,
+                slot: 0,
+                dir: PinDir::Input,
+            }
+        ));
+        app.update(&InputState::default(), &InputState::default());
+        assert!(app.compiled.is_ok());
+    }
+}

BIN
dist/n64-shader-studio.z64


+ 48 - 0
el plan.md

@@ -0,0 +1,48 @@
+### The Master Plan: "N64 Node Shader Studio" in Rust
+
+Since i have real hardware and a flashcart (which is ideal, because emulators often inaccuracies-mask RDP quirks that real hardware catches), here is a clean, realistic roadmap to build this in Rust.
+
+#### Phase 1: The Rust + N64 Toolchain Setup
+
+* **Option B: Pure Rust (`cargo-n64` / `n64-pac`)** — Zero C dependencies, super clean `#[no_std]` Rust, great if you want to write the low-level hardware drivers yourself, though you'll write more boilerplate for fonts and UI rendering.
+
+#### Phase 2: Architecture of the App (Split-Screen Workspace)
+
+Because the N64 runs best at **320×240** (or **640×480 interlaced** if you want extra crisp text for a node editor—and you have an Expansion Pak), we can split the screen into two zones:
+
+* **Left 65% of Screen: The Node Canvas**
+* Dark SGI-style grid background.
+* Movable node boxes (Input nodes on left $\rightarrow$ Math/Combiner nodes in middle $\rightarrow$ Material Output on right).
+* Bezier/segmented wires connecting pins.
+* Cursor controlled by the **N64 Analog Stick** (with D-Pad snapping to pins for precision!) or a real **N64 Mouse**.
+
+
+* **Right 35% of Screen: Live 3D Preview Viewport**
+* Renders a spinning 3D primitive (Sphere, Torus, Cube, or Classic Teapot) using the compiled shader in real time.
+* A-button or C-buttons let you rotate the mesh, toggle wireframe, or switch preview shapes/lighting presets.
+
+
+
+#### Phase 3: The Rust Node Graph & Compiler Core (`#[no_std]`)
+
+This is the heart of the project. You can build and unit-test this pure Rust module on your PC before even flashing it to the N64!
+
+1. **Data Model:**
+* `NodeId`, `PinId`, and `NodeType` (`Texture0`, `Texture1`, `VertexColor`, `PrimColor`, `EnvColor`, `Noise`, `Mix`, `Multiply`, `Add`, `Fresnel`, `Output`).
+* An arena or fixed-size array (`heapless::Vec<Node, 32>`) so you never deal with heap fragmentation in 4 MB of RDRAM.
+
+
+2. **The Graph-to-RDP Compiler:**
+* Runs only when a wire is connected, disconnected, or a slider/color value changes (`is_dirty = true`).
+* Walks backward from the `Output` node.
+* Maps up to two math operations into **RDP Cycle 1** and **RDP Cycle 2** (`(A - B) * C + D`).
+* Packs the result into an `rdpq_combiner_t` configuration (or raw 64-bit `G_SETCOMBINE` command word).
+* If the graph exceeds what the RDP can do in 2 cycles (e.g., trying to multiply 4 different textures together), the compiler returns `Err(CompileError::ExceedsTwoCycles(node_id))` and highlights that node red!
+
+
+
+#### Phase 4: Polish & "Wow" Features for Real Hardware
+
+* **Preset Library (Start Menu):** Include 5–6 pre-wired node graphs (e.g., *Mario 64 Metal Cap Chrome*, *Lava Flow*, *Hologram*, *Toon Cel-Shader*, *Water Caustics*) so anyone booting the ROM immediately sees cool visuals and can dissect how the nodes are wired.
+* **Hardware Performance Overlay:** Show live RSP/RDP cycle counts and frame time in microseconds—flexing how fast the real 1996 silicon renders your custom node graph.
+* **Controller Pak / Flashcart Save:** Allow saving/loading custom node graphs to SRAM/EEPROM so you can show off your shaders on real hardware without rewiring them every boot.