Skip to content

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

150 KB
Raw Blame
//! Dedicated high-priority engine/render thread with wake-on-input scheduling,
//! zero-IPC ring buffer ingestion, native camera navigation, Phase 4 native stroke &
//! GPU instanced brush engine, sub-millisecond tile commits, and throttled event emission.

use crate::brush::{GpuBrushDab, NativeBrushConfig, RibbonRepeatMode, StrokeDabEmitter};
use crate::camera::{clamp_zoom, viewport_css_to_doc, NativeCameraNavigator};
use crate::clock;
use crate::compositor::{
    calculate_visible_doc_bounds, CompositorDisplayConfig, DocBounds, FlattenOptions,
};
use crate::document::{DocumentManager, ExpressionColor};
use crate::gpu::{GpuRenderer, RenderOutcome};
use crate::hit_test::SharedHitTest;
use crate::memory::{
    GpuPoolStats, InMemoryScratchBackend, MemoryBudgetConfig, ScratchBackend, ViewportFrustum,
};
use crate::natural_paint::{
    BristleRibbonSimulator, GpuBristleCapsule, RibbonMeshBuilder, RibbonVertex,
};
use crate::ring::{create_input_rings, InputConsumers, InputProducers, WakeSignal};
use crate::stroke::{
    polyline_to_bezier_segments, CommittedStrokePoint, CompiledCurveLut, CubicBezierSegment,
    DabInstance, GlobalPressureCurve, NativeStrokePipeline, PerspectiveRulerConfig,
    StraightRulerConfig, StrokeDabGenerator, StrokePipelineConfig, StrokePoint,
};
use crate::tiles::{RectI32, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKind, TILE_SIZE};
use crate::types::{
    BrushParams, CameraState, CursorConfig, EngineCommand, EngineDiagnostics, EngineEvent,
    InteractionPolicy, NativeInputSample, NativeNavEvent, SurfaceTarget, ThumbnailUpdate,
    ViewportRect, WheelNavMode,
};
use crossbeam_channel::{Receiver, Sender};
use parking_lot::RwLock;
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::Duration;

/// Initial configuration when spawning an `ink-engine` instance.
pub struct EngineConfig {
    pub doc_width: u32,
    pub doc_height: u32,
    pub show_checkerboard: bool,
    pub matte_color: [f32; 4],
    pub memory_budget: MemoryBudgetConfig,
    pub scratch_backend: Option<Arc<dyn ScratchBackend>>,
}

impl Default for EngineConfig {
    fn default() -> Self {
        Self {
            doc_width: 1920,
            doc_height: 1080,
            show_checkerboard: true,
            matte_color: [0.086, 0.086, 0.086, 1.0], // #161616 default Graphite Atelier matte
            memory_budget: MemoryBudgetConfig::default(),
            scratch_backend: None,
        }
    }
}

/// Lock-free performance & regression telemetry counters exposed on [`EngineHandle`].
#[derive(Debug, Default)]
pub struct EnginePerfCounters {
    /// Total batched GPU brush stamp dispatches (`stamp_gpu_stroke_dabs`, ribbon, natural paint, color mixing).
    pub stamp_dispatches: AtomicU64,
    /// Number of synchronous CPU PNG thumbnails encoded on the DX12 render thread during pen-up (target: 0).
    pub sync_render_thread_thumbnails: AtomicU64,
    /// Number of asynchronous thumbnails finished by the background thumbnail worker thread.
    pub async_thumbnails_completed: AtomicU64,
}

/// Snapshot of [`EnginePerfCounters`] for diagnostics and headless regression benchmarks.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EnginePerfSnapshot {
    pub stamp_dispatches: u64,
    pub sync_render_thread_thumbnails: u64,
    pub async_thumbnails_completed: u64,
}

/// Thread-safe handle to a running `ink-engine` instance.
///
/// The host sends control commands via [`send_command`], shares [`hit_test`] directly with
/// native input hooks, mutates documents via [`documents`], and consumes throttled
/// [`EngineEvent`]s via [`events`].
pub struct EngineHandle {
    cmd_tx: Sender<EngineCommand>,
    event_rx: Receiver<EngineEvent>,
    wake: Arc<WakeSignal>,
    hit_test: SharedHitTest,
    documents: Arc<RwLock<DocumentManager>>,
    retouch_session: Arc<Mutex<crate::tools::RetouchSession>>,
    gpu_pool_stats: Arc<RwLock<GpuPoolStats>>,
    diagnostics: Arc<Mutex<EngineDiagnostics>>,
    perf_counters: Arc<EnginePerfCounters>,
    stroke_active: Arc<AtomicBool>,
    running: Arc<AtomicBool>,
    thread: Mutex<Option<JoinHandle<()>>>,
}

impl EngineHandle {
    /// Spawns the dedicated DX12 engine thread and returns `(EngineHandle, InputProducers)`.
    pub fn spawn(
        target: SurfaceTarget,
        mut config: EngineConfig,
    ) -> Result<(Self, InputProducers), String> {
        let wake = WakeSignal::new();
        let (producers, consumers) = create_input_rings(&wake);
        let (cmd_tx, cmd_rx) = crossbeam_channel::unbounded::<EngineCommand>();
        let (event_tx, event_rx) = crossbeam_channel::bounded::<EngineEvent>(512);
        let hit_test = SharedHitTest::new();
        let scratch: Arc<dyn ScratchBackend> = config
            .scratch_backend
            .take()
            .unwrap_or_else(|| Arc::new(InMemoryScratchBackend::new()));
        let vram_budget = config.memory_budget.vram_budget_bytes;
        let documents = Arc::new(RwLock::new(DocumentManager::new(
            config.memory_budget,
            scratch,
        )));
        let gpu_pool_stats = Arc::new(RwLock::new(GpuPoolStats::default()));
        let diagnostics = Arc::new(Mutex::new(EngineDiagnostics {
            doc_width: config.doc_width,
            doc_height: config.doc_height,
            gpu_vram_budget_bytes: vram_budget,
            ..Default::default()
        }));
        let perf_counters = Arc::new(EnginePerfCounters::default());
        let stroke_active = Arc::new(AtomicBool::new(false));
        let running = Arc::new(AtomicBool::new(true));

        let (init_tx, init_rx) = crossbeam_channel::bounded::<Result<EngineDiagnostics, String>>(1);

        let wake_thread = Arc::clone(&wake);
        let hit_test_thread = hit_test.clone();
        let docs_thread = Arc::clone(&documents);
        let pool_stats_thread = Arc::clone(&gpu_pool_stats);
        let diag_thread = Arc::clone(&diagnostics);
        let perf_thread = Arc::clone(&perf_counters);
        let stroke_active_thread = Arc::clone(&stroke_active);
        let running_thread = Arc::clone(&running);

        let handle = std::thread::Builder::new()
            .name("inkstudio-gpu-engine".to_string())
            .spawn(move || {
                elevate_render_thread_priority();

                let renderer = match GpuRenderer::new_with_vram(
                    target,
                    config.doc_width,
                    config.doc_height,
                    vram_budget,
                ) {
                    Ok(r) => r,
                    Err(err) => {
                        running_thread.store(false, Ordering::SeqCst);
                        let _ = init_tx.send(Err(err));
                        return;
                    }
                };

                let pool_stats = renderer.gpu_pool_stats();
                *pool_stats_thread.write() = pool_stats;

                let initial_diag = EngineDiagnostics {
                    ready: true,
                    adapter_name: renderer.adapter_name().to_string(),
                    backend: "DX12".to_string(),
                    present_mode: renderer.present_mode_label().to_string(),
                    doc_width: config.doc_width,
                    doc_height: config.doc_height,
                    max_frame_latency: 1,
                    composition_mode: renderer.composition_mode_label().to_string(),
                    gpu_vram_used_bytes: pool_stats.used_bytes,
                    gpu_vram_budget_bytes: pool_stats.capacity_bytes,
                    gpu_tiles_resident: pool_stats.slots_used,
                    gpu_tiles_capacity: pool_stats.slots_capacity,
                    ..Default::default()
                };
                if let Ok(mut g) = diag_thread.lock() {
                    *g = initial_diag.clone();
                }
                let _ = event_tx.try_send(EngineEvent::Diagnostics(initial_diag.clone()));
                let _ = init_tx.send(Ok(initial_diag));

                let mut state = EngineThreadState::new(
                    renderer,
                    config,
                    consumers,
                    cmd_rx,
                    event_tx,
                    wake_thread,
                    hit_test_thread,
                    docs_thread,
                    pool_stats_thread,
                    diag_thread,
                    perf_thread,
                    stroke_active_thread,
                    running_thread,
                );
                state.run_loop();
            })
            .map_err(|e| format!("Failed to spawn ink-engine thread: {e}"))?;

        match init_rx.recv_timeout(Duration::from_secs(30)) {
            Ok(Ok(_diag)) => Ok((
                Self {
                    cmd_tx,
                    event_rx,
                    wake,
                    hit_test,
                    documents,
                    retouch_session: Arc::new(Mutex::new(crate::tools::RetouchSession::default())),
                    gpu_pool_stats,
                    diagnostics,
                    perf_counters,
                    stroke_active,
                    running,
                    thread: Mutex::new(Some(handle)),
                },
                producers,
            )),
            Ok(Err(e)) => {
                let _ = handle.join();
                Err(e)
            }
            Err(_) => {
                running.store(false, Ordering::SeqCst);
                let _ = handle.join();
                Err("Timed out initializing wgpu DX12 engine thread".to_string())
            }
        }
    }

    /// Sends a typed command to the engine thread and immediately wakes it.
    /// Single source of truth for synchronous `SharedHitTest` updates (zero duplicate locks!).
    pub fn send_command(&self, cmd: EngineCommand) {
        let cmd = match cmd {
            EngineCommand::SetViewport(vp) => {
                self.hit_test.set_viewport(vp);
                EngineCommand::SetViewport(vp)
            }
            EngineCommand::SetOccludedRects(rects) => {
                self.hit_test.set_occluded_rects(rects);
                EngineCommand::SetOccludedRects(Vec::new())
            }
            EngineCommand::SetVisible(vis) => {
                self.hit_test.set_visible(vis);
                EngineCommand::SetVisible(vis)
            }
            EngineCommand::SetInteractionPolicy(policy) => {
                self.hit_test.set_policy(policy);
                EngineCommand::SetInteractionPolicy(policy)
            }
            other => other,
        };
        let _ = self.cmd_tx.send(cmd);
        self.wake.wake();
    }

    pub fn hit_test(&self) -> SharedHitTest {
        self.hit_test.clone()
    }

    /// Lock-free check indicating whether a native GPU stroke is currently active or committing.
    #[inline]
    pub fn is_stroke_active(&self) -> bool {
        self.stroke_active.load(Ordering::Acquire)
    }

    /// Returns the shared lock-free `stroke_active` atomic flag for background tasks.
    pub fn stroke_active_flag(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.stroke_active)
    }

    /// Returns a shared thread-safe handle to the multi-tab Rust [`DocumentManager`].
    pub fn documents(&self) -> Arc<RwLock<DocumentManager>> {
        Arc::clone(&self.documents)
    }

    /// Returns the shared interactive Retouch session handle.
    pub fn retouch_session(&self) -> Arc<Mutex<crate::tools::RetouchSession>> {
        Arc::clone(&self.retouch_session)
    }

    // --- Phase 6 Synchronous GPU Command Helpers ---

    pub fn liquify_begin(
        &self,
        multi_layer: bool,
        layer_ids: Option<Vec<String>>,
    ) -> Result<Vec<String>, String> {
        let (tx, rx) = crossbeam_channel::bounded(1);
        self.send_command(EngineCommand::LiquifyBegin {
            multi_layer,
            layer_ids,
            reply: tx,
        });
        rx.recv_timeout(Duration::from_secs(10))
            .map_err(|_| "Timed out waiting for LiquifyBegin".to_string())?
    }

    pub fn liquify_step(
        &self,
        step: crate::tools::LiquifyStepParams,
    ) -> Result<RectI32, String> {
        let (tx, rx) = crossbeam_channel::bounded(1);
        self.send_command(EngineCommand::LiquifyStep { step, reply: tx });
        rx.recv_timeout(Duration::from_secs(10))
            .map_err(|_| "Timed out waiting for LiquifyStep".to_string())?
    }

    pub fn liquify_commit(&self) -> Result<(Vec<String>, RectI32), String> {
        let (tx, rx) = crossbeam_channel::bounded(1);
        self.send_command(EngineCommand::LiquifyCommit { reply: tx });
        rx.recv_timeout(Duration::from_secs(20))
            .map_err(|_| "Timed out waiting for LiquifyCommit".to_string())?
    }

    pub fn transform_begin(
        &self,
        mode: crate::tools::TransformMode,
        layer_ids: Option<Vec<String>>,
    ) -> Result<crate::tools::TransformSessionSnapshot, String> {
        let (tx, rx) = crossbeam_channel::bounded(1);
        self.send_command(EngineCommand::TransformBegin {
            mode,
            layer_ids,
            reply: tx,
        });
        rx.recv_timeout(Duration::from_secs(15))
            .map_err(|_| "Timed out waiting for TransformBegin".to_string())?
    }

    pub fn transform_update(
        &self,
        payload: crate::tools::TransformUpdatePayload,
    ) -> Result<crate::tools::TransformSessionSnapshot, String> {
        let (tx, rx) = crossbeam_channel::bounded(1);
        self.send_command(EngineCommand::TransformUpdate { payload, reply: tx });
        rx.recv_timeout(Duration::from_secs(10))
            .map_err(|_| "Timed out waiting for TransformUpdate".to_string())?
    }

    pub fn transform_switch_mode(
        &self,
        next_mode: crate::tools::TransformMode,
    ) -> Result<crate::tools::TransformSessionSnapshot, String> {
        let (tx, rx) = crossbeam_channel::bounded(1);
        self.send_command(EngineCommand::TransformSwitchMode {
            next_mode,
            reply: tx,
        });
        rx.recv_timeout(Duration::from_secs(15))
            .map_err(|_| "Timed out waiting for TransformSwitchMode".to_string())?
    }

    pub fn transform_commit(&self) -> Result<crate::tools::TransformCommitResult, String> {
        let (tx, rx) = crossbeam_channel::bounded(1);
        self.send_command(EngineCommand::TransformCommit { reply: tx });
        rx.recv_timeout(Duration::from_secs(20))
            .map_err(|_| "Timed out waiting for TransformCommit".to_string())?
    }

    /// Returns the latest L1 GPU VRAM tile atlas telemetry snapshot.
    pub fn gpu_pool_stats(&self) -> GpuPoolStats {
        *self.gpu_pool_stats.read()
    }

    pub fn events(&self) -> &Receiver<EngineEvent> {
        &self.event_rx
    }

    pub fn diagnostics(&self) -> EngineDiagnostics {
        self.diagnostics
            .lock()
            .map(|g| g.clone())
            .unwrap_or_default()
    }

    /// Returns a lock-free snapshot of GPU stamp batching & async thumbnail counters.
    pub fn perf_snapshot(&self) -> EnginePerfSnapshot {
        EnginePerfSnapshot {
            stamp_dispatches: self.perf_counters.stamp_dispatches.load(Ordering::Relaxed),
            sync_render_thread_thumbnails: self
                .perf_counters
                .sync_render_thread_thumbnails
                .load(Ordering::Relaxed),
            async_thumbnails_completed: self
                .perf_counters
                .async_thumbnails_completed
                .load(Ordering::Relaxed),
        }
    }

    pub fn is_running(&self) -> bool {
        self.running.load(Ordering::Relaxed)
    }

    /// Executes headless document-space GPU flattening directly on the running DX12 render
    /// thread using the warm L1 `GpuTilePool` and returns `(width, height, straight_rgba8)`.
    pub fn render_document_flattened(
        &self,
        doc_id: Option<String>,
        options: FlattenOptions,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        if !self.is_running() {
            return Err("Native DX12 engine is not running".to_string());
        }
        let (tx, rx) = crossbeam_channel::bounded(1);
        self.send_command(EngineCommand::RenderDocumentFlattened {
            doc_id,
            options,
            reply: tx,
        });
        rx.recv_timeout(Duration::from_secs(30))
            .map_err(|_| "Timed out waiting for GPU document flatten".to_string())?
    }

    /// Executes a GPU-accurate single-layer thumbnail render on the running DX12 render thread.
    pub fn render_layer_thumbnail_gpu(
        &self,
        doc_id: Option<String>,
        layer_id: String,
        max_dim: u32,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        if !self.is_running() {
            return Err("Native DX12 engine is not running".to_string());
        }
        let (tx, rx) = crossbeam_channel::bounded(1);
        self.send_command(EngineCommand::RenderLayerThumbnail {
            doc_id,
            layer_id,
            max_dim,
            reply: tx,
        });
        rx.recv_timeout(Duration::from_secs(10))
            .map_err(|_| "Timed out waiting for GPU layer thumbnail".to_string())?
    }

    /// Gracefully stops and joins the engine thread so the `wgpu::Surface` is dropped
    /// strictly BEFORE the host tears down its DirectComposition visual tree.
    pub fn shutdown(&self) {
        self.running.store(false, Ordering::SeqCst);
        let _ = self.cmd_tx.send(EngineCommand::Shutdown);
        self.wake.wake();
        if let Ok(mut guard) = self.thread.lock() {
            if let Some(handle) = guard.take() {
                let _ = handle.join();
            }
        }
    }
}

