Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

33.0 KB
Raw Blame
//! Comprehensive Phase 2 Rust unit & headless DX12 GPU verification suite.

use crate::document::{
    BlendMode, CanvasColorMode, CanvasDimensions, Document, DocumentManager, ExpressionColor,
    LayerNodeMeta, LayerPropsPatch,
};
use crate::io::{
    encode_cow_deltas_to_wal_payload, encode_document_checkpoint, parse_ink_document,
    replay_recovery_into_document, serialize_ink_document, WalRawEntry,
};
use crate::memory::{
    FileScratchBackend, GpuTileKey, GpuTilePool, InMemoryScratchBackend, MemoryBudgetConfig,
    ScratchBackend,
};
use crate::tiles::{
    pack_rgba8_to_1bit, pack_rgba8_to_8bit, rgba16f_to_rgba8_dithered, rgba16f_to_rgba8_lossless,
    rgba8_to_rgba16f, unpack_1bit_to_rgba8, unpack_8bit_to_rgba8, CowTileDelta, RectI32,
    SparseLayerGrid,
    TileCoord, TileData, TileFormat, TileKind, TileStorage, BYTES_16F, BYTES_1BIT, BYTES_32BIT,
    BYTES_8BIT, TILE_PIXELS, TILE_SIZE,
};
use crate::gpu::GpuRenderer;
use crate::SurfaceTarget;
use half::f16;
use std::sync::Arc;

#[test]
fn test_sparse_virtual_tiles_solid_color_and_compaction() {
    let mut grid = SparseLayerGrid::new(TileFormat::Color32Bit);
    assert_eq!(grid.tiles.len(), 0);

    // 4K solid white fill uses SolidColor tiles with ZERO 256 KB raw buffers allocated!
    grid.fill_solid_layer(4096, 4096, [255, 255, 255, 255]);
    assert_eq!(grid.tiles.len(), 16 * 16);
    for tile in grid.tiles.values() {
        assert!(matches!(
            tile.storage,
            TileStorage::SolidColor {
                rgba8: [255, 255, 255, 255],
                ..
            }
        ));
        assert_eq!(tile.ram_bytes(), 0);
    }

    // Mutate a single pixel at (10, 10) -> promotes ONLY tile (0,0) to Raw
    let red_px = [220u8, 30, 40, 255];
    let touched = grid
        .write_rgba8_rect(&red_px, RectI32::new(10, 10, 1, 1), 128, None)
        .expect("write failed");
    assert_eq!(touched, vec![TileCoord::new(0, 0)]);
    assert!(matches!(
        grid.tiles.get(&TileCoord::new(0, 0)).unwrap().storage,
        TileStorage::Raw(_)
    ));
    // Neighbor tile (1, 0) remains zero-allocation SolidColor
    assert!(matches!(
        grid.tiles.get(&TileCoord::new(1, 0)).unwrap().storage,
        TileStorage::SolidColor {
            rgba8: [255, 255, 255, 255],
            ..
        }
    ));

    // Read back exact pixel
    let read = grid
        .read_rgba8_rect(RectI32::new(10, 10, 1, 1), false, None)
        .expect("read failed");
    assert_eq!(read, red_px);

    // Paint the entire (0,0) tile transparent -> tile is pruned from sparse map completely
    let clear_tile = vec![0u8; BYTES_32BIT];
    grid.write_rgba8_rect(&clear_tile, RectI32::new(0, 0, 256, 256), 128, None)
        .expect("clear write failed");
    assert!(!grid.tiles.contains_key(&TileCoord::new(0, 0)));

    // Paint tile (2,2) solid blue -> auto-compacts back to zero-allocation SolidColor
    let mut blue_tile = vec![0u8; BYTES_32BIT];
    for px in blue_tile.chunks_exact_mut(4) {
        px.copy_from_slice(&[10, 80, 240, 255]);
    }
    grid.write_rgba8_rect(&blue_tile, RectI32::new(512, 512, 256, 256), 128, None)
        .expect("solid blue write failed");
    assert!(matches!(
        grid.tiles.get(&TileCoord::new(2, 2)).unwrap().storage,
        TileStorage::SolidColor {
            rgba8: [10, 80, 240, 255],
            ..
        }
    ));
}

