Skip to content

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

119 KB
Raw Blame
//! Phase 5 Comprehensive Physical Media, Painterly Compute, Ribbon, Impasto & 4K Benchmark Tests.
//!
//! Covers all Phase 5 deliverables on real headless DX12 GPU hardware:
//! 1. Linear sRGB <-> OKLab <-> 8-band Kubelka-Munk + Saunderson subtractive pigment mixing.
//! 2. Zero-readback GPU canvas pickup (`color_pool` + `ground_pool` for `mixGroundColor`),
//!    all 4 `NaturalMixingMode`s (`Blend`, `RunningColor`, `Smear`, `ImpastoMix`), and
//!    standard CSP `colorMixing` (`amountOfPaint`, `densityOfPaint`, `colorStretch`, `useBlur`,
//!    `blurStrength`, sensors).
//! 3. Multi-bristle spatial mixing (4..64 independent GPU bristle reservoirs), paint load
//!    depletion, `autoClean: false` dirty brush persistence + `clean_dirty_brush()`, all 7
//!    `BristleProfilePreset`s, and `BrushRenderMode::BristleHybrid`.
//! 4. Dry-brush valley skipping on 512×512 seamless surface heightfield (`penetrationCurve`)
//!    and watercolor valley granulation.
//! 5. Continuous UV-mapped Ribbon mesh engine (smooth S-curve UV continuity, sharp corner bevels,
//!    `repeat`/`reverse`/`once`, `subTips`, `flipH`/`flipV`, `isColorTip`/`isDualToneTip`,
//!    Dual Brush ribbon, headless DX12 GPU raster).
//! 6. Persistent `R16Float` impasto heightfield accumulation, CoW Undo/Redo atomicity,
//!    `.ink` v2 ZIP round-trip persistence, and live GPU `WgpuCompositor` directional relief
//!    lighting (azimuth shift moves highlights & cast shadows).
//! 7. Native mask-mode stroke painting (`SetMaskMode(true)`) + CoW Undo, and native DX12 GPU
//!    S-curve brush preview rendering across all 4 brush engine paths.
//! 8. 4096×4096 heavy 250px `impasto-bristle-oil` and `wet-mixing-filbert` benchmark verifying
//!    zero CPU `readPixels` stalls and smooth interactive GPU frame times.

use crate::brush::{
    BristleProfilePreset, BristleSettings, BrushRenderMode, BrushTextureKind, CspDualBrushConfig,
    CspPaperTextureMode, CspSensorConfig, CspSubTipOrder, CspTipFlipMode, DualBrushCompositeMode,
    ImpastoSettings, NativeBrushConfig, NaturalMixingMode, NaturalPaintSettings, RibbonRepeatMode,
    StrokeDabEmitter,
};
use crate::clock;
use crate::compositor::{CompositorDisplayConfig, FlattenOptions};
use crate::document::{
    CanvasColorMode, CanvasDimensions, Document, ImpastoLayerLight, LayerNodeMeta,
};
use crate::engine::{EngineConfig, EngineHandle};
use crate::gpu::GpuRenderer;
use crate::io::ink_format::{parse_ink_document, serialize_ink_document};
use crate::natural_paint::{
    encode_pigment_over_white, linear_rgb_to_oklab, mix_oklab_srgb, mix_pigments_srgb,
    oklab_to_linear_rgb, spectral_state_to_srgb, srgb_to_spectral_state, BristleRibbonSimulator,
    RibbonMeshBuilder, RibbonVertex,
};
use crate::stroke::{centripetal_catmull_rom_to_bezier, StrokePoint};
use crate::tiles::RectI32;
use crate::types::{
    CameraState, CursorConfig, EngineCommand, EngineEvent, NativeInputSample, SurfaceTarget,
    ViewportRect,
};
use std::collections::HashMap;
use std::time::{Duration, Instant};

fn make_headless_renderer(w: u32, h: u32, doc_w: u32, doc_h: u32) -> Option<GpuRenderer> {
    match GpuRenderer::new(
        SurfaceTarget::Headless {
            width: w,
            height: h,
        },
        doc_w,
        doc_h,
    ) {
        Ok(r) => Some(r),
        Err(err) => {
            eprintln!("Skipping DX12 Phase 5 GPU test (no adapter available): {err}");
            None
        }
    }
}

fn make_doc(id: &str, w: u32, h: u32) -> Document {
    Document::new_blank(
        id,
        id,
        CanvasDimensions {
            width: w,
            height: h,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "transparent",
        60.0,
        50,
    )
}

fn fill_layer_rect(
    doc: &mut Document,
    layer_id: &str,
    x: i32,
    y: i32,
    w: u32,
    h: u32,
    rgba: [u8; 4],
) {
    let mut pixels = vec![0u8; (w * h * 4) as usize];
    for chunk in pixels.as_chunks_mut::<4>().0 {
        chunk.copy_from_slice(&rgba);
    }
    if let Some(layer) = doc.layer_mut(layer_id) {
        let _ = layer
            .grid
            .write_rgba8_rect(&pixels, RectI32::new(x, y, w, h), 128, None);
    }
}

fn make_line_points(
    x0: f64,
    y0: f64,
    x1: f64,
    y1: f64,
    count: usize,
    width: f32,
    pressure: f32,
) -> Vec<StrokePoint> {
    let mut pts = Vec::with_capacity(count);
    for i in 0..count {
        let t = if count <= 1 {
            0.0
        } else {
            i as f64 / (count - 1) as f64
        };
        pts.push(StrokePoint {
            x: x0 + (x1 - x0) * t,
            y: y0 + (y1 - y0) * t,
            pressure,
            width,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            velocity: 0.45,
            timestamp_ms: i as f64 * 4.0,
            is_corner: false,
        });
    }
    pts
}

fn run_natural_paint_stroke(
    renderer: &mut GpuRenderer,
    doc: &mut Document,
    layer_id: &str,
    brush: NativeBrushConfig,
    pts: &[StrokePoint],
    seed: u32,
) -> (usize, usize) {
    let _ = renderer.sync_document(doc, None);
    let mut sim = BristleRibbonSimulator::new(&brush, seed);
    let mut caps = Vec::with_capacity(pts.len() * 32);
    sim.step_points(pts, &brush, &mut caps);
    assert!(!caps.is_empty(), "BristleRibbonSimulator must emit capsules");

    renderer.begin_natural_paint_stroke(
        &doc.id,
        layer_id,
        doc.dimensions.width,
        doc.dimensions.height,
        brush.clone(),
    );
    let layer_clone = doc.layer(layer_id).cloned().expect("layer exists");
    let _ = renderer.dispatch_natural_paint_capsules(doc, &layer_clone, &caps, None);
    let batch = renderer
        .commit_natural_paint_to_layer()
        .expect("commit natural paint stroke");

    let color_tiles_count = batch.color_tiles.len();
    let impasto_tiles_count = batch.impasto_tiles.len();
    let empty_snap = HashMap::new();
    if let Some(layer) = doc.layer_mut(layer_id) {
        let _ =
            layer
                .grid
                .apply_gpu_committed_tiles(layer_id, batch.color_tiles, &empty_snap, 128);
        if !batch.impasto_tiles.is_empty() {
            let _ = layer.grid.apply_gpu_committed_impasto_tiles(
                layer_id,
                batch.impasto_tiles,
                &empty_snap,
            );
            layer.meta.impasto_light = brush.impasto_layer_light();
        }
    }
    (color_tiles_count, impasto_tiles_count)
}

fn sample_region_mean_rgba(
    doc: &Document,
    layer_id: &str,
    x0: i32,
    y0: i32,
    x1: i32,
    y1: i32,
) -> ([f32; 3], f32, usize) {
    let layer = doc.layer(layer_id).expect("layer exists");
    let mut sr = 0.0f64;
    let mut sg = 0.0f64;
    let mut sb = 0.0f64;
    let mut sa = 0.0f64;
    let mut opaque_count = 0usize;
    let mut total = 0usize;
    for y in y0..y1 {
        for x in x0..x1 {
            let px = layer.grid.get_pixel_rgba8(x, y, None);
            total += 1;
            sa += px[3] as f64 / 255.0;
            if px[3] > 20 {
                let w = px[3] as f64 / 255.0;
                sr += (px[0] as f64 / 255.0) * w;
                sg += (px[1] as f64 / 255.0) * w;
                sb += (px[2] as f64 / 255.0) * w;
                opaque_count += 1;
            }
        }
    }
    let avg_a = if total > 0 { (sa / total as f64) as f32 } else { 0.0 };
    if sa > 1e-4 {
        (
            [(sr / sa) as f32, (sg / sa) as f32, (sb / sa) as f32],
            avg_a,
            opaque_count,
        )
    } else {
        ([0.0, 0.0, 0.0], avg_a, opaque_count)
    }
}

fn make_oil_impasto_brush(fg: [f32; 3], size: f32) -> NativeBrushConfig {
    NativeBrushConfig {
        fg_color: fg,
        size,
        min_size_factor: 0.35,
        opacity: 1.0,
        flow: 0.95,
        brush_density: 0.95,
        hardness: 0.85,
        spacing: 0.08,
        preset_key: Some("impasto-bristle-oil".to_string()),
        render_mode: BrushRenderMode::BristleRibbon,
        color_mixing: true,
        perceptual_mixing: true,
        amount_of_paint: 0.72,
        density_of_paint: 0.92,
        color_stretch: 0.65,
        mixing_mode: NaturalMixingMode::ImpastoMix,
        surface_texture_id: Some("canvas-linen".to_string()),
        grain: 0.25,
        bristle: Some(BristleSettings {
            profile: BristleProfilePreset::Filbert,
            count: 32,
            clumping: 0.35,
            stiffness: 0.65,
            length: 1.0,
            splay: 0.35,
            irregularity: 0.25,
            edge_ridge: 0.65,
        }),
        natural_paint: Some(NaturalPaintSettings {
            enabled: true,
            spatial_mixing: true,
            pigment_mixing_strength: 1.0,
            paint_load: 0.92,
            depletion_rate: 0.2,
            wetness: 0.65,
            viscosity: 0.7,
            auto_clean: true,
            charge_per_pressure: 0.5,
            dry_brush: 0.08,
            granulation: 0.0,
            penetration_curve: 1.0,
        }),
        impasto: Some(ImpastoSettings {
            enabled: true,
            depth: 1.0,
            bristle_relief: 0.85,
            gloss: 0.65,
            relief_contrast: 1.35,
            light_azimuth: 315.0,
            light_elevation: 42.0,
        }),
        ..NativeBrushConfig::default()
    }
}

fn make_wet_filbert_brush(fg: [f32; 3], size: f32) -> NativeBrushConfig {
    NativeBrushConfig {
        fg_color: fg,
        size,
        min_size_factor: 0.3,
        opacity: 1.0,
        flow: 0.92,
        brush_density: 0.92,
        hardness: 0.75,
        spacing: 0.08,
        preset_key: Some("wet-mixing-filbert".to_string()),
        render_mode: BrushRenderMode::BristleRibbon,
        color_mixing: true,
        perceptual_mixing: true,
        amount_of_paint: 0.55,
        density_of_paint: 0.88,
        color_stretch: 0.75,
        mix_ground_color: true,
        mixing_mode: NaturalMixingMode::Blend,
        surface_texture_id: Some("cold-press-watercolor".to_string()),
        grain: 0.2,
        bristle: Some(BristleSettings {
            profile: BristleProfilePreset::Filbert,
            count: 28,
            clumping: 0.3,
            stiffness: 0.5,
            length: 1.0,
            splay: 0.45,
            irregularity: 0.3,
            edge_ridge: 0.35,
        }),
        natural_paint: Some(NaturalPaintSettings {
            enabled: true,
            spatial_mixing: true,
            pigment_mixing_strength: 1.0,
            paint_load: 0.88,
            depletion_rate: 0.25,
            wetness: 0.78,
            viscosity: 0.42,
            auto_clean: true,
            charge_per_pressure: 0.55,
            dry_brush: 0.12,
            granulation: 0.15,
            penetration_curve: 1.0,
        }),
        impasto: None,
        ..NativeBrushConfig::default()
    }
}

// ============================================================================
// 1. Kubelka-Munk Spectral Pigment & OKLab Math Parity
// ============================================================================

#[test]
fn test_p5_kubelka_munk_and_oklab_pigment_mixing() {
    let samples = [
        [1.0f32, 0.0, 0.0],
        [0.0, 1.0, 0.0],
        [0.0, 0.4, 0.8],
        [1.0, 0.85, 0.0],
        [0.5, 0.25, 0.75],
    ];
    for c in samples {
        let lab = linear_rgb_to_oklab(c[0], c[1], c[2]);
        let rt = oklab_to_linear_rgb(lab[0], lab[1], lab[2]);
        assert!((rt[0] - c[0]).abs() < 1e-3, "OKLab R mismatch: {rt:?} vs {c:?}");
        assert!((rt[1] - c[1]).abs() < 1e-3, "OKLab G mismatch: {rt:?} vs {c:?}");
        assert!((rt[2] - c[2]).abs() < 1e-3, "OKLab B mismatch: {rt:?} vs {c:?}");
    }

    // Blue (#0033CC) + Yellow (#FFDD00) -> vibrant Green (far greener than linear RGB!)
    let blue = [0.0, 0.20, 0.80];
    let yellow = [1.0, 0.87, 0.0];
    let green_km = mix_pigments_srgb(blue, yellow, 0.5, 1.0);
    let linear_mid = mix_pigments_srgb(blue, yellow, 0.5, 0.0);
    let km_green_dom = green_km[1] - green_km[0].max(green_km[2]);
    let lin_green_dom = linear_mid[1] - linear_mid[0].max(linear_mid[2]);
    assert!(
        km_green_dom > 0.10 && km_green_dom > lin_green_dom + 0.08,
        "Blue + Yellow KM must yield vibrant Green: km={green_km:?}, linear={linear_mid:?}"
    );

    // Dark Phthalo Blue + White -> luminous Cerulean
    let phthalo_blue = [0.05, 0.11, 0.27];
    let white = [1.0, 1.0, 1.0];
    let cerulean = mix_pigments_srgb(phthalo_blue, white, 0.5, 1.0);
    let lin_slate = mix_pigments_srgb(phthalo_blue, white, 0.5, 0.0);
    assert!(
        cerulean[2] - cerulean[0] > lin_slate[2] - lin_slate[0] + 0.04,
        "Dark blue + white KM must stay more chromatic cerulean than linear: km={cerulean:?}, lin={lin_slate:?}"
    );

    // Red + Yellow -> Orange; Red + Blue -> Violet
    let red = [0.88, 0.08, 0.06];
    let orange = mix_pigments_srgb(red, yellow, 0.5, 1.0);
    assert!(orange[0] > orange[1] && orange[1] > orange[2] + 0.20, "Red+Yellow=Orange: {orange:?}");
    let violet = mix_pigments_srgb(red, blue, 0.5, 1.0);
    assert!(violet[0] > violet[1] && violet[2] > violet[1], "Red+Blue=Violet: {violet:?}");

    // Self-mix invariance & 12-float spectral state round-trip
    for c in [blue, yellow, red, phthalo_blue, [0.2, 0.75, 0.45]] {
        let st = srgb_to_spectral_state(c);
        let rt = spectral_state_to_srgb(&st);
        for ch in 0..3 {
            assert!((rt[ch] - c[ch]).abs() < 0.015, "Spectral round-trip mismatch: {rt:?} vs {c:?}");
        }
        let self_mix = mix_pigments_srgb(c, c, 0.37, 1.0);
        for ch in 0..3 {
            assert!((self_mix[ch] - c[ch]).abs() < 0.01, "Self-mix invariance violated: {self_mix:?} vs {c:?}");
        }
    }

    // Strict achromatic neutrality for Black + White
    let gray = mix_pigments_srgb([0.0, 0.0, 0.0], [1.0, 1.0, 1.0], 0.5, 1.0);
    assert!(
        (gray[0] - gray[1]).abs() < 1e-3 && (gray[1] - gray[2]).abs() < 1e-3,
        "Gray must be neutral: {gray:?}"
    );

    // OKLab mix & encode_pigment_over_white spectral dilution consistency
    let oklab_mid = mix_oklab_srgb(red, blue, 0.5);
    assert!(oklab_mid[0] > 0.2 && oklab_mid[2] > 0.2);
    let over_white_state = encode_pigment_over_white(phthalo_blue, 0.5);
    let over_white_rgb = spectral_state_to_srgb(&over_white_state);
    let expected = mix_pigments_srgb(white, phthalo_blue, 0.5, 1.0);
    for ch in 0..3 {
        assert!(
            (over_white_rgb[ch] - expected[ch]).abs() < 0.015,
            "encode_pigment_over_white mismatch ch={ch}: got={over_white_rgb:?} expected={expected:?}"
        );
    }
}

// ============================================================================
// 2. Zero-Readback GPU Pickup, mixGroundColor, All 4 NaturalMixingModes & CSP ColorMixing
// ============================================================================

#[test]
fn test_p5_gpu_zero_readback_pickup_ground_mix_and_all_4_modes() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(256, 256, 512, 512) else {
        return;
    };

    let mut doc = make_doc("p5-ground-mix", 512, 512);
    let ground_id = doc.layers[0].meta.id.clone();
    fill_layer_rect(&mut doc, &ground_id, 0, 0, 512, 512, [0, 50, 215, 255]);
    let top_meta = LayerNodeMeta::new_raster("layer-top", "Paint Top");
    let _ = doc.add_layer(top_meta, Some(0), true, false);
    let top_id = "layer-top".to_string();

    // A) mix_ground_color = true: Yellow brush on transparent top layer picks up Blue from ground -> GREEN!
    let mut brush_ground = make_wet_filbert_brush([1.0, 0.88, 0.0], 48.0);
    brush_ground.mix_ground_color = true;
    brush_ground.amount_of_paint = 0.45;
    let pts_a = make_line_points(60.0, 120.0, 260.0, 120.0, 28, 48.0, 0.9);
    run_natural_paint_stroke(&mut renderer, &mut doc, &top_id, brush_ground, &pts_a, 101);

    let (rgb_ground, alpha_ground, _) = sample_region_mean_rgba(&doc, &top_id, 130, 108, 220, 132);
    assert!(alpha_ground > 0.4, "Top layer stroke must have visible paint: a={alpha_ground}");
    assert!(
        rgb_ground[1] > rgb_ground[0] + 0.04 && rgb_ground[1] > rgb_ground[2],
        "mixGroundColor=true Yellow over Blue ground must produce Green! got={rgb_ground:?}"
    );

    // B) mix_ground_color = false: Yellow brush on transparent region stays YELLOW
    let mut brush_no_ground = make_wet_filbert_brush([1.0, 0.88, 0.0], 48.0);
    brush_no_ground.mix_ground_color = false;
    let pts_b = make_line_points(60.0, 260.0, 260.0, 260.0, 28, 48.0, 0.9);
    run_natural_paint_stroke(&mut renderer, &mut doc, &top_id, brush_no_ground, &pts_b, 202);

    let (rgb_no_ground, alpha_no_ground, _) = sample_region_mean_rgba(&doc, &top_id, 130, 248, 220, 272);
    assert!(alpha_no_ground > 0.4);
    assert!(
        rgb_no_ground[0] > 0.80 && rgb_no_ground[1] > 0.72 && rgb_no_ground[2] < 0.20,
        "mixGroundColor=false over empty active layer must stay pure Yellow! got={rgb_no_ground:?}"
    );

    // C) Smear mode drags existing blue paint onto transparent area without adding red fg
    let mut doc_smear = make_doc("p5-smear", 512, 512);
    let smear_layer = doc_smear.layers[0].meta.id.clone();
    fill_layer_rect(&mut doc_smear, &smear_layer, 0, 0, 180, 256, [15, 70, 235, 255]);
    let mut smear_brush = make_wet_filbert_brush([1.0, 0.0, 0.0], 44.0);
    smear_brush.mix_ground_color = false;
    smear_brush.mixing_mode = NaturalMixingMode::Smear;
    smear_brush.amount_of_paint = 0.0;
    smear_brush.color_stretch = 0.85;
    let pts_smear = make_line_points(110.0, 128.0, 250.0, 128.0, 32, 44.0, 0.9);
    run_natural_paint_stroke(&mut renderer, &mut doc_smear, &smear_layer, smear_brush, &pts_smear, 303);

    let (rgb_drag, a_drag, _) = sample_region_mean_rgba(&doc_smear, &smear_layer, 195, 118, 228, 138);
    assert!(a_drag > 0.15, "Smear must drag existing blue paint across into empty canvas! a={a_drag}");
    assert!(
        rgb_drag[2] > rgb_drag[0] + 0.25,
        "Smear must carry blue canvas paint, NOT red fg! got={rgb_drag:?}"
    );

    // D) Standard CSP ColorMixing (`BrushRenderMode::Stamp` + `color_mixing: true` + `use_blur`)
    let mut doc_cmix = make_doc("p5-csp-cmix", 512, 512);
    let cmix_layer = doc_cmix.layers[0].meta.id.clone();
    fill_layer_rect(&mut doc_cmix, &cmix_layer, 0, 0, 256, 256, [0, 45, 210, 255]);
    let cmix_brush = NativeBrushConfig {
        fg_color: [1.0, 0.90, 0.0],
        size: 46.0,
        min_size_factor: 0.4,
        opacity: 1.0,
        flow: 0.95,
        brush_density: 0.95,
        hardness: 0.8,
        spacing: 0.12,
        preset_key: Some("csp-wet-round".to_string()),
        render_mode: BrushRenderMode::Stamp,
        color_mixing: true,
        perceptual_mixing: true,
        amount_of_paint: 0.45,
        density_of_paint: 0.9,
        color_stretch: 0.75,
        use_blur: true,
        blur_strength: 0.45,
        mixing_mode: NaturalMixingMode::RunningColor,
        amount_of_paint_sensor: Some(CspSensorConfig {
            use_pressure: true,
            pressure_min: 0.3,
            ..CspSensorConfig::default()
        }),
        ..NativeBrushConfig::default()
    };
    assert!(cmix_brush.is_color_mixing_stamp_brush());

    let _ = renderer.sync_document(&mut doc_cmix, None);
    let metrics = renderer.resolve_brush_tip_metrics(&cmix_brush);
    let mut emitter = StrokeDabEmitter::new(cmix_brush.clone(), 404, metrics.0, metrics.1);
    let pts_c = make_line_points(60.0, 128.0, 220.0, 128.0, 24, 46.0, 0.85);
    let mut dabs = Vec::new();
    emitter.emit_initial_point(&pts_c[0], None, 0.0, &mut dabs);
    for i in 1..pts_c.len() {
        let p0 = pts_c[i.saturating_sub(2)];
        let p1 = pts_c[i - 1];
        let p2 = pts_c[i];
        let p3 = pts_c[(i + 1).min(pts_c.len() - 1)];
        let seg = centripetal_catmull_rom_to_bezier(p0, p1, p2, p3, 0.5);
        emitter.emit_segment(&seg, None, 0.0, &mut dabs);
    }
    renderer.begin_natural_paint_stroke(&doc_cmix.id, &cmix_layer, 512, 512, cmix_brush);
    let lclone = doc_cmix.layer(&cmix_layer).cloned().unwrap();
    let _ = renderer.dispatch_color_mixing_dabs(&doc_cmix, &lclone, &dabs, None);
    let batch = renderer.commit_natural_paint_to_layer().expect("commit color mix");
    let empty_snap = HashMap::new();
    let _ = doc_cmix
        .layer_mut(&cmix_layer)
        .unwrap()
        .grid
        .apply_gpu_committed_tiles(&cmix_layer, batch.color_tiles, &empty_snap, 128);

    let (rgb_cmix, a_cmix, _) = sample_region_mean_rgba(&doc_cmix, &cmix_layer, 110, 118, 190, 138);
    assert!(a_cmix > 0.8);
    assert!(
        rgb_cmix[1] > rgb_cmix[0] && rgb_cmix[1] > 0.35,
        "CSP ColorMixing Yellow over Blue must mix toward Green! got={rgb_cmix:?}"
    );
}