impl Drop for EngineHandle {
    fn drop(&mut self) {
        self.shutdown();
    }
}

#[cfg(target_os = "windows")]
fn elevate_render_thread_priority() {
    use windows_sys::Win32::System::Threading::{
        GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,
    };
    unsafe {
        SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
    }
}

#[cfg(not(target_os = "windows"))]
fn elevate_render_thread_priority() {}

/// Active Phase 4 GPU stroke session state owned strictly by the engine thread.
enum ActiveStrokeKind {
    /// Phase 4 instanced stamp / dual-brush / spray / wet-edge / binary ink / eraser.
    Stamp,
    /// Phase 5 continuous UV-mapped ribbon mesh (primary and optional dual-brush ribbon).
    Ribbon {
        primary: RibbonMeshBuilder,
        secondary: Option<RibbonMeshBuilder>,
        secondary_cfg: Option<Box<NativeBrushConfig>>,
        primary_verts: Vec<RibbonVertex>,
        secondary_verts: Vec<RibbonVertex>,
    },
    /// Phase 5 GPU compute multi-bristle natural paint + impasto R16Float heightfield.
    NaturalPaint {
        simulator: BristleRibbonSimulator,
        before_impasto_tiles: HashMap<TileCoord, Option<Arc<TileData>>>,
    },
    /// Phase 5 GPU compute 16×16 SpatialTipMixer color-mixing stamp engine.
    ColorMixingStamp,
}

struct ActiveGpuStroke {
    doc_id: String,
    layer_id: String,
    stroke_seed: u64,
    brush: NativeBrushConfig,
    mono_layer: bool,
    is_mask_stroke: bool,
    is_selection_stroke: bool,
    is_selection_erase: bool,
    kind: ActiveStrokeKind,
    primary_tip_metrics: (usize, f32),
    secondary_tip_metrics: Option<(usize, f32)>,
    primary_emitter: StrokeDabEmitter,
    secondary_emitter: Option<StrokeDabEmitter>,
    /// Lazy Copy-on-Write tile snapshots captured BEFORE the first dab touches `(tx, ty)`.
    before_tiles: HashMap<TileCoord, Option<Arc<TileData>>>,
    /// Lazy Copy-on-Write mask tile snapshots when `is_mask_stroke == true`.
    before_mask_tiles: HashMap<TileCoord, Option<Arc<TileData>>>,
}

struct ThumbnailJob {
    doc_id: String,
    layer_id: String,
    doc_w: u32,
    doc_h: u32,
    layer_version: u64,
    is_mask: bool,
    tiles: HashMap<TileCoord, Arc<TileData>>,
    mask_default_value: u8,
    tint: Option<([u8; 4], [u8; 4])>,
    scratch: Arc<dyn ScratchBackend>,
}

fn spawn_thumbnail_worker(
    documents: Arc<RwLock<DocumentManager>>,
    event_tx: Sender<EngineEvent>,
    perf_counters: Arc<EnginePerfCounters>,
) -> (Option<Sender<ThumbnailJob>>, Option<JoinHandle<()>>) {
    let (tx, rx) = crossbeam_channel::unbounded::<ThumbnailJob>();
    let worker = std::thread::Builder::new()
        .name("inkstudio-thumbnail-worker".to_string())
        .spawn(move || {
            while let Ok(first) = rx.recv() {
                // Coalesce/debounce rapid consecutive pen-ups for the same (doc, layer, is_mask)
                let mut latest: HashMap<(String, String, bool), ThumbnailJob> = HashMap::new();
                latest.insert(
                    (first.doc_id.clone(), first.layer_id.clone(), first.is_mask),
                    first,
                );
                while let Ok(next) = rx.try_recv() {
                    latest.insert(
                        (next.doc_id.clone(), next.layer_id.clone(), next.is_mask),
                        next,
                    );
                }

                for (_, job) in latest {
                    let encoded = if job.is_mask {
                        crate::io::compositor_cpu::render_mask_thumbnail_rgba_from_tiles(
                            &job.tiles,
                            job.mask_default_value,
                            job.doc_w,
                            job.doc_h,
                            64,
                            64,
                            Some(job.scratch.as_ref()),
                        )
                        .and_then(|(tw, th, rgba)| {
                            crate::io::png_codec::encode_rgba8_to_png(tw, th, &rgba)
                        })
                        .map(|png| crate::io::png_codec::png_bytes_to_data_url(&png))
                        .ok()
                    } else {
                        crate::io::compositor_cpu::render_layer_thumbnail_rgba_from_tiles(
                            &job.tiles,
                            job.tint,
                            job.doc_w,
                            job.doc_h,
                            64,
                            64,
                            Some(job.scratch.as_ref()),
                        )
                        .and_then(|(tw, th, rgba)| {
                            crate::io::png_codec::encode_rgba8_to_png(tw, th, &rgba)
                        })
                        .map(|png| crate::io::png_codec::png_bytes_to_data_url(&png))
                        .ok()
                    };

                    let Some(url) = encoded else {
                        continue;
                    };

                    // Brief write lock ONLY to store finished URL if layer version hasn't moved on
                    {
                        let mut mgr = documents.write();
                        if let Some(doc) = mgr.get_document_mut(&job.doc_id) {
                            if let Some(l) = doc.layer_mut(&job.layer_id) {
                                if l.grid.layer_version == job.layer_version {
                                    if job.is_mask {
                                        l.meta.mask_thumbnail_url = Some(url.clone());
                                    } else {
                                        l.meta.thumbnail_url = Some(url.clone());
                                    }
                                }
                            }
                        }
                    }

                    perf_counters
                        .async_thumbnails_completed
                        .fetch_add(1, Ordering::Relaxed);

                    let update = if job.is_mask {
                        ThumbnailUpdate {
                            layer_id: job.layer_id,
                            thumbnail_url: None,
                            mask_thumbnail_url: Some(url),
                        }
                    } else {
                        ThumbnailUpdate {
                            layer_id: job.layer_id,
                            thumbnail_url: Some(url),
                            mask_thumbnail_url: None,
                        }
                    };
                    let _ = event_tx.try_send(EngineEvent::ThumbnailsUpdated {
                        doc_id: job.doc_id,
                        updates: vec![update],
                    });
                }
            }
        })
        .ok();
    match worker {
        Some(handle) => (Some(tx), Some(handle)),
        None => (None, None),
    }
}

/// Maximum gap between two consecutive rendered frames to count as an active continuous
/// frame interval (gaps >= 150 ms are on-demand idle pauses and must never drag FPS down).
const ACTIVE_FRAME_GAP_THRESHOLD_MS: f64 = 150.0;
/// Time since the last rendered frame after which the HUD enters explicit Idle state.
const IDLE_DISPLAY_TIMEOUT_MS: f64 = 350.0;
/// Upper cap for reported active display FPS.
const MAX_DISPLAY_FPS: f32 = 240.0;

/// Owns the live `GpuRenderer` while allowing device-lost recovery to drop the old DX12 device,
/// swapchain, atlases, and compositor targets BEFORE constructing the replacement (preventing 2× VRAM spikes).
struct RendererSlot(Option<GpuRenderer>);

impl RendererSlot {
    #[inline]
    fn is_present(&self) -> bool {
        self.0.is_some()
    }
}

impl std::ops::Deref for RendererSlot {
    type Target = GpuRenderer;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.0
            .as_ref()
            .expect("GpuRenderer must be present during active engine loop")
    }
}

impl std::ops::DerefMut for RendererSlot {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.0
            .as_mut()
            .expect("GpuRenderer must be present during active engine loop")
    }
}

struct EngineThreadState {
    renderer: RendererSlot,
    pending_recovery: Option<(u32, u32, u64, SurfaceTarget)>,
    viewport_commit_pending: bool,
    consumers: InputConsumers,
    cmd_rx: Receiver<EngineCommand>,
    event_tx: Sender<EngineEvent>,
    wake: Arc<WakeSignal>,
    hit_test: SharedHitTest,
    documents: Arc<RwLock<DocumentManager>>,
    shared_pool_stats: Arc<RwLock<GpuPoolStats>>,
    shared_diag: Arc<Mutex<EngineDiagnostics>>,
    perf_counters: Arc<EnginePerfCounters>,
    stroke_active: Arc<AtomicBool>,
    running: Arc<AtomicBool>,
    thumb_tx: Option<Sender<ThumbnailJob>>,
    thumb_worker: Option<JoinHandle<()>>,
    collab_points_enabled: bool,
    deferred_readback_cmds: VecDeque<EngineCommand>,

    viewport: ViewportRect,
    visible: bool,
    show_checkerboard: bool,
    matte_color: [f32; 4],
    display_config: CompositorDisplayConfig,
    camera: CameraState,
    cursor_cfg: CursorConfig,
    brush_params: BrushParams,
    full_brush: NativeBrushConfig,
    mask_mode: bool,
    brush_pressure_lut: Option<CompiledCurveLut>,
    global_pressure_curve: GlobalPressureCurve,
    global_pressure_lut: Option<CompiledCurveLut>,
    straight_ruler: Option<StraightRulerConfig>,
    perspective_ruler: Option<PerspectiveRulerConfig>,
    policy: InteractionPolicy,

    navigator: NativeCameraNavigator,
    stylus_nav_backend: u8,

    // Phase 4 full native stroke & GPU brush state
    stroke_pipeline: NativeStrokePipeline,
    active_gpu_stroke: Option<ActiveGpuStroke>,
    frame_dirty_doc_bounds: Option<DocBounds>,
    last_stroke_end_point: Option<StrokePoint>,
    stroke_id_counter: u64,

    // Per-frame stroke batching scratch buffers (flushed ONCE right before render_and_present,
    // or immediately before pen-up / stroke-cancel so 200-300 Hz packets = 1 GPU submit/frame!)
    pending_stamp_primary_dabs: Vec<GpuBrushDab>,
    pending_stamp_secondary_dabs: Vec<GpuBrushDab>,
    pending_cmix_dabs: Vec<GpuBrushDab>,
    pending_cmix_secondary_dabs: Vec<GpuBrushDab>,
    pending_np_pts: Vec<StrokePoint>,
    pending_np_capsules: Vec<GpuBristleCapsule>,
    pending_ribbon_pts: Vec<StrokePoint>,

    // Legacy fallback for document-less Phase 1 PoC harness only
    legacy_stroke_gen: StrokeDabGenerator,
    legacy_pending_dabs: Vec<DabInstance>,
    merged_samples: Vec<NativeInputSample>,
    stashed_nav_events: VecDeque<NativeNavEvent>,

    cursor_local_phys: Option<(f32, f32)>,
    cursor_over_occluded: bool,
    last_tablet_sample_ms: f64,
    last_wintab_sample_ms: f64,
    /// Owning input backend for the currently active stroke: 0=none, 1=wintab, 2=windows-ink, 3=mouse.
    active_stroke_backend: u8,

    // Throttling & telemetry
    dirty: bool,
    pending_doc_sync: bool,
    pending_camera_emit: bool,
    pending_camera_commit: bool,
    pending_wheel_commit_deadline_ms: Option<f64>,
    last_camera_emit_ms: f64,
    last_diag_emit_ms: f64,
    last_pointer_stat_ms: f64,
    latest_pointer_doc: Option<(i32, i32)>,
    latest_pointer_pressure: f32,
    pointer_stat_dirty: bool,

    newest_input_timestamp_ms: f64,
    ema_frame_time_ms: f32,
    ema_input_latency_ms: f32,
    last_present_ms: f64,
    ema_active_frame_interval_ms: f32,
    active_interval_count: u32,
    measured_fps: f32,
    was_idle_diag: bool,
    total_frames: u64,
    active_stroke_dabs: u64,
    device_lost_recoveries: u32,
}

impl EngineThreadState {
    #[allow(clippy::too_many_arguments)]
    fn new(
        renderer: GpuRenderer,
        config: EngineConfig,
        consumers: InputConsumers,
        cmd_rx: Receiver<EngineCommand>,
        event_tx: Sender<EngineEvent>,
        wake: Arc<WakeSignal>,
        hit_test: SharedHitTest,
        documents: Arc<RwLock<DocumentManager>>,
        shared_pool_stats: Arc<RwLock<GpuPoolStats>>,
        shared_diag: Arc<Mutex<EngineDiagnostics>>,
        perf_counters: Arc<EnginePerfCounters>,
        stroke_active: Arc<AtomicBool>,
        running: Arc<AtomicBool>,
    ) -> Self {
        let now = clock::now_ms();
        let default_params = BrushParams::default();
        let full_brush = NativeBrushConfig::from_basic_params(&default_params);
        let (thumb_tx, thumb_worker) = spawn_thumbnail_worker(
            Arc::clone(&documents),
            event_tx.clone(),
            Arc::clone(&perf_counters),
        );
        Self {
            renderer: RendererSlot(Some(renderer)),
            pending_recovery: None,
            viewport_commit_pending: false,
            consumers,
            cmd_rx,
            event_tx,
            wake,
            hit_test,
            documents,
            shared_pool_stats,
            shared_diag,
            perf_counters,
            stroke_active,
            running,
            thumb_tx,
            thumb_worker,
            collab_points_enabled: false,
            deferred_readback_cmds: VecDeque::new(),
            viewport: ViewportRect::default(),
            visible: false,
            show_checkerboard: config.show_checkerboard,
            matte_color: config.matte_color,
            display_config: CompositorDisplayConfig {
                show_checkerboard: config.show_checkerboard,
                matte_color: config.matte_color,
                ..Default::default()
            },
            camera: CameraState::default(),
            cursor_cfg: CursorConfig::default(),
            brush_params: default_params,
            full_brush,
            mask_mode: false,
            brush_pressure_lut: None,
            global_pressure_curve: GlobalPressureCurve::default(),
            global_pressure_lut: None,
            straight_ruler: None,
            perspective_ruler: None,
            policy: InteractionPolicy::default(),
            navigator: NativeCameraNavigator::default(),
            stylus_nav_backend: 0,
            stroke_pipeline: NativeStrokePipeline::new(),
            active_gpu_stroke: None,
            frame_dirty_doc_bounds: None,
            last_stroke_end_point: None,
            stroke_id_counter: 1,
            pending_stamp_primary_dabs: Vec::with_capacity(256),
            pending_stamp_secondary_dabs: Vec::with_capacity(128),
            pending_cmix_dabs: Vec::with_capacity(128),
            pending_cmix_secondary_dabs: Vec::with_capacity(128),
            pending_np_pts: Vec::with_capacity(64),
            pending_np_capsules: Vec::with_capacity(512),
            pending_ribbon_pts: Vec::with_capacity(64),
            legacy_stroke_gen: StrokeDabGenerator::default(),
            legacy_pending_dabs: Vec::with_capacity(256),
            merged_samples: Vec::with_capacity(128),
            stashed_nav_events: VecDeque::with_capacity(16),
            cursor_local_phys: None,
            cursor_over_occluded: false,
            last_tablet_sample_ms: f64::NEG_INFINITY,
            last_wintab_sample_ms: f64::NEG_INFINITY,
            active_stroke_backend: 0,
            dirty: false,
            pending_doc_sync: false,
            pending_camera_emit: false,
            pending_camera_commit: false,
            pending_wheel_commit_deadline_ms: None,
            last_camera_emit_ms: 0.0,
            last_diag_emit_ms: now,
            last_pointer_stat_ms: 0.0,
            latest_pointer_doc: None,
            latest_pointer_pressure: 0.0,
            pointer_stat_dirty: false,
            newest_input_timestamp_ms: 0.0,
            ema_frame_time_ms: 0.0,
            ema_input_latency_ms: 0.0,
            last_present_ms: 0.0,
            ema_active_frame_interval_ms: 0.0,
            active_interval_count: 0,
            measured_fps: 0.0,
            was_idle_diag: true,
            total_frames: 0,
            active_stroke_dabs: 0,
            device_lost_recoveries: 0,
        }
    }

