Skip to content

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

72.7 KB
Raw Blame

InkStudio Hybrid Native Rust + wgpu (DX12) Engine Migration

Target Platform: Windows 10/11 Desktop Only (wgpu DX12 + DirectComposition + transparent WebView2 UI)
Status: Phase 6 of 6 (Complete Canvas Offload, Native Tools/Collab & WebView2 Purge) — Migration Complete


1. Architecture & Crate / Module Layout

InkStudio is structured as a Cargo workspace with a strictly decoupled GPU engine crate (crates/ink-engine) hosted beneath the transparent WebView2 UI in src-tauri:

inkstudio/
├── Cargo.toml                                    # Cargo workspace root (members: crates/ink-engine, src-tauri)
├── crates/
│   └── ink-engine/                               # Pure Rust DX12 engine — ZERO tauri/wry/tao/WebView deps
│       ├── Cargo.toml                            # wgpu 30 (dx12/wgsl), rtrb, crossbeam-channel, pollster, bytemuck, windows-sys (QPC/thread)
│       └── src/
│           ├── lib.rs                            # Public engine API + headless DX12 vertical-slice integration test
│           ├── clock.rs                          # Shared Windows QPC monotonic millisecond clock (matches tablet_input.rs)
│           ├── types.rs                          # ViewportRect, UiRect, CameraState, CursorConfig, BrushParams, InteractionPolicy,
│           │                                     # NativeInputSample, NativeNavEvent, EngineCommand, EngineEvent, EngineDiagnostics, SurfaceTarget
│           ├── camera.rs                         # Exact 2D affine camera math matching formatArtboardTransform + NativeCameraNavigator
│           ├── hit_test.rs                       # Thread-safe physical-pixel viewport & UI occlusion mask (blocking + try_* non-blocking)
│           ├── ring.rs                           # Dedicated wait-free SPSC rtrb rings (wintab, winink, nav) + WakeSignal
│           ├── shaders.rs                        # WGSL shaders: artboard compositor, instanced GPU dab rasterizer, analytic SDF GPU cursor
│           ├── stroke.rs                         # Pressure-sensitive spacing-interpolated dab generator + eraser support
│           ├── gpu.rs                            # DX12 wgpu renderer (CreateSwapChainForComposition, waitable latency=1, device-lost recovery)
│           └── engine.rs                         # Dedicated above-normal priority render thread, chronological ring drain, EMA latency telemetry
├── src-tauri/
│   ├── tauri.conf.json                           # main window: decorations: false, transparent: true
│   └── src/
│       ├── dcomp_host.rs                         # Windows DirectComposition visual tree host + live DX12 composition swapchain test
│       ├── native_engine.rs                      # Tauri host lifecycle, WM_SIZE/DPI subclass, WH_MOUSE_LL zero-IPC nav/hover hook, event pump
│       ├── tablet_input.rs                       # Direct WinTab & Windows Ink SPSC ring push + zero-IPC Channel suppression on native strokes
│       └── lib.rs                                # WEBVIEW2_DEFAULT_BACKGROUND_COLOR=0, startup init, 11 native_engine_* commands, ordered exit
└── src/
    ├── index.css                                 # :root[data-native-canvas="true"] RGBA(0,0,0,0) viewport cutout + opaque chrome seam sealing
    ├── utils/nativeEngineBridge.ts               # Typed Tauri IPC + event client (no-op in non-Tauri / Vitest environments)
    ├── hooks/useNativeEngineViewport.ts          # ResizeObserver/DPR/interfaceScale viewport sync, UI occlusion observer, bidirectional camera sync
    └── components/
        ├── CanvasArea.tsx                        # Mounts native engine hook, hides legacy WebGL2 canvas when native DX12 is active
        ├── FloatingBrushPill.tsx                 # Tagged with data-native-occluder="true"
        ├── AnimationTimeline.tsx                 # Tagged with data-native-occluder="true"
        └── canvasArea/
            ├── useCompositorViewport.ts          # Keeps DOM artboard overlay transform synced; bypasses WebGL2 renders when DX12 is active
            ├── useCanvasEffects.ts               # Suppresses DOM brush outline ring for native-handled tools so GPU SDF cursor is sole cursor
            ├── useCanvasPointerHandlers.ts       # Skips JS brush/eraser stroke dispatch when native DX12 owns strokes
            └── CanvasViewportHud.tsx             # Native DX12 Perf HUD pill (GPU adapter, FPS, frame time, input-to-present latency, Clear button)

Hard Decoupling Invariant

crates/ink-engine has zero dependencies on tauri, wry, tao, or webview2-com. It accepts only:

  • SurfaceTarget::CompositionVisual { visual_ptr, on_configured } (or SurfaceTarget::Headless { width, height } for automated GPU testing),
  • Lock-free SPSC rtrb input ring producers (InputProducers { wintab, winink, nav }), and
  • Typed EngineCommand control messages.

A future pure-Rust UI shell can host crates/ink-engine directly with no modifications to the engine crate.


2. Windows DirectComposition + WebView2 COM Integration & Lifecycle Invariants

Visual Tree Layering (Single Top-Level HWND, Zero Canvas Child HWND)

On Windows, wry (0.57.x/0.58.x) hosts WebView2 via a child container HWND (WRY_WEBVIEW) inside the top-level main_hwnd using a windowed ICoreWebView2Controller. When "transparent": true is enabled on main in src-tauri/tauri.conf.json:

  1. tao activates DWM transparency (DwmEnableBlurBehindWindow with an empty region) on main_hwnd.
  2. src-tauri/src/lib.rs sets WEBVIEW2_DEFAULT_BACKGROUND_COLOR=0 before WebView2 boots, and DCompHost::configure_webview2_controller calls ICoreWebView2Controller2::SetDefaultBackgroundColor(COREWEBVIEW2_COLOR { A: 0, R: 0, G: 0, B: 0 }) so the transparent cutout never flashes white.
  3. DCompHost::new(main_hwnd) creates an IDCompositionDevice via DCompositionCreateDevice2(None) and binds an IDCompositionTarget via device.CreateTargetForHwnd(main_hwnd, false) (topmost = false):
    • topmost = false places our DirectComposition visual tree (root_visual -> canvas_visual) strictly beneath WRY_WEBVIEW and Chromium's own compositor visual tree in DWM.
    • No opaque child HWND is created for the canvas. WebView2 dropdown menus, tooltips, floating dock panels, modals, FloatingBrushPill, and QuickBrushPanel composite seamlessly above the DX12 canvas with zero clipping.
    • Future-proofing: configure_webview2_controller also probes controller.cast::<ICoreWebView2CompositionController>() and, if a future wry switches to visual-hosting mode, attaches a top webview_visual above canvas_visual via AddVisual(&webview_visual, true, Some(&canvas_visual)) + SetRootVisualTarget(&webview_visual).

wgpu DX12 Composition Swapchain Details

Inside crates/ink-engine/src/gpu.rs:

  • Backend: Explicitly wgpu::Backends::DX12, Dx12SwapchainKind::DxgiFromVisual, Dx12UseFrameLatencyWaitableObject::Wait.
  • Surface Creation: instance.create_surface_unsafe(SurfaceTargetUnsafe::CompositionVisual { visual }). wgpu-hal borrows and AddRefs the IDCompositionVisual pointer (from_raw_borrowed + to_owned) and releases it cleanly when wgpu::Surface drops.
  • Swapchain Configuration:
    • Calls IDXGIFactory2::CreateSwapChainForComposition with DXGI_SWAP_EFFECT_FLIP_DISCARD, DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT, and SetMaximumFrameLatency(1) (desired_maximum_frame_latency: 1).
    • Present Mode: Prefers PresentMode::Mailbox when advertised by the adapter, falling back to PresentMode::Fifo.
    • Alpha Mode: Explicitly selects CompositeAlphaMode::Opaque (DXGI_ALPHA_MODE_IGNORE) or CompositeAlphaMode::PreMultiplied (DXGI_ALPHA_MODE_PREMULTIPLIED) — never Auto/Inherit (DXGI_ALPHA_MODE_UNSPECIFIED), which CreateSwapChainForComposition rejects with DXGI_ERROR_INVALID_CALL.
    • Mandatory Commit Hook: wgpu-hal calls IDCompositionVisual::SetContent(&swap_chain1) inside surface.configure(...) but does not call IDCompositionDevice::Commit(). ink-engine invokes the host's on_configured callback immediately after every surface.configure(...) so DCompHost::commit() commits the swapchain binding to DWM.
  • Viewport Positioning & Clipping: DCompHost::set_canvas_viewport(x_px, y_px, width_px, height_px, visible) applies SetOffsetX2, SetOffsetY2, SetClip2 (0..width_px, 0..height_px, or 0..0 when hidden), and Commit().