// ============================================================================
// 3. Multi-Bristle Spatial Mixing, Depletion, autoClean & All 7 Profiles
// ============================================================================

#[test]
fn test_p5_gpu_spatial_bristle_mixing_depletion_autoclean_and_profiles() {
    let _dx12_guard = crate::lock_dx12_test();
    let profiles = [
        BristleProfilePreset::Round,
        BristleProfilePreset::Flat,
        BristleProfilePreset::Filbert,
        BristleProfilePreset::Fan,
        BristleProfilePreset::Rake,
        BristleProfilePreset::Knife,
        BristleProfilePreset::Custom,
    ];
    let test_pts = make_line_points(40.0, 100.0, 220.0, 100.0, 18, 42.0, 0.85);
    for profile in profiles {
        let mut bs = make_oil_impasto_brush([0.8, 0.2, 0.1], 42.0);
        bs.bristle.as_mut().unwrap().profile = profile;
        let mut sim = BristleRibbonSimulator::new(&bs, 555);
        let mut caps = Vec::new();
        sim.step_points(&test_pts, &bs, &mut caps);
        assert!(!caps.is_empty(), "Profile {profile:?} emitted zero capsules");
        assert!(caps.iter().all(|c| c.p0_p1.iter().all(|v| v.is_finite())));
    }
    let mut hybrid_bs = make_oil_impasto_brush([0.2, 0.5, 0.9], 44.0);
    hybrid_bs.render_mode = BrushRenderMode::BristleHybrid;
    let mut hsim = BristleRibbonSimulator::new(&hybrid_bs, 777);
    let mut hcaps = Vec::new();
    hsim.step_points(&test_pts, &hybrid_bs, &mut hcaps);
    assert!(
        hcaps.iter().any(|c| ((c.strand[3] + 0.5) as u32 & 2) != 0),
        "BristleHybrid must emit hybrid textured stamp capsules (flag bit 2)"
    );

    let Some(mut renderer) = make_headless_renderer(256, 256, 1024, 512) else {
        return;
    };

    // Spatial Mixing: Top half Blue (y<128), Bottom half Red (y>=128); horizontal Yellow brush straddles y=128
    let mut doc = make_doc("p5-spatial", 1024, 512);
    let lid = doc.layers[0].meta.id.clone();
    fill_layer_rect(&mut doc, &lid, 0, 0, 400, 128, [0, 50, 220, 255]);
    fill_layer_rect(&mut doc, &lid, 0, 128, 400, 128, [225, 25, 25, 255]);

    let mut spatial_brush = make_wet_filbert_brush([1.0, 0.90, 0.0], 64.0);
    spatial_brush.mix_ground_color = false;
    spatial_brush.amount_of_paint = 0.35;
    spatial_brush.natural_paint.as_mut().unwrap().spatial_mixing = true;
    spatial_brush.natural_paint.as_mut().unwrap().wetness = 0.82;
    let pts_sp = make_line_points(60.0, 128.0, 340.0, 128.0, 36, 64.0, 0.95);
    run_natural_paint_stroke(&mut renderer, &mut doc, &lid, spatial_brush, &pts_sp, 601);

    let (top_rgb, _, _) = sample_region_mean_rgba(&doc, &lid, 160, 102, 280, 122);
    let (bot_rgb, _, _) = sample_region_mean_rgba(&doc, &lid, 160, 134, 280, 154);
    assert!(
        top_rgb[1] > top_rgb[0] && bot_rgb[0] > top_rgb[0] + 0.25,
        "Spatial bristles must carry distinct pigment across ferrule! top={top_rgb:?}, bot={bot_rgb:?}"
    );

    // Paint Load Depletion along a long stroke
    let mut doc_dep = make_doc("p5-depletion", 1024, 256);
    let dep_lid = doc_dep.layers[0].meta.id.clone();
    let mut dep_brush = make_wet_filbert_brush([0.1, 0.1, 0.1], 36.0);
    dep_brush.mix_ground_color = false;
    dep_brush.natural_paint.as_mut().unwrap().paint_load = 0.65;
    dep_brush.natural_paint.as_mut().unwrap().depletion_rate = 1.0;
    dep_brush.natural_paint.as_mut().unwrap().charge_per_pressure = 0.0;
    let pts_dep = make_line_points(40.0, 128.0, 920.0, 128.0, 90, 36.0, 0.7);
    run_natural_paint_stroke(&mut renderer, &mut doc_dep, &dep_lid, dep_brush, &pts_dep, 701);

    let (_, start_a, _) = sample_region_mean_rgba(&doc_dep, &dep_lid, 60, 118, 120, 138);
    let (_, end_a, _) = sample_region_mean_rgba(&doc_dep, &dep_lid, 820, 118, 880, 138);
    assert!(
        start_a > end_a + 0.10,
        "High depletionRate must reduce paint coverage along stroke! start_a={start_a}, end_a={end_a}"
    );

    // autoClean: false persists dirty pigment across Stroke 2 until clean_dirty_brush() resets it
    let mut doc_dirty = make_doc("p5-autoclean", 512, 512);
    let dlid = doc_dirty.layers[0].meta.id.clone();
    fill_layer_rect(&mut doc_dirty, &dlid, 0, 0, 220, 200, [10, 40, 230, 255]);

    let mut dirty_brush = make_wet_filbert_brush([0.05, 0.2, 0.95], 44.0);
    dirty_brush.preset_key = Some("dirty-test-oil".to_string());
    dirty_brush.mix_ground_color = false;
    dirty_brush.amount_of_paint = 0.25;
    dirty_brush.natural_paint.as_mut().unwrap().auto_clean = false;
    dirty_brush.natural_paint.as_mut().unwrap().wetness = 0.85;
    dirty_brush.natural_paint.as_mut().unwrap().depletion_rate = 0.05;

    let pts1 = make_line_points(40.0, 100.0, 180.0, 100.0, 20, 44.0, 0.9);
    run_natural_paint_stroke(&mut renderer, &mut doc_dirty, &dlid, dirty_brush.clone(), &pts1, 801);

    dirty_brush.fg_color = [1.0, 1.0, 1.0];
    let pts2 = make_line_points(60.0, 300.0, 180.0, 300.0, 18, 44.0, 0.9);
    run_natural_paint_stroke(&mut renderer, &mut doc_dirty, &dlid, dirty_brush.clone(), &pts2, 802);
    let (dirty_rgb, dirty_a, _) = sample_region_mean_rgba(&doc_dirty, &dlid, 75, 290, 150, 310);
    assert!(dirty_a > 0.3);
    assert!(
        dirty_rgb[2] > dirty_rgb[0] + 0.15,
        "autoClean=false Stroke 2 must retain dirty Blue pigment from Stroke 1! got={dirty_rgb:?}"
    );

    renderer.clean_dirty_brush(Some("dirty-test-oil"));
    let pts3 = make_line_points(60.0, 420.0, 180.0, 420.0, 18, 44.0, 0.9);
    run_natural_paint_stroke(&mut renderer, &mut doc_dirty, &dlid, dirty_brush, &pts3, 803);
    let (clean_rgb, clean_a, _) = sample_region_mean_rgba(&doc_dirty, &dlid, 75, 410, 150, 430);
    assert!(clean_a > 0.3);
    assert!(
        (clean_rgb[0] - clean_rgb[2]).abs() < 0.05 && clean_rgb[0] > 0.90,
        "After clean_dirty_brush(), Stroke 3 must be clean White! got={clean_rgb:?}"
    );
}

// ============================================================================
// 4. Dry-Brush Valley Skipping & Watercolor Granulation
// ============================================================================

#[test]
fn test_p5_gpu_dry_brush_valley_skipping_and_watercolor_granulation() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(256, 256, 512, 512) else {
        return;
    };

    let mut doc = make_doc("p5-drybrush", 512, 512);
    let lid = doc.layers[0].meta.id.clone();

    let mut wet_bs = make_wet_filbert_brush([0.15, 0.25, 0.75], 44.0);
    wet_bs.mix_ground_color = false;
    wet_bs.surface_texture_id = Some("cold-press-watercolor".to_string());
    wet_bs.natural_paint.as_mut().unwrap().dry_brush = 0.0;
    wet_bs.natural_paint.as_mut().unwrap().granulation = 0.0;
    wet_bs.grain = 0.0;

    let mut dry_bs = wet_bs.clone();
    dry_bs.natural_paint.as_mut().unwrap().dry_brush = 0.88;
    dry_bs.natural_paint.as_mut().unwrap().penetration_curve = 0.65;

    let pts_wet = make_line_points(40.0, 90.0, 240.0, 90.0, 28, 44.0, 0.28);
    let pts_dry_light = make_line_points(40.0, 210.0, 240.0, 210.0, 28, 44.0, 0.28);
    let pts_dry_heavy = make_line_points(40.0, 340.0, 240.0, 340.0, 28, 44.0, 0.96);

    run_natural_paint_stroke(&mut renderer, &mut doc, &lid, wet_bs, &pts_wet, 901);
    run_natural_paint_stroke(&mut renderer, &mut doc, &lid, dry_bs.clone(), &pts_dry_light, 902);
    run_natural_paint_stroke(&mut renderer, &mut doc, &lid, dry_bs, &pts_dry_heavy, 903);

    let (_, wet_a, _) = sample_region_mean_rgba(&doc, &lid, 70, 78, 210, 102);
    let (_, dry_light_a, _) = sample_region_mean_rgba(&doc, &lid, 70, 198, 210, 222);
    let (_, dry_heavy_a, _) = sample_region_mean_rgba(&doc, &lid, 70, 328, 210, 352);

    assert!(
        wet_a > dry_light_a + 0.15,
        "High dryBrush must skip surface valleys vs wet stroke! wet_a={wet_a}, dry_light_a={dry_light_a}"
    );
    assert!(
        dry_heavy_a > dry_light_a + 0.08,
        "Heavy pressure must penetrate deeper into valleys than light pressure! heavy={dry_heavy_a}, light={dry_light_a}"
    );

    let mut doc_gran = make_doc("p5-granulation", 512, 256);
    let glid = doc_gran.layers[0].meta.id.clone();
    let mut gran_bs = make_wet_filbert_brush([0.1, 0.35, 0.85], 44.0);
    gran_bs.mix_ground_color = false;
    gran_bs.surface_texture_id = Some("rough-cold-press".to_string());
    gran_bs.natural_paint.as_mut().unwrap().dry_brush = 0.0;
    gran_bs.natural_paint.as_mut().unwrap().granulation = 0.95;
    gran_bs.flow = 0.14;
    gran_bs.brush_density = 0.22;
    gran_bs.density_of_paint = 0.25;
    gran_bs.bristle.as_mut().unwrap().count = 14;
    let pts_g = make_line_points(40.0, 128.0, 240.0, 128.0, 20, 44.0, 0.7);
    run_natural_paint_stroke(&mut renderer, &mut doc_gran, &glid, gran_bs, &pts_g, 904);

    let layer = doc_gran.layer(&glid).unwrap();
    let mut alphas = Vec::new();
    for y in 118..138 {
        for x in 70..210 {
            let a = layer.grid.get_pixel_rgba8(x, y, None)[3] as f32 / 255.0;
            if a > 0.02 {
                alphas.push(a);
            }
        }
    }
    let mean = alphas.iter().sum::<f32>() / alphas.len().max(1) as f32;
    let var = alphas.iter().map(|v| (v - mean) * (v - mean)).sum::<f32>() / alphas.len().max(1) as f32;
    assert!(
        var > 0.0005 && mean > 0.1,
        "Watercolor granulation must create valley-settled density variation! mean={mean}, var={var}"
    );
}