    #[inline]
    fn is_any_stroke_active(&self) -> bool {
        self.active_gpu_stroke.is_some() || self.legacy_stroke_gen.is_active()
    }

    #[inline]
    fn sync_stroke_active_flag(&self) {
        self.stroke_active
            .store(self.is_any_stroke_active(), Ordering::Release);
    }

    fn clear_pending_stroke_batch(&mut self) {
        self.pending_stamp_primary_dabs.clear();
        self.pending_stamp_secondary_dabs.clear();
        self.pending_cmix_dabs.clear();
        self.pending_cmix_secondary_dabs.clear();
        self.pending_np_pts.clear();
        self.pending_np_capsules.clear();
        self.pending_ribbon_pts.clear();
    }

    fn cancel_active_stroke(&mut self) {
        self.active_gpu_stroke = None;
        self.active_stroke_backend = 0;
        self.clear_pending_stroke_batch();
        self.stroke_pipeline.reset();
        self.legacy_stroke_gen.reset();
        self.legacy_pending_dabs.clear();
        self.frame_dirty_doc_bounds = None;
        self.renderer.clear_live_stroke();
        self.stroke_active.store(false, Ordering::Release);
        self.dirty = true;
    }

    /// Sends high-frequency telemetry events ONLY while queue headroom remains so critical
    /// state-sync events (`StrokeCommitted`, `HistoryChanged`, `ThumbnailsUpdated`,
    /// `SelectionChanged`, `ViewportInvalidated`) can never be starved or dropped.
    #[inline]
    fn send_throttled_event(&self, evt: EngineEvent) {
        if self.event_tx.len() < 448 {
            let _ = self.event_tx.try_send(evt);
        }
    }

    fn sync_viewport_frustum_locked(&self, mgr: &mut DocumentManager) {
        let Some(doc) = mgr.active_document() else {
            mgr.set_viewport_frustum(None);
            return;
        };
        let css_w = self.viewport.css_width();
        let css_h = self.viewport.css_height();
        if css_w <= 0.0 || css_h <= 0.0 {
            mgr.set_viewport_frustum(None);
            return;
        }
        let bounds = calculate_visible_doc_bounds(
            css_w,
            css_h,
            &self.camera,
            doc.dimensions.width,
            doc.dimensions.height,
        );
        mgr.set_viewport_frustum(Some(ViewportFrustum {
            min_x: bounds.min_x,
            min_y: bounds.min_y,
            max_x: bounds.max_x,
            max_y: bounds.max_y,
        }));
    }

    fn sync_viewport_frustum(&self) {
        let mut mgr = self.documents.write();
        self.sync_viewport_frustum_locked(&mut mgr);
    }

    fn sync_active_document_if_needed(&mut self) {
        if !self.pending_doc_sync {
            return;
        }
        self.pending_doc_sync = false;
        // Read-only lock + O(resident_slots) stale-key invalidation: NEVER hold documents.write()
        // or upload offscreen tiles across all layers; frustum-culled prepare_document_gpu_resources
        // uploads visible tiles lazily on demand!
        let mgr = self.documents.read();
        if let Some(doc) = mgr.active_document() {
            self.renderer.sync_document_lazy(doc);
            *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();
            self.dirty = true;
        }
    }

    /// Captures lazy Copy-on-Write `Arc<TileData>` references for tiles BEFORE the first
    /// dab touches `(tx, ty)` (zero full-layer snapshot scan!).
    fn capture_cow_before_tiles(&self, stroke: &mut ActiveGpuStroke, newly_touched: &[TileCoord]) {
        if newly_touched.is_empty() {
            return;
        }
        let mgr = self.documents.read();
        let Some(doc) = mgr.get_document(&stroke.doc_id) else {
            return;
        };
        let Some(layer) = doc.layer(&stroke.layer_id) else {
            return;
        };
        for &coord in newly_touched {
            if stroke.is_mask_stroke {
                stroke
                    .before_mask_tiles
                    .entry(coord)
                    .or_insert_with(|| layer.grid.mask_tiles.get(&coord).cloned());
            } else {
                stroke
                    .before_tiles
                    .entry(coord)
                    .or_insert_with(|| layer.grid.tiles.get(&coord).cloned());
                if let ActiveStrokeKind::NaturalPaint {
                    ref mut before_impasto_tiles,
                    ..
                } = stroke.kind
                {
                    before_impasto_tiles
                        .entry(coord)
                        .or_insert_with(|| layer.grid.impasto_tiles.get(&coord).cloned());
                }
            }
        }
    }

    fn expand_frame_dirty_doc_aabb(&mut self, bounds: (f32, f32, f32, f32)) {
        let b = DocBounds {
            min_x: bounds.0.floor() as i32,
            min_y: bounds.1.floor() as i32,
            max_x: bounds.2.ceil() as i32,
            max_y: bounds.3.ceil() as i32,
        };
        self.frame_dirty_doc_bounds = Some(match self.frame_dirty_doc_bounds {
            Some(prev) => DocBounds {
                min_x: prev.min_x.min(b.min_x),
                min_y: prev.min_y.min(b.min_y),
                max_x: prev.max_x.max(b.max_x),
                max_y: prev.max_y.max(b.max_y),
            },
            None => b,
        });
    }

    fn sample_segments_to_points(segs: &[CubicBezierSegment], out: &mut Vec<StrokePoint>) {
        for seg in segs {
            let chord = (seg.p3.x - seg.p0.x).hypot(seg.p3.y - seg.p0.y);
            let steps = ((chord / 3.5).ceil() as usize).clamp(2, 16);
            for s in 1..=steps {
                let t = s as f64 / steps as f64;
                let (x, y, _, _) = seg.eval_pos_tangent(t);
                let tf = t as f32;
                out.push(StrokePoint {
                    x,
                    y,
                    pressure: seg.p0.pressure + (seg.p3.pressure - seg.p0.pressure) * tf,
                    width: seg.p0.width + (seg.p3.width - seg.p0.width) * tf,
                    tilt_x: seg.p0.tilt_x + (seg.p3.tilt_x - seg.p0.tilt_x) * tf,
                    tilt_y: seg.p0.tilt_y + (seg.p3.tilt_y - seg.p0.tilt_y) * tf,
                    twist: seg.p0.twist + (seg.p3.twist - seg.p0.twist) * tf,
                    velocity: seg.p0.velocity + (seg.p3.velocity - seg.p0.velocity) * t,
                    timestamp_ms: seg.p0.timestamp_ms
                        + (seg.p3.timestamp_ms - seg.p0.timestamp_ms) * t,
                    is_corner: s == steps && seg.p3.is_corner,
                });
            }
        }
    }

    /// Coarse curvature-preserving Bezier sampling for `BristleRibbonSimulator` (which already
    /// performs physical substepping), eliminating redundant double-subdivision!
    fn sample_segments_for_natural_paint(
        segs: &[CubicBezierSegment],
        brush_size: f32,
        out: &mut Vec<StrokePoint>,
    ) {
        let target_step = (brush_size as f64 * 0.22).clamp(5.0, 18.0);
        for seg in segs {
            let chord = (seg.p3.x - seg.p0.x).hypot(seg.p3.y - seg.p0.y);
            let steps = ((chord / target_step).ceil() as usize).clamp(1, 8);
            for s in 1..=steps {
                let t = s as f64 / steps as f64;
                let (x, y, _, _) = seg.eval_pos_tangent(t);
                let tf = t as f32;
                out.push(StrokePoint {
                    x,
                    y,
                    pressure: seg.p0.pressure + (seg.p3.pressure - seg.p0.pressure) * tf,
                    width: seg.p0.width + (seg.p3.width - seg.p0.width) * tf,
                    tilt_x: seg.p0.tilt_x + (seg.p3.tilt_x - seg.p0.tilt_x) * tf,
                    tilt_y: seg.p0.tilt_y + (seg.p3.tilt_y - seg.p0.tilt_y) * tf,
                    twist: seg.p0.twist + (seg.p3.twist - seg.p0.twist) * tf,
                    velocity: seg.p0.velocity + (seg.p3.velocity - seg.p0.velocity) * t,
                    timestamp_ms: seg.p0.timestamp_ms
                        + (seg.p3.timestamp_ms - seg.p0.timestamp_ms) * t,
                    is_corner: s == steps && seg.p3.is_corner,
                });
            }
        }
    }

    /// Starts a Phase 4/5 native GPU stroke on the active editable raster layer (or 8-bit layer mask / selection mask).
    fn begin_native_gpu_stroke(
        &mut self,
        doc_x: f64,
        doc_y: f64,
        sample: NativeInputSample,
    ) {
        let shift_held = (sample.buttons & 0x0100) != 0;
        let alt_held = (sample.buttons & 0x0200) != 0;
        let inverted_eraser = (sample.buttons & 8) != 0;
        let is_selection_stroke = self.policy.active_tool.is_selection_brush_tool();
        let is_selection_erase =
            self.policy.active_tool == crate::types::NativeToolKind::SelectEraser || inverted_eraser;

        let target_info = {
            let mgr = self.documents.read();
            let Some(doc) = mgr.active_document() else {
                let before = self.legacy_pending_dabs.len();
                self.legacy_stroke_gen.begin(
                    doc_x as f32,
                    doc_y as f32,
                    sample.pressure,
                    inverted_eraser,
                    &self.brush_params,
                    &mut self.legacy_pending_dabs,
                );
                self.active_stroke_dabs = (self.legacy_pending_dabs.len() - before) as u64;
                self.sync_stroke_active_flag();
                self.dirty = true;
                return;
            };
            let Some(layer_id) = doc.active_layer_id.clone() else {
                return;
            };
            let Some(layer) = doc.layer(&layer_id) else {
                return;
            };
            let is_mask_stroke = !is_selection_stroke && self.mask_mode && layer.grid.has_mask;
            if !is_selection_stroke
                && ((!is_mask_stroke && !layer.meta.layer_type.has_tiles())
                    || layer.meta.locked
                    || !doc.is_layer_effectively_visible(&layer_id))
            {
                return;
            }
            let is_mono = !is_mask_stroke
                && !is_selection_stroke
                && (layer.grid.format == TileFormat::Monochrome1Bit
                    || matches!(layer.meta.expression_color, Some(ExpressionColor::Monochrome)));
            (
                doc.id.clone(),
                layer_id,
                doc.dimensions.width.max(1),
                doc.dimensions.height.max(1),
                is_mono,
                is_mask_stroke,
            )
        };

        let (doc_id, layer_id, doc_w, doc_h, mono_layer, is_mask_stroke) = target_info;

        let mut stroke_brush = self.full_brush.clone();
        if inverted_eraser && !is_selection_stroke {
            stroke_brush.is_eraser = true;
        }
        if is_selection_stroke {
            // Select Pen / Select Eraser paints translucent preview ink and commits alpha onto SparseSelectionMask!
            stroke_brush.fg_color = if is_selection_erase {
                [0.25, 0.55, 1.0]
            } else {
                [0.18, 0.78, 0.45]
            };
            stroke_brush.opacity = 0.55;
            stroke_brush.is_eraser = false;
            stroke_brush.is_transparent_ink = false;
            stroke_brush.is_bg_eraser = false;
            stroke_brush.color_mixing = false;
            stroke_brush.natural_paint = None;
            stroke_brush.impasto = None;
            stroke_brush.render_mode = crate::brush::BrushRenderMode::Stamp;
            stroke_brush.brush_combine_mode = crate::brush::CspBrushCombineMode::Normal;
        } else if is_mask_stroke {
            // Mask mode paints luminance (white = reveal, black/eraser = hide) cleanly via Stamp/Ribbon!
            let lum = if stroke_brush.is_effective_eraser() {
                0.0
            } else {
                (stroke_brush.fg_color[0] * 0.299
                    + stroke_brush.fg_color[1] * 0.587
                    + stroke_brush.fg_color[2] * 0.114)
                    .clamp(0.0, 1.0)
            };
            stroke_brush.fg_color = [lum, lum, lum];
            stroke_brush.is_eraser = false;
            stroke_brush.is_transparent_ink = false;
            stroke_brush.is_bg_eraser = false;
            stroke_brush.color_mixing = false;
            stroke_brush.natural_paint = None;
            stroke_brush.impasto = None;
            stroke_brush.render_mode = crate::brush::BrushRenderMode::Stamp;
            stroke_brush.brush_combine_mode = crate::brush::CspBrushCombineMode::Normal;
        }

        self.stroke_id_counter = self.stroke_id_counter.wrapping_add(1);
        let stroke_seed = self
            .stroke_id_counter
            .wrapping_mul(0x9E37_79B9_7F4A_7C15)
            ^ (sample.timestamp_ms.to_bits());

        let primary_metrics = self.renderer.resolve_brush_tip_metrics(&stroke_brush);
        let primary_emitter = StrokeDabEmitter::new(
            stroke_brush.clone(),
            stroke_seed,
            primary_metrics.0,
            primary_metrics.1,
        );

        let (secondary_metrics, secondary_emitter) =
            if let Some(sec_cfg) = stroke_brush.build_secondary_brush_config() {
                let sm = self.renderer.resolve_brush_tip_metrics(&sec_cfg);
                let se = StrokeDabEmitter::new(
                    sec_cfg,
                    stroke_seed ^ 0xA5A5_5A5A_F0F0_0F0F,
                    sm.0,
                    sm.1,
                );
                (Some(sm), Some(se))
            } else {
                (None, None)
            };

        let grain_offset = primary_emitter.stroke_grain_offset;
        let kind = if !is_mask_stroke && stroke_brush.is_natural_paint_brush() {
            self.renderer.begin_natural_paint_stroke(
                &doc_id,
                &layer_id,
                doc_w,
                doc_h,
                stroke_brush.clone(),
            );
            ActiveStrokeKind::NaturalPaint {
                simulator: BristleRibbonSimulator::new(&stroke_brush, stroke_seed as u32),
                before_impasto_tiles: HashMap::with_capacity(16),
            }
        } else if !is_mask_stroke && stroke_brush.is_color_mixing_stamp_brush() {
            self.renderer.begin_natural_paint_stroke(
                &doc_id,
                &layer_id,
                doc_w,
                doc_h,
                stroke_brush.clone(),
            );
            self.renderer
                .set_natural_paint_stroke_rand_offset(grain_offset);
            ActiveStrokeKind::ColorMixingStamp
        } else if stroke_brush.is_ribbon_brush() {
            self.renderer.begin_gpu_stroke(
                doc_w,
                doc_h,
                mono_layer,
                stroke_brush.clone(),
                grain_offset,
            );
            let (tw, th, sub_c) = self.renderer.resolve_ribbon_tip_dims(&stroke_brush);
            let primary = RibbonMeshBuilder::new(tw, th, sub_c, stroke_seed);
            let (secondary, secondary_cfg) =
                if let Some(sec_cfg) = stroke_brush.build_secondary_brush_config() {
                    if sec_cfg.is_ribbon {
                        let (stw, sth, ssub) = self.renderer.resolve_ribbon_tip_dims(&sec_cfg);
                        (
                            Some(RibbonMeshBuilder::new(
                                stw,
                                sth,
                                ssub,
                                stroke_seed ^ 0xA5A5_5A5A_F0F0_0F0F,
                            )),
                            Some(Box::new(sec_cfg)),
                        )
                    } else {
                        (None, None)
                    }
                } else {
                    (None, None)
                };
            ActiveStrokeKind::Ribbon {
                primary,
                secondary,
                secondary_cfg,
                primary_verts: Vec::with_capacity(256),
                secondary_verts: Vec::with_capacity(128),
            }
        } else {
            self.renderer.begin_gpu_stroke(
                doc_w,
                doc_h,
                mono_layer,
                stroke_brush.clone(),
                grain_offset,
            );
            self.renderer.set_selection_brush_stroke(is_selection_stroke);
            ActiveStrokeKind::Stamp
        };

        let pipe_cfg = StrokePipelineConfig {
            base_size: stroke_brush.size,
            min_size_factor: stroke_brush.min_size_factor,
            use_pressure: stroke_brush.use_pressure,
            pressure_curve_gamma: stroke_brush.pressure_curve_gamma,
            brush_pressure_lut: self.brush_pressure_lut.clone(),
            global_pressure_curve: self.global_pressure_curve.clone(),
            global_pressure_lut: self.global_pressure_lut.clone(),
            stabilization: stroke_brush.stabilization,
            sharp_corners: stroke_brush.sharp_corners,
            post_correction: stroke_brush.post_correction,
            smoothing: stroke_brush.smoothing,
            enable_flick_taper: stroke_brush.enable_flick_taper,
            zoom: self.camera.zoom.max(0.05) as f64,
            straight_ruler: self.straight_ruler.clone(),
            perspective_ruler: self.perspective_ruler.clone(),
        };

        let shift_anchor = if shift_held {
            self.last_stroke_end_point
        } else {
            None
        };

        let step = self.stroke_pipeline.begin(
            doc_x,
            doc_y,
            sample.pressure,
            sample.tilt_x,
            sample.tilt_y,
            sample.twist,
            sample.timestamp_ms,
            alt_held,
            shift_anchor,
            pipe_cfg,
        );

        let mut active = ActiveGpuStroke {
            doc_id,
            layer_id,
            stroke_seed,
            brush: stroke_brush,
            mono_layer,
            is_mask_stroke,
            is_selection_stroke,
            is_selection_erase,
            kind,
            primary_tip_metrics: primary_metrics,
            secondary_tip_metrics: secondary_metrics,
            primary_emitter,
            secondary_emitter,
            before_tiles: HashMap::with_capacity(32),
            before_mask_tiles: HashMap::with_capacity(16),
        };

        self.clear_pending_stroke_batch();
        self.active_stroke_dabs = 0;
        self.frame_dirty_doc_bounds = None;

        self.accumulate_stroke_step(&mut active, step.initial_point, &step.sealed_segments);
        self.active_gpu_stroke = Some(active);
        self.sync_stroke_active_flag();
        self.dirty = true;
    }