Lifecycle, Recovery & Ordered Teardown Invariants

  • WM_SIZE (SIZE_MINIMIZED / restore): lifecycle_subclass_proc on main_hwnd immediately pauses rendering (SetVisible(false) + empty DirectComposition clip) when minimized and restores viewport visibility + sends NotifySurfaceInvalidated on restore.
  • WM_DPICHANGED / WM_DISPLAYCHANGE: Sends NotifySurfaceInvalidated to reconfigure the swapchain cleanly; React simultaneously observes window.devicePixelRatio via matchMedia and pushes updated physical bounds.
  • Device-Lost / Swapchain Outdated Recovery: GpuRenderer::render_frame handles SurfaceError::Outdated | Lost by reconfiguring the swapchain, and SurfaceError::Timeout | OutOfMemory | Other by tracking device-lost recoveries and rebuilding the DX12 device + pipelines + canvas texture cleanly if needed.
  • Strict Shutdown Order (native_engine::shutdown in RunEvent::Exit):
    1. Mark engine inactive and detach tablet_input ring producers (tablet_input::detach_engine_rings()).
    2. Stop inkstudio-native-mouse (WH_MOUSE_LL) hook thread (PostThreadMessageW(WM_QUIT) + join).
    3. Remove main_hwnd lifecycle subclass (RemoveWindowSubclass).
    4. Call EngineHandle::shutdown() and join "inkstudio-gpu-engine" — guarantees wgpu::Surface and the DXGI composition swapchain drop strictly before DirectComposition teardown.
    5. Join the event bridge thread, call DCompHost::clear_content() (SetContent(None) + Commit()), and drop DCompHost.
  • Lock Hierarchy: RUNTIME -> DCompHost::inner. on_configured only locks DCompHost::inner, and shutdown() releases RUNTIME before joining the GPU thread, eliminating AB-BA deadlocks.

3. Zero-IPC Hot Paths & Coordinate System Parity

Lock-Free SPSC Input Routing (Zero JSON, Zero Tauri IPC During Strokes/Nav)

Three dedicated wait-free rtrb SPSC rings feed ink-engine and wake the render thread immediately via WakeSignal:

  1. wintab ring (inkstudio-wintab thread -> ink-engine): tablet_input.rs maps WinTab packets to sub-pixel physical client coordinates (phys_x, phys_y) and pushes NativeInputSample batches directly into rtrb. When a pen-down lands inside the unoccluded canvas viewport for a native-handled tool (Brush/Eraser), native_stroke_owned suppresses Tauri Channel serialization completely for the entire stroke and unoccluded hover.
  2. winink ring (UI thread ink_subclass_proc -> ink-engine): Same direct rtrb batch push + Channel suppression for Windows Ink WM_POINTER* history bursts.
  3. nav ring (inkstudio-native-mouse WH_MOUSE_LL thread -> ink-engine): Non-blocking (try_read on SharedHitTest + wait-free rtrb push) delivery of mouse hover (120–240 Hz GPU cursor), mouse wheel zoom/scroll, middle-mouse pan/rotate/zoom, Space+Left-drag pan/rotate/zoom, and mouse PoC drawing (automatically suppressing pen/touch-synthesized mouse events via MI_WP_SIGNATURE and recent stylus timestamp). WM_MOUSEMOVE is never swallowed so the OS cursor never stalls.

Physical Pixel Coordinate Invariance (DPI + interfaceScale)

  • Native input coordinates (WinTab, Windows Ink, WH_MOUSE_LL) arrive as physical client pixels relative to main_hwnd (ScreenToClient without dividing by DPI).
  • React sends viewport cutout bounds and UI occlusion rects as DOMRect * window.devicePixelRatio. Because WebView2 scales window.devicePixelRatio = os_dpi_scale * native_webview_zoom, physical pixel coordinates remain pixel-exact across all Windows DPI settings (100%–200%+) and InkStudio interfaceScale levels (60%–200%).
  • ink-engine converts physical pixels to zoomed viewport-local CSS pixels via (phys - viewport_origin) / dpr, matching formatArtboardTransform (src/components/canvasArea/types.ts) and CanvasArtboardOverlays pixel-for-pixel.

4. React <-> Rust IPC Surface (Control & Telemetry Only)

All IPC calls are strictly off the hot stroke/navigation path (fired only on layout changes, tool/setting edits, document opens, or throttled background sync):

Commands (invoke from React -> Rust)

Command Purpose
native_engine_is_active() Returns true if Windows DirectComposition + DX12 engine initialized cleanly.
native_engine_set_viewport(xPx, yPx, widthPx, heightPx, dpr, visible) Updates physical cutout bounds, DirectComposition offset/clip, and swapchain size.
native_engine_set_occluded_rects(rects) Replaces physical-pixel UI occlusion rects (modals, popovers, menus, FloatingBrushPill, floating dock windows, QuickBrushPanel, AnimationTimeline, perf HUD).
native_engine_set_document(width, height, showCheckerboard) Resizes/recreates the GPU document canvas surface.
native_engine_set_appearance(matteRgba, showCheckerboard) Syncs --ui-canvas-matte theme color and checkerboard grid toggle.
native_engine_set_camera(camera) Applies programmatic UI camera updates (Fit-to-Screen, Navigator, Flip H/V, Reset Rotation).
native_engine_set_cursor(config) Updates GPU SDF brush outline cursor size, shape, aspect/thickness, tip angle, and visibility.
native_engine_set_brush(params) Updates Phase 1 PoC GPU dab brush size, opacity, hardness, spacing, pressure toggles, color, and eraser mode.
native_engine_set_policy(policy) Syncs active tool classification, wheel mode, Webtoon mode, text-input focus, workspace splitter drag lock, and modal guard.
native_engine_clear_canvas() Clears the Phase 1 PoC GPU canvas texture to transparent.
native_engine_get_diagnostics() Returns latest EngineDiagnostics snapshot on demand.

Throttled Events (Rust -> React)

Event Cadence Purpose
native-engine://camera ~60 Hz during native nav + final commit: true Keeps useCanvasNavigation.ts & CanvasArtboardOverlays pixel-aligned with native Rust pan/zoom/rotate.
native-engine://diagnostics ~4 Hz Drives the minimal Native DX12 Perf HUD (adapterName, fps, frameTimeMs, inputToPresentMs, presentMode).
native-engine://pointer-stat ~30 Hz Dispatches canvas-pointer-stat so StatusBar coordinates & live pressure readout stay active during zero-IPC strokes.

5. Phase 1 Completion Checklist

  • Cargo workspace root created with strictly decoupled crates/ink-engine (zero Tauri/wry/WebView deps).
  • Windows DirectComposition single-HWND visual tree (CreateTargetForHwnd(main_hwnd, false)) layering DX12 CreateSwapChainForComposition (SetMaximumFrameLatency(1), PresentMode::Mailbox preferred else Fifo) beneath transparent WebView2 (COREWEBVIEW2_COLOR = 0).
  • Transparent WebView2 viewport cutout across flat, hairline, islands, and Focus Mode with zero seam leakage and full UI occlusion rect reporting.
  • Direct lock-free rtrb SPSC ring routing from src-tauri/src/tablet_input.rs (WinTab + Windows Ink) and WH_MOUSE_LL directly into ink-engine (zero IPC during active strokes and camera nav).
  • Native 120–240 Hz GPU camera navigation (pan/zoom 0.01..32.0/rotate/flip) matching formatArtboardTransform pixel-for-pixel + throttled sync back to React.
  • Analytic SDF dual-tone GPU brush outline cursor ring + minimal GPU dab test brush + minimal DX12 Perf HUD with live GPU adapter, FPS, frame time, input-to-present latency, and Clear button.
  • Verified live DirectComposition + DX12 swapchain presentation test, workspace Rust tests, Clippy, TypeScript/Vite build, and Vitest suite.

6. Phase 2: Document & Tile Memory Single Source of Truth in Rust

Phase 2 eliminates dual JS/Rust raster storage on Windows desktop. crates/ink-engine is now the single source of truth for all document pixel grids, non-destructive 8-bit layer masks, multi-tab sessions, tiered GPU/RAM/Scratch memory, Copy-on-Write undo/redo history, and binary .ink / .clip / .psd / .psb / WAL crash recovery / timelapse I/O. React receives only compact JSON metadata (DocumentMetaSnapshot, HistoryStateSnapshot, MemoryStats) and small 64×64 PNG data-URL thumbnails — never full-resolution layer buffers.

Phase 2 Crate & File Additions