// ============================================================================
// 5. Continuous Ribbon Mesh UV Continuity, Anti-Bowtie Corners & GPU Raster
// ============================================================================

#[test]
fn test_p5_ribbon_uv_continuity_anti_bowtie_and_gpu_raster() {
    let _dx12_guard = crate::lock_dx12_test();
    let mut brush = NativeBrushConfig {
        fg_color: [0.15, 0.25, 0.85],
        bg_color: [0.95, 0.75, 0.15],
        size: 32.0,
        opacity: 1.0,
        flow: 1.0,
        is_ribbon: true,
        ribbon_repeat_mode: RibbonRepeatMode::Repeat,
        is_dual_tone_tip: true,
        flip_h: CspTipFlipMode::Alternate,
        flip_v: CspTipFlipMode::None,
        sub_tip_order: CspSubTipOrder::Sequential,
        ..NativeBrushConfig::default()
    };

    let mut s_pts = Vec::new();
    for i in 0..=40 {
        let t = i as f64 / 40.0;
        s_pts.push(StrokePoint {
            x: 30.0 + t * 340.0,
            y: 128.0 + (t * std::f64::consts::TAU).sin() * 55.0,
            pressure: 0.85,
            width: 32.0,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            velocity: 0.5,
            timestamp_ms: i as f64 * 4.0,
            is_corner: false,
        });
    }
    let mut rb = RibbonMeshBuilder::new(64, 64, 3, 12345);
    let mut s_verts: Vec<RibbonVertex> = Vec::new();
    rb.push_points(&s_pts, &brush, &mut s_verts);
    rb.finish(&brush, &mut s_verts);
    assert!(s_verts.len() >= 120 && s_verts.len().is_multiple_of(3));
    assert!(s_verts.iter().all(|v| {
        v.doc_pos[0].is_finite() && v.doc_pos[1].is_finite() && v.uv[0].is_finite()
    }));
    let max_tip_idx = s_verts
        .iter()
        .map(|v| (v.sub_bg[0] + 0.5) as u32)
        .max()
        .unwrap_or(0);
    assert!(max_tip_idx >= 1, "Multi-subTip ribbon must cycle across sub-tip layers!");

    let hairpin_pts = vec![
        StrokePoint { x: 40.0, y: 80.0, pressure: 0.9, width: 30.0, ..Default::default() },
        StrokePoint { x: 180.0, y: 80.0, pressure: 0.9, width: 30.0, is_corner: true, ..Default::default() },
        StrokePoint { x: 180.0, y: 200.0, pressure: 0.9, width: 30.0, is_corner: true, ..Default::default() },
        StrokePoint { x: 60.0, y: 175.0, pressure: 0.9, width: 30.0, ..Default::default() },
    ];
    for mode in [RibbonRepeatMode::Repeat, RibbonRepeatMode::Reverse, RibbonRepeatMode::Once] {
        brush.ribbon_repeat_mode = mode;
        let mut hrb = RibbonMeshBuilder::new(64, 64, 1, 99);
        let mut hv = Vec::new();
        hrb.push_points(&hairpin_pts, &brush, &mut hv);
        hrb.finish(&brush, &mut hv);
        assert!(hv.len() >= 18 && hv.len() % 3 == 0);
        for v in &hv {
            assert!(v.doc_pos[0].is_finite() && v.doc_pos[1].is_finite());
            assert!(
                v.doc_pos[0] > -20.0
                    && v.doc_pos[0] < 260.0
                    && v.doc_pos[1] > 10.0
                    && v.doc_pos[1] < 270.0
            );
        }
    }

    let Some(mut renderer) = make_headless_renderer(256, 256, 512, 256) else {
        return;
    };
    let mut tip_rgba = vec![0u8; 32 * 32 * 4];
    for y in 0..32usize {
        for x in 0..32usize {
            let dx = (x as f32 - 15.5).abs() / 15.5;
            let dy = (y as f32 - 15.5).abs() / 15.5;
            let a = if dx + dy <= 1.05 { 255u8 } else { 0u8 };
            let i = (y * 32 + x) * 4;
            tip_rgba[i] = 255;
            tip_rgba[i + 1] = 255;
            tip_rgba[i + 2] = 255;
            tip_rgba[i + 3] = a;
        }
    }
    let _ = renderer.upload_brush_texture(
        "ribbon-diamond".to_string(),
        BrushTextureKind::Tip,
        false,
        32,
        32,
        tip_rgba,
    );

    let mut gpu_ribbon = brush.clone();
    gpu_ribbon.tip_key = Some("ribbon-diamond".to_string());
    gpu_ribbon.ribbon_repeat_mode = RibbonRepeatMode::Repeat;
    gpu_ribbon.dual_brush = true;
    gpu_ribbon.dual_brush_config = Some(CspDualBrushConfig {
        enabled: true,
        combine_mode: DualBrushCompositeMode::Multiply,
        is_ribbon: true,
        tip_key: Some("ribbon-diamond".to_string()),
        ..CspDualBrushConfig::default()
    });

    let mut doc = make_doc("p5-ribbon-gpu", 512, 256);
    let lid = doc.layers[0].meta.id.clone();
    let _ = renderer.sync_document(&mut doc, None);

    let (tw, th, sub_c) = renderer.resolve_ribbon_tip_dims(&gpu_ribbon);
    let mut rb_gpu = RibbonMeshBuilder::new(tw, th, sub_c, 4242);
    let mut p_verts = Vec::new();
    rb_gpu.push_points(&s_pts, &gpu_ribbon, &mut p_verts);
    rb_gpu.finish(&gpu_ribbon, &mut p_verts);

    let mut sec_verts = Vec::new();
    if let Some(sec_cfg) = gpu_ribbon.build_secondary_brush_config() {
        let (stw, sth, ssub) = renderer.resolve_ribbon_tip_dims(&sec_cfg);
        let mut srb = RibbonMeshBuilder::new(stw, sth, ssub, 4343);
        srb.push_points(&s_pts, &sec_cfg, &mut sec_verts);
        srb.finish(&sec_cfg, &mut sec_verts);
    }

    renderer.begin_gpu_stroke(512, 256, false, gpu_ribbon, [0.0, 0.0]);
    let touched = renderer.stamp_gpu_ribbon_vertices(&p_verts, &sec_verts, false);
    assert!(!touched.is_empty(), "Ribbon GPU stamp must touch at least one tile");

    let layer_grid = doc.layer(&lid).unwrap().grid.clone();
    let batch = renderer
        .commit_gpu_stroke_to_layer(&doc.id, &lid, &layer_grid, None, false, false)
        .expect("commit GPU ribbon");
    let empty_snap = HashMap::new();
    let _ = doc
        .layer_mut(&lid)
        .unwrap()
        .grid
        .apply_gpu_committed_tiles(&lid, batch.tiles, &empty_snap, 128);
    renderer.clear_live_stroke();

    for &sample_x in &[100i32, 200, 300] {
        let (_, _, count) = sample_region_mean_rgba(&doc, &lid, sample_x - 8, 60, sample_x + 8, 200);
        assert!(
            count > 40,
            "Ribbon stroke must have continuous pixels near x={sample_x}, found only {count}"
        );
    }
}

// ============================================================================
// 6. Persistent R16Float Impasto + CoW Undo/Redo + .ink Round-Trip + Live Lighting
// ============================================================================

#[test]
fn test_p5_gpu_impasto_r16f_cow_undo_ink_roundtrip_and_live_relief_lighting() {
    let _dx12_guard = crate::lock_dx12_test();
    let (handle, mut producers) = match EngineHandle::spawn(
        SurfaceTarget::Headless {
            width: 512,
            height: 512,
        },
        EngineConfig {
            doc_width: 512,
            doc_height: 512,
            ..EngineConfig::default()
        },
    ) {
        Ok(v) => v,
        Err(err) => {
            eprintln!("Skipping DX12 Impasto EngineHandle test: {err}");
            return;
        }
    };

    let doc_id = "p5-impasto-e2e".to_string();
    {
        let docs_lock = handle.documents();
        let mut mgr = docs_lock.write();
        mgr.create_document(
            &doc_id,
            "Impasto E2E",
            CanvasDimensions {
                width: 512,
                height: 512,
                dpi: 300,
            },
            CanvasColorMode::Color,
            "#f5f5f5",
            60.0,
        );
    }

    handle.send_command(EngineCommand::SyncActiveDocument);
    handle.send_command(EngineCommand::SetVisible(true));
    handle.send_command(EngineCommand::SetViewport(ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 512,
        height_px: 512,
        dpr: 1.0,
    }));
    handle.send_command(EngineCommand::SetCamera(CameraState {
        pan_x: 256.0,
        pan_y: 256.0,
        zoom: 1.0,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    }));
    let oil_brush = make_oil_impasto_brush([0.82, 0.30, 0.16], 54.0);
    handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(oil_brush)));

    // Paint a vertical oil impasto ridge down center (x=256, y=90..420) via lock-free SPSC ring!
    // Use a fixed base timestamp so `stroke_seed` (and bristle clump geometry) is deterministic.
    let now = 1000.0;
    let steps = 26usize;
    let mut samples = Vec::with_capacity(steps + 1);
    for i in 0..=steps {
        let t = i as f64 / steps as f64;
        let phase = if i == 0 {
            1
        } else if i == steps {
            3
        } else {
            2
        };
        samples.push(NativeInputSample {
            phys_x: 256.0,
            phys_y: (90.0 + t * 330.0) as f32,
            pressure: if phase == 3 { 0.0 } else { 0.92 },
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            timestamp_ms: now + i as f64 * 4.0,
            buttons: if phase == 3 { 0 } else { 1 },
            phase,
            backend: 1,
        });
    }
    producers.wintab.push_batch(&samples);

    let mut committed = false;
    let deadline = Instant::now() + Duration::from_secs(6);
    while Instant::now() < deadline && !committed {
        for ev in handle.events().try_iter() {
            if matches!(ev, EngineEvent::StrokeCommitted { .. }) {
                committed = true;
                break;
            }
        }
        if !committed {
            std::thread::sleep(Duration::from_millis(8));
        }
    }
    assert!(committed, "EngineHandle must commit impasto stroke");

    // 1. Verify persistent R16Float impasto_tiles + impasto_light persisted on active layer
    let docs_lock = handle.documents();
    let (layer_id, peak_height, saved_zip) = {
        let mgr = docs_lock.read();
        let doc = mgr.get_document(&doc_id).unwrap();
        let lid = doc.active_layer_id.clone().unwrap();
        let layer = doc.layer(&lid).unwrap();
        assert!(!layer.grid.tiles.is_empty(), "Raster tiles must be populated");
        assert!(
            !layer.grid.impasto_tiles.is_empty(),
            "Persistent R16Float impasto_tiles must be populated!"
        );
        assert!(layer.meta.impasto_light.is_some(), "Layer impasto_light metadata must be set");

        let mut max_h = 0.0f32;
        for y in 150..350 {
            for x in 225..288 {
                let h = layer.grid.get_impasto_height_f32(x, y, None);
                if h > max_h {
                    max_h = h;
                }
            }
        }
        assert!(max_h > 0.15, "Impasto heightfield peak must be substantial: {max_h}");

        let serialized = serialize_ink_document(doc, 3, None).expect("serialize .ink with impasto");
        (lid, max_h, serialized.bytes)
    };

    // 2. Round-trip parse .ink v2 ZIP and verify exact R16Float heightfield + impasto_light!
    let reloaded = parse_ink_document(&saved_zip, "p5-impasto-reloaded", "Reloaded", 10)
        .expect("parse .ink with impasto");
    let reloaded_layer = reloaded.layer(&layer_id).expect("reloaded layer exists");
    assert!(!reloaded_layer.grid.impasto_tiles.is_empty(), ".ink must preserve impasto_tiles");
    assert!(reloaded_layer.meta.impasto_light.is_some(), ".ink must preserve impasto_light");
    let mut reloaded_max_h = 0.0f32;
    for y in 150..350 {
        for x in 225..288 {
            reloaded_max_h = reloaded_max_h.max(reloaded_layer.grid.get_impasto_height_f32(x, y, None));
        }
    }
    assert!(
        (reloaded_max_h - peak_height).abs() < 0.005,
        "Reloaded .ink R16Float peak must match original: {reloaded_max_h} vs {peak_height}"
    );

    // 3. CoW Undo clears BOTH raster tiles and R16Float impasto tiles; Redo restores both!
    {
        let mut mgr = docs_lock.write();
        let doc = mgr.get_document_mut(&doc_id).unwrap();
        assert!(!doc.undo().changed_layer_ids.is_empty());
        let layer_after_undo = doc.layer(&layer_id).unwrap();
        assert!(layer_after_undo.grid.tiles.is_empty(), "Undo must clear raster tiles");
        assert!(
            layer_after_undo.grid.impasto_tiles.is_empty(),
            "Undo must atomically clear R16Float impasto_tiles!"
        );

        assert!(!doc.redo().changed_layer_ids.is_empty());
        let layer_after_redo = doc.layer(&layer_id).unwrap();
        assert!(!layer_after_redo.grid.tiles.is_empty(), "Redo must restore raster tiles");
        assert!(
            !layer_after_redo.grid.impasto_tiles.is_empty(),
            "Redo must restore R16Float impasto_tiles!"
        );
    }

    handle.shutdown();

    // 4. Live GPU Impasto Relief Lighting Pass: rotating light_azimuth 180° shifts relief across ridge!
    let Some(mut renderer) = make_headless_renderer(256, 256, 512, 512) else {
        return;
    };
    let mut lit_doc = reloaded;
    lit_doc.layer_mut(&layer_id).unwrap().meta.impasto_light = Some(ImpastoLayerLight {
        enabled: true,
        light_azimuth: 180.0,
        light_elevation: 32.0,
        gloss: 0.75,
        relief_contrast: 1.8,
        depth: 1.2,
    });
    let _ = renderer.sync_document(&mut lit_doc, None);
    let (w_l, _h_l, rgba_left) = renderer
        .render_document_flattened(&lit_doc, None, &FlattenOptions::default())
        .expect("flatten impasto left light");

    lit_doc.layer_mut(&layer_id).unwrap().meta.impasto_light = Some(ImpastoLayerLight {
        enabled: true,
        light_azimuth: 0.0,
        light_elevation: 32.0,
        gloss: 0.75,
        relief_contrast: 1.8,
        depth: 1.2,
    });
    let _ = renderer.sync_document(&mut lit_doc, None);
    let (w_r, _h_r, rgba_right) = renderer
        .render_document_flattened(&lit_doc, None, &FlattenOptions::default())
        .expect("flatten impasto right light");

    let flank_diff = |buf: &[u8], w: u32| -> f32 {
        let mut left_sum = 0.0f64;
        let mut right_sum = 0.0f64;
        let mut n = 0usize;
        for y in 160..340u32 {
            for dx in 0..14u32 {
                let li = ((y * w + (232 + dx)) * 4) as usize;
                let ri = ((y * w + (266 + dx)) * 4) as usize;
                left_sum += 0.299 * buf[li] as f64 + 0.587 * buf[li + 1] as f64 + 0.114 * buf[li + 2] as f64;
                right_sum += 0.299 * buf[ri] as f64 + 0.587 * buf[ri + 1] as f64 + 0.114 * buf[ri + 2] as f64;
                n += 1;
            }
        }
        ((left_sum - right_sum) / n as f64) as f32
    };
    let diff_left_light = flank_diff(&rgba_left, w_l);
    let diff_right_light = flank_diff(&rgba_right, w_r);
    assert!(
        (diff_left_light - diff_right_light).abs() > 8.0,
        "Rotating impasto light_azimuth 180° must shift relief illumination! left={diff_left_light:.2}, right={diff_right_light:.2}"
    );
}