    /// Accumulates stabilized points/segments into per-frame scratch buffers WITHOUT submitting
    /// to the GPU, so 200-300 Hz input packets collapse into ONE batched GPU dispatch per frame!
    fn accumulate_stroke_step(
        &mut self,
        active: &mut ActiveGpuStroke,
        initial_point: Option<StrokePoint>,
        sealed_segments: &[CubicBezierSegment],
    ) {
        match &mut active.kind {
            ActiveStrokeKind::Stamp => {
                if let Some(ref pt) = initial_point {
                    active.primary_emitter.emit_initial_point(
                        pt,
                        None,
                        0.0,
                        &mut self.pending_stamp_primary_dabs,
                    );
                    if let Some(ref mut se) = active.secondary_emitter {
                        se.emit_initial_point(
                            pt,
                            None,
                            0.0,
                            &mut self.pending_stamp_secondary_dabs,
                        );
                    }
                }
                for seg in sealed_segments {
                    active.primary_emitter.emit_segment(
                        seg,
                        None,
                        0.0,
                        &mut self.pending_stamp_primary_dabs,
                    );
                    if let Some(ref mut se) = active.secondary_emitter {
                        se.emit_segment(seg, None, 0.0, &mut self.pending_stamp_secondary_dabs);
                    }
                }
            }
            ActiveStrokeKind::Ribbon { .. } => {
                if let Some(pt) = initial_point {
                    self.pending_ribbon_pts.push(pt);
                }
                Self::sample_segments_to_points(sealed_segments, &mut self.pending_ribbon_pts);
            }
            ActiveStrokeKind::NaturalPaint { .. } => {
                if let Some(pt) = initial_point {
                    self.pending_np_pts.push(pt);
                }
                Self::sample_segments_for_natural_paint(
                    sealed_segments,
                    active.brush.size,
                    &mut self.pending_np_pts,
                );
            }
            ActiveStrokeKind::ColorMixingStamp => {
                if let Some(ref pt) = initial_point {
                    active.primary_emitter.emit_initial_point(
                        pt,
                        None,
                        0.0,
                        &mut self.pending_cmix_dabs,
                    );
                    if let Some(ref mut se) = active.secondary_emitter {
                        se.emit_initial_point(
                            pt,
                            None,
                            0.0,
                            &mut self.pending_cmix_secondary_dabs,
                        );
                    }
                }
                for seg in sealed_segments {
                    active.primary_emitter.emit_segment(
                        seg,
                        None,
                        0.0,
                        &mut self.pending_cmix_dabs,
                    );
                    if let Some(ref mut se) = active.secondary_emitter {
                        se.emit_segment(seg, None, 0.0, &mut self.pending_cmix_secondary_dabs);
                    }
                }
            }
        }
    }

    /// Flushes all accumulated per-frame stroke geometry/dabs/capsules for `active` in ONE
    /// batched GPU dispatch! Called once per frame right before `render_and_present()`, or
    /// right before pen-up commit (`finish_ribbon = true`).
    fn flush_pending_stroke_batch_for(
        &mut self,
        active: &mut ActiveGpuStroke,
        finish_ribbon: bool,
    ) {
        match &mut active.kind {
            ActiveStrokeKind::Stamp => {
                if self.pending_stamp_primary_dabs.is_empty()
                    && self.pending_stamp_secondary_dabs.is_empty()
                {
                    return;
                }
                self.active_stroke_dabs += self.pending_stamp_primary_dabs.len() as u64;
                let mut union_bounds: Option<(f32, f32, f32, f32)> = None;
                for d in &self.pending_stamp_primary_dabs {
                    let b = d.doc_bounds();
                    union_bounds = Some(match union_bounds {
                        Some(p) => (p.0.min(b.0), p.1.min(b.1), p.2.max(b.2), p.3.max(b.3)),
                        None => b,
                    });
                }
                let newly_touched = self.renderer.stamp_gpu_stroke_dabs(
                    &self.pending_stamp_primary_dabs,
                    &self.pending_stamp_secondary_dabs,
                );
                self.perf_counters
                    .stamp_dispatches
                    .fetch_add(1, Ordering::Relaxed);
                self.pending_stamp_primary_dabs.clear();
                self.pending_stamp_secondary_dabs.clear();
                self.capture_cow_before_tiles(active, &newly_touched);
                if let Some(b) = union_bounds {
                    self.expand_frame_dirty_doc_aabb(b);
                }
            }
            ActiveStrokeKind::Ribbon {
                primary,
                secondary,
                secondary_cfg,
                primary_verts,
                secondary_verts,
            } => {
                if self.pending_ribbon_pts.is_empty() && !finish_ribbon {
                    return;
                }
                let is_once = active.brush.ribbon_repeat_mode == RibbonRepeatMode::Once;
                if !is_once {
                    primary_verts.clear();
                    secondary_verts.clear();
                }
                let mut bounds: Option<(f32, f32, f32, f32)> = None;
                if !self.pending_ribbon_pts.is_empty() {
                    bounds =
                        primary.push_points(&self.pending_ribbon_pts, &active.brush, primary_verts);
                    if let (Some(sec), Some(scfg)) = (secondary.as_mut(), secondary_cfg.as_ref()) {
                        let _ = sec.push_points(&self.pending_ribbon_pts, scfg, secondary_verts);
                    }
                    self.pending_ribbon_pts.clear();
                }
                if finish_ribbon {
                    if let Some(fb) = primary.finish(&active.brush, primary_verts) {
                        bounds = Some(match bounds {
                            Some(p) => (
                                p.0.min(fb.0),
                                p.1.min(fb.1),
                                p.2.max(fb.2),
                                p.3.max(fb.3),
                            ),
                            None => fb,
                        });
                    }
                    if let (Some(sec), Some(scfg)) = (secondary.as_mut(), secondary_cfg.as_ref()) {
                        let _ = sec.finish(scfg, secondary_verts);
                    }
                }
                if !primary_verts.is_empty() || !secondary_verts.is_empty() {
                    self.active_stroke_dabs += (primary_verts.len() / 6) as u64;
                    let newly_touched = self.renderer.stamp_gpu_ribbon_vertices(
                        primary_verts,
                        secondary_verts,
                        is_once,
                    );
                    self.perf_counters
                        .stamp_dispatches
                        .fetch_add(1, Ordering::Relaxed);
                    self.capture_cow_before_tiles(active, &newly_touched);
                    if let Some(b) = bounds {
                        self.expand_frame_dirty_doc_aabb(b);
                    }
                }
            }
            ActiveStrokeKind::NaturalPaint { simulator, .. } => {
                if self.pending_np_pts.is_empty() && !finish_ribbon {
                    return;
                }
                self.pending_np_capsules.clear();
                if !self.pending_np_pts.is_empty() {
                    simulator.step_points(
                        &self.pending_np_pts,
                        &active.brush,
                        &mut self.pending_np_capsules,
                    );
                    self.pending_np_pts.clear();
                }
                if finish_ribbon {
                    simulator.flush_pending_tap(&active.brush, &mut self.pending_np_capsules);
                }
                if self.pending_np_capsules.is_empty() {
                    return;
                }
                self.active_stroke_dabs += self.pending_np_capsules.len() as u64;
                let (newly_touched, bounds) = {
                    let mgr = self.documents.read();
                    let scratch = Arc::clone(mgr.scratch_backend());
                    if let Some(doc) = mgr.get_document(&active.doc_id) {
                        if let Some(layer) = doc.layer(&active.layer_id) {
                            self.renderer.dispatch_natural_paint_capsules(
                                doc,
                                layer,
                                &self.pending_np_capsules,
                                Some(scratch.as_ref()),
                            )
                        } else {
                            (Vec::new(), None)
                        }
                    } else {
                        (Vec::new(), None)
                    }
                };
                self.perf_counters
                    .stamp_dispatches
                    .fetch_add(1, Ordering::Relaxed);
                self.pending_np_capsules.clear();
                self.capture_cow_before_tiles(active, &newly_touched);
                if let Some(b) = bounds {
                    self.expand_frame_dirty_doc_aabb(b);
                }
            }
            ActiveStrokeKind::ColorMixingStamp => {
                if self.pending_cmix_dabs.is_empty() && self.pending_cmix_secondary_dabs.is_empty() {
                    return;
                }
                self.active_stroke_dabs += self.pending_cmix_dabs.len() as u64;
                let (newly_touched, bounds) = {
                    let mgr = self.documents.read();
                    let scratch = Arc::clone(mgr.scratch_backend());
                    if let Some(doc) = mgr.get_document(&active.doc_id) {
                        if let Some(layer) = doc.layer(&active.layer_id) {
                            self.renderer.dispatch_color_mixing_dabs_with_secondary(
                                doc,
                                layer,
                                &self.pending_cmix_dabs,
                                &self.pending_cmix_secondary_dabs,
                                Some(scratch.as_ref()),
                            )
                        } else {
                            (Vec::new(), None)
                        }
                    } else {
                        (Vec::new(), None)
                    }
                };
                self.perf_counters
                    .stamp_dispatches
                    .fetch_add(1, Ordering::Relaxed);
                self.pending_cmix_dabs.clear();
                self.pending_cmix_secondary_dabs.clear();
                self.capture_cow_before_tiles(active, &newly_touched);
                if let Some(b) = bounds {
                    self.expand_frame_dirty_doc_aabb(b);
                }
            }
        }
    }

    fn flush_pending_stroke_batch(&mut self) {
        if let Some(mut active) = self.active_gpu_stroke.take() {
            self.flush_pending_stroke_batch_for(&mut active, false);
            self.active_gpu_stroke = Some(active);
        }
    }

    fn push_native_gpu_stroke_move(
        &mut self,
        doc_x: f64,
        doc_y: f64,
        sample: NativeInputSample,
    ) {
        if self.active_gpu_stroke.is_none() {
            if self.legacy_stroke_gen.is_active() {
                let before = self.legacy_pending_dabs.len();
                self.legacy_stroke_gen.push_move(
                    doc_x as f32,
                    doc_y as f32,
                    sample.pressure,
                    &self.brush_params,
                    &mut self.legacy_pending_dabs,
                );
                self.active_stroke_dabs += (self.legacy_pending_dabs.len() - before) as u64;
                self.dirty = true;
            }
            return;
        }

        let alt_held = (sample.buttons & 0x0200) != 0;
        let step = self.stroke_pipeline.push_move(
            doc_x,
            doc_y,
            sample.pressure,
            sample.tilt_x,
            sample.tilt_y,
            sample.twist,
            sample.timestamp_ms,
            alt_held,
        );

        if step.sealed_segments.is_empty() {
            self.dirty = true;
            return;
        }

        if let Some(mut active) = self.active_gpu_stroke.take() {
            self.accumulate_stroke_step(&mut active, None, &step.sealed_segments);
            self.active_gpu_stroke = Some(active);
        }
        self.dirty = true;
    }

    /// Pen-up finalization & sub-millisecond GPU-to-GPU tile commit into `GpuTilePool`
    /// + `SparseLayerGrid` + CoW Undo/Redo (raster + impasto `R16F` + mask) + `StrokeCommitted`!
    fn finish_and_commit_gpu_stroke(&mut self, lift_timestamp_ms: f64) {
        self.finish_and_commit_gpu_stroke_inner(lift_timestamp_ms);
        self.sync_stroke_active_flag();
    }