crates/ink-engine/src/
├── tiles/
│   ├── mod.rs                # TILE_SIZE = 256, TileFormat (Monochrome1Bit / Grayscale8Bit / Color32Bit / Rgba16Float),
│   │                         # TileCoord, RectI32, TileKind (Raster / Mask), atomic tile version IDs
│   ├── format.rs             # Fast SIMD-friendly 1-bit / 8-bit / 32-bit / 16f conversions, U8->F16 LUT,
│   │                         # 4×4 Bayer ordered dithering (Rgba16Float -> RGBA8 at I/O boundaries)
│   ├── tile_data.rs          # TileStorage (SolidColor zero-alloc / Raw / Lz4Ram / ScratchDisk), CoW Arc<TileData> helpers
│   └── grid.rs               # SparseLayerGrid (raster tiles + non-destructive 8-bit mask_tiles + solid fill + auto-pruning)
├── memory/
│   ├── mod.rs                # MemoryBudgetConfig, MemoryStats, EvictionReport
│   ├── scratch.rs            # Pure-Rust ScratchBackend trait + InMemoryScratchBackend + FileScratchBackend
│   ├── tiered.rs             # LRU tiered eviction coordinator (L1 VRAM <-> L2 lz4_flex RAM <-> L3 Scratch Disk)
│   └── gpu_pool.rs           # wgpu DX12 GpuTilePool (Rgba16Float + R8Unorm Texture2DArray pools, LRU eviction,
│                             # MIPMAP_COMPUTE_WGSL compute shader regenerating dirty LOD 1..3 tiles on GPU)
├── document/
│   ├── mod.rs                # Re-exports for DocumentManager, Document, LayerNode, LayerNodeMeta, snapshots
│   ├── types.rs              # Full InkStudio layer metadata parity (BlendMode, ExpressionColor, screentone, layer color,
│   │                         # mask flags, adjustments, styles, comic frames, text/balloon/vector metadata)
│   ├── doc.rs                # Layer CRUD, O(1) CoW duplicate, reorder/reparent, merge down, merge folder, mask CRUD/apply,
│   │                         # atomic canvas resize/crop, raw dirty-rect ingestion, CoW undo/redo & selective collab undo
│   └── manager.rs            # Multi-tab DocumentManager keyed by DocumentId (instant tab switch + inactive-tab offloading)
├── history/
│   └── mod.rs                # CoW HistoryStack (Arc<TileData> deltas, 800ms slider coalesce_key, resize/tree snapshots,
│                             # collaborative selective undo/redo tombstones with peer_id / stroke_id / undone)
├── io/
│   ├── mod.rs                # I/O re-exports
│   ├── png_codec.rs          # Zero-dependency pure-Rust PNG encoder/decoder + 64×64 layer/mask thumbnail generator
│   ├── compositor_cpu.rs     # Parallel Rayon multi-layer CPU compositor (blend modes, masks, clipping, folders, downscale)
│   ├── ink_format.rs         # Direct parallel Rayon `.ink` v2 ZIP serializer & parser (tile/mask/preview/manifest parity)
│   └── wal.rs                # Direct `INKG v1` checkpoint + `TD v1` WAL encoder/replayer (wire-compatible with recovery.rs)
└── phase2_tests.rs           # Comprehensive Phase 2 Rust unit + headless DX12 GPU verification suite

src-tauri/src/
├── scratch_disk.rs           # Unified in-process sync helpers (init/write/read/clear_sync) sharing SCRATCH_IO_LOCK + registry
├── doc_wire.rs               # Factored ParsedDocumentAssembled struct shared by clip_parser, psd_parser, and native_docs
├── clip_parser.rs            # Added parse_clip_assembled for zero-copy hydration into ink-engine (skips INKD encode/IPC)
├── psd_parser.rs             # Added parse_psd_assembled for zero-copy hydration into ink-engine (skips INKD encode/IPC)
├── native_docs.rs            # TauriScratchDiskBackend (zero-IPC), zero-copy .clip/.psd/.psb/.ink open/save,
│                             # all layer/mask/history/memory/thumbnail/timelapse/recovery handlers + integration tests
└── native_engine.rs          # Injects TauriScratchDiskBackend, exposes shared DocumentManager, pumps Phase 2 events

src/utils/nativeEngineBridge.ts  # Full typed Phase 2 TS facade (documents, layers, masks, binary dirty-rect ingest,
                                 # CoW history, memory budgets, thumbnails, timelapse, recovery, event listeners)

Key Architectural Guarantees

  1. Sparse Virtual Tiles & Zero-Allocation Fast Paths:
    • Every layer stores both tiles: HashMap<TileCoord, Arc<TileData>> and mask_tiles: HashMap<TileCoord, Arc<TileData>> at TILE_SIZE = 256.
    • Supported formats: Monochrome1Bit (8 KB), Grayscale8Bit (64 KB), Color32Bit (256 KB), and internal Rgba16Float (512 KB GPU working format with exact lossless u8 <-> f16 round-trip plus 4×4 Bayer ordered dithering at 8-bit I/O boundaries).
    • Uniform tiles (e.g., white Paper fill on a 6071×8598 manga canvas, or newly added opaque masks) stay TileStorage::SolidColor (0 bytes heap allocated), promoting to Raw only on mutated tiles and auto-pruning fully transparent tiles.
  2. Tiered L1 ↔ L2 ↔ L3 Memory Pipeline + GPU Compute Mipmaps:
    • L1 (DX12 GPU VRAM): GpuTilePool maintains Rgba16Float raster and R8Unorm mask wgpu::Texture2DArray slot pools bounded by the VRAM budget preset (low=128 MB, medium=256 MB, high=512 MB, ultra=1024 MB) with LRU eviction. Dirty LOD 1..3 tiles regenerate asynchronously on the GPU via MIPMAP_COMPUTE_WGSL.
    • L2 (CPU RAM): Cold tiles compress in-memory with lz4_flex (TileStorage::Lz4Ram).
    • L3 (Scratch Disk): When RAM exceeds budget (or tabs go inactive), TauriScratchDiskBackend pages cold compressed tiles directly in-process into src-tauri/src/scratch_disk.rs (zero Tauri IPC).
    • Device-Lost Resilience: After DX12 TDR recovery, GpuRenderer::sync_document re-hydrates GPU VRAM directly from Rust's CPU/LZ4/Scratch source of truth with zero data loss.
  3. Copy-on-Write (Arc<TileData>) Undo/Redo & Collaborative Selective Undo:
    • Layer duplication (duplicate_layer), history tile deltas (CowTileDelta), and full-document resize/crop snapshots clone only Arc pointers (O(1) for untouched tiles); mutations copy only dirty tiles via Arc::make_mut.
    • Slider drags (e.g., opacity) coalesce within an 800 ms window via coalesce_key.
    • Collaborative selective undo/redo marks individual (peer_id, stroke_id) entries with tombstones (undone = true) and protects tiles later modified by other peers (conflict_protected).
    • Native DX12 strokes stamp at 240 Hz straight into the live display texture and commit dabs onto the active SparseLayerGrid + CoW HistoryStack on pen-up, emitting native-engine://stroke-committed, native-engine://history, and native-engine://thumbnails.
  4. Zero-Copy Open, Save, Recovery, Thumbnails & Timelapse:
    • Opening .clip, .csp, .lip, .psd, .psb, or .ink parses directly in Rust (parse_clip_assembled / parse_psd_assembled / parse_ink_document), hydrates tiles into DocumentManager, generates 64×64 PNG thumbnails in parallel with Rayon, syncs the DX12 GPU renderer, and returns only compact metadata to React.
    • Saving .ink reads straight from Rust tiles with Rayon parallel deflate compression and atomic file writes (via save_dialog::write_file_atomic).
    • Crash recovery checkpoints (native_engine_recovery_checkpoint) and restores (native_engine_recovery_restore) call recovery.rs in-process using the exact INKG v1 / TD v1 wire format.
    • Artwork timelapse captures (native_engine_capture_timelapse_frame) downscale-composite directly in Rust and write PNG frames in-process via timelapse.rs.

Phase 2 Tauri Commands & Events

Group Commands (invoke from React → Rust)
Documents & Zero-Copy I/O native_engine_create_document, native_engine_open_file, native_engine_open_file_bytes, native_engine_save_ink, native_engine_save_ink_with_dialog, native_engine_switch_document, native_engine_close_document, native_engine_get_document_state, native_engine_resize_canvas
Layer Tree, Masks & Dirty-Rect Ingest native_engine_add_layer, native_engine_delete_layer, native_engine_duplicate_layer, native_engine_reorder_layers, native_engine_update_layer, native_engine_sync_layers, native_engine_clear_layer, native_engine_merge_down, native_engine_merge_folder, native_engine_add_mask, native_engine_remove_mask, native_engine_ingest_dirty_rect (raw binary body + x-doc-id / x-layer-id / x-rect-* headers)
CoW Undo/Redo & Collab Selective Undo native_engine_undo, native_engine_redo, native_engine_jump_history, native_engine_selective_undo, native_engine_selective_redo, native_engine_push_history_meta, native_engine_get_history, native_engine_reset_history
Memory, Thumbnails, Timelapse & Recovery native_engine_get_memory_stats, native_engine_set_memory_budget, native_engine_purge_memory, native_engine_request_thumbnails, native_engine_capture_timelapse_frame, native_engine_recovery_checkpoint, native_engine_recovery_restore
New Phase 2 Events (Rust → React) Purpose
native-engine://history Pushes compact HistoryStateSnapshot (items: HistoryItemMeta[], currentIndex, canUndo, canRedo) after native strokes or history commands.
native-engine://thumbnails Streams async 64×64 PNG data-URL layer & mask thumbnail updates to useLayerManager.ts.
native-engine://stroke-committed Notifies React on pen-up commit with dirty tile count, document ID, and layer ID (triggers timelapse & recovery hooks).

Deleted / Retired Legacy JS & IPC Plumbing

  • Deleted Tauri commands in src-tauri/src/lib.rs: removed save_undo_tile_cache, load_undo_tile_cache, clear_undo_tile_cache, and MAX_UNDO_CACHE_BYTES.
  • Removed JS undo-cache disk IPC in src/utils/undoCache.ts: eliminated all invoke('save_undo_tile_cache' / 'load_undo_tile_cache' / 'clear_undo_tile_cache') round-trips.
  • Bypassed JS pixel hydration & history duplication on Windows desktop (isNativeCanvasActive()):
    • DocumentLifecycleManager.tsx: opens .ink/.clip/.csp/.lip/.psd/.psb, saves .ink, switches/closes tabs, resizes canvases, restores crash recovery, and syncs memory budgets/purges directly via nativeEngineBridge.ts without allocating JS SparseTileGrid pixel buffers.
    • useLayerDocumentOps.ts, useLayerCrud.ts, useLayerPropertiesAndMasks.ts, useLayerManager.ts: deterministic blank layer IDs (layer-1-{docId}, layer-bg-{docId}), zero JS white-tile fill on new canvas, zero JS mask canvas allocation on native mask creation, and full Rust layer/mask/merge/duplicate synchronization.
    • useDrawingHistory.ts: delegates undo, redo, jump-to-index, selective collab undo/redo, clear, and reset directly to Rust CoW history; skips JS TileDelta capture and JS UndoCacheManager writes when native is active.
    • vectorLayerRenderer.ts, recoveryService.ts, timelapseEngine.ts: text/balloon commits push tight RGBA8 dirty-rects via binary native_engine_ingest_dirty_rect; recovery checkpoints and artwork timelapse frames run directly in-process in Rust.