// ============================================================================
// 7. Native Mask-Mode Stroke Painting & Native DX12 GPU Brush Previews
// ============================================================================

#[test]
fn test_p5_native_mask_mode_stroke_and_gpu_brush_preview() {
    let _dx12_guard = crate::lock_dx12_test();
    let (handle, mut producers) = match EngineHandle::spawn(
        SurfaceTarget::Headless {
            width: 256,
            height: 256,
        },
        EngineConfig {
            doc_width: 256,
            doc_height: 256,
            ..EngineConfig::default()
        },
    ) {
        Ok(v) => v,
        Err(err) => {
            eprintln!("Skipping DX12 Mask-Mode EngineHandle test: {err}");
            return;
        }
    };

    let doc_id = "p5-mask-mode".to_string();
    let docs_lock = handle.documents();
    let layer_id = {
        let mut mgr = docs_lock.write();
        mgr.create_document(
            &doc_id,
            "Mask Mode Doc",
            CanvasDimensions {
                width: 256,
                height: 256,
                dpi: 300,
            },
            CanvasColorMode::Color,
            "transparent",
            60.0,
        );
        let doc = mgr.get_document_mut(&doc_id).unwrap();
        let lid = doc.active_layer_id.clone().unwrap();
        fill_layer_rect(doc, &lid, 0, 0, 256, 256, [220, 40, 60, 255]);
        let _ = doc.add_layer_mask(&lid, 255, false);
        lid
    };

    handle.send_command(EngineCommand::SyncActiveDocument);
    handle.send_command(EngineCommand::SetVisible(true));
    handle.send_command(EngineCommand::SetViewport(ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 256,
        height_px: 256,
        dpr: 1.0,
    }));
    handle.send_command(EngineCommand::SetCamera(CameraState {
        pan_x: 128.0,
        pan_y: 128.0,
        zoom: 1.0,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    }));
    handle.send_command(EngineCommand::SetMaskMode(true));
    handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(NativeBrushConfig {
        fg_color: [0.0, 0.0, 0.0],
        size: 36.0,
        min_size_factor: 0.8,
        opacity: 1.0,
        flow: 1.0,
        hardness: 1.0,
        spacing: 0.08,
        ..NativeBrushConfig::default()
    })));

    let now = clock::now_ms();
    let mut samples = Vec::with_capacity(15);
    for i in 0..=14usize {
        let t = i as f64 / 14.0;
        let phase = if i == 0 {
            1
        } else if i == 14 {
            3
        } else {
            2
        };
        samples.push(NativeInputSample {
            phys_x: (48.0 + t * 160.0) as f32,
            phys_y: 128.0,
            pressure: if phase == 3 { 0.0 } else { 1.0 },
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            timestamp_ms: now + i as f64 * 4.0,
            buttons: if phase == 3 { 0 } else { 1 },
            phase,
            backend: 1,
        });
    }
    producers.wintab.push_batch(&samples);

    let mut committed = false;
    let deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < deadline && !committed {
        for ev in handle.events().try_iter() {
            if matches!(ev, EngineEvent::StrokeCommitted { .. }) {
                committed = true;
                break;
            }
        }
        if !committed {
            std::thread::sleep(Duration::from_millis(8));
        }
    }
    assert!(committed, "Mask-mode stroke must commit natively");

    {
        let mut mgr = docs_lock.write();
        let doc = mgr.get_document_mut(&doc_id).unwrap();
        let layer = doc.layer(&layer_id).unwrap();
        let mask_center = layer.grid.get_mask_alpha(128, 128, None);
        let mask_corner = layer.grid.get_mask_alpha(16, 16, None);
        let raster_center = layer.grid.get_pixel_rgba8(128, 128, None);
        assert!(mask_center < 40, "Black stroke on mask must carve mask alpha: got {mask_center}");
        assert_eq!(mask_corner, 255, "Untouched mask corner must stay opaque 255");
        assert_eq!(raster_center, [220, 40, 60, 255], "Mask stroke must NOT alter raster pixels!");

        let _ = doc.undo();
        let mask_after_undo = doc.layer(&layer_id).unwrap().grid.get_mask_alpha(128, 128, None);
        assert_eq!(mask_after_undo, 255, "Undo must restore mask alpha to 255");
    }

    let preview_cases = [
        ("Standard Pen", NativeBrushConfig::default()),
        ("Impasto Oil", make_oil_impasto_brush([0.9, 0.9, 0.9], 28.0)),
        (
            "Continuous Ribbon",
            NativeBrushConfig {
                is_ribbon: true,
                size: 20.0,
                ..NativeBrushConfig::default()
            },
        ),
        (
            "CSP ColorMixing",
            NativeBrushConfig {
                color_mixing: true,
                size: 22.0,
                ..NativeBrushConfig::default()
            },
        ),
    ];
    for (label, cfg) in preview_cases {
        let (tx, rx) = crossbeam_channel::bounded(1);
        handle.send_command(EngineCommand::RenderBrushPreview {
            brush: Box::new(cfg),
            width: 180,
            height: 48,
            reply: tx,
        });
        let (pw, ph, rgba) = rx
            .recv_timeout(Duration::from_secs(5))
            .expect("receive preview")
            .expect("preview ok");
        assert_eq!((pw, ph), (180, 48));
        assert_eq!(rgba.len(), (180 * 48 * 4) as usize);
        let non_empty = rgba.as_chunks::<4>().0.iter().filter(|p| p[3] > 20).count();
        assert!(
            non_empty > 100,
            "GPU brush preview for '{label}' must produce visible stroke pixels (got {non_empty})"
        );
    }

    handle.shutdown();
}

#[test]
fn test_p5_brush_studio_live_scratchpad_preview_replays_edits() {
    let _dx12_guard = crate::lock_dx12_test();
    let (handle, _producers) = match EngineHandle::spawn(
        SurfaceTarget::Headless {
            width: 320,
            height: 240,
        },
        EngineConfig {
            doc_width: 512,
            doc_height: 512,
            ..Default::default()
        },
    ) {
        Ok(pair) => pair,
        Err(err) => {
            eprintln!("Skipping DX12 scratchpad preview test (no adapter): {err}");
            return;
        }
    };

    let stroke = crate::types::ScratchpadStrokeInput {
        points: (0..=24)
            .map(|i| {
                let t = i as f32 / 24.0;
                crate::types::ScratchpadStrokePoint {
                    x: 40.0 + t * 200.0,
                    y: 90.0 + (t * std::f32::consts::TAU).sin() * 26.0,
                    pressure: 0.75,
                    tilt_x: 0.0,
                    tilt_y: 0.0,
                    twist: 0.0,
                    timestamp_ms: i as f64 * 4.0,
                }
            })
            .collect(),
        color: [0.1, 0.25, 0.85],
        seed: 0x1234_5678,
    };

    let render_with_size = |size: f32| -> usize {
        let (tx, rx) = crossbeam_channel::bounded(1);
        handle.send_command(EngineCommand::RenderScratchpadPreview {
            brush: Box::new(NativeBrushConfig {
                size,
                opacity: 1.0,
                flow: 1.0,
                hardness: 1.0,
                spacing: 0.08,
                ..NativeBrushConfig::default()
            }),
            strokes: vec![stroke.clone()],
            width: 280,
            height: 180,
            reply: tx,
        });
        let (pw, ph, rgba) = rx
            .recv_timeout(Duration::from_secs(5))
            .expect("receive scratchpad preview")
            .expect("scratchpad preview ok");
        assert_eq!((pw, ph), (280, 180));
        rgba.as_chunks::<4>().0.iter().filter(|p| p[3] > 20).count()
    };

    let thin_px = render_with_size(6.0);
    let thick_px = render_with_size(36.0);
    assert!(
        thin_px > 200,
        "thin scratchpad stroke must render visible pixels (got {thin_px})"
    );
    assert!(
        thick_px > thin_px * 3,
        "editing brush size from 6px to 36px must visibly widen the recorded stroke ({thin_px} -> {thick_px})"
    );

    handle.shutdown();
}

// ============================================================================
// 8. 4096×4096 Heavy 250px Impasto Oil & Wet Mixing Filbert Benchmark
// ============================================================================

#[test]
fn test_benchmark_4k_250px_impasto_and_wet_filbert() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(1280, 720, 4096, 4096) else {
        return;
    };

    let mut doc = make_doc("p5-bench-4k", 4096, 4096);
    let ground_id = doc.layers[0].meta.id.clone();
    fill_layer_rect(&mut doc, &ground_id, 512, 512, 1536, 1536, [20, 65, 200, 255]);
    let paint_meta = LayerNodeMeta::new_raster("paint-4k", "4K Oil Paint");
    let _ = doc.add_layer(paint_meta, Some(0), true, false);
    let paint_id = "paint-4k".to_string();

    let viewport = ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 1280,
        height_px: 720,
        dpr: 1.0,
    };
    let cam = CameraState {
        pan_x: 640.0,
        pan_y: 360.0,
        zoom: 0.25,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    };
    let display = CompositorDisplayConfig::default();
    let cursor_cfg = CursorConfig::default();
    let _ = renderer.sync_document(&mut doc, None);

    // Warm up 3-slice compositor cache
    renderer.render_document_frame_with_brush(
        &doc,
        None,
        &display,
        &viewport,
        &cam,
        &[],
        false,
        false,
        &[],
        None,
        &cursor_cfg,
        None,
        true,
    );

    // Benchmark 1: Heavy 250px `impasto-bristle-oil` (32 bristles, spatial mixing, persistent R16F impasto)
    let impasto_brush = make_oil_impasto_brush([0.92, 0.72, 0.14], 250.0);
    let pts_oil = make_line_points(700.0, 900.0, 2100.0, 1450.0, 32, 250.0, 0.92);
    let mut sim_oil = BristleRibbonSimulator::new(&impasto_brush, 0xBEEF_0001);

    renderer.begin_natural_paint_stroke(&doc.id, &paint_id, 4096, 4096, impasto_brush.clone());
    let layer_snap = doc.layer(&paint_id).cloned().unwrap();

    let t0 = Instant::now();
    let mut frame_ms_oil = Vec::with_capacity(pts_oil.len());
    let mut total_caps_oil = 0usize;
    let mut caps_chunk = Vec::with_capacity(128);
    for pair in pts_oil.windows(2) {
        let ft = Instant::now();
        caps_chunk.clear();
        sim_oil.step_points(pair, &impasto_brush, &mut caps_chunk);
        total_caps_oil += caps_chunk.len();
        let _ = renderer.dispatch_natural_paint_capsules(&doc, &layer_snap, &caps_chunk, None);
        renderer.render_document_frame_with_brush(
            &doc,
            None,
            &display,
            &viewport,
            &cam,
            &[],
            false,
            true,
            &[],
            None,
            &cursor_cfg,
            Some((640.0, 360.0)),
            false,
        );
        frame_ms_oil.push(ft.elapsed().as_secs_f64() * 1000.0);
    }
    let oil_stroke_ms = t0.elapsed().as_secs_f64() * 1000.0;
    let oil_commit_t0 = Instant::now();
    let oil_batch = renderer
        .commit_natural_paint_to_layer()
        .expect("commit 4K 250px impasto stroke");
    let oil_commit_ms = oil_commit_t0.elapsed().as_secs_f64() * 1000.0;

    let oil_color_tiles = oil_batch.color_tiles.len();
    let oil_impasto_tiles = oil_batch.impasto_tiles.len();
    let empty_snap = HashMap::new();
    if let Some(l) = doc.layer_mut(&paint_id) {
        let _ = l
            .grid
            .apply_gpu_committed_tiles(&paint_id, oil_batch.color_tiles, &empty_snap, 128);
        let _ = l.grid.apply_gpu_committed_impasto_tiles(
            &paint_id,
            oil_batch.impasto_tiles,
            &empty_snap,
        );
        l.meta.impasto_light = impasto_brush.impasto_layer_light();
    }

    assert!(oil_color_tiles > 0 && oil_impasto_tiles > 0, "4K 250px impasto must commit tiles");

    // Benchmark 2: Heavy 250px `wet-mixing-filbert` (28 bristles, mixGroundColor=true, KM pigment mixing)
    let filbert_brush = make_wet_filbert_brush([0.98, 0.85, 0.05], 250.0);
    let pts_filb = make_line_points(700.0, 1300.0, 2100.0, 1000.0, 32, 250.0, 0.88);
    let mut sim_filb = BristleRibbonSimulator::new(&filbert_brush, 0xBEEF_0002);

    let _ = renderer.sync_document(&mut doc, None);
    renderer.begin_natural_paint_stroke(&doc.id, &paint_id, 4096, 4096, filbert_brush.clone());
    let layer_snap2 = doc.layer(&paint_id).cloned().unwrap();

    let t1 = Instant::now();
    let mut frame_ms_filb = Vec::with_capacity(pts_filb.len());
    let mut total_caps_filb = 0usize;
    for pair in pts_filb.windows(2) {
        let ft = Instant::now();
        caps_chunk.clear();
        sim_filb.step_points(pair, &filbert_brush, &mut caps_chunk);
        total_caps_filb += caps_chunk.len();
        let _ = renderer.dispatch_natural_paint_capsules(&doc, &layer_snap2, &caps_chunk, None);
        renderer.render_document_frame_with_brush(
            &doc,
            None,
            &display,
            &viewport,
            &cam,
            &[],
            false,
            true,
            &[],
            None,
            &cursor_cfg,
            Some((640.0, 360.0)),
            false,
        );
        frame_ms_filb.push(ft.elapsed().as_secs_f64() * 1000.0);
    }
    let filb_stroke_ms = t1.elapsed().as_secs_f64() * 1000.0;
    let filb_commit_t0 = Instant::now();
    let filb_batch = renderer
        .commit_natural_paint_to_layer()
        .expect("commit 4K 250px wet filbert stroke");
    let filb_commit_ms = filb_commit_t0.elapsed().as_secs_f64() * 1000.0;
    assert!(!filb_batch.color_tiles.is_empty());

    let avg_oil_ms = frame_ms_oil.iter().sum::<f64>() / frame_ms_oil.len().max(1) as f64;
    let avg_filb_ms = frame_ms_filb.iter().sum::<f64>() / frame_ms_filb.len().max(1) as f64;

    println!(
        "\n[PHASE 5 4K 250px GPU BENCHMARK — Adapter: {}]\n\
         - impasto-bristle-oil (32 bristles, R16F impasto + live relief lighting):\n\
           {total_caps_oil} capsules, {oil_color_tiles} color + {oil_impasto_tiles} R16F tiles | \
           stroke={oil_stroke_ms:.1}ms (avg {avg_oil_ms:.2}ms/step, {:.1} FPS), commit={oil_commit_ms:.1}ms, 0 CPU readPixels stalls\n\
         - wet-mixing-filbert (28 bristles, mixGroundColor + KM pigment compute):\n\
           {total_caps_filb} capsules, {} color tiles | \
           stroke={filb_stroke_ms:.1}ms (avg {avg_filb_ms:.2}ms/step, {:.1} FPS), commit={filb_commit_ms:.1}ms, 0 CPU readPixels stalls",
        renderer.adapter_name(),
        1000.0 / avg_oil_ms.max(0.01),
        filb_batch.color_tiles.len(),
        1000.0 / avg_filb_ms.max(0.01),
    );
}

// ============================================================================
// 9. ColorMixingStamp Sub-Rect Perf Benchmark & Full CSP/Moko.art Parity Suite
// ============================================================================