    fn finish_and_commit_gpu_stroke_inner(&mut self, lift_timestamp_ms: f64) {
        self.active_stroke_backend = 0;
        let Some(mut active) = self.active_gpu_stroke.take() else {
            if self.legacy_stroke_gen.is_active() {
                self.legacy_stroke_gen.end();
                self.dirty = true;
            }
            return;
        };

        let step = self.stroke_pipeline.end(lift_timestamp_ms);
        let finalized_points = step
            .finalized_points
            .unwrap_or_else(|| self.stroke_pipeline.committed_points().to_vec());

        if let Some(&last_pt) = finalized_points.last() {
            self.last_stroke_end_point = Some(last_pt);
        }

        let exit_vel = finalized_points.last().map(|p| p.velocity).unwrap_or(0.0);
        let is_natural_or_cmix = matches!(
            active.kind,
            ActiveStrokeKind::NaturalPaint { .. } | ActiveStrokeKind::ColorMixingStamp
        );

        if matches!(
            active.kind,
            ActiveStrokeKind::Stamp | ActiveStrokeKind::ColorMixingStamp
        ) && active.brush.requires_finalize_reraster()
            && finalized_points.len() >= 2
        {
            self.clear_pending_stroke_batch();
            let segs = polyline_to_bezier_segments(&finalized_points, 0.0);
            let total_len: f64 = finalized_points
                .windows(2)
                .map(|w| (w[1].x - w[0].x).hypot(w[1].y - w[0].y))
                .sum();

            let mut p_emitter = StrokeDabEmitter::new(
                active.brush.clone(),
                active.stroke_seed,
                active.primary_tip_metrics.0,
                active.primary_tip_metrics.1,
            );
            let mut s_emitter = active.brush.build_secondary_brush_config().map(|sec_cfg| {
                let sm = active.secondary_tip_metrics.unwrap_or((1, 1.0));
                StrokeDabEmitter::new(
                    sec_cfg,
                    active.stroke_seed ^ 0xA5A5_5A5A_F0F0_0F0F,
                    sm.0,
                    sm.1,
                )
            });

            let mut p_dabs = Vec::with_capacity(256);
            let mut s_dabs = Vec::with_capacity(256);
            for seg in &segs {
                p_emitter.emit_segment(seg, Some(total_len), exit_vel, &mut p_dabs);
                if let Some(ref mut se) = s_emitter {
                    se.emit_segment(seg, Some(total_len), exit_vel, &mut s_dabs);
                }
            }

            let (doc_w, doc_h) = self.renderer.doc_size();
            if matches!(active.kind, ActiveStrokeKind::ColorMixingStamp) {
                self.renderer.begin_natural_paint_stroke(
                    &active.doc_id,
                    &active.layer_id,
                    doc_w,
                    doc_h,
                    active.brush.clone(),
                );
                self.renderer
                    .set_natural_paint_stroke_rand_offset(p_emitter.stroke_grain_offset);
                if !p_dabs.is_empty() || !s_dabs.is_empty() {
                    let newly_touched = {
                        let mgr = self.documents.read();
                        let scratch = Arc::clone(mgr.scratch_backend());
                        if let Some(doc) = mgr.get_document(&active.doc_id) {
                            if let Some(layer) = doc.layer(&active.layer_id) {
                                self.renderer
                                    .dispatch_color_mixing_dabs_with_secondary(
                                        doc,
                                        layer,
                                        &p_dabs,
                                        &s_dabs,
                                        Some(scratch.as_ref()),
                                    )
                                    .0
                            } else {
                                Vec::new()
                            }
                        } else {
                            Vec::new()
                        }
                    };
                    self.perf_counters
                        .stamp_dispatches
                        .fetch_add(1, Ordering::Relaxed);
                    self.capture_cow_before_tiles(&mut active, &newly_touched);
                }
            } else {
                self.renderer.begin_gpu_stroke(
                    doc_w,
                    doc_h,
                    active.mono_layer,
                    active.brush.clone(),
                    p_emitter.stroke_grain_offset,
                );
                if !p_dabs.is_empty() || !s_dabs.is_empty() {
                    let newly_touched = self.renderer.stamp_gpu_stroke_dabs(&p_dabs, &s_dabs);
                    self.perf_counters
                        .stamp_dispatches
                        .fetch_add(1, Ordering::Relaxed);
                    self.capture_cow_before_tiles(&mut active, &newly_touched);
                }
            }
        } else {
            if !step.sealed_segments.is_empty() {
                self.accumulate_stroke_step(&mut active, None, &step.sealed_segments);
            }
            // Flush all accumulated move dabs + trailing segments (+ ribbon finish) in ONE dispatch
            self.flush_pending_stroke_batch_for(&mut active, true);
        }

        // Handle Select Pen / Select Eraser strokes directly onto Document::selection!
        if active.is_selection_stroke {
            let alpha_tiles = match self.renderer.readback_stroke_alpha_tiles() {
                Ok(t) => t,
                Err(err) => {
                    eprintln!("[ink-engine] selection brush readback failed: {err}");
                    self.renderer.clear_live_stroke();
                    return;
                }
            };
            self.renderer.clear_live_stroke();
            let sel_snap = {
                let mut mgr = self.documents.write();
                if let Some(doc) = mgr.get_document_mut(&active.doc_id) {
                    let mask = doc.selection.get_or_insert_with(|| {
                        crate::selection::SparseSelectionMask::new_empty(
                            doc.dimensions.width,
                            doc.dimensions.height,
                        )
                    });
                    // Scale alpha back up since preview stroke used opacity 0.55
                    let scaled_tiles: Vec<(TileCoord, Vec<u8>)> = alpha_tiles
                        .into_iter()
                        .map(|(c, mut a)| {
                            for v in &mut a {
                                *v = ((*v as f32 / 0.55).round().clamp(0.0, 255.0)) as u8;
                            }
                            (c, a)
                        })
                        .collect();
                    mask.apply_alpha_tiles(&scaled_tiles, active.is_selection_erase);
                    let snap = mask.snapshot_meta();
                    if mask.is_empty() {
                        doc.selection = None;
                    }
                    doc.dirty_for_render = true;
                    Some(snap)
                } else {
                    None
                }
            };
            self.frame_dirty_doc_bounds = None;
            self.dirty = true;
            if let Some(selection) = sel_snap {
                let _ = self.event_tx.try_send(EngineEvent::SelectionChanged {
                    doc_id: active.doc_id,
                    selection,
                });
            }
            return;
        }

        // Step A: Snapshot minimal read-only metadata / touched base Arc<TileData> refs under a
        // microsecond read lock, then release ALL document locks BEFORE GPU commit + poll!
        enum PreCommitInput {
            NaturalPaint {
                scratch: Arc<dyn ScratchBackend>,
                mono_thresh: u8,
                doc_rect: RectI32,
            },
            Mask {
                scratch: Arc<dyn ScratchBackend>,
                mask_tiles: HashMap<TileCoord, Arc<TileData>>,
                touched_coords: Vec<TileCoord>,
                mask_default_value: u8,
            },
            Raster {
                scratch: Arc<dyn ScratchBackend>,
                alpha_locked: bool,
                mono_thresh: u8,
                doc_selection: Option<crate::selection::SparseSelectionMask>,
                base_subset: SparseLayerGrid,
            },
        }

        let pre_input = {
            let mgr = self.documents.read();
            let scratch = Arc::clone(mgr.scratch_backend());
            let Some(doc) = mgr.get_document(&active.doc_id) else {
                self.renderer.clear_live_stroke();
                return;
            };
            let Some(layer) = doc.layer(&active.layer_id) else {
                self.renderer.clear_live_stroke();
                return;
            };
            let is_editable =
                (active.is_mask_stroke || layer.meta.layer_type.has_tiles()) && !layer.meta.locked;
            if !is_editable {
                self.renderer.clear_live_stroke();
                self.dirty = true;
                return;
            }
            let alpha_locked = layer.meta.alpha_locked.unwrap_or(false);
            let mono_thresh = layer.meta.mono_threshold.unwrap_or(128);
            let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);

            if is_natural_or_cmix {
                PreCommitInput::NaturalPaint {
                    scratch,
                    mono_thresh,
                    doc_rect,
                }
            } else if active.is_mask_stroke {
                // O(touched) snapshot of ONLY mask tiles touched by this stroke (never clone/unpack entire mask grid!)
                let touched_coords = self.renderer.touched_stroke_coords();
                let mut mask_tiles = HashMap::with_capacity(touched_coords.len());
                for &coord in &touched_coords {
                    if let Some(tile_arc) = layer.grid.mask_tiles.get(&coord) {
                        mask_tiles.insert(coord, Arc::clone(tile_arc));
                    }
                }
                PreCommitInput::Mask {
                    scratch,
                    mask_tiles,
                    touched_coords,
                    mask_default_value: layer.grid.mask_default_value,
                }
            } else {
                // O(touched) Arc::clone of ONLY base tiles touched by this stroke (zero pixel copies!)
                let mut base_subset = SparseLayerGrid::new(layer.grid.format);
                for coord in self.renderer.touched_stroke_coords() {
                    if let Some(tile_arc) = layer.grid.tiles.get(&coord) {
                        base_subset.tiles.insert(coord, Arc::clone(tile_arc));
                    }
                }
                PreCommitInput::Raster {
                    scratch,
                    alpha_locked,
                    mono_thresh,
                    doc_selection: doc.selection.clone(),
                    base_subset,
                }
            }
        };

        // Execute GPU commit + staging readback completely OUTSIDE documents.write()!
        enum GpuCommitResult {
            NaturalPaint {
                batch: crate::natural_paint::CommittedNaturalPaintBatch,
                scratch: Arc<dyn ScratchBackend>,
                mono_thresh: u8,
                doc_rect: RectI32,
            },
            Mask {
                batch: crate::brush::CommittedTileBatch,
                scratch: Arc<dyn ScratchBackend>,
            },
            Raster {
                batch: crate::brush::CommittedTileBatch,
                scratch: Arc<dyn ScratchBackend>,
                mono_thresh: u8,
            },
        }

        let gpu_commit = match pre_input {
            PreCommitInput::NaturalPaint {
                scratch,
                mono_thresh,
                doc_rect,
            } => match self.renderer.commit_natural_paint_to_layer() {
                Ok(batch) => GpuCommitResult::NaturalPaint {
                    batch,
                    scratch,
                    mono_thresh,
                    doc_rect,
                },
                Err(err) => {
                    eprintln!("[ink-engine] GPU natural paint commit failed: {err}");
                    self.renderer.clear_live_stroke();
                    return;
                }
            },
            PreCommitInput::Mask {
                scratch,
                mask_tiles,
                touched_coords,
                mask_default_value,
            } => {
                // Build temporary RGBA base grid ONLY for mask tiles touched by this stroke off the doc lock
                let mut mask_base = SparseLayerGrid::new(TileFormat::Color32Bit);
                for (&c, t) in &mask_tiles {
                    if let Ok(rgba) = t.to_rgba8(Some(scratch.as_ref()), false) {
                        mask_base.set_tile(
                            c,
                            Arc::new(TileData::from_raw_auto_compact(
                                TileFormat::Color32Bit,
                                TileKind::Raster,
                                rgba,
                            )),
                        );
                    }
                }
                for &c in touched_coords
                    .iter()
                    .chain(active.before_mask_tiles.keys())
                {
                    mask_base.tiles.entry(c).or_insert_with(|| {
                        Arc::new(TileData::new_solid(
                            TileFormat::Color32Bit,
                            TileKind::Raster,
                            [mask_default_value, mask_default_value, mask_default_value, 255],
                        ))
                    });
                }
                let mask_tmp_id = format!("{}__mask_tmp", active.layer_id);
                let commit_res = self.renderer.commit_gpu_stroke_to_layer(
                    &active.doc_id,
                    &mask_tmp_id,
                    &mask_base,
                    Some(scratch.as_ref()),
                    false,
                    false,
                );
                // Always evict temporary `__mask_tmp` VRAM slots immediately after commit so VRAM never leaks!
                self.renderer
                    .invalidate_layer_tiles(&active.doc_id, &mask_tmp_id);
                match commit_res {
                    Ok(batch) => GpuCommitResult::Mask { batch, scratch },
                    Err(err) => {
                        eprintln!("[ink-engine] GPU mask stroke commit failed: {err}");
                        self.renderer.clear_live_stroke();
                        return;
                    }
                }
            }
            PreCommitInput::Raster {
                scratch,
                alpha_locked,
                mono_thresh,
                doc_selection,
                base_subset,
            } => match self.renderer.commit_gpu_stroke_to_layer_with_selection(
                &active.doc_id,
                &active.layer_id,
                &base_subset,
                doc_selection.as_ref(),
                Some(scratch.as_ref()),
                alpha_locked,
                active.mono_layer,
            ) {
                Ok(batch) => GpuCommitResult::Raster {
                    batch,
                    scratch,
                    mono_thresh,
                },
                Err(err) => {
                    eprintln!("[ink-engine] GPU stroke commit failed: {err}");
                    self.renderer.clear_live_stroke();
                    return;
                }
            },
        };

        // Step B: Tight, microsecond documents.write() lock ONLY for applying committed tiles,
        // recording CoW history deltas, draining dirty LOD coords, and taking a zero-copy
        // Arc<TileData> snapshot for off-thread PNG thumbnail encoding!
        struct PostCommitWork {
            doc_id: String,
            layer_id: String,
            entry_id: Option<String>,
            dirty_rect: RectI32,
            history: crate::history::HistoryStateSnapshot,
            mask_changed: bool,
            dirty_lods: [Vec<TileCoord>; 3],
            cleared_coords: Vec<TileCoord>,
            scratch: Arc<dyn ScratchBackend>,
            thumb_job: ThumbnailJob,
        }

        let post_work: Option<PostCommitWork> = {
            let mut mgr = self.documents.write();
            let Some(doc) = mgr.get_document_mut(&active.doc_id) else {
                self.renderer.clear_live_stroke();
                return;
            };
            let doc_w = doc.dimensions.width;
            let doc_h = doc.dimensions.height;
            let Some(layer) = doc.layer_mut(&active.layer_id) else {
                self.renderer.clear_live_stroke();
                return;
            };

            let (deltas, dirty_rect, mask_changed, cleared_coords, dirty_lods, scratch) =
                match gpu_commit {
                    GpuCommitResult::NaturalPaint {
                        batch,
                        scratch,
                        mono_thresh,
                        doc_rect,
                    } => {
                        let mut drect = RectI32::empty();
                        for &(c, _, _) in &batch.color_tiles {
                            drect = drect.union(RectI32::new(
                                c.tx * TILE_SIZE as i32,
                                c.ty * TILE_SIZE as i32,
                                TILE_SIZE as u32,
                                TILE_SIZE as u32,
                            ));
                        }
                        let (mut all_deltas, cleared) = layer.grid.apply_gpu_committed_tiles(
                            &active.layer_id,
                            batch.color_tiles,
                            &active.before_tiles,
                            mono_thresh,
                        );
                        if !batch.impasto_tiles.is_empty() {
                            let before_imp = match &active.kind {
                                ActiveStrokeKind::NaturalPaint {
                                    before_impasto_tiles,
                                    ..
                                } => before_impasto_tiles,
                                _ => &active.before_tiles,
                            };
                            let (imp_deltas, _) = layer.grid.apply_gpu_committed_impasto_tiles(
                                &active.layer_id,
                                batch.impasto_tiles,
                                before_imp,
                            );
                            all_deltas.extend(imp_deltas);
                            if let Some(light) = active.brush.impasto_layer_light() {
                                layer.meta.impasto_light = Some(light);
                            }
                        }
                        let dlods = [
                            layer.grid.dirty_lods[0].drain().collect(),
                            layer.grid.dirty_lods[1].drain().collect(),
                            layer.grid.dirty_lods[2].drain().collect(),
                        ];
                        (
                            all_deltas,
                            drect.intersect(doc_rect),
                            false,
                            cleared,
                            dlods,
                            scratch,
                        )
                    }
                    GpuCommitResult::Mask { batch, scratch } => {
                        let (mask_deltas, _) = layer.grid.apply_gpu_committed_mask_tiles(
                            &active.layer_id,
                            batch.tiles,
                            &active.before_mask_tiles,
                        );
                        layer.meta.mask_version = Some(layer.grid.mask_version);
                        (
                            mask_deltas,
                            batch.dirty_rect,
                            true,
                            Vec::new(),
                            [Vec::new(), Vec::new(), Vec::new()],
                            scratch,
                        )
                    }
                    GpuCommitResult::Raster {
                        batch,
                        scratch,
                        mono_thresh,
                    } => {
                        let drect = batch.dirty_rect;
                        let (deltas, cleared) = layer.grid.apply_gpu_committed_tiles(
                            &active.layer_id,
                            batch.tiles,
                            &active.before_tiles,
                            mono_thresh,
                        );
                        let dlods = [
                            layer.grid.dirty_lods[0].drain().collect(),
                            layer.grid.dirty_lods[1].drain().collect(),
                            layer.grid.dirty_lods[2].drain().collect(),
                        ];
                        (deltas, drect, false, cleared, dlods, scratch)
                    }
                };

            if deltas.is_empty() {
                None
            } else {
                // Zero-copy O(N) Arc<TileData> snapshot for background thumbnail worker!
                let thumb_job = ThumbnailJob {
                    doc_id: active.doc_id.clone(),
                    layer_id: active.layer_id.clone(),
                    doc_w,
                    doc_h,
                    layer_version: layer.grid.layer_version,
                    is_mask: mask_changed,
                    tiles: if mask_changed {
                        layer.grid.mask_tiles.clone()
                    } else {
                        layer.grid.tiles.clone()
                    },
                    mask_default_value: layer.grid.mask_default_value,
                    tint: if mask_changed {
                        None
                    } else {
                        crate::io::compositor_cpu::extract_layer_tint(layer)
                    },
                    scratch: Arc::clone(&scratch),
                };

                let is_eraser = active.brush.is_effective_eraser();
                let (action_type, label) = if mask_changed {
                    ("mask", "Mask Stroke")
                } else if is_eraser {
                    ("erase", "Erase")
                } else {
                    ("brush", "Brush Stroke")
                };
                let entry_id = doc.record_stroke_deltas(
                    &active.layer_id,
                    action_type,
                    label,
                    deltas,
                    Some("local".to_string()),
                    Some(format!("stroke-{}", active.stroke_seed)),
                );
                let history = doc.history.snapshot();
                self.sync_viewport_frustum_locked(&mut mgr);
                let _ = mgr.enforce_memory_budget();

                Some(PostCommitWork {
                    doc_id: active.doc_id,
                    layer_id: active.layer_id,
                    entry_id,
                    dirty_rect,
                    history,
                    mask_changed,
                    dirty_lods,
                    cleared_coords,
                    scratch,
                    thumb_job,
                })
            }
        };

        // Step C: Outside documents.write() — batch mipmaps (1 submit!), clear live stroke,
        // dispatch off-thread thumbnail job (ZERO render-thread PNG encoding!), and emit events!
        self.frame_dirty_doc_bounds = None;