#[test]
fn test_pixel_format_conversions_1bit_8bit_32bit_16f_and_bayer_dithering() {
    assert_eq!(TileFormat::Monochrome1Bit.byte_size(), BYTES_1BIT);
    assert_eq!(TileFormat::Grayscale8Bit.byte_size(), BYTES_8BIT);
    assert_eq!(TileFormat::Color32Bit.byte_size(), BYTES_32BIT);
    assert_eq!(TileFormat::Rgba16Float.byte_size(), BYTES_16F);

    // 1. Lossless Color32Bit <-> Rgba16Float round-trip for ALL 256 channel intensities
    let mut rgba_in = vec![0u8; BYTES_32BIT];
    for i in 0..TILE_PIXELS {
        let v = (i & 255) as u8;
        rgba_in[i * 4] = v;
        rgba_in[i * 4 + 1] = 255 - v;
        rgba_in[i * 4 + 2] = v.wrapping_mul(3);
        rgba_in[i * 4 + 3] = 255;
    }
    let mut f16_buf = vec![0u8; BYTES_16F];
    rgba8_to_rgba16f(&rgba_in, &mut f16_buf);
    let mut rgba_out = vec![0u8; BYTES_32BIT];
    rgba16f_to_rgba8_lossless(&f16_buf, &mut rgba_out);
    assert_eq!(rgba_in, rgba_out, "Color32Bit <-> Rgba16Float must be bit-exact lossless");

    // 2. Bayer 4x4 ordered dithering preserves exact 0 and 255 endpoints while dithering mid-values
    let mut grad_f16 = vec![0u8; BYTES_16F];
    for i in 0..TILE_PIXELS {
        let off = i * 8;
        let x = i % TILE_SIZE;
        let val = if x == 0 {
            0.0f32
        } else if x == 1 {
            1.0f32
        } else {
            // Exact half-step 127.5 / 255.0 where Bayer dithering produces balanced 127/128 pattern
            127.5 / 255.0
        };
        let h = f16::from_f32(val).to_le_bytes();
        let one = f16::from_f32(1.0).to_le_bytes();
        grad_f16[off..off + 2].copy_from_slice(&h);
        grad_f16[off + 2..off + 4].copy_from_slice(&h);
        grad_f16[off + 4..off + 6].copy_from_slice(&h);
        grad_f16[off + 6..off + 8].copy_from_slice(&one);
    }
    let mut dithered = vec![0u8; BYTES_32BIT];
    rgba16f_to_rgba8_dithered(&grad_f16, &mut dithered);
    // Exact 0 and 255 endpoints never get dither noise
    for y in 0..TILE_SIZE {
        assert_eq!(dithered[(y * TILE_SIZE) * 4], 0);
        assert_eq!(dithered[(y * TILE_SIZE + 1) * 4], 255);
    }
    // Mid-step region contains both 127 and 128 (anti-banding dithering active)
    let mut c127 = 0usize;
    let mut c128 = 0usize;
    for y in 0..16 {
        for x in 2..18 {
            let r = dithered[(y * TILE_SIZE + x) * 4];
            if r == 127 {
                c127 += 1;
            } else if r == 128 {
                c128 += 1;
            }
        }
    }
    assert!(c127 > 50 && c128 > 50, "Expected balanced Bayer 4x4 dither (127={c127}, 128={c128})");

    // 3. Grayscale8Bit pack/unpack (matches pixelCodec.ts: BT.601 luma, 0 -> transparent, v -> [v,v,v,255])
    let mut gray_raw = vec![0u8; BYTES_8BIT];
    pack_rgba8_to_8bit(&rgba_in, &mut gray_raw);
    let mut gray_rgba = vec![0u8; BYTES_32BIT];
    unpack_8bit_to_rgba8(&gray_raw, &mut gray_rgba);
    // Pixel (0,0) had R=0, G=255, B=0, A=255 -> luma = (255*587 + 500)/1000 = 150 -> [150, 150, 150, 255]
    assert_eq!(&gray_rgba[0..4], &[150, 150, 150, 255]);

    // 4. Monochrome1Bit pack/unpack
    let mut mono_in = vec![0u8; BYTES_32BIT];
    // Mark first 8 pixels alternating opaque black ink & transparent
    for x in 0..8 {
        if x % 2 == 0 {
            mono_in[x * 4..x * 4 + 4].copy_from_slice(&[0, 0, 0, 255]);
        }
    }
    let mut mono_raw = vec![0u8; BYTES_1BIT];
    pack_rgba8_to_1bit(&mono_in, &mut mono_raw, 128);
    let mut mono_out = vec![0u8; BYTES_32BIT];
    unpack_1bit_to_rgba8(&mono_raw, &mut mono_out, [0, 0, 0, 255], [0, 0, 0, 0]);
    for x in 0..8 {
        let expected = if x % 2 == 0 { [0, 0, 0, 255] } else { [0, 0, 0, 0] };
        assert_eq!(&mono_out[x * 4..x * 4 + 4], &expected);
    }
}