#[test]
fn test_p5_color_mixing_stamp_subrect_perf_and_csp_parity() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(512, 512, 512, 512) else {
        return;
    };

    // Helper: emit primary (+ optional dual-brush secondary) dabs along a straight line
    let emit_line_dabs = |renderer: &mut GpuRenderer,
                          brush: &NativeBrushConfig,
                          x0: f64,
                          y0: f64,
                          x1: f64,
                          y1: f64,
                          seed: u64|
     -> (Vec<crate::brush::GpuBrushDab>, Vec<crate::brush::GpuBrushDab>, [f32; 2]) {
        let metrics = renderer.resolve_brush_tip_metrics(brush);
        let mut emitter = StrokeDabEmitter::new(brush.clone(), seed, metrics.0, metrics.1);
        let mut sec_emitter = brush.build_secondary_brush_config().map(|sc| {
            let sm = renderer.resolve_brush_tip_metrics(&sc);
            StrokeDabEmitter::new(sc, seed ^ 0xA5A5_5A5A, sm.0, sm.1)
        });
        let pts = make_line_points(x0, y0, x1, y1, 24, brush.size, 0.9);
        let mut p_dabs = Vec::with_capacity(256);
        let mut s_dabs = Vec::with_capacity(256);
        emitter.emit_initial_point(&pts[0], None, 0.0, &mut p_dabs);
        if let Some(ref mut se) = sec_emitter {
            se.emit_initial_point(&pts[0], None, 0.0, &mut s_dabs);
        }
        for i in 1..pts.len() {
            let p0 = pts[i.saturating_sub(2)];
            let p1 = pts[i - 1];
            let p2 = pts[i];
            let p3 = pts[(i + 1).min(pts.len() - 1)];
            let seg = centripetal_catmull_rom_to_bezier(p0, p1, p2, p3, 0.5);
            emitter.emit_segment(&seg, None, 0.0, &mut p_dabs);
            if let Some(ref mut se) = sec_emitter {
                se.emit_segment(&seg, None, 0.0, &mut s_dabs);
            }
        }
        (p_dabs, s_dabs, emitter.stroke_grain_offset)
    };

    // ------------------------------------------------------------------------
    // 1 & 2. Fast 300px oil-flat-alla-prima (size=48, spacing=0.05) sub-rect
    //        efficiency + Blue + Yellow subtractive KM Green + zero BG churn
    // ------------------------------------------------------------------------
    let mut doc = make_doc("p5-cmix-subrect-bench", 512, 512);
    let layer_id = doc.layers[0].meta.id.clone();
    fill_layer_rect(&mut doc, &layer_id, 40, 180, 400, 140, [0, 45, 215, 255]);
    let _ = renderer.sync_document(&mut doc, None);

    let oil_brush = NativeBrushConfig {
        fg_color: [1.0, 0.90, 0.0],
        size: 48.0,
        min_size_factor: 0.35,
        opacity: 1.0,
        flow: 0.95,
        brush_density: 0.92,
        hardness: 0.85,
        spacing: 0.05,
        preset_key: Some("oil-flat-alla-prima".to_string()),
        render_mode: BrushRenderMode::Stamp,
        color_mixing: true,
        perceptual_mixing: true,
        amount_of_paint: 0.52,
        density_of_paint: 0.90,
        color_stretch: 0.72,
        mixing_mode: NaturalMixingMode::Blend,
        ..NativeBrushConfig::default()
    };
    assert!(oil_brush.is_color_mixing_stamp_brush());

    let (dabs_300, _, grain_off) = emit_line_dabs(&mut renderer, &oil_brush, 80.0, 250.0, 380.0, 250.0, 1001);
    assert!(
        dabs_300.len() >= 100,
        "300px stroke at size=48, spacing=0.05 should emit >= 100 raw dabs, got {}",
        dabs_300.len()
    );

    renderer.begin_natural_paint_stroke(&doc.id, &layer_id, 512, 512, oil_brush.clone());
    renderer.set_natural_paint_stroke_rand_offset(grain_off);
    let layer_snap = doc.layer(&layer_id).cloned().unwrap();

    let t0 = Instant::now();
    let _ = renderer.dispatch_color_mixing_dabs(&doc, &layer_snap, &dabs_300, None);
    let subrect_px = renderer.brush_engine().natural_paint.cmix_last_batch_subrect_pixels;
    let full_tile_px = renderer.brush_engine().natural_paint.cmix_last_batch_full_tile_pixels;
    let dispatched_dabs = renderer.brush_engine().natural_paint.cmix_last_batch_dispatched_dabs;
    let bg_rebuilds_after_first = renderer.brush_engine().natural_paint.cmix_bind_group_rebuilds;

    // Dispatch a second batch on the same stroke to verify ZERO BindGroup rebuild churn
    let (dabs_next, _, _) = emit_line_dabs(&mut renderer, &oil_brush, 380.0, 250.0, 420.0, 250.0, 1002);
    let _ = renderer.dispatch_color_mixing_dabs(&doc, &layer_snap, &dabs_next, None);
    let bg_rebuilds_after_second = renderer.brush_engine().natural_paint.cmix_bind_group_rebuilds;
    let batch_ms = t0.elapsed().as_secs_f64() * 1000.0;

    let batch = renderer
        .commit_natural_paint_to_layer()
        .expect("commit oil-flat-alla-prima stroke");
    let empty_snap = HashMap::new();
    let _ = doc
        .layer_mut(&layer_id)
        .unwrap()
        .grid
        .apply_gpu_committed_tiles(&layer_id, batch.color_tiles, &empty_snap, 128);

    let area_ratio = subrect_px as f64 / full_tile_px.max(1) as f64;
    println!(
        "\n[COLOR-MIXING SUB-RECT BENCHMARK — Adapter: {}]\n\
         - oil-flat-alla-prima (300px, size=48, spacing=0.05): raw_dabs={}, dispatched_dabs={}, \
         subrect_ratio={:.2}% ({subrect_px}/{full_tile_px} px), bg_rebuilds={}->{}, elapsed={batch_ms:.2}ms",
        renderer.adapter_name(),
        dabs_300.len(),
        dispatched_dabs,
        area_ratio * 100.0,
        bg_rebuilds_after_first,
        bg_rebuilds_after_second,
    );

    assert!(
        area_ratio < 0.15,
        "Sub-rect dispatch & copy area must be < 15% of full-tile area! got {:.2}% ({subrect_px}/{full_tile_px})",
        area_ratio * 100.0
    );
    assert!(
        dispatched_dabs < dabs_300.len(),
        "Adaptive micro-step coalescing must reduce dense >32-dab frame passes ({dispatched_dabs} vs {})",
        dabs_300.len()
    );
    assert_eq!(
        bg_rebuilds_after_first, bg_rebuilds_after_second,
        "Consecutive ColorMixingStamp frames must allocate ZERO new BindGroups!"
    );

    let (rgb_mix, a_mix, _) = sample_region_mean_rgba(&doc, &layer_id, 130, 240, 320, 260);
    assert!(a_mix > 0.85, "Mixed stroke must be opaque: a={a_mix}");
    assert!(
        rgb_mix[1] > rgb_mix[0] + 0.04 && rgb_mix[1] > rgb_mix[2] && rgb_mix[1] > 0.35,
        "Fast per-pixel KM Blue+Yellow must produce vivid Green! got={rgb_mix:?}"
    );

    // ------------------------------------------------------------------------
    // 3. Zero dark-halo artifact on transparent edges during live strokes
    //    (SPARSE_STROKE_PROJECT_WGSL halo-free premultiplied 2x2 bilinear)
    // ------------------------------------------------------------------------
    let mut doc_halo = make_doc("p5-cmix-halo", 512, 512);
    let bg_id = doc_halo.layers[0].meta.id.clone();
    fill_layer_rect(&mut doc_halo, &bg_id, 0, 0, 512, 512, [255, 255, 255, 255]);
    let _ = doc_halo.add_layer(LayerNodeMeta::new_raster("top-halo", "Top"), Some(0), true, false);
    let top_id = "top-halo".to_string();
    doc_halo.active_layer_id = Some(top_id.clone());
    let _ = renderer.sync_document(&mut doc_halo, None);

    let mut bright_yellow = oil_brush.clone();
    bright_yellow.fg_color = [1.0, 0.96, 0.0];
    bright_yellow.size = 44.0;
    bright_yellow.spacing = 0.12;
    bright_yellow.hardness = 0.7;
    bright_yellow.amount_of_paint = 0.95;
    let (halo_dabs, _, halo_off) =
        emit_line_dabs(&mut renderer, &bright_yellow, 140.0, 256.0, 360.0, 256.0, 2001);

    renderer.begin_natural_paint_stroke(&doc_halo.id, &top_id, 512, 512, bright_yellow);
    renderer.set_natural_paint_stroke_rand_offset(halo_off);
    let top_snap = doc_halo.layer(&top_id).cloned().unwrap();
    let _ = renderer.dispatch_color_mixing_dabs(&doc_halo, &top_snap, &halo_dabs, None);

    // Render live viewport at fractional zoom (1.37x) to exercise bilinear sampling across edges!
    let vp = ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 512,
        height_px: 512,
        dpr: 1.0,
    };
    let cam = CameraState {
        pan_x: 256.3,
        pan_y: 256.4,
        zoom: 1.37,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    };
    let display = CompositorDisplayConfig::default();
    let cursor_cfg = CursorConfig::default();
    renderer.render_document_frame_with_brush(
        &doc_halo,
        None,
        &display,
        &vp,
        &cam,
        &[],
        false,
        true,
        &[],
        None,
        &cursor_cfg,
        None,
        true,
    );
    let (rw, rh, fb_rgba) = renderer
        .readback_headless_rgba8()
        .expect("readback live viewport framebuffer");
    assert_eq!((rw, rh), (512, 512));

    // Every pixel in the live yellow-over-white stroke region must stay bright (ZERO dark edge halo!)
    let mut min_r = 255u8;
    let mut min_g = 255u8;
    let mut yellow_edge_pixels = 0usize;
    for y in 200..312usize {
        for x in 140..372usize {
            let off = (y * 512 + x) * 4;
            let r = fb_rgba[off];
            let g = fb_rgba[off + 1];
            let b = fb_rgba[off + 2];
            if b < 245 && b > 20 {
                yellow_edge_pixels += 1;
                min_r = min_r.min(r);
                min_g = min_g.min(g);
            }
        }
    }
    let _ = renderer.commit_natural_paint_to_layer();
    assert!(
        yellow_edge_pixels > 50,
        "Expected anti-aliased edge pixels in live stroke viewport, found {yellow_edge_pixels}"
    );
    assert!(
        min_r >= 230 && min_g >= 220,
        "Live ColorMixingStamp stroke had dark premultiplied alpha halo on transparent edge! min_r={min_r}, min_g={min_g} (expected >= 230, 220)"
    );

    // ------------------------------------------------------------------------
    // 4. Paper Texture Mode = Compare vs Multiply AND Dual Brush = true vs false
    // ------------------------------------------------------------------------
    let run_cmix_variant =
        |renderer: &mut GpuRenderer, name: &str, brush: &NativeBrushConfig| -> Vec<u8> {
            let mut d = make_doc(name, 512, 512);
            let lid = d.layers[0].meta.id.clone();
            let _ = renderer.sync_document(&mut d, None);
            let (pd, sd, goff) =
                emit_line_dabs(renderer, brush, 90.0, 256.0, 380.0, 256.0, 3001);
            renderer.begin_natural_paint_stroke(&d.id, &lid, 512, 512, brush.clone());
            renderer.set_natural_paint_stroke_rand_offset(goff);
            let lsnap = d.layer(&lid).cloned().unwrap();
            let _ = renderer.dispatch_color_mixing_dabs_with_secondary(&d, &lsnap, &pd, &sd, None);
            let b = renderer
                .commit_natural_paint_to_layer()
                .expect("commit variant");
            let es = HashMap::new();
            let _ = d
                .layer_mut(&lid)
                .unwrap()
                .grid
                .apply_gpu_committed_tiles(&lid, b.color_tiles, &es, 128);
            let layer = d.layer(&lid).unwrap();
            let mut out = Vec::with_capacity((340 * 100 * 4) as usize);
            for y in 206..306 {
                for x in 70..410 {
                    out.extend_from_slice(&layer.grid.get_pixel_rgba8(x, y, None));
                }
            }
            out
        };

    let mean_abs_diff = |a: &[u8], b: &[u8]| -> f64 {
        assert_eq!(a.len(), b.len());
        let sum: u64 = a
            .iter()
            .zip(b.iter())
            .map(|(&x, &y)| x.abs_diff(y) as u64)
            .sum();
        sum as f64 / a.len().max(1) as f64
    };

    // 4a. Paper Texture Mode: Multiply vs Compare
    let mut paper_mult = oil_brush.clone();
    paper_mult.fg_color = [0.22, 0.35, 0.78];
    paper_mult.hardness = 0.45;
    paper_mult.spacing = 0.16;
    paper_mult.flow = 0.65;
    paper_mult.brush_density = 0.65;
    paper_mult.surface_texture_id = Some("cold-press-watercolor".to_string());
    paper_mult.grain = 0.85;
    paper_mult.paper_texture_mode = CspPaperTextureMode::Multiply;

    let mut paper_cmp = paper_mult.clone();
    paper_cmp.paper_texture_mode = CspPaperTextureMode::Compare;

    let px_mult = run_cmix_variant(&mut renderer, "p5-cmix-paper-mult", &paper_mult);
    let px_cmp = run_cmix_variant(&mut renderer, "p5-cmix-paper-cmp", &paper_cmp);
    let paper_diff = mean_abs_diff(&px_mult, &px_cmp);
    assert!(
        paper_diff > 2.5,
        "paper_texture_mode=Compare must produce measurably distinct output from Multiply on ColorMixingStamp! diff={paper_diff:.3}"
    );

    // 4b. Dual Brush: disabled vs enabled (Multiply with smaller scattered secondary mask)
    let mut dual_off = oil_brush.clone();
    dual_off.fg_color = [0.75, 0.22, 0.18];
    dual_off.spacing = 0.14;
    dual_off.dual_brush = false;
    dual_off.dual_brush_config = None;

    let mut dual_on = dual_off.clone();
    dual_on.dual_brush = true;
    dual_on.dual_brush_config = Some(CspDualBrushConfig {
        enabled: true,
        combine_mode: DualBrushCompositeMode::Multiply,
        link_size: false,
        size: 20.0,
        spacing: 1.4, // wide spacing so secondary leaves clear gaps that carve primary
        hardness: 0.85,
        density: 0.85,
        ..CspDualBrushConfig::default()
    });

    let px_dual_off = run_cmix_variant(&mut renderer, "p5-cmix-dual-off", &dual_off);
    let px_dual_on = run_cmix_variant(&mut renderer, "p5-cmix-dual-on", &dual_on);
    let dual_diff = mean_abs_diff(&px_dual_off, &px_dual_on);
    assert!(
        dual_diff > 5.0,
        "dual_brush=true must produce measurably distinct output on ColorMixingStamp! diff={dual_diff:.3}"
    );

    // 4c. Stroke-level config.opacity capping & watercolor wet_edge
    let mut wash_brush = oil_brush.clone();
    wash_brush.fg_color = [0.15, 0.55, 0.88];
    wash_brush.opacity = 0.45;
    wash_brush.spacing = 0.08;
    wash_brush.wet_edge = 0.0;
    let px_wash_no_wet = run_cmix_variant(&mut renderer, "p5-cmix-opacity-cap", &wash_brush);
    let max_alpha = px_wash_no_wet
        .chunks_exact(4)
        .map(|c| c[3])
        .max()
        .unwrap_or(0);
    assert!(
        max_alpha > 80 && max_alpha <= 130,
        "Stroke-level config.opacity=0.45 must cap overlapping stroke alpha near ~115 (got max_alpha={max_alpha})"
    );

    let mut wash_wet = wash_brush.clone();
    wash_wet.wet_edge = 0.48;
    wash_wet.wet_edge_radius = 4.0;
    let px_wash_wet = run_cmix_variant(&mut renderer, "p5-cmix-wet-edge", &wash_wet);
    let wet_diff = mean_abs_diff(&px_wash_no_wet, &px_wash_wet);
    let max_wet_px_diff = px_wash_no_wet
        .iter()
        .zip(px_wash_wet.iter())
        .map(|(&a, &b)| a.abs_diff(b))
        .max()
        .unwrap_or(0);
    let max_alpha_wet = px_wash_wet
        .chunks_exact(4)
        .map(|c| c[3])
        .max()
        .unwrap_or(0);
    assert!(
        wet_diff > 0.2 && max_wet_px_diff >= 6 && max_alpha_wet > max_alpha,
        "wet_edge=0.48 must produce measurable watercolor edge darkening/pooling on ColorMixingStamp! diff={wet_diff:.3}, max_px_diff={max_wet_px_diff}, max_alpha={max_alpha}->{max_alpha_wet}"
    );
}

// ============================================================================
// 9. Performance & Parity Regression Tests (Binning, Underbed, TiltMax, Ribbon, GPU Pack)
// ============================================================================