Phase 2 Verification Summary

  • cargo test --workspace: 97 passed, 0 failed (ink-engine: 16 passed including sparse solid tiles, 1/8/32/16f conversions + 4×4 Bayer dithering, non-destructive masks, CoW Arc sharing + coalescing + resize undo, collab selective undo tombstones, LRU → L2 LZ4 → L3 scratch disk round-trip, headless DX12 GpuTilePool LRU + MIPMAP_COMPUTE_WGSL GPU readback, .ink + WAL + PNG timelapse; src-tauri: 81 passed including TauriScratchDiskBackend in-process round-trip and zero-copy .psd & .clip → ink-engine → .ink round-trips).
  • cargo clippy -p ink-engine --all-targets -- -D warnings: 0 errors, 0 warnings (cargo clippy --workspace --all-targets passes with 0 warnings in all Phase 2 files).
  • npm run build (tsc && vite build): 0 errors.
  • npm run test (Vitest): 126 test files / 1,074 tests passing.

7. Phase 3: Feature-Complete WGSL Layer Compositor & Legacy WebGL2 Removal

Phase 3 replaces InkStudio's entire legacy WebGL2/Canvas2D ViewportCompositor with a native DX12 wgpu + WGSL multi-layer compositor inside crates/ink-engine/src/compositor/, eliminates Phase 2's CPU full-canvas flattening on sync_document, and deletes src/utils/compositor/ and <canvas ref={viewportCanvasRef} /> so WebView2 allocates zero viewport GPU FBOs or canvas textures.

Phase 3 Crate & Module Layout

crates/ink-engine/src/
├── compositor/
│   ├── mod.rs                # CmykStandard, SoftProofConfig, OnionSkinFrame, CompositorDisplayConfig,
│   │                         # FlattenOptions, ParsedLayerStyles, hex_to_rgb_f32
│   ├── layer_tree.rs         # LayerTreeNode, clipping-chain grouping, nested folder/frame-folder partitioning,
│   │                         # AboveSliceStrategy (Empty / NormalStack / BakedSingleBlend / Dynamic)
│   ├── stack_cache.rs        # DocBounds, ScissorRect, LOD 0..3 zoom selection, frustum culling, Fnv1a64 signatures,
│   │                         # LayerStackCacheTracker (3-slice invalidation + cache hit/rebuild telemetry)
│   ├── lut.rs                # Fritsch-Carlson cubic spline Curves, Levels, Gradient Map, Color Balance + GPU LUT cache
│   ├── frame_geometry.rs     # Ear-clipping polygon triangulation & mitered border geometry for comic frame-folders
│   ├── targets.rs            # Rgba16Float SurfaceRgba16F (scissored copy_region_to), DocMaskCache (R8Unorm),
│   │                         # StyledLayerCache (8-entry LRU), growable folder/clip/frame surface stacks
│   ├── renderer.rs           # WgpuCompositor: FrameArenas (dynamic-offset uniform/instance staging, zero per-pass allocs),
│   │                         # 3-slice stack caching + dirty-rect scissor WYSIWYG live stroke compositing,
│   │                         # chunked (>2048px) headless render_document_flattened, render_layer_thumbnail_gpu
│   └── shaders/
│       ├── mod.rs            # Shared WGSL shader re-exports
│       ├── blend_modes.rs    # All 28 BlendModes (0..27: Normal..Luminosity) ported accurately from blendModesGlsl.ts
│       ├── screentone.rs     # CSP screentone halftones (circle/euclidean/line/diamond, specified vs image density, DPI)
│       ├── layer_tile.rs     # Instanced Rgba16Float tile + R8Unorm mask shader with expressionColor, layerColor tint & tone
│       ├── blit.rs           # Fullscreen & scissored clear, straight-over, custom-blend (28 modes) & clip-masked blit
│       ├── adjustment.rs     # GPU Curves / Levels / Gradient Map (256×1 LUT) + Color Balance (preserveLuminosity)
│       ├── layer_styles.rs   # 2-pass separable Gaussian alpha blur + Stroke (outside/inside/center), Drop Shadow, Outer Glow
│       ├── frame_poly.rs     # Comic frame-folder polygon mask, opaque fill, and mitered border rasterization
│       ├── viewport_present.rs # Matte, artboard shadow/border, checkerboard, CMYK Soft Proof (3 standards + gamut warning),
│       │                       # perceptual Rec.709 Value Check, high-zoom pixel grid, 4×4 Bayer dithering
│       └── live_dab.rs       # In-stack WYSIWYG live brush/eraser dab stamping + active-layer base/live merge shader
├── compositor_tests.rs       # Pure unit + headless DX12 GPU pixel-readback test suite (all 28 blend modes, masks,
│                             # clipping chains, pass-through vs isolated folders, comic frames, expression/tint/tones,
│                             # all 4 adjustments, layer styles + LRU cache hits, 3-slice cache + live strokes + display passes)
├── gpu.rs                    # Hosts WgpuCompositor, pure-VRAM sync_document (no CPU flatten), render_document_frame,
│                             # render_document_flattened, render_layer_thumbnail_gpu, headless readback
└── engine.rs                 # Manages CompositorDisplayConfig, handles Phase 3 EngineCommands, clears live stroke on commit

Key Architectural Guarantees

  1. Complete Feature Parity in Rgba16Float WGSL:
    • All 28 blend modes (0..=27), CSP expressionColor (color / gray / monochrome with threshold & black/white visibility), two-tone layerColor / layerSubColor tint, screentone halftones (circle, euclidean, line, diamond, specified vs image density at document DPI), all 4 non-destructive adjustments (curves, levels, gradient-map, color-balance), and cached non-destructive layer styles (stroke outside/inside/center, dropShadow, outerGlow).
    • Full hierarchical compositing: base + clipped sibling chains (clipped: true), nested folder and frame-folder (comic polygon clipping + fill + mitered borders) in both pass-through and isolated modes, and per-layer non-destructive 8-bit mask_tiles.
    • Viewport display passes: animation onion skin tinted ghosts (rendered over paper/below layers and underneath the active cel), CMYK soft proofing (japan-color-2001, us-web-coated-swop, iso-coated-v2) with out-of-gamut warning, linear Rec.709 perceptual valueCheck, high-zoom pixel grid, and artboard checkerboard + border + drop shadow.
  2. 3-Slice Baked Stack Cache, Frustum Culling, Auto-LOD & Dirty-Rect Scissor Live Strokes:
    • Partitioned Rgba16Float GPU caches (below_active_cache, active_unit_surface, above_active_cache with AboveSliceStrategy) keep painting on any layer of a 150-layer stack to a tight dirty-rect scissor re-composite of 3 surfaces without rebuilding below/above caches.
    • Live native brush/eraser dabs merge in-stack at WYSIWYG fidelity (clipped siblings, layer masks, expression color, screentones, and upper blend modes all apply live during the stroke).
    • Dynamic-offset FrameArenas staging buffers eliminate per-pass GPU buffer allocations and queue write hazards; scissored BackdropScratch copies prevent stale-pixel artifacts outside the dirty scissor.
  3. Isolated Headless GPU Flattening, Timelapse, Navigator & Thumbnails:
    • render_document_flattened renders full-resolution or scaled previews using dedicated export targets (never disturbing live viewport stack caches), automatically chunking canvases >2048px with layer-style margin overlap for seamless 600 DPI manga & Webtoon exports.
    • native_docs.rs routes flatten_document_rgba, capture_timelapse_frame, and effect-bearing async layer thumbnails through the DX12 GPU compositor first (with CPU fallback when headless/non-Windows).

New Phase 3 Tauri Commands & Diagnostics

Command / Field Purpose
native_engine_set_display_config(config) Pushes CompositorDisplayConfig (onion skins, cel visibility overrides, soft proof, value check, pixel grid, checkerboard, matte color, stack caching toggle).
native_engine_invalidate_compositor_cache() Forces full 3-slice stack, styled-layer, mask, and LUT cache invalidation.
native_engine_flush_gpu_pool() Evicts cold VRAM tile slots on memory-pressure purge (performanceManager).
native_engine_flatten_document(docId, options) Headless DX12 GPU document flatten returning binary [w: u32 LE, h: u32 LE, rgba8...] for PNG/JPEG/WebP/PSD export.
native_engine_render_navigator_preview(docId, maxDim, options) Fast DX12 GPU downscaled preview for NavigatorPanel.tsx.
EngineDiagnostics::{stack_cache_hits, stack_cache_rebuilds} Exposes 3-slice stack cache hit/rebuild counters to performanceManager & diagnostics subscribers.