#[test]
fn test_per_layer_non_destructive_mask_tiles_and_apply_undo() {
    let mut doc = Document::new_blank(
        "doc-mask",
        "Mask Test",
        CanvasDimensions {
            width: 512,
            height: 512,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        50,
    );
    let top_id = doc.active_layer_id.clone().unwrap();

    // Paint a 16x16 opaque red square on Layer 1
    let mut red_rect = vec![0u8; 16 * 16 * 4];
    for px in red_rect.chunks_exact_mut(4) {
        px.copy_from_slice(&[255, 0, 0, 255]);
    }
    doc.ingest_dirty_rect(
        &top_id,
        RectI32::new(0, 0, 16, 16),
        &red_rect,
        false,
        true,
        "brush",
        "Red Square",
        None,
        None,
        None,
    )
    .expect("ingest raster failed");

    // Add reveal-all mask -> ZERO mask tiles allocated!
    doc.add_layer_mask(&top_id, 255, true)
        .expect("add_layer_mask failed");
    assert!(doc.layer(&top_id).unwrap().grid.has_mask);
    assert_eq!(doc.layer(&top_id).unwrap().grid.mask_tiles.len(), 0);

    // Mask out left half (8x16 -> alpha 0)
    let zero_mask = vec![0u8; 8 * 16];
    doc.ingest_dirty_rect(
        &top_id,
        RectI32::new(0, 0, 8, 16),
        &zero_mask,
        true,
        true,
        "mask",
        "Paint Mask",
        None,
        None,
        None,
    )
    .expect("ingest mask failed");
    assert_eq!(doc.layer(&top_id).unwrap().grid.mask_tiles.len(), 1);

    // Apply mask permanently onto raster
    doc.remove_layer_mask(&top_id, true, true, None)
        .expect("apply mask failed");
    assert!(!doc.layer(&top_id).unwrap().grid.has_mask);

    let px_masked = doc
        .layer(&top_id)
        .unwrap()
        .grid
        .read_rgba8_rect(RectI32::new(2, 2, 1, 1), false, None)
        .unwrap();
    let px_visible = doc
        .layer(&top_id)
        .unwrap()
        .grid
        .read_rgba8_rect(RectI32::new(10, 2, 1, 1), false, None)
        .unwrap();
    assert_eq!(px_masked[3], 0, "Masked pixel alpha must become 0 after apply");
    assert_eq!(px_visible, [255, 0, 0, 255], "Unmasked pixel must stay opaque red");

    // Undo apply mask -> mask & full red square both restored!
    doc.undo();
    assert!(doc.layer(&top_id).unwrap().grid.has_mask);
    let px_restored = doc
        .layer(&top_id)
        .unwrap()
        .grid
        .read_rgba8_rect(RectI32::new(2, 2, 1, 1), false, None)
        .unwrap();
    assert_eq!(px_restored, [255, 0, 0, 255]);
}

#[test]
fn test_cow_arc_sharing_undo_redo_coalescing_and_canvas_resize() {
    let mut doc = Document::new_blank(
        "doc-cow",
        "CoW Test",
        CanvasDimensions {
            width: 512,
            height: 512,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        50,
    );
    let layer_id = doc.active_layer_id.clone().unwrap();

    // Paint 2 distinct tiles: (0,0) and (1,0)
    let green = [0u8, 200, 50, 255];
    let blue = [0u8, 80, 255, 255];
    doc.ingest_dirty_rect(
        &layer_id,
        RectI32::new(10, 10, 1, 1),
        &green,
        false,
        true,
        "brush",
        "Green Dot",
        None,
        None,
        None,
    )
    .unwrap();
    doc.ingest_dirty_rect(
        &layer_id,
        RectI32::new(300, 10, 1, 1),
        &blue,
        false,
        true,
        "brush",
        "Blue Dot",
        None,
        None,
        None,
    )
    .unwrap();

    // Duplicate layer -> O(1) Arc pointer sharing on BOTH tiles!
    doc.duplicate_layer(&layer_id, "layer-dup", true).unwrap();
    let orig_t0 = Arc::clone(doc.layer(&layer_id).unwrap().grid.tiles.get(&TileCoord::new(0, 0)).unwrap());
    let dup_t0 = Arc::clone(doc.layer("layer-dup").unwrap().grid.tiles.get(&TileCoord::new(0, 0)).unwrap());
    let orig_t1 = Arc::clone(doc.layer(&layer_id).unwrap().grid.tiles.get(&TileCoord::new(1, 0)).unwrap());
    let dup_t1 = Arc::clone(doc.layer("layer-dup").unwrap().grid.tiles.get(&TileCoord::new(1, 0)).unwrap());
    assert!(Arc::ptr_eq(&orig_t0, &dup_t0), "CoW duplicate must share untouched tile (0,0)");
    assert!(Arc::ptr_eq(&orig_t1, &dup_t1), "CoW duplicate must share untouched tile (1,0)");

    // Mutate ONLY tile (0,0) on duplicate -> (0,0) clones, (1,0) STAYS shared!
    doc.ingest_dirty_rect(
        "layer-dup",
        RectI32::new(12, 12, 1, 1),
        &[255, 255, 0, 255],
        false,
        true,
        "brush",
        "Yellow Dot",
        None,
        None,
        None,
    )
    .unwrap();
    let dup_t0_after = doc.layer("layer-dup").unwrap().grid.tiles.get(&TileCoord::new(0, 0)).unwrap();
    let dup_t1_after = doc.layer("layer-dup").unwrap().grid.tiles.get(&TileCoord::new(1, 0)).unwrap();
    assert!(!Arc::ptr_eq(&orig_t0, dup_t0_after), "Mutated tile (0,0) must split via CoW");
    assert!(Arc::ptr_eq(&orig_t1, dup_t1_after), "Untouched tile (1,0) must stay shared");

    // Slider coalesce_key: 3 rapid opacity updates collapse into 1 history entry
    let hist_before_slider = doc.history.len();
    for op in [0.8f32, 0.6, 0.4] {
        doc.update_layer_props(
            "layer-dup",
            LayerPropsPatch {
                opacity: Some(op),
                coalesce_key: Some("opacity:layer-dup".to_string()),
                record_history: Some(true),
                ..Default::default()
            },
            None,
        )
        .unwrap();
    }
    assert_eq!(doc.history.len(), hist_before_slider + 1, "Rapid slider edits must coalesce");
    assert!((doc.layer("layer-dup").unwrap().meta.opacity - 0.4).abs() < 1e-4);

    // Undo slider -> restores full 1.0 opacity in one step
    doc.undo();
    assert!((doc.layer("layer-dup").unwrap().meta.opacity - 1.0).abs() < 1e-4);
    doc.redo();
    assert!((doc.layer("layer-dup").unwrap().meta.opacity - 0.4).abs() < 1e-4);

    // Canvas resize/crop with offset + atomic undo/redo
    doc.resize_canvas(
        CanvasDimensions {
            width: 256,
            height: 256,
            dpi: 300,
        },
        -10,
        -10,
        false,
        "#ffffff",
        true,
        None,
    )
    .unwrap();
    assert_eq!(doc.dimensions.width, 256);
    // Original green dot at (10,10) shifted by (-10,-10) is now at (0,0)!
    let shifted = doc
        .layer(&layer_id)
        .unwrap()
        .grid
        .read_rgba8_rect(RectI32::new(0, 0, 1, 1), false, None)
        .unwrap();
    assert_eq!(shifted, green);

    // Undo canvas resize restores 512x512 and green dot back at (10,10)
    doc.undo();
    assert_eq!(doc.dimensions.width, 512);
    let orig_pos = doc
        .layer(&layer_id)
        .unwrap()
        .grid
        .read_rgba8_rect(RectI32::new(10, 10, 1, 1), false, None)
        .unwrap();
    assert_eq!(orig_pos, green);
}

#[test]
fn test_collaborative_selective_undo_tombstones_and_conflict_protection() {
    let mut doc = Document::new_blank(
        "doc-collab",
        "Collab Room",
        CanvasDimensions {
            width: 512,
            height: 512,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        50,
    );
    let lid = doc.active_layer_id.clone().unwrap();

    // 1. Local peer paints uncontested tile (0,0) and soon-to-be-contested tile (1,0)
    doc.ingest_dirty_rect(
        &lid,
        RectI32::new(20, 20, 1, 1),
        &[255, 0, 0, 255],
        false,
        true,
        "brush",
        "Local Stroke 1",
        Some("local".to_string()),
        Some("stroke-local-1".to_string()),
        None,
    )
    .unwrap();

    // 2. Local peer paints tile (1,0) at (300, 20)
    doc.ingest_dirty_rect(
        &lid,
        RectI32::new(300, 20, 1, 1),
        &[0, 255, 0, 255],
        false,
        true,
        "brush",
        "Local Stroke 2",
        Some("local".to_string()),
        Some("stroke-local-2".to_string()),
        None,
    )
    .unwrap();

    // 3. Remote peer "peer-alice" paints on tile (1,0) at (305, 20) — bumps remote_epoch on (1,0)!
    doc.ingest_dirty_rect(
        &lid,
        RectI32::new(305, 20, 1, 1),
        &[0, 0, 255, 255],
        false,
        true,
        "brush",
        "Alice Stroke",
        Some("peer-alice".to_string()),
        Some("stroke-alice-1".to_string()),
        None,
    )
    .unwrap();

    // Selective undo of local's stroke-local-2 on contested tile (1,0) MUST preserve Alice's edit!
    let outcome_contested = doc.selective_undo(Some("local"), Some("stroke-local-2"));
    assert!(outcome_contested.applied);
    assert!(outcome_contested.preserved_peer_edits);
    assert_eq!(outcome_contested.contested_tile_count, 1);
    let alice_px = doc
        .layer(&lid)
        .unwrap()
        .grid
        .read_rgba8_rect(RectI32::new(305, 20, 1, 1), false, None)
        .unwrap();
    assert_eq!(alice_px, [0, 0, 255, 255], "Alice's pixel on contested tile must be preserved");

    // Selective undo of local's uncontested stroke-local-1 on tile (0,0) reverts cleanly!
    let outcome_clean = doc.selective_undo(Some("local"), Some("stroke-local-1"));
    assert!(outcome_clean.applied);
    assert!(!outcome_clean.preserved_peer_edits);
    let reverted_px = doc
        .layer(&lid)
        .unwrap()
        .grid
        .read_rgba8_rect(RectI32::new(20, 20, 1, 1), false, None)
        .unwrap();
    assert_eq!(reverted_px[3], 0, "Uncontested tile must revert to transparent");

    // Selective redo reapplies local's uncontested stroke
    let redo_outcome = doc.selective_redo(Some("local"));
    assert!(redo_outcome.applied);
    let restored_px = doc
        .layer(&lid)
        .unwrap()
        .grid
        .read_rgba8_rect(RectI32::new(20, 20, 1, 1), false, None)
        .unwrap();
    assert_eq!(restored_px, [255, 0, 0, 255]);
}

#[test]
fn test_tiered_memory_lru_to_lz4_ram_to_scratch_disk_roundtrip() {
    let temp_dir = std::env::temp_dir().join(format!(
        "ink_engine_tiered_test_{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    let scratch: Arc<dyn ScratchBackend> =
        Arc::new(FileScratchBackend::new(temp_dir.clone(), true));

    // Tight 200 KB RAM budget to trigger both L2 LZ4 compression AND L3 Scratch Disk paging!
    let mut mgr = DocumentManager::new(
        MemoryBudgetConfig {
            ram_budget_bytes: 200 * 1024,
            vram_budget_bytes: 32 * 1024 * 1024,
            max_history_steps: 20,
            offload_inactive_tabs: true,
        },
        Arc::clone(&scratch),
    );

    mgr.create_document(
        "tab-1",
        "Tab 1",
        CanvasDimensions {
            width: 1024,
            height: 1024,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
    );

    // Write pseudo-random (harder to compress) tile data across 4 tiles = 1 MB raw (> 200 KB budget!)
    let mut expected_samples: Vec<(i32, i32, [u8; 4])> = Vec::new();
    {
        let doc = mgr.get_document_mut("tab-1").unwrap();
        let lid = doc.active_layer_id.clone().unwrap();
        for ty in 0..2 {
            for tx in 0..2 {
                let mut tile_buf = vec![0u8; BYTES_32BIT];
                let mut seed = (tx as u32 * 7919 + ty as u32 * 104729 + 17) as u64;
                for b in &mut tile_buf {
                    seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
                    *b = ((seed >> 33) & 0xff) as u8;
                }
                // Force alpha opaque so tile isn't sparse-pruned
                for px in tile_buf.chunks_exact_mut(4) {
                    px[3] = 255;
                }
                expected_samples.push((
                    tx * 256 + 7,
                    ty * 256 + 13,
                    [
                        tile_buf[(13 * 256 + 7) * 4],
                        tile_buf[(13 * 256 + 7) * 4 + 1],
                        tile_buf[(13 * 256 + 7) * 4 + 2],
                        255,
                    ],
                ));
                doc.ingest_dirty_rect(
                    &lid,
                    RectI32::new(tx * 256, ty * 256, 256, 256),
                    &tile_buf,
                    false,
                    false,
                    "brush",
                    "Noise",
                    None,
                    None,
                    Some(scratch.as_ref()),
                )
                .unwrap();
            }
        }
    }

    let before_stats = mgr.memory_stats();
    assert!(before_stats.ram_total_bytes >= 4 * BYTES_32BIT as u64);

    // Open Tab 2 -> switches away from Tab 1 (triggers L2 LZ4 compression of inactive tab)
    mgr.create_document(
        "tab-2",
        "Tab 2",
        CanvasDimensions {
            width: 512,
            height: 512,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
    );

    // Enforce tight 200 KB budget -> pushes inactive tab-1's incompressible tiles to L3 Scratch Disk!
    let (_lz4_cnt, disk_cnt, freed) = mgr.enforce_memory_budget().expect("enforce_budget failed");
    let after_stats = mgr.memory_stats();
    assert!(disk_cnt > 0 || after_stats.disk_paged_tiles > 0, "Expected tiles paged to L3 scratch disk");
    assert!(freed > 0 && after_stats.ram_total_bytes < before_stats.ram_total_bytes);

    // Switch back to Tab 1 and verify EVERY pixel promotes bit-exact from L3 Scratch Disk!
    mgr.switch_document("tab-1").unwrap();
    let doc1 = mgr.get_document("tab-1").unwrap();
    let lid = doc1.active_layer_id.as_deref().unwrap();
    for (x, y, expected_px) in expected_samples {
        let got = doc1
            .layer(lid)
            .unwrap()
            .grid
            .read_rgba8_rect(RectI32::new(x, y, 1, 1), false, Some(scratch.as_ref()))
            .expect("L3 scratch readback failed");
        assert_eq!(got, expected_px, "L3 scratch disk round-trip pixel mismatch at ({x},{y})");
    }

    // Close documents cleans up scratch sessions
    assert!(mgr.close_document("tab-1"));
    assert!(mgr.close_document("tab-2"));
    let _ = std::fs::remove_dir_all(&temp_dir);
}

#[test]
fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {
    let _dx12_guard = crate::lock_dx12_test();
    let mut renderer = match GpuRenderer::new_with_vram(
        SurfaceTarget::Headless {
            width: 256,
            height: 256,
        },
        512,
        512,
        16 * BYTES_16F as u64, // Small 16-slot L1 pool to verify LRU eviction cleanly
    ) {
        Ok(r) => r,
        Err(err) => {
            eprintln!("Skipping headless DX12 GpuTilePool test (no adapter): {err}");
            return;
        }
    };

    let make_solid_tile = |rgba: [u8; 4]| TileData::new_solid(TileFormat::Color32Bit, TileKind::Raster, rgba);
    let t_tl = make_solid_tile([255, 0, 0, 255]); // Red
    let t_tr = make_solid_tile([0, 255, 0, 255]); // Green
    let t_bl = make_solid_tile([0, 0, 255, 255]); // Blue
    let t_br = make_solid_tile([255, 255, 255, 255]); // White

    let device = renderer.device().clone();
    let queue = renderer.queue().clone();
    let mut pool = GpuTilePool::new(&device, 16 * BYTES_16F as u64);
    assert_eq!(pool.capacity(), 16);

    pool.begin_frame();
    let d1 = pool.intern_doc("d1");
    let l1 = pool.intern_layer("l1");
    let s_tl = pool
        .ensure_tile_uploaded(
            &queue,
            GpuTileKey {
                doc_id: d1,
                layer_id: l1,
                lod: 0,
                coord: TileCoord::new(0, 0),
            },
            &t_tl,
            None,
        )
        .unwrap();
    let s_tr = pool
        .ensure_tile_uploaded(
            &queue,
            GpuTileKey {
                doc_id: d1,
                layer_id: l1,
                lod: 0,
                coord: TileCoord::new(1, 0),
            },
            &t_tr,
            None,
        )
        .unwrap();
    let s_bl = pool
        .ensure_tile_uploaded(
            &queue,
            GpuTileKey {
                doc_id: d1,
                layer_id: l1,
                lod: 0,
                coord: TileCoord::new(0, 1),
            },
            &t_bl,
            None,
        )
        .unwrap();
    let s_br = pool
        .ensure_tile_uploaded(
            &queue,
            GpuTileKey {
                doc_id: d1,
                layer_id: l1,
                lod: 0,
                coord: TileCoord::new(1, 1),
            },
            &t_br,
            None,
        )
        .unwrap();

    // Dispatch WGSL compute mipmap shader (4 LOD 0 quadrants -> 1 LOD 1 parent tile)
    let lod1_slot = pool.generate_mipmap_tile(
        &device,
        &queue,
        GpuTileKey {
            doc_id: d1,
            layer_id: l1,
            lod: 1,
            coord: TileCoord::new(0, 0),
        },
        [Some(s_tl), Some(s_tr), Some(s_bl), Some(s_br)],
        1,
    );
    assert_eq!(pool.stats().mipmaps_generated, 1);

    // Read back the LOD 1 Rgba16Float slice from DX12 GPU VRAM and verify all 4 quadrants!
    let lod1_f16 = pool
        .readback_slot_rgba16f(&device, &queue, lod1_slot)
        .expect("GPU readback failed");
    let mut lod1_rgba8 = vec![0u8; BYTES_32BIT];
    rgba16f_to_rgba8_lossless(&lod1_f16, &mut lod1_rgba8);

    let px_at = |x: usize, y: usize| -> [u8; 4] {
        let o = (y * TILE_SIZE + x) * 4;
        [lod1_rgba8[o], lod1_rgba8[o + 1], lod1_rgba8[o + 2], lod1_rgba8[o + 3]]
    };
    assert_eq!(px_at(32, 32), [255, 0, 0, 255], "LOD 1 TL quadrant must be Red");
    assert_eq!(px_at(192, 32), [0, 255, 0, 255], "LOD 1 TR quadrant must be Green");
    assert_eq!(px_at(32, 192), [0, 0, 255, 255], "LOD 1 BL quadrant must be Blue");
    assert_eq!(px_at(192, 192), [255, 255, 255, 255], "LOD 1 BR quadrant must be White");

    // Verify SolidColor deduplication collapses 20 identical solid-red tiles onto the existing shared slot
    let l_solid = pool.intern_layer("l_solid");
    for i in 0..20i32 {
        let _ = pool
            .ensure_tile_uploaded(
                &queue,
                GpuTileKey {
                    doc_id: d1,
                    layer_id: l_solid,
                    lod: 0,
                    coord: TileCoord::new(i, 0),
                },
                &t_tl,
                None,
            )
            .unwrap();
    }
    assert_eq!(
        pool.stats().slots_used,
        5,
        "20 identical SolidColor tiles must share 1 VRAM slot (4 solid + 1 LOD1 = 5)"
    );

    // Verify LRU eviction triggers cleanly when exceeding the 16-slot VRAM capacity with non-solid tiles
    let mut non_solid_raw = vec![0u8; BYTES_32BIT];
    non_solid_raw[0..4].copy_from_slice(&[255, 0, 0, 255]);
    non_solid_raw[4..8].copy_from_slice(&[0, 255, 0, 255]);
    let non_solid_tile = TileData::from_raw(TileFormat::Color32Bit, TileKind::Raster, non_solid_raw);
    let l_evict = pool.intern_layer("l_evict");
    for i in 0..20i32 {
        pool.begin_frame();
        let _ = pool
            .ensure_tile_uploaded(
                &queue,
                GpuTileKey {
                    doc_id: d1,
                    layer_id: l_evict,
                    lod: 0,
                    coord: TileCoord::new(i, 0),
                },
                &non_solid_tile,
                None,
            )
            .unwrap();
    }
    let st = pool.stats();
    assert_eq!(st.slots_used, 16);
    assert!(st.evictions >= 9, "Expected LRU evictions when exceeding 16 slots, got {}", st.evictions);

    // Also verify GpuRenderer::sync_document uploads dirty tiles + compute mipmaps + display texture
    let mut doc = Document::new_blank(
        "doc-gpu-sync",
        "GPU Sync",
        CanvasDimensions {
            width: 512,
            height: 512,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        20,
    );
    renderer
        .sync_document(&mut doc, Some(&InMemoryScratchBackend::new()))
        .expect("GpuRenderer::sync_document failed");
    assert!(!doc.dirty_for_render);
    assert!(renderer.gpu_pool_stats().slots_used > 0);
}

#[test]
fn test_zero_copy_ink_roundtrip_wal_recovery_and_timelapse_png() {
    let mut doc = Document::new_blank(
        "doc-io",
        "Manga Page 01",
        CanvasDimensions {
            width: 512,
            height: 512,
            dpi: 600,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        50,
    );

    // Add a monochrome ink layer inside a folder
    let folder = LayerNodeMeta::new_folder("folder-ink", "Inks");
    doc.add_layer(folder, Some(0), false, true);

    let mut mono_meta = LayerNodeMeta::new_raster("layer-mono", "Lineart");
    mono_meta.parent_id = Some("folder-ink".to_string());
    mono_meta.expression_color = Some(ExpressionColor::Monochrome);
    mono_meta.blend_mode = BlendMode::Multiply;
    mono_meta.opacity = 0.85;
    doc.add_layer(mono_meta, Some(1), true, true);

    // Paint black stroke into monochrome layer + add partial mask
    let mut ink_box = vec![0u8; 32 * 32 * 4];
    for px in ink_box.chunks_exact_mut(4) {
        px.copy_from_slice(&[0, 0, 0, 255]);
    }
    doc.ingest_dirty_rect(
        "layer-mono",
        RectI32::new(64, 64, 32, 32),
        &ink_box,
        false,
        true,
        "brush",
        "Ink Box",
        None,
        None,
        None,
    )
    .unwrap();
    doc.add_layer_mask("layer-mono", 255, true).unwrap();
    doc.ingest_dirty_rect(
        "layer-mono",
        RectI32::new(64, 64, 16, 32),
        &vec![128u8; 16 * 32],
        true,
        true,
        "mask",
        "Half Mask",
        None,
        None,
        None,
    )
    .unwrap();

    // 1. Parallel .ink v2 ZIP save & reload round-trip
    let saved = serialize_ink_document(&doc, 1, None).expect("serialize_ink_document failed");
    assert!(saved.bytes.starts_with(b"PK\x03\x04"));
    assert!(saved.preview_png.as_ref().map(|p| p.starts_with(b"\x89PNG")).unwrap_or(false));
    assert!(saved.tile_count >= 5); // 4 bg + 1 mono
    assert_eq!(saved.mask_count, 1);

    let reloaded = parse_ink_document(&saved.bytes, "doc-io-reload", "Manga Page 01", 50)
        .expect("parse_ink_document failed");
    assert_eq!(reloaded.dimensions, doc.dimensions);
    assert_eq!(reloaded.layers.len(), doc.layers.len());
    let mono_reloaded = reloaded.layer("layer-mono").expect("missing mono layer");
    assert_eq!(mono_reloaded.meta.expression_color, Some(ExpressionColor::Monochrome));
    assert_eq!(mono_reloaded.meta.blend_mode, BlendMode::Multiply);
    assert!(mono_reloaded.grid.has_mask);
    assert!(mono_reloaded.meta.thumbnail_url.is_some());
    assert!(mono_reloaded.meta.mask_thumbnail_url.is_some());

    let ink_px = mono_reloaded
        .grid
        .read_rgba8_rect(RectI32::new(70, 70, 1, 1), false, None)
        .unwrap();
    assert_eq!(ink_px, [0, 0, 0, 255]);
    let mask_px = mono_reloaded
        .grid
        .read_mask8_rect(RectI32::new(70, 70, 1, 1), None)
        .unwrap();
    assert_eq!(mask_px, vec![128u8]);

    // 2. Crash recovery checkpoint (INKG v1) + WAL tile delta (TD v1) replay
    let (manifest_json, checkpoint_bytes, thumb_png) =
        encode_document_checkpoint(&doc, None).expect("encode_document_checkpoint failed");
    assert!(thumb_png.starts_with(b"\x89PNG"));

    // Record an extra stroke AFTER checkpoint as a WAL entry
    let top_layer = doc.layer("layer-mono").unwrap();
    let before_snap = top_layer.grid.snapshot_all_cow(TileKind::Raster);
    let mut after_grid = top_layer.grid.clone_cow();
    after_grid
        .write_rgba8_rect(&[0, 0, 0, 255], RectI32::new(200, 200, 1, 1), 128, None)
        .unwrap();
    let wal_deltas = after_grid.diff_from_full_snapshot("layer-mono", TileKind::Raster, &before_snap);
    let wal_payload =
        encode_cow_deltas_to_wal_payload(&wal_deltas, None).expect("WAL encode failed");

    let (recovered, strokes_replayed, _) = replay_recovery_into_document(
        "doc-recovered",
        &manifest_json,
        Some(&checkpoint_bytes),
        &[WalRawEntry {
            entry_type: 1,
            payload: wal_payload,
        }],
        50,
    )
    .expect("replay_recovery_into_document failed");
    assert_eq!(strokes_replayed, 1);
    let wal_px = recovered
        .layer("layer-mono")
        .unwrap()
        .grid
        .read_rgba8_rect(RectI32::new(200, 200, 1, 1), false, None)
        .unwrap();
    assert_eq!(wal_px, [0, 0, 0, 255], "Post-checkpoint WAL stroke must replay accurately");

    // 2b. Raster-journal style frames (current state only, no `before`) followed by an eraser
    // that clears the whole tile: replay must remove the tile WITHOUT converting the 1-bit
    // layer to 32-bit color (removal frames carry only a placeholder format byte).
    let mono_fmt = doc.layer("layer-mono").unwrap().grid.format;
    let journal_stroke: Vec<CowTileDelta> = wal_deltas
        .iter()
        .map(|d| CowTileDelta {
            before: None,
            ..d.clone()
        })
        .collect();
    let erased_coord = journal_stroke[0].coord;
    let journal_erase = vec![CowTileDelta {
        layer_id: "layer-mono".to_string(),
        kind: TileKind::Raster,
        coord: erased_coord,
        before: None,
        after: None,
        remote_epoch: 0,
    }];
    let (recovered2, replayed2, _) = replay_recovery_into_document(
        "doc-recovered-2",
        &manifest_json,
        Some(&checkpoint_bytes),
        &[
            WalRawEntry {
                entry_type: 1,
                payload: encode_cow_deltas_to_wal_payload(&journal_stroke, None).unwrap(),
            },
            WalRawEntry {
                entry_type: 1,
                payload: encode_cow_deltas_to_wal_payload(&journal_erase, None).unwrap(),
            },
        ],
        50,
    )
    .expect("journal replay failed");
    assert_eq!(replayed2, 2);
    let mono_rec = recovered2.layer("layer-mono").unwrap();
    assert_eq!(
        mono_rec.grid.format, mono_fmt,
        "eraser removal frame must not change the layer's storage format"
    );
    assert!(
        mono_rec.grid.get_tile(erased_coord).is_none(),
        "erased tile must be removed on replay"
    );

    // 3. Flattened PNG timelapse frame generation
    let (fw, fh, png) = doc
        .render_flattened_png(256, true, None)
        .expect("render_flattened_png failed");
    assert_eq!((fw, fh), (256, 256));
    assert!(png.starts_with(b"\x89PNG"));
}