#[test]
fn test_p5_natural_paint_per_tile_capsule_binning_and_wet_edge() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(256, 256, 1024, 256) else {
        return;
    };

    // Multi-tile horizontal NaturalPaint stroke spanning 4 tiles (x = 40..980)
    let mut brush = make_wet_filbert_brush([0.12, 0.42, 0.86], 44.0);
    brush.preset_key = Some("p5-binning-test".to_string());
    brush.mix_ground_color = false;
    brush.natural_paint.as_mut().unwrap().auto_clean = true;
    brush.natural_paint.as_mut().unwrap().spatial_mixing = true;
    brush.natural_paint.as_mut().unwrap().depletion_rate = 0.0;

    let pts = make_line_points(40.0, 128.0, 980.0, 128.0, 48, 44.0, 0.85);
    let mut sim = BristleRibbonSimulator::new(&brush, 777);
    let mut capsules = Vec::new();
    sim.step_points(&pts, &brush, &mut capsules);
    assert!(capsules.len() >= 200, "Expected multi-tile capsule batch, got {}", capsules.len());

    // A) Full 4-tile binned dispatch
    let mut doc_binned = make_doc("p5-np-binned", 1024, 256);
    let lid_b = doc_binned.layers[0].meta.id.clone();
    let _ = renderer.sync_document(&mut doc_binned, None);
    renderer.begin_natural_paint_stroke(&doc_binned.id, &lid_b, 1024, 256, brush.clone());
    let lsnap_b = doc_binned.layer(&lid_b).cloned().unwrap();
    let _ = renderer.dispatch_natural_paint_capsules(&doc_binned, &lsnap_b, &capsules, None);

    let binned_checks = renderer.brush_engine().natural_paint.np_last_batch_binned_checks;
    let unbinned_checks = renderer.brush_engine().natural_paint.np_last_batch_unbinned_checks;
    let subrect_px = renderer.brush_engine().natural_paint.np_last_batch_subrect_pixels;
    let bg_rebuilds_1 = renderer.brush_engine().natural_paint.np_bind_group_rebuilds;

    // Second dispatch on same stroke should NOT rebuild cached pickup/raster BindGroups!
    let _ = renderer.dispatch_natural_paint_capsules(&doc_binned, &lsnap_b, &capsules[..16], None);
    let bg_rebuilds_2 = renderer.brush_engine().natural_paint.np_bind_group_rebuilds;

    assert!(
        binned_checks > 0 && binned_checks * 2 < unbinned_checks,
        "Per-tile capsule binning must check < 50% of unbinned tile×capsule pairs! binned={binned_checks}, unbinned={unbinned_checks}"
    );
    assert!(
        subrect_px < 4 * 256 * 256 / 2,
        "Tight tile-local sub-rect must cover < 50% of 4 full tiles! subrect_px={subrect_px}"
    );
    assert_eq!(
        bg_rebuilds_1, bg_rebuilds_2,
        "Cached pickup_bg/raster_bg must incur 0 BindGroup rebuilds on steady-state follow-up batches!"
    );
    let _ = renderer.commit_natural_paint_to_layer();

    // B) Verify binned multi-tile rendering is bit-identical to unbinned single-tile reference
    let mut doc_all = make_doc("p5-np-bin-all", 1024, 256);
    let lid_all = doc_all.layers[0].meta.id.clone();
    let _ = renderer.sync_document(&mut doc_all, None);
    renderer.begin_natural_paint_stroke(&doc_all.id, &lid_all, 1024, 256, brush.clone());
    let lsnap_all = doc_all.layer(&lid_all).cloned().unwrap();
    let _ = renderer.dispatch_natural_paint_capsules(&doc_all, &lsnap_all, &capsules, None);
    let batch_all = renderer.commit_natural_paint_to_layer().expect("commit all");
    let empty_snap = HashMap::new();
    let _ = doc_all
        .layer_mut(&lid_all)
        .unwrap()
        .grid
        .apply_gpu_committed_tiles(&lid_all, batch_all.color_tiles, &empty_snap, 128);

    // Filter strictly to capsules whose AABB overlaps tile (0, 0) (`x < 256`) and dispatch alone
    let tile0_caps: Vec<_> = capsules
        .iter()
        .copied()
        .filter(|c| {
            let (x0, _, x1, _) = c.doc_bounds();
            x0 < 256.0 && x1 >= 0.0
        })
        .collect();
    assert!(tile0_caps.len() < capsules.len() / 2);

    let mut doc_ref = make_doc("p5-np-bin-ref", 1024, 256);
    let lid_ref = doc_ref.layers[0].meta.id.clone();
    let _ = renderer.sync_document(&mut doc_ref, None);
    renderer.begin_natural_paint_stroke(&doc_ref.id, &lid_ref, 1024, 256, brush.clone());
    let lsnap_ref = doc_ref.layer(&lid_ref).cloned().unwrap();
    let _ = renderer.dispatch_natural_paint_capsules(&doc_ref, &lsnap_ref, &tile0_caps, None);
    let batch_ref = renderer.commit_natural_paint_to_layer().expect("commit ref");
    let _ = doc_ref
        .layer_mut(&lid_ref)
        .unwrap()
        .grid
        .apply_gpu_committed_tiles(&lid_ref, batch_ref.color_tiles, &empty_snap, 128);

    let l_all = doc_all.layer(&lid_all).unwrap();
    let l_ref = doc_ref.layer(&lid_ref).unwrap();
    let mut max_diff = 0u8;
    let mut painted_px = 0usize;
    for y in 64..192 {
        for x in 16..240 {
            let pa = l_all.grid.get_pixel_rgba8(x, y, None);
            let pr = l_ref.grid.get_pixel_rgba8(x, y, None);
            if pa[3] > 20 {
                painted_px += 1;
            }
            for c in 0..4 {
                max_diff = max_diff.max(pa[c].abs_diff(pr[c]));
            }
        }
    }
    assert!(painted_px > 2000, "Expected painted pixels in tile 0, got {painted_px}");
    assert!(
        max_diff <= 1,
        "Per-tile capsule binning must match unbinned tile-local reference (max_diff={max_diff})"
    );

    // C) Verify wet_edge > 0.01 works on NaturalPaint (e.g. granulating-watercolor)
    let mut wc_off = make_wet_filbert_brush([0.14, 0.48, 0.85], 40.0);
    wc_off.preset_key = Some("p5-np-wet-off".to_string());
    wc_off.mix_ground_color = false;
    wc_off.opacity = 0.55;
    wc_off.wet_edge = 0.0;

    let mut wc_on = wc_off.clone();
    wc_on.preset_key = Some("p5-np-wet-on".to_string());
    wc_on.wet_edge = 0.65;
    wc_on.wet_edge_radius = 4.0;

    let wc_pts = make_line_points(60.0, 128.0, 260.0, 128.0, 24, 40.0, 0.8);
    let mut doc_w0 = make_doc("p5-np-wet0", 512, 256);
    let lw0 = doc_w0.layers[0].meta.id.clone();
    run_natural_paint_stroke(&mut renderer, &mut doc_w0, &lw0, wc_off, &wc_pts, 801);

    let mut doc_w1 = make_doc("p5-np-wet1", 512, 256);
    let lw1 = doc_w1.layers[0].meta.id.clone();
    run_natural_paint_stroke(&mut renderer, &mut doc_w1, &lw1, wc_on, &wc_pts, 801);

    let l0 = doc_w0.layer(&lw0).unwrap();
    let l1 = doc_w1.layer(&lw1).unwrap();
    let mut wet_max_diff = 0u8;
    for y in 90..166 {
        for x in 45..275 {
            let p0 = l0.grid.get_pixel_rgba8(x, y, None);
            let p1 = l1.grid.get_pixel_rgba8(x, y, None);
            for c in 0..4 {
                wet_max_diff = wet_max_diff.max(p0[c].abs_diff(p1[c]));
            }
        }
    }
    assert!(
        wet_max_diff >= 8,
        "NaturalPaint with wet_edge=0.65 must produce measurable rim darkening/pooling! wet_max_diff={wet_max_diff}"
    );
}

#[test]
fn test_p5_underbed_bands_do_not_corrupt_bristles_0_to_4() {
    let _dx12_guard = crate::lock_dx12_test();
    use crate::natural_paint::{
        GpuBristleCapsule, MAX_BRISTLES, TOTAL_BRISTLE_SLOTS, UNDERBED_BANDS, UNDERBED_SLOT_BASE,
    };

    // 1. CPU BristleRibbonSimulator must assign dedicated reservoir indices `64..69` to underbed bands
    let brush = make_wet_filbert_brush([1.0, 1.0, 1.0], 48.0);
    let mut sim = BristleRibbonSimulator::new(&brush, 1234);
    let pts = make_line_points(40.0, 128.0, 220.0, 128.0, 18, 48.0, 0.85);
    let mut caps = Vec::new();
    sim.step_points(&pts, &brush, &mut caps);

    let mut underbed_count = 0usize;
    let mut bristle_count = 0usize;
    for cap in &caps {
        let flags = (cap.strand[3] + 0.5) as u32;
        let idx = (cap.strand[0] + 0.5) as usize;
        if (flags & 1) != 0 {
            underbed_count += 1;
            assert!(
                idx >= UNDERBED_SLOT_BASE && idx < TOTAL_BRISTLE_SLOTS,
                "Underbed band must use dedicated slot in {}..{}, got {}",
                UNDERBED_SLOT_BASE,
                TOTAL_BRISTLE_SLOTS,
                idx
            );
        } else {
            bristle_count += 1;
            assert!(
                idx < MAX_BRISTLES,
                "Real bristle must use slot in 0..{}, got {}",
                MAX_BRISTLES,
                idx
            );
        }
    }
    assert!(underbed_count >= UNDERBED_BANDS && bristle_count > 50);

    // 2. GPU verification: real bristles 0..4 pass over pure BLUE, while underbed bands 64..68
    //    pass over pure RED — assert slots 0..4 stay BLUE and are NEVER corrupted by RED!
    let Some(mut renderer) = make_headless_renderer(256, 256, 512, 256) else {
        return;
    };
    let mut doc = make_doc("p5-underbed-isolation", 512, 256);
    let lid = doc.layers[0].meta.id.clone();
    fill_layer_rect(&mut doc, &lid, 0, 0, 512, 128, [10, 35, 245, 255]); // top half: BLUE
    fill_layer_rect(&mut doc, &lid, 0, 128, 512, 128, [245, 15, 15, 255]); // bottom half: RED
    let _ = renderer.sync_document(&mut doc, None);

    let mut iso_brush = make_wet_filbert_brush([1.0, 1.0, 1.0], 32.0);
    iso_brush.preset_key = Some("p5-underbed-iso-key".to_string());
    iso_brush.mix_ground_color = false;
    iso_brush.amount_of_paint = 0.05;
    iso_brush.natural_paint.as_mut().unwrap().spatial_mixing = true;
    iso_brush.natural_paint.as_mut().unwrap().auto_clean = true;
    iso_brush.natural_paint.as_mut().unwrap().wetness = 0.95;

    let mut test_caps = Vec::new();
    for step in 0..6 {
        let x0 = 60.0 + step as f32 * 24.0;
        let x1 = x0 + 24.0;
        for b in 0..5usize {
            // Real bristles 0..4 travel across top BLUE half (y = 40..80)
            let yb = 40.0 + b as f32 * 10.0;
            test_caps.push(GpuBristleCapsule {
                p0_p1: [x0, yb, x1, yb],
                geom: [4.0, 4.0, 0.9, 0.8],
                strand: [b as f32, 0.1, 1.0, 0.0],
                motion: [step as f32 * 24.0, (step as f32 + 1.0) * 24.0, 0.0, 0.0],
                phys: [0.8, 0.8, 0.8, 1.0],
            });
            // Underbed bands 64..68 travel across bottom RED half (y = 160..200)
            let yu = 160.0 + b as f32 * 10.0;
            test_caps.push(GpuBristleCapsule {
                p0_p1: [x0, yu, x1, yu],
                geom: [8.0, 8.0, 0.9, 0.6],
                strand: [(UNDERBED_SLOT_BASE + b) as f32, 0.2, 1.0, 1.0],
                motion: [step as f32 * 24.0, (step as f32 + 1.0) * 24.0, 0.0, 0.0],
                phys: [0.6, 0.36, 0.36, 1.0],
            });
        }
    }

    renderer.begin_natural_paint_stroke(&doc.id, &lid, 512, 256, iso_brush);
    let lsnap = doc.layer(&lid).cloned().unwrap();
    let _ = renderer.dispatch_natural_paint_capsules(&doc, &lsnap, &test_caps, None);
    let slots = renderer
        .brush_engine()
        .natural_paint
        .readback_bristle_slots(renderer.device(), renderer.queue(), "p5-underbed-iso-key")
        .expect("readback bristle + underbed slots");
    let _ = renderer.commit_natural_paint_to_layer();

    assert_eq!(slots.len(), TOTAL_BRISTLE_SLOTS);
    for b in 0..5usize {
        let rgb = slots[b].color_load;
        assert!(
            rgb[2] > rgb[0] + 0.20,
            "Real bristle slot {b} must retain BLUE pickup and NEVER be corrupted by RED underbed! got={rgb:?}"
        );
    }
    for u in 0..UNDERBED_BANDS {
        let rgb = slots[UNDERBED_SLOT_BASE + u].color_load;
        assert!(
            rgb[0] > rgb[2] + 0.20,
            "Underbed slot {} must independently track RED pickup! got={rgb:?}",
            UNDERBED_SLOT_BASE + u
        );
    }
}