Deleted Legacy WebGL2 Compositor & Frontend Migration

  • Deleted completely:
    • src/utils/compositor/ (all 21 legacy WebGL2/Canvas2D compositor, FBO, GLSL shader, and tile-draw modules)
    • src/utils/compositor.ts
    • src/utils/__tests__/compositor.test.ts
    • <canvas ref={viewportCanvasRef} /> element in src/components/CanvasArea.tsx
  • Replaced with lightweight pure-TS / native-bridge modules:
    • src/components/canvasArea/useCompositorViewport.ts: zero-<canvas>, zero-WebGL2 state-sync hook pushing NativeCompositorDisplayConfig to ink-engine, syncing DOM overlay transforms via navigation.subscribeCamera, and registering DX12 telemetry (backend: 'dx12') & flushNativeGpuPool() with performanceManager.
    • src/utils/saveManager/gpuComposite.ts & src/components/NavigatorPanel.tsx: use flattenNativeDocument / renderNativeNavigatorPreview on DX12 desktop (with pure Canvas2D/CPU fallback only for headless Vitest).
    • src/utils/layerTree.ts & src/utils/previewRenderer.ts: zero-WebGL pure-TS tree helpers and non-Tauri preview fallback.

Phase 3 Verification Summary

  • cargo test --workspace: 109 passed, 0 failed (ink-engine: 28 passed including headless DX12 GPU pixel-readback verification of all 28 blend modes, clipping chains, 8-bit masks, pass-through vs isolated folders, comic frame folders, expression color/tint/screentones, all 4 adjustments, layer styles + LRU cache hits, 3-slice stack caching + dirty-rect WYSIWYG live strokes + onion skin + CMYK soft proof & gamut warning + value check + chunked >2048px flatten; src-tauri: 81 passed including live DirectComposition + DX12 swapchain presentation).
  • cargo clippy --workspace --all-targets: 0 errors, 0 warnings across all Phase 3 files (crates/ink-engine/src/compositor/*, compositor_tests.rs, gpu.rs, src-tauri/src/native_docs.rs, native_engine.rs, lib.rs).
  • npm run build (tsc && vite build): 0 errors (built in 5.17s).
  • Vitest (vitest run): 125 test files / 1,024 tests passing, 0 failures.
  • Hard decoupling invariant preserved: crates/ink-engine/Cargo.toml still has zero dependencies on tauri, wry, tao, or webview2-com.

8. Phase 4: Core Native Stroke & GPU Brush Engine

Phase 4 moves InkStudio's entire stroke geometry pipeline (curves, CSP stabilizer, sharp corners, post-correction, Catmull–Rom/Hermite spline & arc-length resampler, taper + ballistic flick, straight & 1/2/3-point perspective ruler snapping, and ephemeral speculative stroke head prediction) plus the full CSP-compatible GPU instanced stamp, multi-subTip, paper-grain, dual-brush, and watercolor wet-edge engine directly into crates/ink-engine/src/stroke/ and crates/ink-engine/src/brush/. Active strokes run end-to-end on the Rust engine thread directly from tablet_input.rs SPSC ring samples to sparse 256×256 Rgba16Float GPU stroke tiles with zero JS involvement during strokes, and delete #ink-predicted-canvas, the hidden draft <canvas>, WebGlBrushEngine.ts, and DualBrushEngine.ts.

Phase 4 Crate & Module Layout

crates/ink-engine/src/
├── stroke/                                       # Replaced flat Phase 1-3 stroke.rs
│   ├── mod.rs                                    # StrokePoint, CommittedStrokePoint, StrokePipelineConfig, NativeStrokePipeline
│   ├── curves.rs                                 # CompiledCurveLut (256-entry Fritsch-Carlson PCHIP + CSP stub protection),
│   │                                             # GlobalPressureCurve, calculate_stroke_width (light-pressure anti-collapse floor)
│   ├── stabilizer.rs                             # OneEuroAxis pressure filter, CSP 0..50 sample-rate-invariant 3-stage isotropic
│   │                                             # cascade, Frenet lateral twitch damping, backtrack spike guard, sharp-corner
│   │                                             # CornerConvergencePlan, full-tail catch-up, apply_csp_post_correction (0..5)
│   ├── spline.rs                                 # Centripetal Catmull-Rom (0.48*d12 clamp, C0 corner breaks), provisional Hermite
│   │                                             # stitching, ArcLengthTable, ArcLengthResampler (exact carry-over)
│   ├── taper.rs                                  # Full CspTaperSettings (inOutType 0..3, inOutBySpeed, sharpness, per-channel targets),
│   │                                             # TaperEngine (G-Pen 3-stage Hermite S-curve, ballistic flick + 32ms dwell/zoom gates)
│   ├── rulers.rs                                 # StraightRulerSnapSession (26/zoom edge vs parallel + Alt override),
│   │                                             # PerspectiveSnapSession (1/2/3-point, 4 doc px lock, |dot| axis + Alt override)
│   └── prediction.rs                             # Strictly ephemeral build_predicted_segments rendered natively in wgpu
├── brush/
│   ├── mod.rs                                    # Public GPU brush exports
│   ├── prng.rs                                   # Deterministic per-stroke Xoshiro256** (SplitMix64 seeded) + dab_hash_float
│   ├── config.rs                                 # NativeBrushConfig mirroring BrushSettings, CspSensorConfig, BrushDynamics,
│   │                                             # CspSpraySettings, CspDualBrushConfig, all 9 paper modes, 4 grain mapping modes,
│   │                                             # 3 tip blend modes, 32 combine modes (0..31), 7 angle dynamics, 6 sub-tip orders,
│   │                                             # 3 tip flip modes, and all 12 DualBrushCompositeModes
│   ├── dynamics.rs                               # GpuBrushDab (80B Pod), spherical tilt, multi-sensor evaluator, elliptical stepping,
│   │                                             # gap-adjusted density, multi-axis jitter (count 1..10, scatter, HSV/temp/FG-BG color),
│   │                                             # spray particle emitter, StrokeDabEmitter (primary + independent dual secondary)
│   ├── procedural_tips.rs                        # Native Sfc32, periodic bilinear grids, Worley cellular domes, all 7 seamless
│   │                                             # 512×512 SurfaceTextureId heightfields + built-in 256×256 procedural brush tips
│   ├── tip_cache.rs                              # Content-hashed TipTextureCache (PNG/RGBA8 upload-once, D2Array multi-subTip sets,
│   │                                             # seamless repeat paper textures)
│   ├── shaders.rs                                # WGSL shaders: PAPER_GRAIN_WGSL (9 modes × 4 mappings), BRUSH_DAB_TILE_WGSL
│   │                                             # (tile + viewport prediction, SDF + D2Array, AA 0..3 / 1-bit binary, dual-tone),
│   │                                             # STROKE_DARKEN_MERGE_WGSL, STROKE_POST_TILE_WGSL (12 Dual Brush modes + per-stroke grain),
│   │                                             # WET_EDGE_TILE_WGSL (2-pass separable Gaussian on 288×288 3×3-neighbor padded window),
│   │                                             # TILE_COMMIT_COMPUTE_WGSL (all 32 combine modes, alphaLocked, mono 1-bit, selection hook)
│   └── sparse_stroke.rs                          # GpuBrushEngine: dynamically growing sparse 256×256 Rgba16Float stroke tile pools
│                                                 # (never full-canvas FBO), batched tile binning, live resolved cache, single-submit
│                                                 # GPU-to-GPU layer pool commit + batched RGBA8 readback
├── io/png_codec.rs                               # Added pure-Rust decode_png_rgba8 (8/16-bit Gray/RGB/Palette/GrayAlpha/RGBA)
├── compositor/                                   # Added SPARSE_STROKE_PROJECT_WGSL, 32-mode live_stroke_merge, LiveGpuStrokeOverlay,
│                                                 # transient predicted-head rendering + prev/cur predicted scissor unioning
├── phase4_tests.rs                               # 12 Phase 4 parity tests + 4096×4096 300px textured dual-brush benchmark
├── gpu.rs                                        # Hosts GpuBrushEngine, texture upload, sparse stamp/commit, GPU mipmap regeneration
└── engine.rs                                     # End-to-end native stroke session: lazy per-tile Arc<TileData> CoW capture,
                                                  # ephemeral prediction, finalize re-raster (postCorrection/useOut), locked/non-raster
                                                  # guards, compact StrokeCommitted event (dirtyRect, history, committed points)

src-tauri/src/
├── tablet_input.rs                               # Added VK_SHIFT (0x0100) & VK_MENU (0x0200) modifier bits to NativeInputSample::buttons
├── native_engine.rs                              # Added native_engine_set_full_brush, native_engine_set_pressure_curve,
└── lib.rs                                        # native_engine_set_rulers, native_engine_upload_brush_texture (raw binary upload)

Key Architectural Guarantees

  1. Sparse 256×256 Rgba16Float GPU Stroke Tiles (Never a Full-Canvas FBO):
    • GpuBrushEngine allocates stroke tiles lazily strictly for (tx, ty) coordinates touched by incoming dabs, projecting only visible stroke tiles into WgpuCompositor's live_stroke_surface in-stack at activeLayerId (so clipping chains, masks, expression color, screentones, and upper blend modes preview WYSIWYG live).
    • Speculative stroke head dabs (prediction.rs) are rendered strictly ephemerally into the viewport live stroke pass and unioned with the previous frame's predicted scissor so predicted tips never leave ghosts or mutate committed geometry.
  2. Seamless 2-Pass GPU Watercolor Wet Edge & Exact Alpha Conventions:
    • WET_EDGE_TILE_WGSL samples a 3×3 neighborhood of sparse stroke tiles into a 288×288 (256 + 2×16 padding) compute scratch texture for separable horizontal + vertical Gaussian blur, guaranteeing zero tile seams across tile boundaries and zero outer halo outside the stroke silhouette.
    • GpuTilePool maintains straight Rgba16Float while GpuBrushEngine & WgpuCompositor active surfaces use premultiplied Rgba16Float; TILE_COMMIT_COMPUTE_WGSL merges straight base + premultiplied stroke across all 32 CspBrushCombineModes (plus alphaLocked, isEraser/isBgEraser, 1-bit monochrome, and Phase 6 selection mask hook) and writes both the updated Rgba16Float VRAM slot and packed RGBA8 readback bytes in a single compute dispatch.
  3. Zero-IPC Hot Strokes & Compact Commit Telemetry:
    • React syncs NativeBrushConfig, FG/BG colors, global PressureCurveSettings, and StraightRuler / PerspectiveRuler only when changed (memoized signatures), uploading custom tips/sub-tips/dual-tips/paper textures once by FNV-1a content hash.
    • Before the first dab touches tile (tx, ty), engine.rs records its lazy Arc<TileData> CoW reference; on pen-up, GPU-to-GPU tile commit + LOD 1..3 compute mipmaps + CoW undo commit emit only a compact StrokeCommitted payload (dirtyRect, history, points) for Shift+Click anchor continuity and collaboration broadcast.

Deleted Legacy Files & DOM Canvases

  • Deleted completely:
    • src/engine/WebGlBrushEngine.ts (3,504 lines of legacy WebGL2 brush/dual/ribbon/paper GLSL engine)
    • src/engine/DualBrushEngine.ts (pure-TS config/CPU helpers extracted into src/utils/dualBrushConfig.ts)
    • <canvas id="ink-predicted-canvas" ... /> and <canvas ref={effectiveDraftCanvasRef} ... /> from src/components/CanvasArea.tsx (zero mounted stroke <canvas> elements remain in the DOM; a detached unmounted canvas is lazily created only for Phase-5-deferred Natural Paint / Ribbon / Bristle brushes and headless Vitest)
  • Temporary Phase 5 Capability Gate (canNativeEngineHandleBrush in src/utils/nativeEngineBridge.ts):
    • Routes all stamp, dual-brush, textured, multi-subTip, spray, wet-edge, binary manga (antiAlias == 0), decoration, and eraser strokes on raster layers directly through Rust ink-engine.
    • Defers ONLY colorMixing / NaturalPaintRenderer / RibbonBrushEngine / BristleRibbonEngine and non-raster/mask layers until Phase 5 deletes the remaining JS stroke engines completely.

4096×4096 300px Textured Dual-Brush Benchmark (--release, DX12)

Measured on NVIDIA GeForce GTX 1650 (DX12, 1920×1080 viewport, 4096×4096 canvas, 60-frame curved sweep with a 300px textured Dual Brush [pro:watercolor-wash-256 + pro:sumi-fude-brush-256], 512×512 cold-press-watercolor paper grain, 2-pass watercolor wetEdge, stabilizer + ephemeral head prediction):

Metric Measured Result
Sparse GPU Stroke Tiles Allocated 31 / 256 tiles (12.1% of a full 4K FBO — zero 4K/8K FBO allocation)
Input → Present Frame Time (stamp + dual + wet edge + 1080p WYSIWYG composite + predicted head) avg 5.78 ms (~173 FPS) · p50 6.83 ms · p95 10.00 ms (includes synchronous headless GPU fence wait)
Pen-Up GPU Tile Commit (all 31 tiles = 2.0M px) 5.75 ms GPU commit (0.185 ms/tile, <1 ms for typical 1–5 tile strokes) · 9.09 ms total including CoW Undo + LOD 1..3 compute mipmaps

Phase 4 Verification Summary

  • cargo test --workspace: 120 passed, 0 failed (ink-engine: 39 passed including all 12 new Phase 4 parity & DX12 GPU tests covering PCHIP curves + anti-collapse floor, CSP stabilizer lag/isotropy/Frenet twitch damping/full-tail catch-up, sharp corners + post-correction + ephemeral prediction, spline arc-length carry-over + G-Pen/ballistic flick + CspTaperSettings, straight & perspective ruler snapping, multi-sensor dynamics + spray + Xoshiro256**, all 7 seamless 512×512 surface heightfields + PNG encode/decode round-trip, 1-bit binary manga inking antiAlias == 0, dual-tone tips, blendTipsMode::Compare, all 9 paper modes per-dab & per-stroke, all 12 Dual Brush modes, seamless 2-pass watercolor wetEdge across the x = 256 tile boundary, alphaLocked / Behind / Clear, end-to-end EngineHandle CoW Undo/Redo, and the 4K 300px dual-brush benchmark; src-tauri: 81 passed).
  • cargo clippy --workspace --all-targets: 0 errors, 0 warnings across all Phase 4 modules (crates/ink-engine/src/stroke/*, crates/ink-engine/src/brush/*, src-tauri/src/native_engine.rs).
  • npm run build (tsc && vite build): 0 errors (built in 2.67s).
  • Vitest (vitest run): 125 test files / 1,021 tests passing, 0 failures.
  • Hard decoupling invariant preserved: crates/ink-engine/Cargo.toml remains 100% free of tauri, wry, tao, and webview2-com.

9. Phase 5: Full Physical Media & Painterly GPU Compute Engine + Legacy JS Brush Engine Deletion

Phase 5 completes the brush migration: 100% of InkStudio brush presets (Pen, Sketch, Brush, Blend, Natural Paint, Texture & FX, Decoration, Ribbon, Bristle-Ribbon, Bristle-Hybrid, Eraser, .sut, .inkb, and Layer Mask painting) now execute exclusively inside crates/ink-engine on Windows DX12 with zero CPU readPixels stalls, persistent R16Float impasto 3D heightfield tiles + live relief lighting, and all legacy JS brush engine files deleted.

Phase 5 Crate & Module Layout

crates/ink-engine/src/
├── natural_paint/                                # New Phase 5 Physical Media & Painterly Engine
│   ├── mod.rs                                    # Public module exports
│   ├── pigment.rs                                # Exact 1:1 8-band cube-root Kubelka-Munk + 6-basis reflectance decomposition +
│   │                                             # Saunderson (k1=0.0052, k2=0.38) + Linear sRGB <-> OKLab (Rust + PIGMENT_WGSL),
│   │                                             # DirtyBrushGpuBank (persistent 64-bristle BrushLoadBuffer + 16×16 SpatialTipMixer,
│   │                                             # honoring autoClean: true/false across strokes + CleanDirtyBrush)
│   ├── bristle_ribbon.rs                         # BristleRibbonSimulator: 4..64 physical strands, spring lag & stiffness,
│   │                                             # all 7 profiles (Round, Flat, Filbert, Fan, Rake, Knife, Custom), clumping,
│   │                                             # pressure/tilt splay + bristleSplaySensor, lift-off, 5-band under-bed,
│   │                                             # BristleRibbon & BristleHybrid capsule generation (GpuBristleCapsule)
│   ├── ribbon.rs                                 # RibbonMeshBuilder & GpuRibbonRenderer: continuous UV-mapped ribbon triangle
│   │                                             # strips, miter clamping + bevel corners + anti-bowtie guard, integer tile splitting,
│   │                                             # repeat/reverse/once modes, subTips, flipH/flipV, Dual Brush ribbon,
│   │                                             # isColorTip/isDualToneTip, paper grain, AA 0..3
│   ├── impasto.rs                                # NaturalPaintTilePools: sparse 256×256 Rgba16Float color + R16Float impasto
│   │                                             # heightfield + lazy GPU-composited mixGroundColor ground_pool (zero readPixels!)
│   └── natural_paint.rs                          # GpuNaturalPaintEngine: 4 WGSL compute pipelines:
│                                                 # - cs_update_bristle_load (zero-readback canvas/ground pickup + belly feed + depletion)
│                                                 # - cs_raster_natural_paint (multi-bristle KM/OKLab mixing, all 4 NaturalMixingModes,
│                                                 #   dryBrush valley skipping + penetrationCurve, watercolor granulation, CSP useBlur,
│                                                 #   and arched 3D R16Float impasto accumulation in the same compute dispatch!)
│                                                 # - cs_color_mix_pickup + cs_color_mix_stamp (standard CSP colorMixing 16×16 SpatialTipMixer)
├── tiles/                                        # Sparse R16Float impasto heightfield tiles (TileFormat::Height16Float)
│   ├── format.rs / tile_data.rs / grid.rs        # TileGrid::impasto_tiles + f16/f32 helpers + CoW apply_gpu_committed_impasto_tiles
├── document/                                     # ImpastoLayerLight metadata + UndoEntry::ImpastoTileDelta / MaskTileDelta
├── memory/                                       # ImpastoGpuAtlas (256×256 R16Float texture array in GpuTilePool) + LZ4/scratch tiering
├── io/                                           # WAL impasto deltas + .ink v2 ZIP `impasto/<layer_id>/<tx>_<ty>.r16f` round-trip
├── compositor/
│   ├── shaders/impasto_lighting.rs               # IMPASTO_HEIGHT_PROJECT_WGSL + IMPASTO_LIGHTING_WGSL (3×3 Sobel normals,
│   │                                             # directional diffuse, 5-tap cast shadow march, concavity micro-AO, chromatic
│   │                                             # trough deepening, 2-lobe Blinn-Phong satin oil gloss & glint)
│   ├── shaders/live_dab.rs                       # Added combine_mode == 32u straight Rgba16Float direct-replace live stroke merge
│   └── renderer.rs / targets.rs / stack_cache.rs # Live Impasto height projection & relief lighting pass integrated per layer
├── brush/
│   ├── config.rs                                 # Added NaturalPaintSettings, BristleSettings, ImpastoSettings, NaturalMixingMode,
│   │                                             # BrushRenderMode, CspRibbonRepeatMode, dryBrush, granulation, autoClean, mixGroundColor
│   └── sparse_stroke.rs                          # Hosts GpuRibbonRenderer + GpuNaturalPaintEngine + direct layer mask commit
├── phase5_tests.rs                               # 8 Phase 5 unit & headless DX12 GPU tests + 4096×4096 250px GPU benchmark
├── gpu.rs / engine.rs / types.rs                 # Native Mask Mode strokes, CleanDirtyBrush, RenderBrushPreview (native GPU PNG/RGBA8)
src-tauri/src/
├── native_engine.rs / native_docs.rs / lib.rs    # Added native_engine_clean_dirty_brush, native_engine_set_mask_mode,
                                                  # native_engine_render_brush_preview; TileFormat::Height16Float support

Key Architectural Guarantees

  1. Zero-Readback GPU Pigment Physics (natural_paint/pigment.rs & natural_paint.rs):
    • Active layer tiles are copied GPU-to-GPU into NaturalPaintTilePools::color_pool; when mixGroundColor is true, layers below activeLayerId are lazily composited into ground_pool directly on the GPU — zero readPixels calls occur during active strokes.
    • DirtyBrushGpuBank keeps persistent VRAM BrushLoadBuffers (64 × GpuBristleSlot) and 16×16 SpatialTipMixer buffers keyed by preset ID, honoring autoClean: false across consecutive strokes until explicitly reset via CleanDirtyBrush (native_engine_clean_dirty_brush).
    • Supports all 4 NaturalMixingModes (blend, running_color, smear, impasto_mix), exact 8-band cube-root Kubelka–Munk subtractive mixing (perceptualMixing, pigmentMixingStrength), OKLab interpolation, CSP amountOfPaint / densityOfPaint / colorStretch / useBlur / blurStrength, 512×512 seamless surface heightfield dryBrush valley skipping (penetrationCurve), and watercolor granulation valley settling.
  2. Persistent Sparse R16Float Impasto Heightfield + Live Relief Lighting:
    • Impasto heightfields are stored per layer as lazily-allocated sparse 256×256 R16Float tiles (TileGrid::impasto_tiles), participating atomically in Copy-on-Write Undo/Redo, tiered LZ4/scratch memory, WAL crash recovery, and .ink v2 ZIP serialization.
    • cs_raster_natural_paint updates color and R16Float height in the exact same GPU compute pass (sculpting an arched macro oil cross-section + bristle grooves + outer edgeRidge without mesa clipping). WgpuCompositor projects committed + live impasto tiles into a viewport R16Float surface and executes IMPASTO_LIGHTING_WGSL live at interactive frame rates.
  3. 100% Native Brush Coverage (Zero JS Brush Fallback):
    • canNativeEngineHandleBrush in src/utils/nativeEngineBridge.ts now returns true for every brush preset on both raster layers and Layer Mask mode (SetMaskMode routes strokes directly into layer.grid.mask_tiles with CoW mask undo).
    • Brush library thumbnails and Brush Studio previews use native DX12 GPU stroke rendering (renderNativeBrushPreview).

Deleted Legacy JS Brush Engines & Files

  • Deleted completely (10 engine/pigment files + brushStrokeSession/ + 16 obsolete JS-only brush engine tests):
    • src/engine/BrushEngine.ts
    • src/engine/NaturalPaintRenderer.ts
    • src/engine/RibbonBrushEngine.ts
    • src/engine/BristleRibbonEngine.ts
    • src/engine/InputStabilizer.ts
    • src/engine/SplineGenerator.ts
    • src/engine/TaperEngine.ts
    • src/engine/StrokePipeline.ts
    • src/utils/colorMixingEngine.ts
    • src/utils/spectralPigmentEngine.ts
    • src/hooks/drawing/brushStrokeSession/ (entire directory)
    • 16 obsolete JS-only brush engine test files in src/utils/__tests__/ (whose parity coverage now lives in Rust phase4_tests.rs & phase5_tests.rs)
  • Minimal pure non-engine helpers retained for UI/gradients/retouch/collab:
    • src/utils/brushMath.ts (lightweight PCHIP/curve preset constants & tip dimension helpers for UI controls & vector/collab paths)
    • src/utils/pigmentMath.ts (pure stateless 8-band KM color math for PigmentBlendControl.tsx, gradientEngine.ts, retouchEngine.ts, and tileEngine/strokeComposite.ts — no brush engine, reservoir, or pixel sampler)
    • src/hooks/drawing/useBrushStrokeSession.ts (slimmed to native Rust stroke-commit bridging + Vector layer drawing only)

4096×4096 250px Physical Media GPU Benchmark (--release, DX12)

Measured on NVIDIA GeForce GTX 1650 (DX12, 1920×1080 viewport, 4096×4096 canvas, 31-step curved sweep with 250px full physical media brushes):

Brush Preset & Workload Capsules / Sparse Tiles Interactive Stroke Time Pen-Up GPU Commit CPU readPixels Stalls
impasto-bristle-oil (250px, 32 bristles, R16Float impasto + live Sobel/shadow/specular relief lighting) 4,620 capsules · 20 color + 20 R16F tiles avg 9.90 ms/step (101.1 FPS) 16.7 ms (all 20 color + 20 R16F tiles) 0
wet-mixing-filbert (250px, 28 bristles, mixGroundColor lazy ground composite + 8-band KM compute) 4,120 capsules · 17 color tiles avg 4.96 ms/step (201.4 FPS) 13.5 ms (all 17 color tiles) 0

Phase 5 Verification Summary

  • cargo test --workspace: 128 passed, 0 failed (ink-engine: 47 passed, including all 8 new Phase 5 Rust & headless DX12 GPU tests covering 8-band cube-root KM + OKLab pigment mixing, zero-readback GPU canvas/ground pickup + all 4 NaturalMixingModes + CSP colorMixing, multi-bristle spatial mixing + depletion + autoClean: false/true + all 7 BristleProfilePresets + BristleHybrid, dry-brush 512×512 heightfield valley skipping + watercolor granulation, continuous ribbon UV continuity + miter/bevel + anti-bowtie + Dual Brush ribbon GPU rasterization, persistent R16Float impasto + CoW Undo/Redo + .ink v2 round-trip + live 180° azimuth relief lighting shift, native mask-mode painting + native DX12 brush preview PNG rendering, and the 4K 250px GPU benchmark; src-tauri: 81 passed).
  • cargo clippy --workspace --all-targets: 0 errors, 0 warnings across all Phase 5 modules (crates/ink-engine/src/natural_paint/*, engine.rs, gpu.rs, brush/sparse_stroke.rs, compositor/shaders/impasto_lighting.rs, phase5_tests.rs, src-tauri/src/native_engine.rs, native_docs.rs).
  • npm run build (tsc && vite build): 0 errors (built in 4.45s).
  • Vitest (vitest run): 110 test files / 820 tests passing, 0 failures.
  • Hard decoupling invariant preserved: crates/ink-engine/Cargo.toml continues to have zero dependencies on tauri, wry, tao, or webview2-com.

10. Phase 6 Complete — Complete Canvas Offload, WebView2 Purge & Final Before/After Metrics

Phase 6 completes the InkStudio Native Rust + wgpu (DX12 / DirectComposition) migration. Every remaining interactive raster, selection, liquify, fill, transform/warp, retouch, gradient, shape, vector rasterization, filter/tonal, and multiplayer remote-draft pipeline now executes natively inside crates/ink-engine. WebView2 is strictly an ultra-lightweight, transparent React UI shell holding zero full-resolution HTMLCanvasElement or OffscreenCanvas backing stores and zero JS pixel-processing loops.

Added & Completed Phase 6 Rust / Tauri Modules

crates/ink-engine/src/
├── selection/
│   ├── mod.rs / mask.rs                          # Sparse R8Unorm 256×256 selection mask tiles bound directly into
│   │                                             # Phase 4/5 brush, ribbon, natural-paint, fill, filter & clear paths;
│   │                                             # exact O(n) Felzenszwalb–Huttenlocher EDT expand/contract + Gaussian feather
│   ├── ops.rs                                    # Rect, 4×4 AA Lasso, Magic Wand (tolerance, contiguous, antiAlias,
│   │                                             # referMode: active/all/reference), Select Pen/Eraser, invert, clear,
│   │                                             # delete-outside, fill, cut/copy/paste, move-to-new-layer, floating selection
│   └── marching_ants.rs                          # Viewport-resolution animated GPU Marching Ants overlay shader
│                                                 # (MARCHING_ANTS_WGSL edge detection on R8Unorm mask — zero DOM SVG ants!)
├── tools/
│   ├── mod.rs                                    # Shared native tool types & hex/color helpers
│   ├── liquify.rs                                # Interactive GPU Rg16Float displacement field (core-spec render pass)
│   │                                             # for all 8 LiquifyModes (push, expand, pinch, push-left, push-right,
│   │                                             # twirl-cw, twirl-ccw, reconstruct), size/strength/hardness/usePressure/
│   │                                             # multiLayer; live in-stack Phase 3 warp + CoW tile bake on commit
│   ├── fill.rs                                   # Direct Rust sparse-tile Flood Fill (refer-all/active/reference, closeGap
│   │                                             # with V-tip recovery, centerline-guarded areaScale, antiAlias, opacity),
│   │                                             # 4×4 AA Lasso Fill, Smart Line Fill (enclose-and-fill, paint-unfilled),
│   │                                             # and instant native Eyedropper/Pipette (<0.03 ms)
│   ├── transform.rs                              # Live GPU in-stack preview + Anti-Ringing Lanczos-3 / Bicubic CoW bake
│   │                                             # for all 5 TransformModes (affine, perspective, Catmull-Rom mesh,
│   │                                             # ARAP puppet warp w/ pin depths, Hormann–Floater MVC cage) across
│   │                                             # single layers, selections, and multi-layer groups + seamless switch_mode
│   ├── retouch.rs                                # 7-mode native tile Retouch (Clone Stamp, Heal, Dodge, Burn, Sponge,
│   │                                             # Smudge w/ 8-band KM pigment mixing, Blur) with CoW undo
│   ├── gradient.rs                               # Linear/Radial/Conical/Diamond/Mesh gradients (live GPU preview + commit)
│   ├── shape.rs                                  # Analytic SDF Shapes, Pen path strokes & QuickShape auto-snapping
│   ├── vector.rs                                 # Fast native vector stroke tessellation & rasterization into layer tiles
│   └── filters.rs                                # Live GPU preview + CoW tile commit for Gaussian blur, motion blur,
│                                                 # unsharp mask, film grain, PCHIP curves, levels, HSL, color balance,
│                                                 # brightness/contrast, gradient map, and RGBA luminance histogram
├── collab/
│   ├── mod.rs                                    # Zero-JS-canvas binary TILE wire codec (EMPTY/SOLID/LZ4/RAW) streaming
│   │                                             # directly between ink-engine sparse tiles and server.rs / WebRTC
│   └── draft_renderer.rs                         # Per-peer live GPU draft layers (PeerDraftSurface) composited natively
│                                                 # inside Phase 3 WgpuCompositor with zero-flicker handoff on commit
├── io/image_codec.rs                             # Pure-Rust lossless WebP (VP8L) + PNG/JPEG export directly from tiles
└── phase6_tests.rs                               # 10 comprehensive Phase 6 unit, DX12 GPU & 4K/8K benchmark tests
src-tauri/src/
├── native_tools.rs                               # Typed Tauri IPC commands for selection, liquify, fill, eyedropper,
│                                                 # transform, retouch, gradient, shape, vector, filters & collab fast-path
└── wic_codec.rs                                  # Hardware-accelerated Windows Imaging Component (WIC) JPEG/PNG encoder

Purged Legacy JS Raster Engines & Dead Pixel-IPC Commands

  • 25 Legacy JS Raster Modules / Directories Deleted (verified absent by src/utils/__tests__/phase6WebviewPurgeAudit.test.ts):
    • src/utils/tileEngine/ (entire directory) & src/utils/tileEngine.ts
    • src/utils/liquifyEngine.ts, src/utils/floodFill.ts, src/utils/smartLineFill.ts
    • src/utils/transformEngine.ts, src/utils/transformResampler.ts, src/utils/puppetWarpEngine.ts, src/utils/cageWarpEngine.ts
    • src/utils/retouchEngine.ts, src/utils/gradientEngine.ts, src/utils/filterEngine.ts, src/utils/tonalEngine.ts
    • src/utils/selectionUtils.ts, src/utils/shapeEngine.ts, src/utils/quickShapeEngine.ts, src/utils/vectorStrokeRenderer.ts
    • src/utils/canvasWebglCompositor.ts, src/utils/canvasBlit.ts, src/utils/pixelSampler.ts, src/utils/layerMaskUtils.ts
    • src/engine/RemoteStrokeRenderer.ts, src/engine/RemoteDraftCanvasManager.ts
    • src/components/canvasArea/SelectionMarchingAnts.tsx (replaced by MARCHING_ANTS_WGSL in wgpu)
    • src/utils/webtoonExporter.ts legacy canvas overload removed (100% native Rust tile slice export)
  • 13 Dead Pixel-IPC Tauri Commands Deleted from src-tauri/src/lib.rs:
    • native_apply_filter, native_flood_fill, native_liquify_step, native_compress_tiles_lz4, native_decompress_tiles_lz4, save_undo_tile_cache, load_undo_tile_cache, parse_psd_file, parse_clip_file, export_psd_file, compose_layer_stack, rasterize_text_layer_legacy, encode_canvas_rgba_png
  • Zero-Canvas WebView2 Memory Audit:
    • src/utils/__tests__/phase6WebviewPurgeAudit.test.ts statically audits all 25 core open, draw, undo, zoom, transform, liquify, collab, webtoon export, and save modules to guarantee zero document.createElement('canvas'), new OffscreenCanvas(...), or full-document <canvas> backing stores exist anywhere in the active WebView2 pipeline.

Final Before / After Architecture & Performance Metrics

Measured in --release on NVIDIA GeForce GTX 1650 (DirectX 12, Windows Desktop, 1920×1080 viewport) via cargo test -p ink-engine phase6_4k_8k --release -- --nocapture and Phase 3–5 DX12 benchmarks:

Metric Legacy WebView2 / WebGL2 + JS Tile Engine (Before) Native Rust + wgpu DX12 Engine (After — Phase 6) Improvement
WebView2 Full-Document Canvas RAM (4K/8K artwork) ~450–900 MB (dense <canvas> + WebGL2 FBOs + JS tile heap) 0 MB (pure transparent React UI shell; zero full-res <canvas>) 100% eliminated
Rust Process Artwork RAM — 4K (3840×2160, 12 layers) (380 MB dense eq.) N/A (duplicated across JS heap & IPC byte copies) 22.75 MB L1 active sparse raw · 0.09 MB L2 LZ4 compressed 16.7× – 4,200× smaller
Rust Process Artwork RAM — 8K (7680×4320, 8 layers) (1,012 MB dense eq.) >1.2 GB / frequent V8 GC pauses & WebGL2 OOM risk 25.00 MB L1 active sparse raw · 0.10 MB L2 LZ4 compressed 40.5× – 10,100× smaller
Stroke Input-to-Photon Frame Time (4K 12-layer, 1080p WYSIWYG DX12) ~18–35 ms (Chromium input -> IPC -> JS brush -> WebGL2 -> DWM) 3.96–5.11 ms (~195–252 FPS; lock-free SPSC Wintab/WinInk -> DX12 waitable swapchain) 4× – 7× lower latency
Pan / Zoom / Rotate Compositor FPS (4K 12-layer, 1080p) 25–55 FPS (JS main-thread + WebGL2 texture uploads) 78–81 FPS worst-case sync headless continuous rotation · 160–240+ FPS live DX12 swapchain w/ 3-slice stack cache 3× – 5× higher FPS
4K Interactive Liquify FPS (160px brush + live 1080p composite) ~8–15 FPS (per-step native_liquify_step CPU/IPC round-trips) 51.5–57.1 FPS sync headless DX12 (120+ FPS pipelined live swapchain; Rg16Float GPU field, 0 IPC) 6× – 10× higher FPS
Undo / Redo Latency (4K 12-layer document, 100-op avg) 15–80 ms (JS ImageData / tile decompress + canvas redraw) 0.039 ms (39.4 µs) (Arc<TileData> O(1) CoW pointer swap) ~400× – 2,000× faster
Eyedropper / Pipette Sample Latency (4K 12-layer composited) 3–12 ms (WebGL2 readPixels GPU pipeline stall) 0.019–0.029 ms (19–29 µs) (direct Rust tile/framebuffer sample) >100× faster (<0.1 ms)

Phase 6 Final Verification Summary

  • cargo test --workspace: 135 passed, 0 failed (ink-engine: 57 passed, including all 10 new Phase 6 unit, DX12 GPU & 4K/8K benchmark tests; src-tauri: 78 passed).
  • cargo clippy --workspace --all-targets: 0 errors across the entire workspace and 0 warnings across all Phase 6 modules (crates/ink-engine/src/selection/*, tools/*, collab/*, io/image_codec.rs, phase6_tests.rs, src-tauri/src/native_tools.rs, wic_codec.rs).
  • npm run build (tsc && vite build): 0 errors (clean production bundle).
  • npm run test (vitest run): 85 test files / 568 tests passing, 0 failures (including phase6WebviewPurgeAudit.test.ts enforcing zero legacy JS raster engines, zero dead pixel-IPC commands, zero full-res <canvas> backing stores, and strict ink-engine decoupling).
  • Hard Decoupling Invariant Preserved: crates/ink-engine/Cargo.toml has zero dependencies on tauri, wry, tao, or webview2-com.