        if let Some(work) = post_work {
            if work.mask_changed {
                self.renderer.invalidate_compositor_cache();
                self.pending_doc_sync = true;
            } else {
                let mgr = self.documents.read();
                if let Some(doc) = mgr.get_document(&work.doc_id) {
                    if let Some(layer) = doc.layer(&work.layer_id) {
                        self.renderer.regenerate_layer_mipmaps_from_dirty(
                            &work.doc_id,
                            &work.layer_id,
                            &layer.grid,
                            &work.dirty_lods,
                            &work.cleared_coords,
                            Some(work.scratch.as_ref()),
                        );
                    }
                }
            }
            self.renderer.clear_live_stroke();
            *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();
            self.dirty = true;

            // Offload PNG thumbnail generation to dedicated background worker thread
            if let Some(ref tx) = self.thumb_tx {
                let _ = tx.send(work.thumb_job);
            }

            let committed_pts: Vec<CommittedStrokePoint> = if self.collab_points_enabled {
                finalized_points
                    .into_iter()
                    .map(CommittedStrokePoint::from)
                    .collect()
            } else {
                Vec::new()
            };
            if let Some(eid) = work.entry_id {
                let _ = self.event_tx.try_send(EngineEvent::StrokeCommitted {
                    doc_id: work.doc_id,
                    layer_id: work.layer_id,
                    entry_id: eid,
                    dirty_rect: work.dirty_rect,
                    history: work.history,
                    points: committed_pts,
                });
            } else {
                let _ = self.event_tx.try_send(EngineEvent::HistoryChanged {
                    doc_id: work.doc_id,
                    history: work.history,
                });
            }
        } else {
            self.renderer.clear_live_stroke();
            self.dirty = true;
        }
    }

    /// Generates ephemeral predicted-head dabs for ALL brush types (`Stamp`, `ColorMixingStamp`,
    /// `NaturalPaint`, and `Ribbon`) WITHOUT mutating active stroke state or PRNG.
    fn build_ephemeral_predicted_dabs(&self) -> Vec<GpuBrushDab> {
        let Some(ref active) = self.active_gpu_stroke else {
            return Vec::new();
        };
        let is_direct_replace = matches!(
            active.kind,
            ActiveStrokeKind::NaturalPaint { .. } | ActiveStrokeKind::ColorMixingStamp
        );
        // Pure smear brushes pick up canvas pigment rather than depositing fg_color; skip fg preview
        if is_direct_replace
            && active.brush.mixing_mode == crate::brush::NaturalMixingMode::Smear
        {
            return Vec::new();
        }
        let pred_segs = self.stroke_pipeline.build_predicted_head();
        if pred_segs.is_empty() {
            return Vec::new();
        }
        let mut temp_emitter = active.primary_emitter.clone();
        let mut out = Vec::with_capacity(32);
        for seg in &pred_segs {
            temp_emitter.emit_segment(seg, None, 0.0, &mut out);
            if out.len() >= 48 {
                out.truncate(48);
                break;
            }
        }
        // Keep predicted head lightweight and visually matched on NaturalPaint / ColorMixingStamp
        if is_direct_replace {
            let paint_scale = (active.brush.opacity.clamp(0.05, 1.0)
                * active.brush.density_of_paint.clamp(0.15, 1.0)
                * (0.35 + 0.65 * active.brush.amount_of_paint.clamp(0.0, 1.0)))
            .clamp(0.08, 0.92);
            for dab in &mut out {
                dab.color_rgba[3] = (dab.color_rgba[3] * paint_scale).clamp(0.02, 0.92);
            }
        }
        out
    }

    fn run_loop(&mut self) {
        while self.running.load(Ordering::Relaxed) {
            if !self.renderer.is_present() {
                self.recover_from_device_lost();
                continue;
            }
            if !self.drain_commands() {
                break;
            }
            self.sync_active_document_if_needed();
            // Drain nav gestures BEFORE tablet rings so Space+Drag / Middle-Button nav
            // activates and commits any prior stroke before concurrent stylus packets in the same frame.
            if !self.drain_nav_ring() {
                break;
            }
            if !self.drain_tablet_rings() {
                break;
            }
            self.flush_pending_stroke_batch();
            self.sync_active_document_if_needed();

            let now = clock::now_ms();

            // Smoothly animate GPU marching ants (~30 Hz) ONLY when a selection is active & visible
            let has_active_sel = self.visible
                && self
                    .documents
                    .read()
                    .active_document()
                    .is_some_and(|d| d.selection.as_ref().is_some_and(|s| !s.is_empty()));
            if has_active_sel {
                self.dirty = true;
            }

            let can_render =
                self.visible && self.viewport.width_px > 0 && self.viewport.height_px > 0;
            if self.dirty && can_render {
                self.render_and_present(now);
            } else {
                if !self.legacy_pending_dabs.is_empty() {
                    self.legacy_pending_dabs.clear();
                }
                if !self.dirty || !can_render {
                    // Prevent stale non-rendering hover/out-of-viewport timestamps from polluting
                    // the next active stroke frame's input-to-present latency (I2P).
                    self.newest_input_timestamp_ms = 0.0;
                }
            }

            self.flush_throttled_events(clock::now_ms());

            // Drain at most ONE deferred offscreen readback (Brush Preview / Navigator / Timelapse)
            // only when no live stroke is in progress so live drawing is never stalled.
            if !self.is_any_stroke_active() {
                if let Some(deferred) = self.deferred_readback_cmds.pop_front() {
                    self.execute_readback_command(deferred);
                }
            }

            let pending_render = self.dirty && can_render;
            let has_stashed_inputs =
                !self.merged_samples.is_empty() || !self.stashed_nav_events.is_empty();
            let has_deferred_readback =
                !self.deferred_readback_cmds.is_empty() && !self.is_any_stroke_active();
            if has_deferred_readback || has_stashed_inputs {
                // Immediately continue next iteration without sleeping
            } else if has_active_sel && !pending_render {
                self.wake.wait_timeout(Duration::from_millis(33));
            } else if !pending_render
                && !self.pending_camera_emit
                && !self.pending_camera_commit
                && self.pending_wheel_commit_deadline_ms.is_none()
            {
                self.wake.wait_timeout(Duration::from_millis(50));
            } else if !pending_render && self.pending_wheel_commit_deadline_ms.is_some() {
                self.wake.wait_timeout(Duration::from_millis(16));
            } else if !pending_render {
                self.wake.wait_timeout(Duration::from_millis(8));
            }
        }
        self.stroke_active.store(false, Ordering::SeqCst);
        self.running.store(false, Ordering::SeqCst);
        self.deferred_readback_cmds.clear();
        // Gracefully drain & stop the background thumbnail worker thread on engine shutdown
        self.thumb_tx.take();
        if let Some(worker) = self.thumb_worker.take() {
            let _ = worker.join();
        }
    }

    fn execute_readback_command(&mut self, cmd: EngineCommand) {
        match cmd {
            EngineCommand::RenderDocumentFlattened {
                doc_id,
                options,
                reply,
            } => {
                // Take a microsecond zero-copy Arc<TileData> snapshot under docs.read() and
                // drop the read guard BEFORE GPU flattening & readback!
                let snap_res = {
                    let mgr = self.documents.read();
                    let scratch = Arc::clone(mgr.scratch_backend());
                    let doc_opt = match doc_id.as_deref() {
                        Some(id) => mgr.get_document(id),
                        None => mgr.active_document(),
                    };
                    match doc_opt {
                        Some(doc) => Ok((doc.clone_cow_snapshot(), scratch)),
                        None => Err("No active document available for GPU flatten".to_string()),
                    }
                };
                let res = match snap_res {
                    Ok((snapshot, scratch)) => self.renderer.render_document_flattened(
                        &snapshot,
                        Some(scratch.as_ref()),
                        &options,
                    ),
                    Err(e) => Err(e),
                };
                let _ = reply.send(res);
            }
            EngineCommand::RenderLayerThumbnail {
                doc_id,
                layer_id,
                max_dim,
                reply,
            } => {
                let snap_res = {
                    let mgr = self.documents.read();
                    let scratch = Arc::clone(mgr.scratch_backend());
                    let doc_opt = match doc_id.as_deref() {
                        Some(id) => mgr.get_document(id),
                        None => mgr.active_document(),
                    };
                    match doc_opt {
                        Some(doc) => Ok((doc.clone_cow_snapshot(), scratch)),
                        None => Err("No active document available for GPU thumbnail".to_string()),
                    }
                };
                let res = match snap_res {
                    Ok((snapshot, scratch)) => self.renderer.render_layer_thumbnail_gpu(
                        &snapshot,
                        &layer_id,
                        Some(scratch.as_ref()),
                        max_dim,
                    ),
                    Err(e) => Err(e),
                };
                let _ = reply.send(res);
            }
            EngineCommand::RenderBrushPreview {
                brush,
                width,
                height,
                reply,
            } => {
                let res = self
                    .renderer
                    .render_brush_preview_rgba8(&brush, width, height);
                let _ = reply.send(res);
            }
            EngineCommand::RenderScratchpadPreview {
                brush,
                strokes,
                width,
                height,
                reply,
            } => {
                let res = self.renderer.render_scratchpad_preview_rgba8(
                    &brush,
                    &strokes,
                    width,
                    height,
                    &self.global_pressure_curve,
                    self.global_pressure_lut.as_ref(),
                );
                let _ = reply.send(res);
            }
            _ => {}
        }
    }

    fn drain_commands(&mut self) -> bool {
        while let Ok(cmd) = self.cmd_rx.try_recv() {
            match cmd {
                EngineCommand::SetViewport(vp) => {
                    if self.viewport != vp {
                        self.viewport = vp;
                        self.viewport_commit_pending = true;
                        self.sync_viewport_frustum();
                        self.dirty = true;
                    }
                }
                EngineCommand::SetOccludedRects(_) => {
                    if let Some((lx, ly)) = self.cursor_local_phys {
                        let px = lx + self.viewport.x_px as f32;
                        let py = ly + self.viewport.y_px as f32;
                        let occluded = !self.hit_test.is_unoccluded_canvas_point(px, py);
                        if occluded != self.cursor_over_occluded {
                            self.cursor_over_occluded = occluded;
                            self.dirty = true;
                        }
                    }
                }
                EngineCommand::SetDocumentSize {
                    width,
                    height,
                    show_checkerboard,
                } => {
                    self.show_checkerboard = show_checkerboard;
                    self.display_config.show_checkerboard = show_checkerboard;
                    self.cancel_active_stroke();
                    self.renderer.invalidate_compositor_cache();
                    let has_active_doc = self.documents.read().active_document().is_some();
                    if has_active_doc {
                        self.pending_doc_sync = true;
                    } else {
                        self.renderer.set_document_size(width, height);
                    }
                    self.active_stroke_dabs = 0;
                    self.dirty = true;
                }
                EngineCommand::SetShowCheckerboard(show) => {
                    if self.show_checkerboard != show {
                        self.show_checkerboard = show;
                        self.display_config.show_checkerboard = show;
                        self.dirty = true;
                    }
                }
                EngineCommand::SetMatteColor(color) => {
                    if self.matte_color != color {
                        self.matte_color = color;
                        self.display_config.matte_color = color;
                        self.dirty = true;
                    }
                }
                EngineCommand::SetDisplayConfig(cfg) => {
                    if self.display_config != cfg {
                        self.show_checkerboard = cfg.show_checkerboard;
                        self.matte_color = cfg.matte_color;
                        self.display_config = cfg;
                        self.dirty = true;
                    }
                }
                EngineCommand::InvalidateCompositorCache => {
                    self.renderer.invalidate_compositor_cache();
                    self.dirty = true;
                }
                cmd @ EngineCommand::RenderDocumentFlattened { .. }
                | cmd @ EngineCommand::RenderLayerThumbnail { .. } => {
                    if self.is_any_stroke_active() {
                        self.deferred_readback_cmds.push_back(cmd);
                    } else {
                        self.execute_readback_command(cmd);
                    }
                }
                EngineCommand::SetCamera(cam) => {
                    // Never allow an in-flight async JS camera echo to snap `self.camera`
                    // backward while the native 120-240 Hz navigator actively owns a gesture.
                    if self.navigator.is_active() {
                        continue;
                    }
                    let sanitized = CameraState {
                        zoom: clamp_zoom(cam.zoom),
                        ..cam
                    };
                    if self.camera != sanitized {
                        self.camera = sanitized;
                        self.sync_viewport_frustum();
                        self.dirty = true;
                    }
                }
                EngineCommand::SetCursorConfig(cfg) => {
                    if self.cursor_cfg != cfg {
                        self.cursor_cfg = cfg;
                        self.dirty = true;
                    }
                }
                EngineCommand::SetBrushParams(params) => {
                    self.brush_params = params;
                    self.full_brush = NativeBrushConfig::from_basic_params(&params);
                    self.brush_pressure_lut = None;
                }
                EngineCommand::SetFullBrushConfig(cfg) => {
                    self.brush_pressure_lut = cfg
                        .pressure_curve
                        .as_ref()
                        .filter(|pts| pts.len() >= 2)
                        .map(|pts| CompiledCurveLut::compile(pts));
                    self.full_brush = *cfg;
                }
                EngineCommand::CleanDirtyBrush(preset_key) => {
                    self.renderer.clean_dirty_brush(preset_key.as_deref());
                }
                EngineCommand::SetMaskMode(enabled) => {
                    self.mask_mode = enabled;
                }
                cmd @ EngineCommand::RenderBrushPreview { .. }
                | cmd @ EngineCommand::RenderScratchpadPreview { .. } => {
                    if self.is_any_stroke_active() {
                        self.deferred_readback_cmds.push_back(cmd);
                    } else {
                        self.execute_readback_command(cmd);
                    }
                }
                EngineCommand::SetGlobalPressureCurve(curve) => {
                    self.global_pressure_lut = curve.compile_lut();
                    self.global_pressure_curve = curve;
                }
                EngineCommand::SetRulers {
                    straight,
                    perspective,
                } => {
                    self.straight_ruler = straight;
                    self.perspective_ruler = perspective;
                }
                EngineCommand::UploadBrushTexture {
                    hash,
                    kind,
                    is_png,
                    width,
                    height,
                    data,
                } => {
                    if let Err(err) = self
                        .renderer
                        .upload_brush_texture(hash, kind, is_png, width, height, data)
                    {
                        eprintln!("[ink-engine] upload_brush_texture failed: {err}");
                    }
                }
                EngineCommand::SetInteractionPolicy(policy) => {
                    let tool_changed = self.policy.active_tool != policy.active_tool;
                    self.policy = policy;
                    if (!policy.native_stroke_enabled
                        || !policy.active_tool.is_native_stroke_tool()
                        || policy.modal_open)
                        && self.is_any_stroke_active()
                    {
                        self.finish_and_commit_gpu_stroke(clock::now_ms());
                    }
                    if tool_changed || policy.modal_open {
                        self.dirty = true;
                    }
                }
                EngineCommand::SetVisible(vis) => {
                    if self.visible != vis {
                        self.visible = vis;
                        if !vis {
                            if self.is_any_stroke_active() {
                                self.finish_and_commit_gpu_stroke(clock::now_ms());
                            }
                            self.navigator.cancel();
                            self.stylus_nav_backend = 0;
                            self.cursor_local_phys = None;
                            self.newest_input_timestamp_ms = 0.0;
                        } else {
                            self.viewport_commit_pending = true;
                            self.dirty = true;
                        }
                    }
                }
                EngineCommand::ClearCanvas => {
                    self.cancel_active_stroke();
                    self.active_stroke_dabs = 0;
                    let cleared_info: Option<(String, crate::history::HistoryStateSnapshot)> = {
                        let mut mgr = self.documents.write();
                        if let Some(doc) = mgr.active_document_mut() {
                            if let Some(aid) = doc.active_layer_id.clone() {
                                let _ = doc.clear_layer(&aid, true);
                            }
                            Some((doc.id.clone(), doc.history.snapshot()))
                        } else {
                            None
                        }
                    };
                    if let Some((doc_id, history)) = cleared_info {
                        self.pending_doc_sync = true;
                        let _ = self.event_tx.try_send(EngineEvent::HistoryChanged {
                            doc_id,
                            history,
                        });
                    } else {
                        self.renderer.clear_canvas();
                    }
                    self.dirty = true;
                }
                EngineCommand::SyncActiveDocument => {
                    self.pending_doc_sync = true;
                    self.dirty = true;
                }
                EngineCommand::SetVramBudget(budget_bytes) => {
                    self.renderer.set_vram_budget(budget_bytes);
                    *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();
                    self.pending_doc_sync = true;
                }
                EngineCommand::FlushGpuPool => {
                    self.renderer.flush_gpu_pool();
                    *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();
                }
                EngineCommand::NotifySurfaceInvalidated => {
                    // Defer swapchain reconfigure until next frame (after any concurrent SetViewport
                    // updates dimensions) so minimize-restore and WM_DPICHANGED never reconfigure twice!
                    self.renderer.schedule_reconfigure();
                    self.viewport_commit_pending = true;
                    self.dirty = true;
                    let _ = self.event_tx.try_send(EngineEvent::ViewportInvalidated);
                }
                EngineCommand::LiquifyBegin {
                    multi_layer,
                    layer_ids,
                    reply,
                } => {
                    let res = {
                        let mgr = self.documents.read();
                        match mgr.active_document() {
                            Some(doc) => self.renderer.liquify_begin(
                                doc,
                                multi_layer,
                                layer_ids.as_deref(),
                            ),
                            None => Err("No active document".to_string()),
                        }
                    };
                    self.dirty = true;
                    let _ = reply.send(res);
                }
                EngineCommand::LiquifyStep { step, reply } => {
                    let res = {
                        let mgr = self.documents.read();
                        let scratch = Arc::clone(mgr.scratch_backend());
                        match mgr.active_document() {
                            Some(doc) => self.renderer.liquify_step(
                                doc,
                                Some(scratch.as_ref()),
                                step,
                            ),
                            None => Err("No active document".to_string()),
                        }
                    };
                    self.dirty = true;
                    let _ = reply.send(res);
                }
                EngineCommand::LiquifyCommit { reply } => {
                    let res = {
                        let mut mgr = self.documents.write();
                        let scratch = Arc::clone(mgr.scratch_backend());
                        match mgr.active_document_mut() {
                            Some(doc) => {
                                let r = self.renderer.liquify_commit(doc, Some(scratch.as_ref()));
                                if r.is_ok() {
                                    self.pending_doc_sync = true;
                                }
                                r
                            }
                            None => Err("No active document".to_string()),
                        }
                    };
                    self.dirty = true;
                    let _ = reply.send(res);
                }
                EngineCommand::LiquifyCancel => {
                    self.renderer.liquify_cancel();
                    self.dirty = true;
                }
                EngineCommand::TransformBegin {
                    mode,
                    layer_ids,
                    reply,
                } => {
                    let res = {
                        let mut mgr = self.documents.write();
                        let scratch = Arc::clone(mgr.scratch_backend());
                        match mgr.active_document_mut() {
                            Some(doc) => {
                                let r = self.renderer.transform_begin(
                                    doc,
                                    mode,
                                    layer_ids.as_deref(),
                                    Some(scratch.as_ref()),
                                );
                                if r.is_ok() {
                                    self.pending_doc_sync = true;
                                }
                                r
                            }
                            None => Err("No active document".to_string()),
                        }
                    };
                    self.dirty = true;
                    let _ = reply.send(res);
                }
                EngineCommand::TransformUpdate { payload, reply } => {
                    let res = self.renderer.transform_update(payload);
                    self.dirty = true;
                    let _ = reply.send(res);
                }
                EngineCommand::TransformSwitchMode { next_mode, reply } => {
                    let res = self.renderer.transform_switch_mode(next_mode);
                    self.dirty = true;
                    let _ = reply.send(res);
                }
                EngineCommand::TransformCommit { reply } => {
                    let res = {
                        let mut mgr = self.documents.write();
                        let scratch = Arc::clone(mgr.scratch_backend());
                        match mgr.active_document_mut() {
                            Some(doc) => {
                                let r = self.renderer.transform_commit(doc, Some(scratch.as_ref()));
                                if r.is_ok() {
                                    self.pending_doc_sync = true;
                                }
                                r
                            }
                            None => Err("No active document".to_string()),
                        }
                    };
                    self.dirty = true;
                    let _ = reply.send(res);
                }
                EngineCommand::TransformCancel => {
                    {
                        let mut mgr = self.documents.write();
                        self.renderer.transform_cancel(mgr.active_document_mut());
                    }
                    self.pending_doc_sync = true;
                    self.dirty = true;
                }
                EngineCommand::SetToolPreviewRgba8 {
                    rect,
                    rgba,
                    opacity,
                    replaced_layer_id,
                } => {
                    self.renderer
                        .set_tool_preview_rgba8(rect, &rgba, opacity, replaced_layer_id);
                    self.dirty = true;
                }
                EngineCommand::ClearToolPreview => {
                    self.renderer.clear_tool_preview();
                    self.dirty = true;
                }
                EngineCommand::RemoteStrokeStart(params) => {
                    self.renderer.remote_stroke_start(params);
                    self.dirty = true;
                }
                EngineCommand::RemoteStrokeChunk {
                    peer_id,
                    stroke_id,
                    points,
                } => {
                    self.renderer
                        .remote_stroke_chunk(&peer_id, &stroke_id, &points);
                    self.dirty = true;
                }
                EngineCommand::RemoteStrokeFinish {
                    peer_id,
                    stroke_id,
                    expected_tiles,
                } => {
                    self.renderer
                        .remote_stroke_finish(&peer_id, &stroke_id, expected_tiles);
                    self.dirty = true;
                }
                EngineCommand::RemoteStrokeDispose { peer_id, stroke_id } => {
                    self.renderer.remote_stroke_dispose(&peer_id, &stroke_id);
                    self.dirty = true;
                }
                EngineCommand::RemotePeerDispose { peer_id } => {
                    self.renderer.remote_peer_dispose(&peer_id);
                    self.dirty = true;
                }
                EngineCommand::RemoteNotifyTileDelta { layer_id } => {
                    self.renderer.remote_notify_tile_delta(&layer_id);
                    self.dirty = true;
                }
                EngineCommand::SetCollabPointsEnabled(enabled) => {
                    self.collab_points_enabled = enabled;
                }
                EngineCommand::Shutdown => {
                    return false;
                }
            }
        }
        true
    }

    fn drain_tablet_rings(&mut self) -> bool {
        self.drain_tablet_rings_inner(true)
    }

    fn drain_tablet_rings_inner(&mut self, allow_commands: bool) -> bool {
        if !allow_commands && !self.cmd_rx.is_empty() {
            return true;
        }
        while let Ok(s) = self.consumers.wintab.pop() {
            self.merged_samples.push(s);
        }
        while let Ok(s) = self.consumers.winink.pop() {
            self.merged_samples.push(s);
        }
        if self.merged_samples.is_empty() {
            return true;
        }
        // Release/Acquire barrier AFTER popping: any command (e.g. SetFullBrushConfig,
        // SetCamera, SetInteractionPolicy, SyncActiveDocument) sent before these samples were
        // pushed is now guaranteed visible in `cmd_rx`.
        if !self.cmd_rx.is_empty() {
            if !allow_commands {
                // Keep popped samples stashed in `self.merged_samples` for the next iteration
                // right after `drain_commands()` runs (never process ahead of pending commands!).
                return true;
            }
            if !self.drain_commands() {
                self.merged_samples.clear();
                return false;
            }
            self.sync_active_document_if_needed();
        }
        if self.merged_samples.len() > 1 {
            self.merged_samples.sort_by(|a, b| {
                a.timestamp_ms
                    .partial_cmp(&b.timestamp_ms)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
        }

        let mut samples = std::mem::take(&mut self.merged_samples);
        for sample in &samples {
            self.process_tablet_sample(*sample);
        }
        samples.clear();
        self.merged_samples = samples;
        true
    }

    fn process_tablet_sample(&mut self, sample: NativeInputSample) {
        if sample.backend == 1 || sample.backend == 2 {
            self.last_tablet_sample_ms = sample.timestamp_ms;
            if sample.backend == 1 {
                self.last_wintab_sample_ms = sample.timestamp_ms;
            }
        }
        if sample.phase == 1 {
            // Reset any prior hover timestamp cleanly on pen-down so I2P reflects genuine stroke latency
            self.newest_input_timestamp_ms = sample.timestamp_ms;
        } else if sample.phase != 4 && sample.timestamp_ms > self.newest_input_timestamp_ms {
            self.newest_input_timestamp_ms = sample.timestamp_ms;
        }

        if sample.phase == 4 {
            if self.stylus_nav_backend != 0 && self.stylus_nav_backend == sample.backend {
                self.stylus_nav_backend = 0;
                if self.navigator.end() {
                    self.pending_camera_emit = true;
                    self.pending_camera_commit = true;
                    self.dirty = true;
                }
            }
            if self.is_any_stroke_active()
                && (self.active_stroke_backend == 0 || self.active_stroke_backend == sample.backend)
            {
                self.finish_and_commit_gpu_stroke(sample.timestamp_ms);
            }
            if !self.is_any_stroke_active() {
                if self.cursor_local_phys.is_some() {
                    self.cursor_local_phys = None;
                    self.dirty = true;
                }
                self.newest_input_timestamp_ms = 0.0;
                self.latest_pointer_doc = None;
                self.latest_pointer_pressure = 0.0;
                self.pointer_stat_dirty = true;
            }
            return;
        }

        let in_unoccluded = self
            .hit_test
            .is_unoccluded_canvas_point(sample.phys_x, sample.phys_y);

        if self.viewport.contains_phys(sample.phys_x, sample.phys_y) {
            let local_phys = self.viewport.phys_to_local_phys(sample.phys_x, sample.phys_y);
            self.cursor_local_phys = Some(local_phys);
            self.cursor_over_occluded = !in_unoccluded;
            self.dirty = true;
        } else if self.cursor_local_phys.is_some() {
            self.cursor_local_phys = None;
            self.dirty = true;
        }

        let (local_css_x, local_css_y) =
            self.viewport.phys_to_local_css(sample.phys_x, sample.phys_y);
        let (doc_w, doc_h) = self.renderer.doc_size();
        let (doc_x, doc_y) = viewport_css_to_doc(
            local_css_x,
            local_css_y,
            doc_w as f32,
            doc_h as f32,
            &self.camera,
        );

        self.latest_pointer_doc = Some((doc_x.round() as i32, doc_y.round() as i32));
        self.latest_pointer_pressure = sample.pressure;
        self.pointer_stat_dirty = true;

        if self.stylus_nav_backend != 0 {
            if sample.backend != self.stylus_nav_backend {
                return;
            }
            match sample.phase {
                2 => {
                    let snap_15_deg = (sample.buttons & (0x0200 | 0x0800)) != 0;
                    if self.navigator.update(
                        local_css_x,
                        local_css_y,
                        snap_15_deg,
                        self.policy.is_webtoon_mode,
                        &mut self.camera,
                    ) {
                        self.dirty = true;
                        self.pending_camera_emit = true;
                    }
                }
                3 | 0 => {
                    self.stylus_nav_backend = 0;
                    if self.navigator.end() {
                        self.pending_camera_emit = true;
                        self.pending_camera_commit = true;
                        self.dirty = true;
                    }
                }
                _ => {}
            }
            return;
        }

        if self.navigator.is_active() {
            if self.is_any_stroke_active() {
                self.finish_and_commit_gpu_stroke(sample.timestamp_ms);
            }
            return;
        }

        let space_held = (sample.buttons & 0x0400) != 0 && !self.hit_test.text_input_focused();
        let ctrl_or_shift_with_alt =
            (sample.buttons & 0x0200) != 0 && (sample.buttons & (0x0100 | 0x0800)) != 0;

        match sample.phase {
            1 => {
                // Space + Stylus Drag -> native 120-240 Hz Pan / Shift+Rotate / Ctrl+ZoomDrag
                if space_held && !ctrl_or_shift_with_alt {
                    if (sample.backend == 1 || sample.backend == 2)
                        && self
                            .hit_test
                            .should_capture_native_nav(sample.phys_x, sample.phys_y)
                    {
                        if self.is_any_stroke_active() {
                            self.finish_and_commit_gpu_stroke(sample.timestamp_ms);
                        }
                        let gesture = if (sample.buttons & 0x0800) != 0 {
                            crate::types::NativeNavGesture::ZoomDrag
                        } else if (sample.buttons & 0x0100) != 0 {
                            crate::types::NativeNavGesture::Rotate
                        } else {
                            crate::types::NativeNavGesture::Pan
                        };
                        self.navigator.begin(
                            gesture,
                            local_css_x,
                            local_css_y,
                            self.viewport.css_width(),
                            self.viewport.css_height(),
                            &self.camera,
                        );
                        self.stylus_nav_backend = sample.backend;
                        self.dirty = true;
                    }
                    return;
                }
                // Never start a brush stroke while Ctrl/Shift+Alt brush resize is held
                if ctrl_or_shift_with_alt {
                    return;
                }
                // Never let a stray mouse down interrupt an active stylus stroke
                if sample.backend == 3
                    && self.is_any_stroke_active()
                    && (self.active_stroke_backend == 1 || self.active_stroke_backend == 2)
                {
                    return;
                }
                if self
                    .hit_test
                    .should_capture_native_stroke(sample.phys_x, sample.phys_y)
                {
                    // Cleanly commit any previous active stroke (e.g. Mouse -> Stylus handoff)
                    // before beginning the new stroke so no stroke or CoW undo entry is ever dropped.
                    if self.is_any_stroke_active() {
                        self.finish_and_commit_gpu_stroke(sample.timestamp_ms);
                    }
                    self.begin_native_gpu_stroke(doc_x as f64, doc_y as f64, sample);
                    self.active_stroke_backend = if self.is_any_stroke_active() {
                        sample.backend
                    } else {
                        0
                    };
                }
            }
            2 => {
                if self.is_any_stroke_active()
                    && (self.active_stroke_backend == 0
                        || self.active_stroke_backend == sample.backend)
                {
                    self.push_native_gpu_stroke_move(doc_x as f64, doc_y as f64, sample);
                }
            }
            3 => {
                if self.is_any_stroke_active()
                    && (self.active_stroke_backend == 0
                        || self.active_stroke_backend == sample.backend)
                {
                    self.finish_and_commit_gpu_stroke(sample.timestamp_ms);
                }
            }
            _ => {}
        }
    }

    fn drain_nav_ring(&mut self) -> bool {
        self.drain_nav_ring_inner(true)
    }

    fn drain_nav_ring_inner(&mut self, allow_commands: bool) -> bool {
        loop {
            let evt = if let Some(stashed) = self.stashed_nav_events.pop_front() {
                stashed
            } else if let Ok(e) = self.consumers.nav.pop() {
                e
            } else {
                break;
            };
            if !self.cmd_rx.is_empty() {
                if !allow_commands {
                    self.stashed_nav_events.push_front(evt);
                    break;
                }
                if !self.drain_commands() {
                    return false;
                }
                self.sync_active_document_if_needed();
            }
            match evt {
                NativeNavEvent::Hover {
                    phys_x,
                    phys_y,
                    timestamp_ms,
                } => {
                    if timestamp_ms - self.last_tablet_sample_ms < 120.0 {
                        continue;
                    }
                    let in_vp = self.viewport.contains_phys(phys_x, phys_y);
                    let in_unoccluded = self.hit_test.is_unoccluded_canvas_point(phys_x, phys_y);
                    if in_vp {
                        if !self.is_any_stroke_active()
                            && timestamp_ms > self.newest_input_timestamp_ms
                        {
                            self.newest_input_timestamp_ms = timestamp_ms;
                        }
                        let local_phys = self.viewport.phys_to_local_phys(phys_x, phys_y);
                        self.cursor_local_phys = Some(local_phys);
                        self.cursor_over_occluded = !in_unoccluded;
                        let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);
                        let (doc_w, doc_h) = self.renderer.doc_size();
                        let (dx, dy) =
                            viewport_css_to_doc(lx, ly, doc_w as f32, doc_h as f32, &self.camera);
                        self.latest_pointer_doc = Some((dx.round() as i32, dy.round() as i32));
                        self.latest_pointer_pressure = 0.0;
                        self.pointer_stat_dirty = true;
                        self.dirty = true;
                    } else if self.cursor_local_phys.is_some() {
                        self.cursor_local_phys = None;
                        self.latest_pointer_doc = None;
                        self.pointer_stat_dirty = true;
                        self.dirty = true;
                    }
                }
                NativeNavEvent::HoverLeave => {
                    self.newest_input_timestamp_ms = 0.0;
                    if self.cursor_local_phys.is_some() {
                        self.cursor_local_phys = None;
                        self.latest_pointer_doc = None;
                        self.pointer_stat_dirty = true;
                        self.dirty = true;
                    }
                }
                NativeNavEvent::GestureStart {
                    gesture,
                    phys_x,
                    phys_y,
                    timestamp_ms,
                } => {
                    if timestamp_ms > self.newest_input_timestamp_ms {
                        self.newest_input_timestamp_ms = timestamp_ms;
                    }
                    if self.is_any_stroke_active() {
                        self.finish_and_commit_gpu_stroke(timestamp_ms);
                    }
                    let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);
                    self.stylus_nav_backend = 0;
                    self.navigator.begin(
                        gesture,
                        lx,
                        ly,
                        self.viewport.css_width(),
                        self.viewport.css_height(),
                        &self.camera,
                    );
                    self.dirty = true;
                }
                NativeNavEvent::GestureMove {
                    phys_x,
                    phys_y,
                    snap_15_deg,
                    timestamp_ms,
                } => {
                    if timestamp_ms > self.newest_input_timestamp_ms {
                        self.newest_input_timestamp_ms = timestamp_ms;
                    }
                    let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);
                    if self.navigator.update(
                        lx,
                        ly,
                        snap_15_deg,
                        self.policy.is_webtoon_mode,
                        &mut self.camera,
                    ) {
                        self.dirty = true;
                        self.pending_camera_emit = true;
                    }
                }
                NativeNavEvent::GestureEnd { timestamp_ms } => {
                    if timestamp_ms > self.newest_input_timestamp_ms {
                        self.newest_input_timestamp_ms = timestamp_ms;
                    }
                    self.stylus_nav_backend = 0;
                    if self.navigator.end() {
                        self.pending_camera_emit = true;
                        self.pending_camera_commit = true;
                        self.dirty = true;
                    }
                }
                NativeNavEvent::Wheel {
                    phys_x,
                    phys_y,
                    delta_x,
                    delta_y,
                    ctrl_held,
                    shift_held,
                    timestamp_ms,
                } => {
                    if timestamp_ms > self.newest_input_timestamp_ms {
                        self.newest_input_timestamp_ms = timestamp_ms;
                    }
                    // Commit any active stroke cleanly before camera zoom/scroll moves the canvas.
                    if self.is_any_stroke_active() {
                        self.finish_and_commit_gpu_stroke(timestamp_ms);
                    }
                    let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);
                    let changed = if (self.policy.wheel_mode == WheelNavMode::Scroll
                        || self.policy.is_webtoon_mode)
                        && !ctrl_held
                    {
                        NativeCameraNavigator::apply_wheel_scroll(
                            delta_x,
                            delta_y,
                            shift_held,
                            self.policy.is_webtoon_mode,
                            &mut self.camera,
                        )
                    } else {
                        NativeCameraNavigator::apply_wheel_zoom(lx, ly, delta_y, &mut self.camera)
                    };
                    if changed {
                        self.dirty = true;
                        self.pending_camera_emit = true;
                        // Debounce React state commit (~120ms after last wheel tick) so wheel
                        // zooming stays 120–240Hz without forcing App re-renders per notch.
                        self.pending_wheel_commit_deadline_ms = Some(clock::now_ms() + 120.0);
                    }
                }
                NativeNavEvent::MouseDraw {
                    phys_x,
                    phys_y,
                    phase,
                    shift_held,
                    timestamp_ms,
                } => {
                    // Never allow mouse events to interfere with an active stylus stroke.
                    if self.active_stroke_backend == 1 || self.active_stroke_backend == 2 {
                        continue;
                    }
                    // Always deliver move/up for an already-active mouse stroke so hover packets
                    // never drop drag/release; gate fresh mouse-down against recent stylus packets
                    // (both WinTab CXO_SYSTEM echo and Windows Ink) using the same 150ms window as `ll_mouse_proc`.
                    let is_active_mouse_continuation =
                        (phase == 2 || phase == 3) && self.active_stroke_backend == 3;
                    if !is_active_mouse_continuation
                        && (timestamp_ms - self.last_wintab_sample_ms < 150.0
                            || timestamp_ms - self.last_tablet_sample_ms < 150.0)
                    {
                        continue;
                    }
                    let mut buttons: u16 = if phase == 3 { 0 } else { 1 };
                    if shift_held {
                        buttons |= 0x0100;
                    }
                    self.process_tablet_sample(NativeInputSample {
                        phys_x,
                        phys_y,
                        pressure: if phase == 3 { 0.0 } else { 1.0 },
                        tilt_x: 0.0,
                        tilt_y: 0.0,
                        twist: 0.0,
                        timestamp_ms,
                        buttons,
                        phase,
                        backend: 3,
                    });
                }
            }
        }
        true
    }

    fn render_and_present(&mut self, _frame_start_ms: f64) {
        // Phase 7 Input-to-Photon optimization: acquire the DXGI swapchain surface texture
        // (waiting on the waitable frame latency object / VSync) BEFORE performing the final
        // non-blocking drain of pending nav/tablet rings + flushing stroke dabs so samples
        // arriving during VSync wait are rendered in the VERY NEXT scanout (-8..16.6 ms latency)!
        let acquired = match self.renderer.acquire_frame_target(&self.viewport) {
            Ok(frame) => frame,
            Err(outcome) => {
                match outcome {
                    RenderOutcome::Skipped => {
                        self.dirty = false;
                        self.newest_input_timestamp_ms = 0.0;
                    }
                    RenderOutcome::NeedsReconfigure => {
                        if !self.renderer.force_reconfigure() {
                            self.dirty = false;
                        }
                    }
                    RenderOutcome::DeviceLost => {
                        self.recover_from_device_lost();
                    }
                    RenderOutcome::Presented => {}
                }
                return;
            }
        };

        // Measure pure CPU+GPU frame render time starting right after VSync acquire
        let frame_start_ms = clock::now_ms();

        // Final non-blocking post-acquire drain (safe: skips cmd_rx so swapchain cannot reconfigure)
        if self.cmd_rx.is_empty() {
            let _ = self.drain_nav_ring_inner(false);
            let _ = self.drain_tablet_rings_inner(false);
            self.flush_pending_stroke_batch();
            self.sync_active_document_if_needed();
        }

        let cursor_suppressed =
            self.cursor_over_occluded || self.navigator.is_active() || self.policy.modal_open;
        let stroke_active = self.is_any_stroke_active();
        let is_mask_stroke = self
            .active_gpu_stroke
            .as_ref()
            .is_some_and(|s| s.is_mask_stroke);
        let dabs_are_eraser = self
            .active_gpu_stroke
            .as_ref()
            .map(|s| s.brush.is_effective_eraser())
            .unwrap_or_else(|| self.legacy_stroke_gen.stroke_is_eraser());
        let predicted_dabs = self.build_ephemeral_predicted_dabs();
        let dirty_doc_bounds = self.frame_dirty_doc_bounds.take();

        let outcome = {
            let mgr = self.documents.read();
            let scratch = Arc::clone(mgr.scratch_backend());
            if let Some(doc) = mgr.active_document() {
                self.renderer.render_document_frame_into_acquired(
                    acquired,
                    doc,
                    Some(scratch.as_ref()),
                    &self.display_config,
                    &self.viewport,
                    &self.camera,
                    &self.legacy_pending_dabs,
                    dabs_are_eraser,
                    stroke_active,
                    is_mask_stroke,
                    &predicted_dabs,
                    dirty_doc_bounds,
                    &self.cursor_cfg,
                    self.cursor_local_phys,
                    cursor_suppressed,
                )
            } else {
                self.renderer.render_frame_into_acquired(
                    acquired,
                    &self.viewport,
                    &self.camera,
                    self.show_checkerboard,
                    self.matte_color,
                    &self.legacy_pending_dabs,
                    dabs_are_eraser,
                    &self.cursor_cfg,
                    self.cursor_local_phys,
                    cursor_suppressed,
                )
            }
        };

        match outcome {
            RenderOutcome::Presented => {
                if self.viewport_commit_pending {
                    self.renderer.commit_surface_viewport();
                    self.viewport_commit_pending = false;
                }
                self.legacy_pending_dabs.clear();
                self.dirty = false;

                let after_ms = clock::now_ms();
                let frame_ms = (after_ms - frame_start_ms).max(0.01) as f32;
                self.ema_frame_time_ms = if self.ema_frame_time_ms <= 0.001 {
                    frame_ms
                } else {
                    self.ema_frame_time_ms * 0.8 + frame_ms * 0.2
                };

                if self.newest_input_timestamp_ms > 0.0 {
                    let lat = (after_ms - self.newest_input_timestamp_ms) as f32;
                    if (0.0..500.0).contains(&lat) {
                        self.ema_input_latency_ms = if self.ema_input_latency_ms <= 0.001 {
                            lat
                        } else {
                            self.ema_input_latency_ms * 0.75 + lat * 0.25
                        };
                    }
                    self.newest_input_timestamp_ms = 0.0;
                }

                self.total_frames = self.total_frames.saturating_add(1);

                // Track active frame intervals (< 150 ms apart) so on-demand idle sleeps never
                // divide 1–2 dirty frames by prior idle time and falsely report "3 FPS"!
                let throughput_fps =
                    (1000.0 / self.ema_frame_time_ms.max(0.5)).min(MAX_DISPLAY_FPS);
                if self.last_present_ms > 0.0 {
                    let dt_ms = after_ms - self.last_present_ms;
                    if dt_ms > 0.1 && dt_ms < ACTIVE_FRAME_GAP_THRESHOLD_MS {
                        self.ema_active_frame_interval_ms = if self.active_interval_count == 0 {
                            dt_ms as f32
                        } else {
                            self.ema_active_frame_interval_ms * 0.75 + (dt_ms as f32) * 0.25
                        };
                        self.active_interval_count = self.active_interval_count.saturating_add(1);

                        if self.active_interval_count >= 2 {
                            let cadence_fps = (1000.0
                                / self.ema_active_frame_interval_ms.max(0.5))
                            .min(MAX_DISPLAY_FPS);
                            // If frame render time itself is fast (< 16 ms) and intervals are sparse
                            // purely due to slow on-demand input arrival, report active throughput.
                            self.measured_fps =
                                if self.ema_frame_time_ms < 16.0 && cadence_fps < 30.0 {
                                    throughput_fps
                                } else {
                                    cadence_fps
                                };
                        } else {
                            // First 1-2 frames after an idle gap: derive cleanly from throughput
                            self.measured_fps = throughput_fps;
                        }
                    } else {
                        // Prior idle gap >= 150 ms: reset active interval tracker & use throughput
                        self.active_interval_count = 0;
                        self.ema_active_frame_interval_ms = 0.0;
                        self.measured_fps = throughput_fps;
                    }
                } else {
                    self.active_interval_count = 0;
                    self.ema_active_frame_interval_ms = 0.0;
                    self.measured_fps = throughput_fps;
                }
                self.last_present_ms = after_ms;

                // Keep shared_diag numeric counters fresh in-place (zero allocation, ~15ns)
                // so handle.diagnostics() reflects rendered frames immediately without IPC spam.
                let (sw, sh) = self.renderer.swapchain_size();
                let (dw, dh) = self.renderer.doc_size();
                if let Ok(mut g) = self.shared_diag.lock() {
                    g.ready = true;
                    g.fps = self.measured_fps;
                    g.frame_time_ms = self.ema_frame_time_ms;
                    g.input_to_present_ms = self.ema_input_latency_ms;
                    g.swapchain_width = sw;
                    g.swapchain_height = sh;
                    g.doc_width = dw;
                    g.doc_height = dh;
                    g.active_stroke_dabs = self.active_stroke_dabs;
                    g.total_frames_rendered = self.total_frames;
                    g.is_idle = false;
                }
            }
            RenderOutcome::Skipped => {
                self.dirty = false;
                self.newest_input_timestamp_ms = 0.0;
            }
            RenderOutcome::NeedsReconfigure => {
                if !self.renderer.force_reconfigure() {
                    // Surface is not configured yet (e.g. awaiting initial physical viewport);
                    // clear dirty so the render loop doesn't busy-spin until SetViewport arrives.
                    self.dirty = false;
                }
            }
            RenderOutcome::DeviceLost => {
                self.recover_from_device_lost();
            }
        }
    }

    fn recover_from_device_lost(&mut self) {
        // Extract recovery parameters and DROP the old GpuRenderer FIRST so DX12 frees
        // the old device, swapchain, tile pool, and compositor targets BEFORE constructing
        // the replacement (eliminating 2× peak VRAM spikes during recovery!).
        let (doc_w, doc_h, vram_budget, target) = if let Some(old) = self.renderer.0.take() {
            let (dw, dh) = old.doc_size();
            let vb = old.vram_budget_bytes();
            let tgt = old.surface_target_for_recovery();
            drop(old);
            (dw, dh, vb, tgt)
        } else if let Some(params) = self.pending_recovery.take() {
            params
        } else {
            return;
        };

        let target_retry = target.clone();
        match GpuRenderer::new_with_vram(target, doc_w, doc_h, vram_budget) {
            Ok(mut fresh) => {
                if self.viewport.width_px > 0 && self.viewport.height_px > 0 {
                    fresh.resize_surface(self.viewport.width_px, self.viewport.height_px);
                }
                self.renderer.0 = Some(fresh);
                *self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();
                self.device_lost_recoveries = self.device_lost_recoveries.saturating_add(1);
                self.cancel_active_stroke();
                self.pending_doc_sync = true;
                self.viewport_commit_pending = true;
                self.dirty = true;
            }
            Err(_) => {
                self.pending_recovery = Some((doc_w, doc_h, vram_budget, target_retry));
                std::thread::sleep(Duration::from_millis(100));
            }
        }
    }

    fn flush_throttled_events(&mut self, now_ms: f64) {
        if let Some(deadline_ms) = self.pending_wheel_commit_deadline_ms {
            if now_ms >= deadline_ms {
                self.pending_wheel_commit_deadline_ms = None;
                self.pending_camera_emit = true;
                self.pending_camera_commit = true;
            }
        }

        if self.pending_camera_emit
            && (self.pending_camera_commit || now_ms - self.last_camera_emit_ms >= 16.0)
        {
            let commit = self.pending_camera_commit;
            self.pending_camera_emit = false;
            self.pending_camera_commit = false;
            self.last_camera_emit_ms = now_ms;
            let evt = EngineEvent::CameraChanged {
                camera: self.camera,
                commit,
            };
            if commit {
                self.sync_viewport_frustum();
                let _ = self.event_tx.try_send(evt);
            } else {
                self.send_throttled_event(evt);
            }
        }

        if self.pointer_stat_dirty && now_ms - self.last_pointer_stat_ms >= 33.0 {
            self.pointer_stat_dirty = false;
            self.last_pointer_stat_ms = now_ms;
            let (doc_x, doc_y) = match self.latest_pointer_doc {
                Some((x, y)) => (Some(x), Some(y)),
                None => (None, None),
            };
            self.send_throttled_event(EngineEvent::PointerStat {
                doc_x,
                doc_y,
                pressure: self.latest_pointer_pressure,
            });
        }

        let is_idle = self.total_frames == 0
            || (self.last_present_ms > 0.0
                && now_ms - self.last_present_ms >= IDLE_DISPLAY_TIMEOUT_MS);
        let idle_changed = is_idle != self.was_idle_diag;
        if is_idle && !self.was_idle_diag && self.total_frames > 0 && !self.is_any_stroke_active() {
            // Reclaim oversized resize slack & unused nested compositor stacks once idle.
            self.renderer.trim_compositor_on_idle();
        }
        let should_emit_diag = now_ms - self.last_diag_emit_ms >= 250.0
            || (idle_changed && now_ms - self.last_diag_emit_ms >= 50.0);

        if should_emit_diag {
            self.last_diag_emit_ms = now_ms;
            self.was_idle_diag = is_idle;
            let fps = if self.total_frames == 0 {
                0.0
            } else {
                self.measured_fps
            };
            let (sw, sh) = self.renderer.swapchain_size();
            let (dw, dh) = self.renderer.doc_size();
            let pool_stats = self.renderer.gpu_pool_stats();
            let cache_stats = self.renderer.stack_cache_stats();
            *self.shared_pool_stats.write() = pool_stats;
            let diag = EngineDiagnostics {
                ready: true,
                adapter_name: self.renderer.adapter_name().to_string(),
                backend: "DX12".to_string(),
                present_mode: self.renderer.present_mode_label().to_string(),
                fps,
                frame_time_ms: self.ema_frame_time_ms,
                input_to_present_ms: self.ema_input_latency_ms,
                swapchain_width: sw,
                swapchain_height: sh,
                doc_width: dw,
                doc_height: dh,
                active_stroke_dabs: self.active_stroke_dabs,
                total_frames_rendered: self.total_frames,
                device_lost_recoveries: self.device_lost_recoveries,
                max_frame_latency: 1,
                composition_mode: self.renderer.composition_mode_label().to_string(),
                gpu_vram_used_bytes: pool_stats.used_bytes,
                gpu_vram_budget_bytes: pool_stats.capacity_bytes,
                gpu_tiles_resident: pool_stats.slots_used,
                gpu_tiles_capacity: pool_stats.slots_capacity,
                stack_cache_hits: cache_stats.cache_hits,
                stack_cache_rebuilds: cache_stats.below_rebuilds + cache_stats.above_rebuilds,
                is_idle,
            };
            if let Ok(mut g) = self.shared_diag.lock() {
                *g = diag.clone();
            }
            self.send_throttled_event(EngineEvent::Diagnostics(diag));
        }
    }
}