#[test]
fn test_p5_size_sensor_tilt_max_grows_brush_size() {
    use crate::brush::{evaluate_csp_sensor, CompiledSensorLuts};

    // 1. JSON deserialization defaults & explicit tiltMax
    let explicit: CspSensorConfig =
        serde_json::from_str(r#"{"useTilt":true,"tiltMin":1.0,"tiltMax":1.5}"#)
            .expect("deserialize explicit tiltMax");
    assert!((explicit.tilt_min - 1.0).abs() < 1e-5);
    assert!((explicit.tilt_max - 1.5).abs() < 1e-5);

    let defaulted: CspSensorConfig =
        serde_json::from_str(r#"{"useTilt":true,"tiltMin":0.25}"#)
            .expect("deserialize default tiltMax");
    assert!((defaulted.tilt_max - 1.0).abs() < 1e-5);

    // 2. Direct evaluate_csp_sensor check
    let luts = CompiledSensorLuts::from_sensor(Some(&explicit));
    let upright_mult = evaluate_csp_sensor(&explicit, Some(&luts), 1.0, 0.0, 0.0, 0.0, 0.5);
    let tilted_mult = evaluate_csp_sensor(&explicit, Some(&luts), 1.0, 1.0, 0.0, 0.0, 0.5);
    assert!(
        (upright_mult - 1.0).abs() < 1e-4,
        "Upright pen must stay 1.0x, got {upright_mult}"
    );
    assert!(
        (tilted_mult - 1.5).abs() < 1e-4,
        "Full pen tilt with tiltMin=1.0, tiltMax=1.5 must grow size by 1.5x! got {tilted_mult}"
    );

    // 3. End-to-end StrokeDabEmitter check (G-Pen style brush with sizeSensor tiltMax=1.5)
    let brush = NativeBrushConfig {
        size: 20.0,
        use_pressure: true,
        use_tilt: true,
        tilt_scale: 1.0, // Pure sizeSensor tiltMax enlargement
        size_sensor: Some(explicit),
        ..NativeBrushConfig::default()
    };
    let mut emitter = StrokeDabEmitter::new(brush, 999, 1, 1.0);
    let mut dabs_upright = Vec::new();
    let mut dabs_tilted = Vec::new();
    let pt_up = StrokePoint {
        x: 100.0,
        y: 100.0,
        pressure: 1.0,
        width: 20.0,
        tilt_x: 0.0,
        tilt_y: 0.0,
        ..Default::default()
    };
    let pt_tilt = StrokePoint {
        x: 100.0,
        y: 100.0,
        pressure: 1.0,
        width: 20.0,
        tilt_x: 75.0,
        tilt_y: 0.0,
        ..Default::default()
    };
    emitter.emit_initial_point(&pt_up, None, 0.0, &mut dabs_upright);
    emitter.emit_initial_point(&pt_tilt, None, 0.0, &mut dabs_tilted);
    let hw_up = dabs_upright[0].pos_size[2];
    let hw_tilt = dabs_tilted[0].pos_size[2];
    assert!(
        ((hw_tilt / hw_up) - 1.5).abs() < 1e-3,
        "StrokeDabEmitter with sizeSensor tiltMin=1.0, tiltMax=1.5 must swell dab width by 1.5x! upright={hw_up}, tilted={hw_tilt}"
    );
}

#[test]
fn test_p5_ribbon_incremental_triangulation_and_paper_contrast() {
    let _dx12_guard = crate::lock_dx12_test();

    // Build a 40-point curved + sharp-corner stroke
    let mut pts = Vec::with_capacity(40);
    for i in 0..40 {
        let t = i as f64 / 39.0;
        let (x, y, corner) = if i == 20 {
            (220.0, 200.0, true)
        } else if i < 20 {
            (30.0 + t * 380.0, 90.0 + (t * std::f64::consts::TAU).sin() * 45.0, false)
        } else {
            (30.0 + t * 380.0, 170.0 - (t * std::f64::consts::TAU).cos() * 40.0, false)
        };
        pts.push(StrokePoint {
            x,
            y,
            pressure: 0.55 + 0.4 * (t as f32),
            width: 28.0,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            velocity: 0.6,
            timestamp_ms: i as f64 * 4.0,
            is_corner: corner,
        });
    }

    // 1. Incremental chunked triangulation (3 pts/frame) must match full single-call triangulation
    //    across ALL 3 RibbonRepeatModes (Repeat, Reverse, Once)!
    for mode in [
        RibbonRepeatMode::Repeat,
        RibbonRepeatMode::Reverse,
        RibbonRepeatMode::Once,
    ] {
        let brush = NativeBrushConfig {
            fg_color: [0.2, 0.35, 0.85],
            bg_color: [0.9, 0.7, 0.2],
            size: 32.0,
            opacity: 0.9,
            flow: 1.0,
            is_ribbon: true,
            ribbon_repeat_mode: mode,
            sub_tip_order: CspSubTipOrder::Sequential,
            flip_h: CspTipFlipMode::Alternate,
            flip_v: CspTipFlipMode::None,
            ..NativeBrushConfig::default()
        };

        let mut full_builder = RibbonMeshBuilder::new(64, 64, 3, 424242);
        let mut full_verts = Vec::new();
        full_builder.push_points(&pts, &brush, &mut full_verts);
        full_builder.finish(&brush, &mut full_verts);

        let mut inc_builder = RibbonMeshBuilder::new(64, 64, 3, 424242);
        let mut inc_verts = Vec::new();
        for chunk in pts.chunks(3) {
            inc_builder.push_points(chunk, &brush, &mut inc_verts);
        }
        inc_builder.finish(&brush, &mut inc_verts);

        assert_eq!(
            inc_verts.len(),
            full_verts.len(),
            "[{mode:?}] Incremental ribbon vertex count must match full triangulation!"
        );
        for (idx, (iv, fv)) in inc_verts.iter().zip(full_verts.iter()).enumerate() {
            assert!(
                (iv.doc_pos[0] - fv.doc_pos[0]).abs() < 1e-3
                    && (iv.doc_pos[1] - fv.doc_pos[1]).abs() < 1e-3
                    && (iv.uv[0] - fv.uv[0]).abs() < 1e-3
                    && (iv.uv[1] - fv.uv[1]).abs() < 1e-3
                    && (iv.fg_alpha[3] - fv.fg_alpha[3]).abs() < 1e-3
                    && (iv.sub_bg[0] - fv.sub_bg[0]).abs() < 1e-3,
                "[{mode:?}] Vertex {idx} mismatch! inc={iv:?}, full={fv:?}"
            );
        }
    }

    // 2. GPU check: RIBBON_MESH_WGSL paper mode Normal (7) + scaled brightness/contrast (-100..100)
    //    must NOT blow out contrast to pure binary black/white, and must differ cleanly from 0 contrast!
    let Some(mut renderer) = make_headless_renderer(256, 256, 768, 256) else {
        return;
    };
    let line_pts = make_line_points(40.0, 128.0, 700.0, 128.0, 36, 48.0, 1.0);

    let render_ribbon_strip = |renderer: &mut GpuRenderer,
                               doc_id: &str,
                               contrast: f32,
                               brightness: f32|
     -> (Vec<u8>, usize, usize) {
        let brush = NativeBrushConfig {
            fg_color: [0.15, 0.25, 0.75],
            size: 48.0,
            opacity: 1.0,
            flow: 1.0,
            is_ribbon: true,
            ribbon_repeat_mode: RibbonRepeatMode::Repeat,
            surface_texture_id: Some("rough-cold-press".to_string()),
            grain: 0.75,
            paper_texture_apply_each_plot: true,
            paper_texture_mode: CspPaperTextureMode::Normal,
            paper_texture_contrast: contrast,
            paper_texture_brightness: brightness,
            ..NativeBrushConfig::default()
        };
        let mut doc = make_doc(doc_id, 768, 256);
        let lid = doc.layers[0].meta.id.clone();
        let _ = renderer.sync_document(&mut doc, None);
        let mut rb = RibbonMeshBuilder::new(64, 64, 1, 5555);
        let mut verts = Vec::new();
        rb.push_points(&line_pts, &brush, &mut verts);
        rb.finish(&brush, &mut verts);
        renderer.begin_gpu_stroke(768, 256, false, brush, [0.0, 0.0]);
        let _ = renderer.stamp_gpu_ribbon_vertices(&verts, &[], false);
        let binned = renderer.brush_engine().ribbon_pipeline.last_batch_binned_indices;
        let unbinned = renderer.brush_engine().ribbon_pipeline.last_batch_unbinned_indices;
        let grid = doc.layer(&lid).unwrap().grid.clone();
        let batch = renderer
            .commit_gpu_stroke_to_layer(&doc.id, &lid, &grid, None, false, false)
            .expect("commit ribbon");
        let es = HashMap::new();
        let _ = doc
            .layer_mut(&lid)
            .unwrap()
            .grid
            .apply_gpu_committed_tiles(&lid, batch.tiles, &es, 128);
        renderer.clear_live_stroke();
        let layer = doc.layer(&lid).unwrap();
        let mut alphas = Vec::with_capacity(600 * 30);
        for y in 113..143 {
            for x in 60..660 {
                alphas.push(layer.grid.get_pixel_rgba8(x, y, None)[3]);
            }
        }
        (alphas, binned, unbinned)
    };

    let (a_base, binned_idx, unbinned_idx) =
        render_ribbon_strip(&mut renderer, "p5-rib-contrast-0", 0.0, 0.0);
    let (a_mod, _, _) = render_ribbon_strip(&mut renderer, "p5-rib-contrast-25", 25.0, 10.0);

    // Per-tile triangle binning must dramatically reduce drawn indices across 3 tiles!
    assert!(
        binned_idx > 0 && binned_idx < unbinned_idx / 2,
        "Ribbon per-tile triangle binning must draw < 50% of unbinned indices! binned={binned_idx}, unbinned={unbinned_idx}"
    );
    // Mid-tone alpha values must survive (not blown out to 0 or 255 by unscaled contrast!)
    let mid_tones = a_mod.iter().filter(|&&a| a > 30 && a < 245).count();
    assert!(
        mid_tones > 1000,
        "RIBBON_MESH_WGSL Normal mode + contrast=25, brightness=10 must preserve rich mid-tone paper grain instead of blowing out to pure 0/255! mid_tones={mid_tones}"
    );
    let mean_diff: f64 = a_base
        .iter()
        .zip(a_mod.iter())
        .map(|(&x, &y)| x.abs_diff(y) as f64)
        .sum::<f64>()
        / a_base.len() as f64;
    assert!(
        mean_diff > 1.0 && mean_diff < 60.0,
        "Scaled brightness/contrast (+10/+25) must gently shift paper grain without clipping! mean_diff={mean_diff:.2}"
    );
}

#[test]
fn test_p5_natural_paint_gpu_rgba8_pack_matches_cpu_dithered() {
    let _dx12_guard = crate::lock_dx12_test();
    use crate::natural_paint::NaturalPaintTilePools;
    use crate::tiles::format::rgba16f_to_rgba8_dithered;
    use crate::tiles::{TileCoord, BYTES_16F, BYTES_32BIT, TILE_SIZE};

    let Some(renderer) = make_headless_renderer(256, 256, 256, 256) else {
        return;
    };

    // Build a deterministic 256×256 Rgba16Float tile covering exact 0.0, exact 1.0, and smooth fractional gradients
    let mut raw_16f = vec![0u8; BYTES_16F];
    for y in 0..TILE_SIZE {
        for x in 0..TILE_SIZE {
            let (r, g, b, a) = if y == 0 {
                (0.0f32, 0.0f32, 0.0f32, 0.0f32)
            } else if y == 1 {
                (1.0f32, 1.0f32, 1.0f32, 1.0f32)
            } else {
                (
                    x as f32 / 255.0,
                    y as f32 / 255.0,
                    ((x + y) as f32 / 510.0) * 0.85 + 0.05,
                    ((x * 3 + y * 5) % 256) as f32 / 255.0,
                )
            };
            let off = (y * TILE_SIZE + x) * 8;
            raw_16f[off..off + 2].copy_from_slice(&half::f16::from_f32(r).to_bits().to_le_bytes());
            raw_16f[off + 2..off + 4]
                .copy_from_slice(&half::f16::from_f32(g).to_bits().to_le_bytes());
            raw_16f[off + 4..off + 6]
                .copy_from_slice(&half::f16::from_f32(b).to_bits().to_le_bytes());
            raw_16f[off + 6..off + 8]
                .copy_from_slice(&half::f16::from_f32(a).to_bits().to_le_bytes());
        }
    }

    // CPU reference Bayer-dithered RGBA8
    let mut cpu_rgba8 = vec![0u8; BYTES_32BIT];
    rgba16f_to_rgba8_dithered(&raw_16f, &mut cpu_rgba8);

    // Upload raw_16f directly to NaturalPaintTilePools slot 0 and commit via GPU Bayer-dithered pack
    let mut pools = NaturalPaintTilePools::new(renderer.device(), 32);
    let coord = TileCoord::new(0, 0);
    pools.coord_to_slot.insert(coord, 0);
    renderer.queue().write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &pools.color_tex,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        &raw_16f,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some((TILE_SIZE * 8) as u32),
            rows_per_image: Some(TILE_SIZE as u32),
        },
        wgpu::Extent3d {
            width: TILE_SIZE as u32,
            height: TILE_SIZE as u32,
            depth_or_array_layers: 1,
        },
    );

    let mut tile_pool = crate::memory::GpuTilePool::new(renderer.device(), 32);
    let batch = pools
        .commit_to_layer_pool(
            renderer.device(),
            renderer.queue(),
            &mut tile_pool,
            "pack-doc",
            "pack-layer",
        )
        .expect("GPU Bayer-dithered RGBA8 commit");

    assert_eq!(batch.color_tiles.len(), 1);
    let (out_coord, gpu_rgba8, out_ver) = &batch.color_tiles[0];
    assert_eq!(*out_coord, coord);
    assert_eq!(gpu_rgba8.len(), BYTES_32BIT);

    // Verify committed tile is immediately resident in GpuTilePool!
    let resident_key = tile_pool.make_key("pack-doc", "pack-layer", 0, coord);
    assert!(
        tile_pool.get_slot_if_version(&resident_key, *out_ver).is_some(),
        "Committed tile must be immediately resident in GpuTilePool at pen-up!"
    );

    // Exact 0.0 -> 0 and 1.0 -> 255 endpoints
    for x in 0..TILE_SIZE {
        let off0 = x * 4;
        assert_eq!(&gpu_rgba8[off0..off0 + 4], &[0, 0, 0, 0], "Exact 0.0 endpoint must stay 0");
        let off1 = (TILE_SIZE + x) * 4;
        assert_eq!(
            &gpu_rgba8[off1..off1 + 4],
            &[255, 255, 255, 255],
            "Exact 1.0 endpoint must stay 255"
        );
    }

    // Compare all 262,144 channels against CPU Bayer-dithered reference
    let mut max_diff = 0u8;
    let mut sum_diff = 0u64;
    for (&g, &c) in gpu_rgba8.iter().zip(cpu_rgba8.iter()) {
        let d = g.abs_diff(c);
        max_diff = max_diff.max(d);
        sum_diff += d as u64;
    }
    let mean_diff = sum_diff as f64 / BYTES_32BIT as f64;
    assert!(
        max_diff <= 1 && mean_diff < 0.05,
        "GPU Bayer-dithered RGBA8 pack must match CPU rgba16f_to_rgba8_dithered! max_diff={max_diff}, mean_diff={mean_diff:.5}"
    );
}

