Skip to content

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

2

soraf712fc7dabfc
diff --git a/docs/rust-engine-migration.md b/docs/rust-engine-migration.md
index 3307a14..887caa8 100644
--- a/docs/rust-engine-migration.md
+++ b/docs/rust-engine-migration.md
@@ -150,16 +150,119 @@ All IPC calls are strictly **off the hot stroke/navigation path** (fired only on
---
-## 6. Phase 2 Handoff Notes (Sparse Tile Engine & Multi-Layer GPU Compositor)
-
-Phase 1 deliberately keeps a single RGBA8 test texture inside `crates/ink-engine/src/gpu.rs` so input-to-photon latency and DirectComposition visual layering could be validated end-to-end first. Phase 2 builds directly on this foundation:
-
-1. **Sparse Tile Pyramid & VRAM Pool (`crates/ink-engine/src/tiles.rs`):**
- - Replace `GpuRenderer`'s single `canvas_tex` with a 256×256 sparse tile atlas (`wgpu::Texture` 2D array + LRU resident page table) matching InkStudio's existing `SparseTileGrid` semantics, with mipmapped/cached composite chunks for zoomed-out canvases.
-2. **Multi-Layer Stack & Blend Mode Compositor (`crates/ink-engine/src/compositor.rs`):**
- - Add typed `EngineCommand`s for layer CRUD/reordering/visibility/opacity/blend-modes/clipping/masks/folders/screentone/monochrome expression color, porting the WGSL equivalents of `src/utils/compositor/shaders/coreShaders.ts` into `crates/ink-engine`.
- - Port document load/import (`.ink`, `.psd`, `.clip`) to upload initial raster tiles directly over binary IPC (`tauri::ipc::Request` raw bytes) into `ink-engine` without routing pixel arrays through JS canvas memory.
-3. **Undo/Redo Tile Snapshots & Scratch Disk Integration:**
- - Capture dirty tile diffs on stroke end inside `ink-engine` and compress directly with `lz4_flex` into `src-tauri/src/scratch_disk.rs` and `recovery.rs` WAL entries in-process.
-4. **Full Brush Engine Port (Phase 3):**
- - Expand `crates/ink-engine/src/stroke.rs` from the Phase 1 radial dab PoC to full custom tip textures, sub-tips, dual brush, tilt/twist dynamics, watercolor/natural paint mixing, ribbon tips, stabilizer/prediction, and ruler/symmetry snapping.
+## 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
+
+```text
+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 Handoff Notes (GPU Tiled Compositor & Native Brush Engine)
+
+With Rust now owning the complete multi-layer sparse tile document store, `GpuTilePool` (`Rgba16Float` + `R8Unorm` `Texture2DArray` + LOD 0..3 compute mipmaps), and CoW undo/redo, Phase 3 replaces the Phase 2 CPU-assisted composite upload (`sync_document`) and PoC dab rasterizer with pure GPU-native rendering and painting:
+
+1. **Direct GPU Tiled Multi-Layer Compositor (`crates/ink-engine/src/compositor/`):**
+ - Render the visible viewport directly from `GpuTilePool`'s `Rgba16Float` raster and `R8Unorm` mask `Texture2DArray` slots (choosing LOD 0..3 from camera zoom) via a tiled WGSL render/compute pass — eliminating `composite_document_full_rgba` CPU readback/upload on `sync_document`.
+ - Port all 28 InkStudio/CSP blend modes, clipping-mask chains, isolated folder groups (`PassThrough` vs explicit blend), screentone halftone shaders (`tone_frequency`, `tone_angle`, `tone_dot_shape`), layer color tint (`layer_color` / `layer_sub_color`), adjustment layers, and layer styles to `Rgba16Float` WGSL.
+2. **Native GPU Brush Engine (`crates/ink-engine/src/brush/`):**
+ - Replace the Phase 1/2 radial dab PoC with full custom brush tips, sub-tips, dual brush, tilt/azimuth/barrel rotation, wet-edge watercolor, natural paint pigment mixing / impasto, ribbon tips, stabilizer/prediction, and ruler/symmetry snapping writing directly into `Rgba16Float` working tiles in `GpuTilePool` (with dirty tile sync back to `SparseLayerGrid` + CoW `HistoryStack` on stroke commit).
+3. **Full Native Tool & Filter Parity (Phases 4–5):**
+ - Move selection/marching-ants masks, flood fill, transform/mesh/liquify previews, and vector/comic-frame GPU rendering directly onto the Rust document store.
diff --git a/src/utils/__tests__/nativeEngineBridge.test.ts b/src/utils/__tests__/nativeEngineBridge.test.ts
index b47ea3b..00d07c8 100644
--- a/src/utils/__tests__/nativeEngineBridge.test.ts
+++ b/src/utils/__tests__/nativeEngineBridge.test.ts
@@ -2,10 +2,10 @@ import { describe, expect, it } from 'vitest';
import {
classifyNativeTool,
fromNativeLayerNodeMeta,
+ getNativeMemoryStats,
isNativeCanvasActive,
isNativeStrokeTool,
nativeGetHistory,
- nativeGetMemoryStats,
parseCssColorToRgba,
toNativeLayerNodeMeta,
vramBudgetMbFromPreset,
@@ -88,6 +88,6 @@ describe('nativeEngineBridge', () => {
expect(vramBudgetMbFromPreset('ultra')).toBe(1024);
expect(await nativeGetHistory('doc1')).toBeNull();
- expect(await nativeGetMemoryStats()).toBeNull();
+ expect(await getNativeMemoryStats()).toBeNull();
});
});