#[test]
#[ignore]
fn test_p5_visual_natural_paint_verification() {
    let _dx12_guard = crate::lock_dx12_test();
    let out_dir = std::path::PathBuf::from(
        r"C:\Users\sora\.gemini\antigravity\brain\d8d4cafd-4d41-415e-8dcd-c9ac7ae877bf\scratch\renders",
    );
    let _ = std::fs::create_dir_all(&out_dir);

    let save_doc = |renderer: &mut GpuRenderer, doc: &Document, name: &str| {
        let opts = FlattenOptions {
            fill_white_background: true,
            show_checkerboard: false,
            ..Default::default()
        };
        let (w, h, rgba) = renderer
            .render_document_flattened(doc, None, &opts)
            .expect("flatten visual doc");
        let png = crate::io::png_codec::encode_rgba8_to_png(w, h, &rgba).expect("encode png");
        std::fs::write(out_dir.join(name), png).expect("write png");
    };

    let make_curve_pts = |x0: f64, y0: f64, x1: f64, y1: f64, amp: f64, n: usize, w: f32, p0: f32, p1: f32| {
        let mut pts = Vec::with_capacity(n);
        for i in 0..n {
            let t = i as f64 / (n - 1).max(1) as f64;
            let x = x0 + (x1 - x0) * t;
            let y = y0 + (y1 - y0) * t + (t * std::f64::consts::PI).sin() * amp;
            let pressure = (p0 + (p1 - p0) * t as f32) * (0.45 + 0.55 * (t * std::f64::consts::PI).sin() as f32).clamp(0.35, 1.0);
            pts.push(StrokePoint {
                x,
                y,
                pressure: pressure.clamp(0.12, 1.0),
                width: w,
                tilt_x: 0.0,
                tilt_y: 0.0,
                twist: 0.0,
                velocity: 0.4,
                timestamp_ms: i as f64 * 4.0,
                is_corner: false,
            });
        }
        pts
    };

    // Scene 1: Deep Prussian Blue overlapping strokes (Ref Image 1)
    {
        let Some(mut renderer) = make_headless_renderer(768, 512, 768, 512) else {
            return;
        };
        let mut doc = make_doc("vis-blue", 768, 512);
        let lid = doc.layers[0].meta.id.clone();
        let prussian = [0.04, 0.20, 0.42];
        let mut oil = make_oil_impasto_brush(prussian, 64.0);
        oil.bristle = Some(BristleSettings {
            profile: BristleProfilePreset::Filbert,
            count: 24,
            clumping: 0.56,
            stiffness: 0.64,
            length: 1.0,
            splay: 0.34,
            irregularity: 0.44,
            edge_ridge: 0.32,
        });
        oil.impasto = Some(ImpastoSettings {
            enabled: true,
            depth: 0.86,
            bristle_relief: 0.90,
            gloss: 0.50,
            relief_contrast: 0.72,
            light_azimuth: 225.0,
            light_elevation: 32.0,
        });
        oil.surface_texture_id = Some("linen-canvas".to_string());
        oil.grain = 0.46;
        oil.texture_density = 0.46;
        oil.paper_texture_scale = 0.85;
        oil.paper_texture_contrast = 24.0;
        oil.natural_paint.as_mut().unwrap().dry_brush = 0.32;

        for (k, (y0, y1, amp)) in [
            (160.0, 90.0, -30.0),
            (230.0, 140.0, -20.0),
            (310.0, 200.0, -15.0),
            (380.0, 260.0, 10.0),
            (430.0, 320.0, 20.0),
        ]
        .iter()
        .enumerate()
        {
            let pts = make_curve_pts(80.0 + k as f64 * 25.0, *y0, 620.0 + k as f64 * 12.0, *y1, *amp, 40, 64.0, 0.88, 0.82);
            run_natural_paint_stroke(&mut renderer, &mut doc, &lid, oil.clone(), &pts, 100 + k as u32);
        }
        save_doc(&mut renderer, &doc, "scene1_blue_strokes.png");
    }

    // Scene 2: Red & Blue parallel bars (Ref Image 2)
    {
        let Some(mut renderer) = make_headless_renderer(768, 512, 768, 512) else {
            return;
        };
        let mut doc = make_doc("vis-redblue", 768, 512);
        let lid = doc.layers[0].meta.id.clone();

        let make_flat = |fg: [f32; 3]| {
            let mut b = make_oil_impasto_brush(fg, 92.0);
            b.bristle = Some(BristleSettings {
                profile: BristleProfilePreset::Flat,
                count: 38,
                clumping: 0.44,
                stiffness: 0.72,
                length: 0.95,
                splay: 0.30,
                irregularity: 0.36,
                edge_ridge: 0.42,
            });
            b.impasto = Some(ImpastoSettings {
                enabled: true,
                depth: 0.84,
                bristle_relief: 0.86,
                gloss: 0.48,
                relief_contrast: 0.74,
                light_azimuth: 225.0,
                light_elevation: 32.0,
            });
            b.surface_texture_id = Some("linen-canvas".to_string());
            b.grain = 0.42;
            b.texture_density = 0.42;
            b.paper_texture_scale = 0.85;
            b.paper_texture_contrast = 24.0;
            b
        };
        let red_b = make_flat([0.92, 0.08, 0.06]);
        let blue_b = make_flat([0.04, 0.36, 0.84]);
        let p_red1 = make_line_points(90.0, 140.0, 720.0, 140.0, 48, 92.0, 0.92);
        let p_red2 = make_line_points(95.0, 200.0, 720.0, 200.0, 48, 92.0, 0.92);
        let p_blu1 = make_line_points(90.0, 290.0, 720.0, 290.0, 48, 92.0, 0.92);
        let p_blu2 = make_line_points(95.0, 355.0, 720.0, 355.0, 48, 92.0, 0.92);
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, red_b.clone(), &p_red1, 201);
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, red_b, &p_red2, 202);
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, blue_b.clone(), &p_blu1, 203);
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, blue_b, &p_blu2, 204);
        save_doc(&mut renderer, &doc, "scene2_red_blue_bars.png");
    }

    // Scene 3: Circular Blue Impasto + Yellow Mixing Over Wet Blue (Ref Images 3 & 4)
    {
        let Some(mut renderer) = make_headless_renderer(768, 768, 768, 768) else {
            return;
        };
        let mut doc = make_doc("vis-circle-mix", 768, 768);
        let lid = doc.layers[0].meta.id.clone();

        let mut blue_oil = make_oil_impasto_brush([0.04, 0.24, 0.56], 82.0);
        blue_oil.impasto = Some(ImpastoSettings {
            enabled: true,
            depth: 0.86,
            bristle_relief: 0.90,
            gloss: 0.52,
            relief_contrast: 0.74,
            light_azimuth: 225.0,
            light_elevation: 32.0,
        });
        blue_oil.surface_texture_id = Some("linen-canvas".to_string());
        blue_oil.grain = 0.44;
        blue_oil.texture_density = 0.44;
        blue_oil.paper_texture_scale = 0.85;
        blue_oil.paper_texture_contrast = 24.0;

        // Spiral circle of deep blue oil
        let mut circle_pts = Vec::new();
        for i in 0..140 {
            let t = i as f64 / 139.0;
            let ang = t * std::f64::consts::TAU * 2.2;
            let rad = 220.0 - t * 110.0;
            circle_pts.push(StrokePoint {
                x: 384.0 + ang.cos() * rad,
                y: 384.0 + ang.sin() * rad,
                pressure: 0.90,
                width: 82.0,
                tilt_x: 0.0,
                tilt_y: 0.0,
                twist: 0.0,
                velocity: 0.4,
                timestamp_ms: i as f64 * 4.0,
                is_corner: false,
            });
        }
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, blue_oil, &circle_pts, 301);

        // Now paint bright Yellow over wet Blue with Creamy Oil Filbert (yellow + blue -> vivid green streaks!)
        let mut yellow_filbert = make_wet_filbert_brush([1.0, 0.92, 0.04], 84.0);
        yellow_filbert.amount_of_paint = 0.72;
        yellow_filbert.color_stretch = 0.85;
        yellow_filbert.natural_paint.as_mut().unwrap().paint_load = 0.72;
        yellow_filbert.natural_paint.as_mut().unwrap().wetness = 0.82;
        yellow_filbert.natural_paint.as_mut().unwrap().pigment_mixing_strength = 0.95;
        yellow_filbert.impasto = Some(ImpastoSettings {
            enabled: true,
            depth: 0.76,
            bristle_relief: 0.82,
            gloss: 0.54,
            relief_contrast: 0.68,
            light_azimuth: 225.0,
            light_elevation: 32.0,
        });
        yellow_filbert.surface_texture_id = Some("linen-canvas".to_string());
        yellow_filbert.grain = 0.36;
        yellow_filbert.texture_density = 0.36;
        yellow_filbert.paper_texture_scale = 0.85;

        let mut yellow_pts = Vec::new();
        for i in 0..80 {
            let t = i as f64 / 79.0;
            let x = 150.0 + t * 440.0 + (t * std::f64::consts::TAU).sin() * 25.0;
            let y = 480.0 - t * 230.0 + (t * std::f64::consts::TAU * 1.5).cos() * 28.0;
            yellow_pts.push(StrokePoint {
                x,
                y,
                pressure: 0.88,
                width: 84.0,
                tilt_x: 0.0,
                tilt_y: 0.0,
                twist: 0.0,
                velocity: 0.4,
                timestamp_ms: i as f64 * 4.0,
                is_corner: false,
            });
        }
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, yellow_filbert, &yellow_pts, 302);
        save_doc(&mut renderer, &doc, "scene3_circle_and_yellow_mix.png");
    }

    // Scene 4: Showcase of distinct Natural Paint brushes (Rake, Knife, Gouache, Watercolor, Fan, Pastel, Blender)
    {
        let Some(mut renderer) = make_headless_renderer(1024, 1024, 1024, 1024) else {
            return;
        };
        let mut doc = make_doc("vis-showcase", 1024, 1024);
        let lid = doc.layers[0].meta.id.clone();

        // Vertical blue wet paint strip on right side (x=660..840) to test mixing/blending on every brush!
        let mut base_blue = make_oil_impasto_brush([0.08, 0.28, 0.72], 90.0);
        base_blue.impasto.as_mut().unwrap().depth = 0.70;
        let strip_pts = make_line_points(740.0, 50.0, 740.0, 970.0, 64, 90.0, 0.90);
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, base_blue, &strip_pts, 400);

        // 1. Impasto Bristle Oil (Crimson)
        let mut b1 = make_oil_impasto_brush([0.85, 0.14, 0.16], 56.0);
        b1.grain = 0.46;
        b1.texture_density = 0.46;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b1, &make_line_points(70.0, 100.0, 920.0, 100.0, 50, 56.0, 0.88), 401);

        // 2. Dry Bristle Rake (Prussian Blue)
        let mut b2 = make_oil_impasto_brush([0.06, 0.24, 0.52], 56.0);
        b2.bristle.as_mut().unwrap().profile = BristleProfilePreset::Rake;
        b2.bristle.as_mut().unwrap().count = 34;
        b2.bristle.as_mut().unwrap().clumping = 0.58;
        b2.bristle.as_mut().unwrap().irregularity = 0.52;
        b2.natural_paint.as_mut().unwrap().dry_brush = 0.38;
        b2.grain = 0.38;
        b2.texture_density = 0.38;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b2, &make_line_points(70.0, 220.0, 920.0, 220.0, 50, 56.0, 0.85), 402);

        // 3. Palette Knife (Warm Ochre Yellow)
        let mut b3 = make_oil_impasto_brush([0.96, 0.76, 0.12], 62.0);
        b3.bristle = Some(BristleSettings {
            profile: BristleProfilePreset::Knife,
            count: 16,
            clumping: 0.05,
            stiffness: 0.96,
            length: 0.65,
            splay: 0.15,
            irregularity: 0.18,
            edge_ridge: 0.92,
        });
        b3.impasto = Some(ImpastoSettings {
            enabled: true,
            depth: 0.92,
            bristle_relief: 0.32,
            gloss: 0.68,
            relief_contrast: 0.82,
            light_azimuth: 225.0,
            light_elevation: 30.0,
        });
        b3.surface_texture_id = Some("coarse-burlap".to_string());
        b3.grain = 0.44;
        b3.texture_density = 0.44;
        b3.natural_paint.as_mut().unwrap().dry_brush = 0.44;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b3, &make_line_points(70.0, 350.0, 920.0, 350.0, 50, 62.0, 0.92), 403);

        // 4. Splayed Bristle Fan (Forest Green)
        let mut b4 = make_oil_impasto_brush([0.14, 0.54, 0.24], 66.0);
        b4.bristle = Some(BristleSettings {
            profile: BristleProfilePreset::Fan,
            count: 36,
            clumping: 0.64,
            stiffness: 0.78,
            length: 1.25,
            splay: 0.56,
            irregularity: 0.58,
            edge_ridge: 0.16,
        });
        b4.surface_texture_id = Some("coarse-burlap".to_string());
        b4.grain = 0.46;
        b4.texture_density = 0.46;
        b4.natural_paint.as_mut().unwrap().dry_brush = 0.48;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b4, &make_line_points(70.0, 480.0, 920.0, 480.0, 50, 66.0, 0.86), 404);

        // 5. Soft Oil Pastel (Coral Orange)
        let mut b5 = make_oil_impasto_brush([0.94, 0.42, 0.18], 46.0);
        b5.render_mode = BrushRenderMode::BristleHybrid;
        b5.bristle.as_mut().unwrap().profile = BristleProfilePreset::Flat;
        b5.surface_texture_id = Some("rough-pastel".to_string());
        b5.grain = 0.78;
        b5.texture_density = 0.78;
        b5.paper_texture_contrast = 36.0;
        b5.natural_paint.as_mut().unwrap().dry_brush = 0.66;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b5, &make_line_points(70.0, 610.0, 920.0, 610.0, 50, 46.0, 0.72), 405);

        // 6. Dry Bristle Blender (Smearing right across the blue strip!)
        let mut b6 = make_oil_impasto_brush([1.0, 1.0, 1.0], 62.0);
        b6.bristle.as_mut().unwrap().profile = BristleProfilePreset::Fan;
        b6.mixing_mode = NaturalMixingMode::Smear;
        b6.amount_of_paint = 0.0;
        b6.color_stretch = 0.85;
        b6.natural_paint.as_mut().unwrap().paint_load = 0.0;
        b6.natural_paint.as_mut().unwrap().depletion_rate = 0.0;
        b6.natural_paint.as_mut().unwrap().wetness = 0.92;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b6, &make_line_points(680.0, 740.0, 960.0, 740.0, 40, 62.0, 0.88), 406);

        // 7. Granulating Watercolor (Turquoise on separate layer so no impasto lighting)
        let mut b7 = make_wet_filbert_brush([0.08, 0.56, 0.74], 54.0);
        b7.bristle.as_mut().unwrap().profile = BristleProfilePreset::Round;
        b7.flow = 0.58;
        b7.opacity = 0.72;
        b7.density_of_paint = 0.65;
        b7.wet_edge = 0.58;
        b7.wet_edge_radius = 3.0;
        b7.impasto = None;
        b7.surface_texture_id = Some("cold-press-watercolor".to_string());
        b7.grain = 0.56;
        b7.texture_density = 0.56;
        b7.natural_paint.as_mut().unwrap().granulation = 0.76;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b7, &make_line_points(70.0, 880.0, 640.0, 880.0, 50, 54.0, 0.82), 407);

        // Keep strong impasto light on showcase layer
        doc.layer_mut(&lid).unwrap().meta.impasto_light = Some(ImpastoLayerLight {
            enabled: true,
            depth: 0.82,
            gloss: 0.50,
            relief_contrast: 0.72,
            light_azimuth: 225.0,
            light_elevation: 32.0,
        });
        save_doc(&mut renderer, &doc, "scene4_showcase.png");
    }

    // Scene 5: Aqueous & Matte Natural Paint brushes (Watercolor, Sumi Ink, Velvet Gouache, Matte Casein, Heavy Body Acrylic, Wide Hog Flat)
    {
        let Some(mut renderer) = make_headless_renderer(1024, 1024, 1024, 1024) else {
            return;
        };
        let mut doc = make_doc("vis-matte-water", 1024, 1024);
        let lid = doc.layers[0].meta.id.clone();

        // 1. Granulating Watercolor (Cerulean Blue + overlapping Magenta wash -> granulation + wet edge + purple mix!)
        let mut wc1 = make_wet_filbert_brush([0.08, 0.46, 0.78], 62.0);
        wc1.bristle = Some(BristleSettings {
            profile: BristleProfilePreset::Round,
            count: 28,
            clumping: 0.14,
            stiffness: 0.32,
            length: 1.35,
            splay: 0.52,
            irregularity: 0.22,
            edge_ridge: 0.05,
        });
        wc1.flow = 0.58;
        wc1.opacity = 0.72;
        wc1.density_of_paint = 0.65;
        wc1.wet_edge = 0.58;
        wc1.wet_edge_radius = 3.0;
        wc1.impasto = None;
        wc1.surface_texture_id = Some("cold-press-watercolor".to_string());
        wc1.grain = 0.56;
        wc1.texture_density = 0.56;
        wc1.natural_paint.as_mut().unwrap().dry_brush = 0.14;
        wc1.natural_paint.as_mut().unwrap().granulation = 0.76;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, wc1.clone(), &make_line_points(80.0, 120.0, 920.0, 120.0, 48, 62.0, 0.78), 501);
        wc1.fg_color = [0.82, 0.18, 0.48];
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, wc1, &make_line_points(280.0, 80.0, 740.0, 180.0, 40, 56.0, 0.72), 502);

        // 2. Sumi Ink Wash (Deep Carbon Sumi with dry flying-white tail!)
        let mut sumi = make_wet_filbert_brush([0.06, 0.07, 0.09], 56.0);
        sumi.bristle = Some(BristleSettings {
            profile: BristleProfilePreset::Round,
            count: 26,
            clumping: 0.32,
            stiffness: 0.42,
            length: 1.4,
            splay: 0.48,
            irregularity: 0.36,
            edge_ridge: 0.08,
        });
        sumi.flow = 0.82;
        sumi.opacity = 0.90;
        sumi.density_of_paint = 0.86;
        sumi.wet_edge = 0.48;
        sumi.wet_edge_radius = 2.5;
        sumi.impasto = None;
        sumi.surface_texture_id = Some("cold-press-watercolor".to_string());
        sumi.grain = 0.50;
        sumi.texture_density = 0.50;
        sumi.natural_paint.as_mut().unwrap().depletion_rate = 0.38;
        sumi.natural_paint.as_mut().unwrap().dry_brush = 0.42;
        sumi.natural_paint.as_mut().unwrap().granulation = 0.58;
        let sumi_pts: Vec<StrokePoint> = (0..56).map(|i| {
            let t = i as f32 / 55.0;
            StrokePoint {
                x: (80.0 + t * 860.0) as f64,
                y: (310.0 + (t * 4.5).sin() * 22.0) as f64,
                pressure: (0.95 - t * 0.55).max(0.25),
                width: 56.0,
                tilt_x: 0.0,
                tilt_y: 0.0,
                twist: 0.0,
                velocity: 0.5,
                timestamp_ms: i as f64 * 4.0,
                is_corner: false,
            }
        }).collect();
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, sumi, &sumi_pts, 503);

        // 3. Velvet Gouache (Rich Opaque Matte Terracotta + Cream overlap)
        let mut gouache = make_wet_filbert_brush([0.78, 0.32, 0.20], 54.0);
        gouache.bristle = Some(BristleSettings {
            profile: BristleProfilePreset::Filbert,
            count: 34,
            clumping: 0.18,
            stiffness: 0.48,
            length: 1.05,
            splay: 0.32,
            irregularity: 0.20,
            edge_ridge: 0.08,
        });
        gouache.amount_of_paint = 0.88;
        gouache.density_of_paint = 0.96;
        gouache.impasto = None;
        gouache.surface_texture_id = Some("gesso-board".to_string());
        gouache.grain = 0.28;
        gouache.texture_density = 0.28;
        gouache.natural_paint.as_mut().unwrap().paint_load = 0.88;
        gouache.natural_paint.as_mut().unwrap().dry_brush = 0.18;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, gouache.clone(), &make_line_points(80.0, 500.0, 920.0, 500.0, 48, 54.0, 0.88), 504);
        gouache.fg_color = [0.95, 0.88, 0.72];
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, gouache, &make_line_points(260.0, 465.0, 720.0, 535.0, 40, 46.0, 0.80), 505);

        // 4. Matte Casein & Tempera (Deep Emerald + Gold Ochre)
        let mut casein = make_wet_filbert_brush([0.12, 0.42, 0.32], 54.0);
        casein.render_mode = BrushRenderMode::BristleHybrid;
        casein.amount_of_paint = 0.86;
        casein.density_of_paint = 0.96;
        casein.impasto = None;
        casein.surface_texture_id = Some("gesso-board".to_string());
        casein.grain = 0.36;
        casein.texture_density = 0.36;
        casein.natural_paint.as_mut().unwrap().paint_load = 0.86;
        casein.natural_paint.as_mut().unwrap().dry_brush = 0.36;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, casein, &make_line_points(80.0, 690.0, 920.0, 690.0, 48, 54.0, 0.85), 506);

        // 5. Heavy Body Acrylic (Cobalt Blue on separate subtle satin impasto layer? Draw flat + Wide Hog Flat below)
        let mut acrylic = make_oil_impasto_brush([0.16, 0.34, 0.82], 58.0);
        acrylic.bristle = Some(BristleSettings {
            profile: BristleProfilePreset::Flat,
            count: 30,
            clumping: 0.38,
            stiffness: 0.76,
            length: 0.90,
            splay: 0.25,
            irregularity: 0.30,
            edge_ridge: 0.28,
        });
        acrylic.impasto = None;
        acrylic.surface_texture_id = Some("fine-cotton".to_string());
        acrylic.grain = 0.32;
        acrylic.texture_density = 0.32;
        run_natural_paint_stroke(&mut renderer, &mut doc, &lid, acrylic, &make_line_points(80.0, 860.0, 920.0, 860.0, 48, 58.0, 0.88), 507);

        // Keep layer matte (no impasto light) so Watercolor, Sumi, Gouache, Casein show true matte/water look
        doc.layer_mut(&lid).unwrap().meta.impasto_light = None;
        save_doc(&mut renderer, &doc, "scene5_matte_and_water.png");
    }
}