Skip to content

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

pre1.0.2

sora1a066fedd14c
diff --git a/package.json b/package.json
index e1401a9..ec6979d 100644
--- a/package.json
+++ b/package.json
@@ -19,14 +19,12 @@
"@tauri-apps/plugin-opener": "^2",
"@tauri-apps/plugin-process": "^2.4.0",
"@tauri-apps/plugin-updater": "^2.14.1",
- "@types/sql.js": "^1.4.11",
"@types/three": "^0.186.0",
"ag-psd": "^31.0.2",
"fflate": "^0.8.3",
"lucide-react": "^1.48.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
- "sql.js": "^1.14.2",
"tailwindcss": "^4.3.3",
"three": "^0.186.1"
},
diff --git a/public/sql-wasm.wasm b/public/sql-wasm.wasm
deleted file mode 100644
index f6487ca..0000000
Binary files a/public/sql-wasm.wasm and /dev/null differ
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 967c463..1013056 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -8,6 +8,18 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "ahash"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "version_check",
+ "zerocopy",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -690,6 +702,25 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
+dependencies = [
+ "crossbeam-utils",
+]
+
[[package]]
name = "crossbeam-utils"
version = "0.8.23"
@@ -1026,6 +1057,12 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+[[package]]
+name = "either"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+
[[package]]
name = "embed-resource"
version = "3.0.11"
@@ -1120,6 +1157,18 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "fallible-iterator"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
+
+[[package]]
+name = "fallible-streaming-iterator"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
+
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -1603,12 +1652,30 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+[[package]]
+name = "hashbrown"
+version = "0.14.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
+dependencies = [
+ "ahash",
+]
+
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+[[package]]
+name = "hashlink"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
+dependencies = [
+ "hashbrown 0.14.5",
+]
+
[[package]]
name = "heck"
version = "0.4.1"
@@ -1957,11 +2024,14 @@ name = "ink-studio"
version = "1.0.1"
dependencies = [
"axum",
+ "flate2",
"futures-util",
"getrandom 0.2.17",
"hex",
"lz4_flex",
"mime_guess",
+ "rayon",
+ "rusqlite",
"rust-embed",
"serde",
"serde_json",
@@ -1973,6 +2043,7 @@ dependencies = [
"tauri-plugin-updater",
"tokio",
"tower-http 0.5.2",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -2258,6 +2329,17 @@ dependencies = [
"libc",
]
+[[package]]
+name = "libsqlite3-sys"
+version = "0.30.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
+dependencies = [
+ "cc",
+ "pkg-config",
+ "vcpkg",
+]
+
[[package]]
name = "link-section"
version = "0.19.4"
@@ -3166,6 +3248,26 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -3287,6 +3389,20 @@ dependencies = [
"windows-sys 0.52.0",
]
+[[package]]
+name = "rusqlite"
+version = "0.32.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
+dependencies = [
+ "bitflags 2.13.2",
+ "fallible-iterator",
+ "fallible-streaming-iterator",
+ "hashlink",
+ "libsqlite3-sys",
+ "smallvec",
+]
+
[[package]]
name = "rust-embed"
version = "8.12.0"
@@ -4974,6 +5090,12 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "vcpkg"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+
[[package]]
name = "version-compare"
version = "0.2.1"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index a1a0f14..1cad739 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -34,6 +34,22 @@ lz4_flex = "0.11"
getrandom = "0.2"
sha2 = "0.10"
hex = "0.4"
+rayon = "1.10"
+flate2 = "1.0"
+rusqlite = { version = "0.32", features = ["bundled", "serialize"] }
+
+[target.'cfg(target_os = "windows")'.dependencies]
+windows-sys = { version = "0.59", features = [
+ "Win32_Foundation",
+ "Win32_Graphics_Gdi",
+ "Win32_System_LibraryLoader",
+ "Win32_System_Performance",
+ "Win32_System_Threading",
+ "Win32_UI_HiDpi",
+ "Win32_UI_Input_Pointer",
+ "Win32_UI_Shell",
+ "Win32_UI_WindowsAndMessaging",
+] }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-updater = "2"
diff --git a/src-tauri/src/clip_parser.rs b/src-tauri/src/clip_parser.rs
new file mode 100644
index 0000000..f208088
--- /dev/null
+++ b/src-tauri/src/clip_parser.rs
@@ -0,0 +1,1802 @@
+use crate::doc_wire::{
+ blit_offset_tile_into_map, pack_parsed_document, AssembledLayer, RawMask, RawTile, BYTES_32BIT,
+ MAX_CANVAS_DIM, TILE_PIXELS, TILE_SIZE,
+};
+use flate2::read::{DeflateDecoder, ZlibDecoder};
+use rayon::prelude::*;
+use rusqlite::{config::DbConfig, types::Value, Connection, DatabaseName};
+use serde::Serialize;
+use std::collections::{HashMap, HashSet};
+use std::io::Read;
+
+const MAX_BLOCKS_PER_LAYER: usize = 16384; // 128x128 tiles = 32768x32768 px
+const MAX_COMPRESSED_TILE_BYTES: usize = 2 * 1024 * 1024;
+const MAX_DECOMPRESSED_TILE_BYTES: usize = 2 * 1024 * 1024;
+const MAX_FOLDER_DEPTH: usize = 64;
+const MAX_LAYERS: usize = 4096;
+const MAX_SQLITE_BYTES: usize = 256 * 1024 * 1024;
+
+const SQLITE_SIG: &[u8; 16] = b"SQLite format 3\0";
+
+fn encode_utf16be_tagged(ascii: &str) -> Vec<u8> {
+ let mut out = Vec::with_capacity(4 + ascii.len() * 2);
+ out.extend_from_slice(&(ascii.len() as u32).to_be_bytes());
+ for &b in ascii.as_bytes() {
+ out.push(0);
+ out.push(b);
+ }
+ out
+}
+
+fn tag_block_begin() -> &'static [u8] {
+ static TAG: std::sync::LazyLock<Vec<u8>> =
+ std::sync::LazyLock::new(|| encode_utf16be_tagged("BlockDataBeginChunk"));
+ &TAG
+}
+
+fn tag_block_end() -> &'static [u8] {
+ static TAG: std::sync::LazyLock<Vec<u8>> =
+ std::sync::LazyLock::new(|| encode_utf16be_tagged("BlockDataEndChunk"));
+ &TAG
+}
+
+fn tag_parameter() -> &'static [u8] {
+ static TAG: std::sync::LazyLock<Vec<u8>> =
+ std::sync::LazyLock::new(|| encode_utf16be_tagged("Parameter"));
+ &TAG
+}
+
+fn tag_init_color() -> &'static [u8] {
+ static TAG: std::sync::LazyLock<Vec<u8>> =
+ std::sync::LazyLock::new(|| encode_utf16be_tagged("InitColor"));
+ &TAG
+}
+
+pub fn map_csp_blend_mode(val: i64) -> &'static str {
+ match val {
+ 0 => "normal",
+ 1 => "darken",
+ 2 => "multiply",
+ 3 => "color-burn",
+ 4 => "linear-burn",
+ 5 => "subtract",
+ 6 => "darker-color",
+ 7 => "lighten",
+ 8 => "screen",
+ 9 => "color-dodge",
+ 10 => "color-dodge-glow",
+ 11 | 12 => "add-glow",
+ 13 => "lighter-color",
+ 14 => "overlay",
+ 15 => "soft-light",
+ 16 => "hard-light",
+ 17 => "vivid-light",
+ 18 => "linear-light",
+ 19 => "pin-light",
+ 20 => "hard-mix",
+ 21 => "difference",
+ 22 => "exclusion",
+ 23 => "hue",
+ 24 => "saturation",
+ 25 => "color",
+ 26 => "luminosity",
+ 30 => "pass-through",
+ 36 => "divide",
+ _ => "normal",
+ }
+}
+
+#[inline]
+fn read_u32_be(buf: &[u8], off: usize) -> Option<u32> {
+ let slice = buf.get(off..off + 4)?;
+ Some(u32::from_be_bytes(slice.try_into().ok()?))
+}
+
+#[inline]
+fn read_u64_be(buf: &[u8], off: usize) -> Option<u64> {
+ let slice = buf.get(off..off + 8)?;
+ Some(u64::from_be_bytes(slice.try_into().ok()?))
+}
+
+fn find_bytes(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
+ let nlen = needle.len();
+ if nlen == 0 || from + nlen > haystack.len() {
+ return None;
+ }
+ let first = needle[0];
+ let mut pos = from;
+ let limit = haystack.len() - nlen;
+ while pos <= limit {
+ let rel = haystack[pos..=limit].iter().position(|&b| b == first)?;
+ let idx = pos + rel;
+ if &haystack[idx..idx + nlen] == needle {
+ return Some(idx);
+ }
+ pos = idx + 1;
+ }
+ None
+}
+
+#[inline]
+fn is_zlib_header(b0: u8, b1: u8) -> bool {
+ b0 == 0x78 && matches!(b1, 0x01 | 0x5e | 0x9c | 0xda)
+}
+
+/// Bounded zlib decompression immune to zip bombs.
+fn safe_unzlib(src: &[u8], max_out: usize) -> Option<Vec<u8>> {
+ if src.len() < 6 || src.len() > MAX_COMPRESSED_TILE_BYTES {
+ return None;
+ }
+ let mut decoder = ZlibDecoder::new(src);
+ let mut out = Vec::new();
+ let mut limited = (&mut decoder).take((max_out as u64) + 1);
+ if limited.read_to_end(&mut out).is_ok() && !out.is_empty() && out.len() <= max_out {
+ return Some(out);
+ }
+
+ // Fallback: raw deflate stream skipping 2-byte zlib header (handles missing/bad adler32)
+ if src.len() > 2 && is_zlib_header(src[0], src[1]) {
+ let mut raw_dec = DeflateDecoder::new(&src[2..]);
+ let mut raw_out = Vec::new();
+ let mut limited_raw = (&mut raw_dec).take((max_out as u64) + 1);
+ if limited_raw.read_to_end(&mut raw_out).is_ok()
+ && !raw_out.is_empty()
+ && raw_out.len() <= max_out
+ {
+ return Some(raw_out);
+ }
+ }
+ None
+}
+
+pub struct CspChunk<'a> {
+ pub name: [u8; 4],
+ pub data: &'a [u8],
+}
+
+pub fn parse_csp_chunks(buffer: &[u8]) -> Vec<CspChunk<'_>> {
+ let mut chunks = Vec::new();
+ if buffer.len() < 24 || &buffer[0..8] != b"CSFCHUNK" {
+ return chunks;
+ }
+ let mut offset = 24usize;
+ while offset + 16 <= buffer.len() {
+ if &buffer[offset..offset + 4] != b"CHNK" {
+ break;
+ }
+ let name: [u8; 4] = buffer[offset + 4..offset + 8].try_into().unwrap();
+ let Some(chunk_size_u64) = read_u64_be(buffer, offset + 8) else {
+ break;
+ };
+ let Ok(chunk_size) = usize::try_from(chunk_size_u64) else {
+ break;
+ };
+ let data_start = offset + 16;
+ let Some(data_end) = data_start.checked_add(chunk_size) else {
+ break;
+ };
+ if data_end > buffer.len() {
+ break;
+ }
+ chunks.push(CspChunk {
+ name,
+ data: &buffer[data_start..data_end],
+ });
+ offset = data_end;
+ if &name == b"Foot" {
+ break;
+ }
+ }
+ chunks
+}
+
+fn find_sqlite_data<'a>(chunks: &[CspChunk<'a>], raw: &'a [u8]) -> Option<&'a [u8]> {
+ if raw.len() >= 16 && &raw[0..16] == SQLITE_SIG {
+ return Some(raw);
+ }
+ if let Some(sqli) = chunks.iter().find(|c| &c.name == b"SQLi") {
+ if let Some(idx) = find_bytes(sqli.data, SQLITE_SIG, 0) {
+ return Some(&sqli.data[idx..]);
+ }
+ }
+ let idx = find_bytes(raw, SQLITE_SIG, 0)?;
+ Some(&raw[idx..])
+}
+
+fn extract_exta_chunks<'a>(chunks: &[CspChunk<'a>]) -> HashMap<String, &'a [u8]> {
+ let mut map = HashMap::new();
+ let tag_begin = tag_block_begin();
+ for c in chunks {
+ if &c.name != b"Exta" || c.data.len() < 16 {
+ continue;
+ }
+ let Some(id_len_u64) = read_u64_be(c.data, 0) else {
+ continue;
+ };
+ if id_len_u64 == 0 || id_len_u64 > 256 {
+ continue;
+ }
+ let id_len = id_len_u64 as usize;
+ let after_id = 8 + id_len;
+ if after_id > c.data.len() {
+ continue;
+ }
+ let external_id = String::from_utf8_lossy(&c.data[8..after_id])
+ .trim_end_matches('\0')
+ .to_string();
+
+ let mut payload_start = after_id;
+ if after_id + 8 <= c.data.len() {
+ if let Some(maybe_len) = read_u64_be(c.data, after_id) {
+ let remaining = (c.data.len() - (after_id + 8)) as u64;
+ if maybe_len == remaining {
+ payload_start = after_id + 8;
+ } else {
+ let t8 = find_bytes(c.data, tag_begin, after_id + 8);
+ let t0 = find_bytes(c.data, tag_begin, after_id);
+ if t8.is_some() && t0 == t8 {
+ payload_start = after_id + 8;
+ }
+ }
+ }
+ }
+ map.insert(external_id, &c.data[payload_start..]);
+ }
+ map
+}
+
+#[derive(Debug, Clone)]
+struct ParsedOffscreenAttribute {
+ bitmap_width: u32,
+ bitmap_height: u32,
+ block_grid_width: u32,
+ block_grid_height: u32,
+ default_fill: u32,
+ init_color: Option<[u8; 4]>,
+}
+
+fn normalize_color_channel_u64(v: u64) -> u8 {
+ if v <= 255 {
+ v as u8
+ } else if v <= 65535 {
+ ((v >> 8) & 0xff) as u8
+ } else {
+ ((v >> 24) & 0xff) as u8
+ }
+}
+
+fn parse_offscreen_attribute(
+ blob: Option<&[u8]>,
+ fallback_w: u32,
+ fallback_h: u32,
+) -> ParsedOffscreenAttribute {
+ let mut def = ParsedOffscreenAttribute {
+ bitmap_width: fallback_w,
+ bitmap_height: fallback_h,
+ block_grid_width: fallback_w.div_ceil(TILE_SIZE as u32).max(1),
+ block_grid_height: fallback_h.div_ceil(TILE_SIZE as u32).max(1),
+ default_fill: 0,
+ init_color: None,
+ };
+
+ let Some(blob) = blob else { return def };
+ if blob.len() < 32 {
+ return def;
+ }
+
+ let t_param = tag_parameter();
+ if let Some(param_idx) = find_bytes(blob, t_param, 0) {
+ let after = param_idx + t_param.len();
+ let mut base = None;
+ for shift in [0usize, 4, 8, 12] {
+ let p = after + shift;
+ if p + 16 > blob.len() {
+ break;
+ }
+ let bw = read_u32_be(blob, p).unwrap_or(0);
+ let bh = read_u32_be(blob, p + 4).unwrap_or(0);
+ let gw = read_u32_be(blob, p + 8).unwrap_or(0);
+ let gh = read_u32_be(blob, p + 12).unwrap_or(0);
+ if bw > 0
+ && bh > 0
+ && bw <= MAX_CANVAS_DIM
+ && bh <= MAX_CANVAS_DIM
+ && gw == bw.div_ceil(TILE_SIZE as u32)
+ && gh == bh.div_ceil(TILE_SIZE as u32)
+ {
+ base = Some(p);
+ break;
+ }
+ }
+ if let Some(p) = base {
+ def.bitmap_width = read_u32_be(blob, p).unwrap_or(fallback_w);
+ def.bitmap_height = read_u32_be(blob, p + 4).unwrap_or(fallback_h);
+ def.block_grid_width = read_u32_be(blob, p + 8).unwrap_or(def.block_grid_width);
+ def.block_grid_height = read_u32_be(blob, p + 12).unwrap_or(def.block_grid_height);
+ if p + 20 <= blob.len() {
+ def.default_fill = read_u32_be(blob, p + 16).unwrap_or(0);
+ }
+ }
+ }
+
+ let t_init = tag_init_color();
+ if let Some(init_idx) = find_bytes(blob, t_init, 0) {
+ let p = init_idx + t_init.len();
+ if p + 20 <= blob.len() {
+ let enabled = read_u32_be(blob, p).unwrap_or(0);
+ if enabled == 1 {
+ let c0 = read_u32_be(blob, p + 4).unwrap_or(0) as u64;
+ let c1 = read_u32_be(blob, p + 8).unwrap_or(0) as u64;
+ let c2 = read_u32_be(blob, p + 12).unwrap_or(0) as u64;
+ let c3 = read_u32_be(blob, p + 16).unwrap_or(0) as u64;
+ def.init_color = Some([
+ normalize_color_channel_u64(c0),
+ normalize_color_channel_u64(c1),
+ normalize_color_channel_u64(c2),
+ if c3 > 0 {
+ normalize_color_channel_u64(c3)
+ } else {
+ 255
+ },
+ ]);
+ }
+ }
+ }
+
+ def
+}
+
+#[inline]
+fn is_valid_tile_byte_len(len: usize) -> bool {
+ matches!(
+ len,
+ 327680 | 262144 | 131072 | 65536 | 16384 | 8192
+ )
+}
+
+fn merge_planes(planes: Vec<Vec<u8>>) -> Option<Vec<u8>> {
+ if planes.is_empty() {
+ return None;
+ }
+ if planes.len() == 1 {
+ return planes.into_iter().next();
+ }
+ let total: usize = planes.iter().map(|p| p.len()).sum();
+ if total > MAX_DECOMPRESSED_TILE_BYTES {
+ return None;
+ }
+ let mut merged = Vec::with_capacity(total);
+ for p in planes {
+ merged.extend_from_slice(&p);
+ }
+ Some(merged)
+}
+
+fn decompress_block_span(span: &[u8]) -> Option<Vec<u8>> {
+ if span.len() < 6 {
+ return None;
+ }
+
+ // Path 1: Standard CSP framed sub-blocks [u32BE outerLen][u32LE innerLen][zlib...]
+ let mut planes = Vec::new();
+ let mut pos = 0usize;
+ while pos + 8 <= span.len() {
+ let outer_len = read_u32_be(span, pos)? as usize;
+ if outer_len < 6 || pos + 4 + outer_len > span.len() {
+ break;
+ }
+ let mut z_start = pos + 8;
+ let z_end = pos + 4 + outer_len;
+ if z_start + 2 <= z_end && is_zlib_header(span[z_start], span[z_start + 1]) {
+ // standard framed
+ } else if pos + 6 <= z_end && is_zlib_header(span[pos + 4], span[pos + 5]) {
+ z_start = pos + 4;
+ } else {
+ break;
+ }
+ let decoded = safe_unzlib(&span[z_start..z_end], MAX_DECOMPRESSED_TILE_BYTES)?;
+ planes.push(decoded);
+ pos = z_end;
+ }
+
+ if !planes.is_empty() {
+ if let Some(merged) = merge_planes(planes) {
+ if pos == span.len() || is_valid_tile_byte_len(merged.len()) {
+ return Some(merged);
+ }
+ }
+ }
+
+ // Path 2: Direct zlib stream at +0, +4, +8
+ for off in [0usize, 4, 8] {
+ if off + 6 <= span.len() && is_zlib_header(span[off], span[off + 1]) {
+ if let Some(decoded) = safe_unzlib(&span[off..], MAX_DECOMPRESSED_TILE_BYTES) {
+ return Some(decoded);
+ }
+ }
+ }
+
+ None
+}
+
+/// Scans BlockData spans sequentially (zero-copy slices), then decompresses all populated blocks in parallel via Rayon.
+fn parse_block_data_payload_parallel(
+ payload: &[u8],
+ expected_blocks: usize,
+) -> Vec<(usize, Vec<u8>)> {
+ let max_blocks = expected_blocks.clamp(1, MAX_BLOCKS_PER_LAYER);
+ let t_begin = tag_block_begin();
+ let t_end = tag_block_end();
+
+ let mut raw_entries: Vec<(usize, Option<&[u8]>)> = Vec::new();
+ let mut cursor = 0usize;
+ let mut seq_idx = 0usize;
+ let mut found_tagged = false;
+
+ while cursor < payload.len() && seq_idx < max_blocks * 2 {
+ let Some(begin_pos) = find_bytes(payload, t_begin, cursor) else {
+ break;
+ };
+ found_tagged = true;
+ let after_begin = begin_pos + t_begin.len();
+ let end_pos = find_bytes(payload, t_end, after_begin);
+ let next_begin = find_bytes(payload, t_begin, after_begin);
+
+ if let Some(nb) = next_begin {
+ if end_pos.map_or(true, |ep| nb < ep) {
+ raw_entries.push((seq_idx, None));
+ seq_idx += 1;
+ cursor = nb;
+ continue;
+ }
+ }
+ let Some(ep) = end_pos else { break };
+ let inner = &payload[after_begin..ep];
+ let raw_index = read_u32_be(inner, 0).map_or(seq_idx, |v| v as usize);
+ raw_entries.push((raw_index, Some(inner)));
+ seq_idx += 1;
+ cursor = ep + t_end.len();
+ }
+
+ if found_tagged {
+ let mut use_raw_index = raw_entries.len() < expected_blocks && !raw_entries.is_empty();
+ if use_raw_index {
+ let mut prev: isize = -1;
+ for (ri, _) in &raw_entries {
+ if (*ri as isize) <= prev || *ri >= max_blocks {
+ use_raw_index = false;
+ break;
+ }
+ prev = *ri as isize;
+ }
+ }
+
+ // Parallel zlib decompression across all blocks
+ return raw_entries
+ .into_par_iter()
+ .enumerate()
+ .filter_map(|(i, (raw_idx, inner_opt))| {
+ let inner = inner_opt?;
+ if inner.len() <= 20 {
+ return None;
+ }
+ let has_data = read_u32_be(inner, 16).unwrap_or(0);
+ let mut decompressed = if has_data != 0 {
+ decompress_block_span(&inner[20..])
+ } else {
+ None
+ };
+ if decompressed.is_none() && inner.len() > 28 {
+ for hdr_len in [16usize, 24, 12, 8] {
+ if inner.len() <= hdr_len + 6 {
+ continue;
+ }
+ if let Some(cand) = decompress_block_span(&inner[hdr_len..]) {
+ if is_valid_tile_byte_len(cand.len()) {
+ decompressed = Some(cand);
+ break;
+ }
+ }
+ }
+ }
+ let data = decompressed?;
+ let grid_idx = if use_raw_index { raw_idx } else { i };
+ Some((grid_idx, data))
+ })
+ .collect();
+ }
+
+ // Fallback: non-tagged raw zlib streams
+ let mut out = Vec::new();
+ let mut block_idx = 0usize;
+ let mut i = 0usize;
+ while i + 8 < payload.len() && block_idx < max_blocks {
+ if is_zlib_header(payload[i], payload[i + 1]) {
+ if let Some(dec) = safe_unzlib(&payload[i..], MAX_DECOMPRESSED_TILE_BYTES) {
+ if is_valid_tile_byte_len(dec.len()) {
+ out.push((block_idx, dec));
+ block_idx += 1;
+ i += 32;
+ continue;
+ }
+ }
+ }
+ i += 1;
+ }
+ out
+}
+
+/// Decodes a decompressed 256x256 CSP tile into RGBA8. Returns None if fully transparent.
+fn decode_csp_tile_to_rgba(raw: &[u8], default_fill: u32) -> Option<Vec<u8>> {
+ let len = raw.len();
+ let mut out = vec![0u8; BYTES_32BIT];
+ let mut has_pixels = false;
+
+ // 1. Standard 32-bit Color: Alpha(65536) + BGRX(262144) = 327680
+ if len >= TILE_PIXELS * 5 {
+ let color = &raw[TILE_PIXELS..];
+ for p in 0..TILE_PIXELS {
+ let a = raw[p];
+ if a != 0 {
+ let di = p << 2;
+ out[di] = color[di + 2];
+ out[di + 1] = color[di + 1];
+ out[di + 2] = color[di];
+ out[di + 3] = a;
+ has_pixels = true;
+ }
+ }
+ return if has_pixels { Some(out) } else { None };
+ }
+
+ // 2. Single-plane BGRA/BGRX (262144)
+ if len >= TILE_PIXELS * 4 {
+ let any_alpha = raw.chunks_exact(4).take(TILE_PIXELS).any(|c| c[3] != 0);
+ for p in 0..TILE_PIXELS {
+ let i = p << 2;
+ let b = raw[i];
+ let g = raw[i + 1];
+ let r = raw[i + 2];
+ let a = if any_alpha {
+ raw[i + 3]
+ } else if (r | g | b) != 0 {
+ 255
+ } else {
+ 0
+ };
+ if a != 0 {
+ out[i] = r;
+ out[i + 1] = g;
+ out[i + 2] = b;
+ out[i + 3] = a;
+ has_pixels = true;
+ }
+ }
+ return if has_pixels { Some(out) } else { None };
+ }
+
+ // 3. Grayscale 2-plane: Alpha(65536) + Gray(65536) = 131072
+ if len >= TILE_PIXELS * 2 {
+ let gray = &raw[TILE_PIXELS..];
+ for p in 0..TILE_PIXELS {
+ let a = raw[p];
+ if a != 0 {
+ let g = gray[p];
+ let di = p << 2;
+ out[di] = g;
+ out[di + 1] = g;
+ out[di + 2] = g;
+ out[di + 3] = a;
+ has_pixels = true;
+ }
+ }
+ return if has_pixels { Some(out) } else { None };
+ }
+
+ // 4. Single-channel 8-bit (65536): Alpha-only ink
+ if len >= TILE_PIXELS {
+ let ink = if default_fill == 1 { 255u8 } else { 0u8 };
+ for p in 0..TILE_PIXELS {
+ let a = raw[p];
+ if a != 0 {
+ let di = p << 2;
+ out[di] = ink;
+ out[di + 1] = ink;
+ out[di + 2] = ink;
+ out[di + 3] = a;
+ has_pixels = true;
+ }
+ }
+ return if has_pixels { Some(out) } else { None };
+ }
+
+ // 5. Monochrome 2-plane 1-bit (16384)
+ if len >= 16384 {
+ for byte_idx in 0..8192 {
+ let a_byte = raw[byte_idx];
+ if a_byte == 0 {
+ continue;
+ }
+ let c_byte = raw[8192 + byte_idx];
+ let base_p = byte_idx << 3;
+ for bit in 0..8 {
+ let mask = 1u8 << (7 - bit);
+ if (a_byte & mask) != 0 {
+ let c = if (c_byte & mask) != 0 { 255 } else { 0 };
+ let di = (base_p + bit) << 2;
+ out[di] = c;
+ out[di + 1] = c;
+ out[di + 2] = c;
+ out[di + 3] = 255;
+ has_pixels = true;
+ }
+ }
+ }
+ return if has_pixels { Some(out) } else { None };
+ }
+
+ // 6. Monochrome 1-plane 1-bit (8192)
+ if len >= 8192 {
+ let ink = if default_fill == 1 { 255u8 } else { 0u8 };
+ for byte_idx in 0..8192 {
+ let a_byte = raw[byte_idx];
+ if a_byte == 0 {
+ continue;
+ }
+ let base_p = byte_idx << 3;
+ for bit in 0..8 {
+ if (a_byte & (1u8 << (7 - bit))) != 0 {
+ let di = (base_p + bit) << 2;
+ out[di] = ink;
+ out[di + 1] = ink;
+ out[di + 2] = ink;
+ out[di + 3] = 255;
+ has_pixels = true;
+ }
+ }
+ }
+ return if has_pixels { Some(out) } else { None };
+ }
+
+ None
+}
+
+fn decode_csp_tile_to_mask(raw: &[u8]) -> Option<Vec<u8>> {
+ if raw.len() >= TILE_PIXELS {
+ return Some(raw[..TILE_PIXELS].to_vec());
+ }
+ if raw.len() >= 8192 {
+ let mut out = vec![0u8; TILE_PIXELS];
+ for byte_idx in 0..8192 {
+ let b = raw[byte_idx];
+ let base = byte_idx << 3;
+ for bit in 0..8 {
+ out[base + bit] = if (b & (1u8 << (7 - bit))) != 0 {
+ 255
+ } else {
+ 0
+ };
+ }
+ }
+ return Some(out);
+ }
+ None
+}
+
+type SqlRow = HashMap<String, Value>;
+
+fn open_readonly_mem_sqlite(sqlite_bytes: &[u8]) -> Result<Connection, String> {
+ if sqlite_bytes.is_empty() || sqlite_bytes.len() > MAX_SQLITE_BYTES {
+ return Err("Embedded SQLite database size is invalid or exceeds 256 MB safety ceiling".to_string());
+ }
+ let mut conn = Connection::open_in_memory()
+ .map_err(|e| format!("Failed to initialize SQLite engine: {}", e))?;
+ // Harden against untrusted SQLite payloads (disable triggers/views/write ops/untrusted schema)
+ let _ = conn.set_db_config(DbConfig::SQLITE_DBCONFIG_DEFENSIVE, true);
+ let _ = conn.set_db_config(DbConfig::SQLITE_DBCONFIG_TRUSTED_SCHEMA, false);
+ let _ = conn.execute_batch("PRAGMA query_only = ON;");
+
+ let sz = sqlite_bytes.len();
+ let raw_ptr = unsafe { rusqlite::ffi::sqlite3_malloc64(sz as u64) } as *mut u8;
+ let Some(non_null) = std::ptr::NonNull::new(raw_ptr) else {
+ return Err("SQLite memory allocation failed".to_string());
+ };
+ unsafe {
+ std::ptr::copy_nonoverlapping(sqlite_bytes.as_ptr(), non_null.as_ptr(), sz);
+ }
+ let owned = unsafe { rusqlite::serialize::OwnedData::from_raw_nonnull(non_null, sz) };
+ conn.deserialize(DatabaseName::Main, owned, true)
+ .map_err(|e| format!("Failed to deserialize embedded SQLite database: {}", e))?;
+ let _ = conn.execute_batch("PRAGMA query_only = ON;");
+ Ok(conn)
+}
+
+fn get_table_names(conn: &Connection) -> HashSet<String> {
+ let mut set = HashSet::new();
+ let Ok(mut stmt) = conn.prepare("SELECT name FROM sqlite_master WHERE type='table'") else {
+ return set;
+ };
+ let Ok(rows) = stmt.query_map([], |r| r.get::<_, String>(0)) else {
+ return set;
+ };
+ for name in rows.flatten() {
+ set.insert(name);
+ }
+ set
+}
+
+fn query_table(conn: &Connection, tables: &HashSet<String>, name: &str) -> Vec<SqlRow> {
+ if !tables.contains(name) {
+ return Vec::new();
+ }
+ let escaped = name.replace('"', "\"\"");
+ let sql = format!("SELECT * FROM \"{}\"", escaped);
+ let Ok(mut stmt) = conn.prepare(&sql) else {
+ return Vec::new();
+ };
+ let col_names: Vec<String> = stmt.column_names().into_iter().map(String::from).collect();
+ let Ok(rows) = stmt.query_map([], |row| {
+ let mut map = HashMap::with_capacity(col_names.len());
+ for (idx, cname) in col_names.iter().enumerate() {
+ if let Ok(val) = row.get::<_, Value>(idx) {
+ map.insert(cname.clone(), val);
+ }
+ }
+ Ok(map)
+ }) else {
+ return Vec::new();
+ };
+ rows.flatten().collect()
+}
+
+fn get_opt_f64(row: &SqlRow, keys: &[&str]) -> Option<f64> {
+ for &k in keys {
+ if let Some(v) = row.get(k) {
+ match v {
+ Value::Integer(i) => return Some(*i as f64),
+ Value::Real(f) if f.is_finite() => return Some(*f),
+ _ => {}
+ }
+ }
+ }
+ None
+}
+
+fn get_i64(row: &SqlRow, keys: &[&str], fallback: i64) -> i64 {
+ get_opt_f64(row, keys).map_or(fallback, |f| f.round() as i64)
+}
+
+fn get_opt_i64(row: &SqlRow, keys: &[&str]) -> Option<i64> {
+ get_opt_f64(row, keys).map(|f| f.round() as i64)
+}
+
+fn get_f64(row: &SqlRow, keys: &[&str], fallback: f64) -> f64 {
+ get_opt_f64(row, keys).unwrap_or(fallback)
+}
+
+fn get_str(row: &SqlRow, keys: &[&str], fallback: &str) -> String {
+ for &k in keys {
+ if let Some(v) = row.get(k) {
+ match v {
+ Value::Text(s) if !s.is_empty() => {
+ return s.trim_end_matches('\0').to_string();
+ }
+ Value::Blob(b) if !b.is_empty() => {
+ let s = String::from_utf8_lossy(b).trim_end_matches('\0').to_string();
+ if !s.is_empty() {
+ return s;
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ fallback.to_string()
+}
+
+fn get_bytes<'a>(row: &'a SqlRow, keys: &[&str]) -> Option<&'a [u8]> {
+ for &k in keys {
+ if let Some(Value::Blob(b)) = row.get(k) {
+ if !b.is_empty() {
+ return Some(b.as_slice());
+ }
+ }
+ }
+ None
+}
+
+fn rgb_to_hex(r: u8, g: u8, b: u8) -> String {
+ format!("#{:02x}{:02x}{:02x}", r, g, b)
+}
+
+#[derive(Clone)]
+struct OffscreenRecord {
+ main_id: i64,
+ block_data_id: String,
+ attribute: Option<Vec<u8>>,
+}
+
+#[derive(Clone, Copy)]
+struct MipmapInfoRecord {
+ offscreen_id: i64,
+ this_scale: f64,
+ next_index: i64,
+}
+
+fn extract_solid_fill_color(
+ layer_row: &SqlRow,
+ attr: Option<&ParsedOffscreenAttribute>,
+ fill_by_layer_id: &HashMap<i64, String>,
+ is_bottom_most: bool,
+) -> Option<String> {
+ let main_id = get_i64(layer_row, &["MainId"], -1);
+ if let Some(hex) = fill_by_layer_id.get(&main_id) {
+ return Some(hex.clone());
+ }
+ if let (Some(r), Some(g), Some(b)) = (
+ get_opt_i64(layer_row, &["LayerFillRed", "FillColorRed", "PaperRed"]),
+ get_opt_i64(layer_row, &["LayerFillGreen", "FillColorGreen", "PaperGreen"]),
+ get_opt_i64(layer_row, &["LayerFillBlue", "FillColorBlue", "PaperBlue"]),
+ ) {
+ return Some(rgb_to_hex(
+ normalize_color_channel_u64(r.max(0) as u64),
+ normalize_color_channel_u64(g.max(0) as u64),
+ normalize_color_channel_u64(b.max(0) as u64),
+ ));
+ }
+ if let Some(packed) = get_opt_i64(layer_row, &["LayerFillColor", "SolidColor", "PaperColor"]) {
+ if packed != 0 {
+ let p = packed as u32;
+ return Some(rgb_to_hex(
+ ((p >> 16) & 0xff) as u8,
+ ((p >> 8) & 0xff) as u8,
+ (p & 0xff) as u8,
+ ));
+ }
+ }
+ if let Some(a) = attr {
+ if let Some(ic) = a.init_color {
+ if ic[3] > 0 {
+ return Some(rgb_to_hex(ic[0], ic[1], ic[2]));
+ }
+ }
+ }
+ let name = get_str(layer_row, &["LayerName"], "").trim().to_lowercase();
+ let is_paper_name = matches!(name.as_str(), "paper" | "用紙" | "papier" | "papel");
+ let layer_type = get_i64(layer_row, &["LayerType"], -1);
+ if is_paper_name
+ || (is_bottom_most && attr.map_or(false, |a| a.default_fill == 1))
+ || layer_type == 1280
+ {
+ return Some("#ffffff".to_string());
+ }
+ None
+}
+
+/// Parses a `.clip` / `.csp` / `.lip` file buffer natively using bundled rusqlite + flate2 + rayon,
+/// returning the compact `INKD` binary wire frame with LZ4-compressed 256x256 tiles.
+pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {
+ let chunks = parse_csp_chunks(bytes);
+ let sqlite_data = find_sqlite_data(&chunks, bytes).ok_or_else(|| {
+ "Could not find SQLite database metadata within Clip Studio Paint file.".to_string()
+ })?;
+
+ let conn = open_readonly_mem_sqlite(sqlite_data)?;
+ let tables = get_table_names(&conn);
+
+ // 1. Canvas metadata
+ let mut width = 1440u32;
+ let mut height = 900u32;
+ let mut dpi = 300u32;
+ let mut root_folder_id: Option<i64> = None;
+
+ let canvas_rows = query_table(&conn, &tables, "Canvas");
+ if let Some(c) = canvas_rows.first() {
+ width = (get_f64(c, &["CanvasWidth"], 1440.0).round() as i64).clamp(1, MAX_CANVAS_DIM as i64)
+ as u32;
+ height = (get_f64(c, &["CanvasHeight"], 900.0).round() as i64)
+ .clamp(1, MAX_CANVAS_DIM as i64) as u32;
+ dpi = (get_f64(c, &["CanvasResolution", "CanvasDpi"], 300.0).round() as i64).clamp(1, 2400)
+ as u32;
+ root_folder_id = get_opt_i64(c, &["CanvasRootFolder"]);
+ }
+
+ // 2. Preview image
+ let mut preview: Option<(Vec<u8>, String)> = None;
+ let preview_rows = query_table(&conn, &tables, "CanvasPreview");
+ if let Some(pr) = preview_rows.first() {
+ if let Some(pb) = get_bytes(pr, &["ImageData"]) {
+ if pb.len() >= 8 {
+ if pb.starts_with(&[0x89, 0x50, 0x4e, 0x47]) {
+ preview = Some((pb.to_vec(), "image/png".to_string()));
+ } else if pb.starts_with(&[0xff, 0xd8, 0xff]) {
+ preview = Some((pb.to_vec(), "image/jpeg".to_string()));
+ }
+ }
+ }
+ }
+
+ // 3. External CHNKExta map
+ let exta_chunks = extract_exta_chunks(&chunks);
+
+ // 4. Mipmap / MipmapInfo / Offscreen lookup tables
+ let mut mipmap_base_info = HashMap::<i64, i64>::new();
+ for row in query_table(&conn, &tables, "Mipmap") {
+ let id = get_i64(&row, &["MainId"], -1);
+ let base_info = get_i64(&row, &["BaseMipmapInfo"], 0);
+ if id >= 0 && base_info > 0 {
+ mipmap_base_info.insert(id, base_info);
+ }
+ }
+
+ let mut mipmap_info_by_id = HashMap::<i64, MipmapInfoRecord>::new();
+ let mipmap_info_table = if tables.contains("MipmapInfo") {
+ Some("MipmapInfo")
+ } else if tables.contains("MipmapStoring") {
+ Some("MipmapStoring")
+ } else {
+ None
+ };
+ if let Some(tname) = mipmap_info_table {
+ for row in query_table(&conn, &tables, tname) {
+ let main_id = get_i64(&row, &["MainId"], -1);
+ if main_id >= 0 {
+ mipmap_info_by_id.insert(
+ main_id,
+ MipmapInfoRecord {
+ offscreen_id: get_i64(&row, &["Offscreen"], 0),
+ this_scale: get_f64(&row, &["ThisScale"], 1.0),
+ next_index: get_i64(&row, &["NextIndex"], 0),
+ },
+ );
+ }
+ }
+ }
+
+ let mut offscreen_by_id = HashMap::<i64, OffscreenRecord>::new();
+ let mut offscreens_by_layer_id = HashMap::<i64, Vec<OffscreenRecord>>::new();
+ for row in query_table(&conn, &tables, "Offscreen") {
+ let main_id = get_i64(&row, &["MainId"], -1);
+ if main_id < 0 {
+ continue;
+ }
+ let layer_id = get_i64(&row, &["LayerId"], -1);
+ let rec = OffscreenRecord {
+ main_id,
+ block_data_id: get_str(&row, &["BlockData"], ""),
+ attribute: get_bytes(&row, &["Attribute"]).map(|b| b.to_vec()),
+ };
+ offscreen_by_id.insert(main_id, rec.clone());
+ if layer_id >= 0 {
+ offscreens_by_layer_id.entry(layer_id).or_default().push(rec);
+ }
+ }
+
+ let mut fill_by_layer_id = HashMap::<i64, String>::new();
+ for fill_table in ["SolidColor", "FillLayer", "Paper", "Fill"] {
+ for row in query_table(&conn, &tables, fill_table) {
+ let lid = get_i64(&row, &["LayerId", "MainId"], -1);
+ if lid < 0 {
+ continue;
+ }
+ if let (Some(r), Some(g), Some(b)) = (
+ get_opt_i64(&row, &["Red", "ColorRed", "FillRed", "R"]),
+ get_opt_i64(&row, &["Green", "ColorGreen", "FillGreen", "G"]),
+ get_opt_i64(&row, &["Blue", "ColorBlue", "FillBlue", "B"]),
+ ) {
+ fill_by_layer_id.insert(
+ lid,
+ rgb_to_hex(
+ normalize_color_channel_u64(r.max(0) as u64),
+ normalize_color_channel_u64(g.max(0) as u64),
+ normalize_color_channel_u64(b.max(0) as u64),
+ ),
+ );
+ }
+ }
+ }
+
+ let resolve_mipmap_to_offscreen = |mipmap_id: i64| -> Option<OffscreenRecord> {
+ if mipmap_id <= 0 {
+ return None;
+ }
+ let mut info_id = *mipmap_base_info.get(&mipmap_id)?;
+ let mut best: Option<OffscreenRecord> = None;
+ let mut seen = HashSet::new();
+ while info_id > 0 && seen.insert(info_id) {
+ let Some(info) = mipmap_info_by_id.get(&info_id) else {
+ break;
+ };
+ if let Some(off) = offscreen_by_id.get(&info.offscreen_id) {
+ if (info.this_scale - 1.0).abs() < 0.001 {
+ return Some(off.clone());
+ }
+ if best.is_none() {
+ best = Some(off.clone());
+ }
+ }
+ info_id = info.next_index;
+ }
+ best
+ };
+
+ // 5. Layer tree
+ let layer_rows = query_table(&conn, &tables, "Layer");
+ let mut layer_row_by_id = HashMap::<i64, &SqlRow>::new();
+ let mut referenced_as_mask_offscreen = HashSet::<i64>::new();
+ for row in &layer_rows {
+ let mid = get_i64(row, &["MainId"], -1);
+ if mid < 0 {
+ continue;
+ }
+ layer_row_by_id.insert(mid, row);
+ let mask_mm = get_i64(row, &["LayerLayerMaskMipmap", "LayerMaskMipmap"], 0);
+ if let Some(off) = resolve_mipmap_to_offscreen(mask_mm) {
+ referenced_as_mask_offscreen.insert(off.main_id);
+ }
+ }
+
+ // Collect flattened layer plan in Ink Studio's top-to-bottom stack order first,
+ // then decode all raster/mask payloads across layers in parallel!
+ struct LayerPlan<'a> {
+ id: String,
+ name: String,
+ is_folder: bool,
+ visible: bool,
+ opacity: f32,
+ blend_mode: String,
+ locked: bool,
+ alpha_locked: bool,
+ clipped: bool,
+ collapsed: bool,
+ parent_id: Option<String>,
+ offset_x: i32,
+ offset_y: i32,
+ mask_offset_x: i32,
+ mask_offset_y: i32,
+ mask_enabled: bool,
+ mask_linked: bool,
+ mask_offscreen: Option<OffscreenRecord>,
+ render_offscreen: Option<OffscreenRecord>,
+ row: &'a SqlRow,
+ is_bottom_most_root: bool,
+ }
+
+ let resolve_render_offscreen = |row: &SqlRow, main_id: i64| -> Option<OffscreenRecord> {
+ let mm = get_i64(row, &["LayerRenderMipmap"], 0);
+ if let Some(o) = resolve_mipmap_to_offscreen(mm) {
+ return Some(o);
+ }
+ let direct = get_i64(row, &["LayerRenderOffscreen"], 0);
+ if direct > 0 {
+ if let Some(o) = offscreen_by_id.get(&direct) {
+ return Some(o.clone());
+ }
+ }
+ let cands = offscreens_by_layer_id.get(&main_id)?;
+ let mut best: Option<OffscreenRecord> = None;
+ let mut best_area: u64 = 0;
+ for c in cands {
+ if referenced_as_mask_offscreen.contains(&c.main_id) {
+ continue;
+ }
+ if c.block_data_id.is_empty() || !exta_chunks.contains_key(&c.block_data_id) {
+ continue;
+ }
+ let a = parse_offscreen_attribute(c.attribute.as_deref(), width, height);
+ let area = (a.bitmap_width as u64) * (a.bitmap_height as u64);
+ if best.is_none() || area > best_area {
+ best_area = area;
+ best = Some(c.clone());
+ }
+ }
+ best
+ };
+
+ fn collect_children<'a>(
+ first_child_id: i64,
+ layer_row_by_id: &HashMap<i64, &'a SqlRow>,
+ visited: &mut HashSet<i64>,
+ ) -> Vec<&'a SqlRow> {
+ let mut list = Vec::new();
+ let mut cur_id = first_child_id;
+ while cur_id > 0 && !visited.contains(&cur_id) && list.len() < MAX_LAYERS {
+ let Some(&row) = layer_row_by_id.get(&cur_id) else {
+ break;
+ };
+ visited.insert(cur_id);
+ list.push(row);
+ cur_id = get_i64(row, &["LayerNextIndex"], 0);
+ }
+ list
+ }
+
+ let mut plans: Vec<LayerPlan<'_>> = Vec::new();
+ let mut seq: usize = 0;
+
+ #[allow(clippy::too_many_arguments)]
+ fn emit_plan<'a>(
+ row: &'a SqlRow,
+ parent_id: Option<String>,
+ visited: &mut HashSet<i64>,
+ depth: usize,
+ is_bottom_most_root: bool,
+ parent_ox: f64,
+ parent_oy: f64,
+ seq: &mut usize,
+ plans: &mut Vec<LayerPlan<'a>>,
+ layer_row_by_id: &HashMap<i64, &'a SqlRow>,
+ resolve_render: &dyn Fn(&SqlRow, i64) -> Option<OffscreenRecord>,
+ resolve_mipmap: &dyn Fn(i64) -> Option<OffscreenRecord>,
+ ) {
+ if depth > MAX_FOLDER_DEPTH || plans.len() >= MAX_LAYERS {
+ return;
+ }
+ let main_id = get_i64(row, &["MainId"], (*seq + 1) as i64);
+ let name = get_str(row, &["LayerName"], &format!("Layer {}", main_id));
+ let layer_folder = get_opt_i64(row, &["LayerFolder"]);
+ let first_child_id = get_i64(row, &["LayerFirstChildIndex"], 0);
+ let layer_type = get_i64(row, &["LayerType"], 1);
+ let composite_val = get_i64(row, &["LayerComposite"], 0);
+ let raw_opacity = get_f64(row, &["LayerOpacity"], 256.0);
+ let vis_val = get_i64(row, &["LayerVisibility"], 1);
+ let lock_val = get_i64(row, &["LayerLock"], 0);
+ let clip_val = get_i64(row, &["LayerClip"], 0);
+ let layer_select = get_opt_i64(row, &["LayerSelect"]);
+
+ let base_ox = parent_ox + get_f64(row, &["LayerOffsetX", "LayerMoveOffsetX"], 0.0);
+ let base_oy = parent_oy + get_f64(row, &["LayerOffsetY", "LayerMoveOffsetY"], 0.0);
+ let offset_x = (base_ox
+ + get_f64(
+ row,
+ &["LayerRenderOffscrOffsetX", "LayerRenderOffsetX"],
+ 0.0,
+ ))
+ .round() as i32;
+ let offset_y = (base_oy
+ + get_f64(
+ row,
+ &["LayerRenderOffscrOffsetY", "LayerRenderOffsetY"],
+ 0.0,
+ ))
+ .round() as i32;
+ let mask_offset_x = (base_ox
+ + get_f64(row, &["LayerMaskOffsetX"], 0.0)
+ + get_f64(row, &["LayerMaskOffscrOffsetX"], 0.0))
+ .round() as i32;
+ let mask_offset_y = (base_oy
+ + get_f64(row, &["LayerMaskOffsetY"], 0.0)
+ + get_f64(row, &["LayerMaskOffscrOffsetY"], 0.0))
+ .round() as i32;
+
+ let render_offscreen = resolve_render(row, main_id);
+ let is_folder = layer_folder.map_or(false, |v| v != 0)
+ || first_child_id > 0
+ || (layer_folder.is_none() && layer_type == 0 && render_offscreen.is_none());
+
+ *seq += 1;
+ let id = format!(
+ "csp-{}-{}-{}",
+ if is_folder { "folder" } else { "layer" },
+ main_id,
+ *seq
+ );
+ let blend_mode = map_csp_blend_mode(composite_val).to_string();
+ let opacity = (raw_opacity / 256.0).clamp(0.0, 1.0) as f32;
+ let visible = (vis_val & 1) != 0;
+ let locked = (lock_val & 1) != 0;
+ let alpha_locked = (lock_val & 16) != 0
+ || get_i64(row, &["LayerLockTransparentPixel", "LayerAlphaLock"], 0) != 0;
+ let clipped = clip_val != 0;
+ let collapsed = layer_folder.map_or(false, |v| (v & 16) != 0);
+
+ let mask_mm = get_i64(row, &["LayerLayerMaskMipmap", "LayerMaskMipmap"], 0);
+ let mask_offscreen = resolve_mipmap(mask_mm);
+ let mask_enabled = if row.contains_key("LayerVisibility") {
+ (vis_val & 2) != 0
+ } else {
+ true
+ };
+ let mask_linked = layer_select.map_or(true, |v| (v & 256) != 0);
+
+ plans.push(LayerPlan {
+ id: id.clone(),
+ name,
+ is_folder,
+ visible,
+ opacity,
+ blend_mode,
+ locked,
+ alpha_locked,
+ clipped,
+ collapsed,
+ parent_id,
+ offset_x,
+ offset_y,
+ mask_offset_x,
+ mask_offset_y,
+ mask_enabled,
+ mask_linked,
+ mask_offscreen,
+ render_offscreen,
+ row,
+ is_bottom_most_root,
+ });
+
+ if is_folder && first_child_id > 0 {
+ let children = collect_children(first_child_id, layer_row_by_id, visited);
+ for child in children.into_iter().rev() {
+ emit_plan(
+ child,
+ Some(id.clone()),
+ visited,
+ depth + 1,
+ false,
+ base_ox,
+ base_oy,
+ seq,
+ plans,
+ layer_row_by_id,
+ resolve_render,
+ resolve_mipmap,
+ );
+ }
+ }
+ }
+
+ let mut visited = HashSet::new();
+ let mut root_row: Option<&SqlRow> = root_folder_id.and_then(|id| layer_row_by_id.get(&id).copied());
+ if root_row.is_none() {
+ let mut referenced = HashSet::new();
+ for r in &layer_rows {
+ let nxt = get_i64(r, &["LayerNextIndex"], 0);
+ let ch = get_i64(r, &["LayerFirstChildIndex"], 0);
+ if nxt > 0 {
+ referenced.insert(nxt);
+ }
+ if ch > 0 {
+ referenced.insert(ch);
+ }
+ }
+ for r in &layer_rows {
+ let id = get_i64(r, &["MainId"], -1);
+ let ch = get_i64(r, &["LayerFirstChildIndex"], 0);
+ if id >= 0 && ch > 0 && !referenced.contains(&id) {
+ root_row = Some(r);
+ break;
+ }
+ }
+ }
+
+ if let Some(rr) = root_row {
+ let r_mid = get_i64(rr, &["MainId"], -1);
+ if r_mid >= 0 {
+ visited.insert(r_mid);
+ }
+ let r_ox = get_f64(rr, &["LayerOffsetX", "LayerMoveOffsetX"], 0.0);
+ let r_oy = get_f64(rr, &["LayerOffsetY", "LayerMoveOffsetY"], 0.0);
+ let first_child = get_i64(rr, &["LayerFirstChildIndex"], 0);
+ if first_child > 0 {
+ let top_level = collect_children(first_child, &layer_row_by_id, &mut visited);
+ let len = top_level.len();
+ for i in (0..len).rev() {
+ emit_plan(
+ top_level[i],
+ None,
+ &mut visited,
+ 0,
+ i == 0,
+ r_ox,
+ r_oy,
+ &mut seq,
+ &mut plans,
+ &layer_row_by_id,
+ &resolve_render_offscreen,
+ &resolve_mipmap_to_offscreen,
+ );
+ }
+ }
+ }
+
+ if plans.is_empty() && !layer_rows.is_empty() {
+ for i in (0..layer_rows.len()).rev() {
+ let row = &layer_rows[i];
+ let mid = get_i64(row, &["MainId"], -1);
+ if root_folder_id == Some(mid) {
+ continue;
+ }
+ emit_plan(
+ row,
+ None,
+ &mut visited,
+ 0,
+ i == 0,
+ 0.0,
+ 0.0,
+ &mut seq,
+ &mut plans,
+ &layer_row_by_id,
+ &resolve_render_offscreen,
+ &resolve_mipmap_to_offscreen,
+ );
+ }
+ }
+
+ // 6. Parallel decode of every layer's tiles and masks via Rayon
+ let doc_w_i32 = width as i32;
+ let doc_h_i32 = height as i32;
+
+ let assembled: Vec<AssembledLayer> = plans
+ .into_par_iter()
+ .map(|plan| {
+ // Decode mask if present
+ let mask = plan.mask_offscreen.as_ref().map(|mo| {
+ let attr = parse_offscreen_attribute(mo.attribute.as_deref(), width, height);
+ let default_val = if attr.default_fill != 0 { 255u8 } else { 0u8 };
+ let mut gray = vec![default_val; (width as usize) * (height as usize)];
+
+ if let Some(&payload) = exta_chunks.get(&mo.block_data_id) {
+ let expected = (attr.block_grid_width as usize)
+ .saturating_mul(attr.block_grid_height as usize);
+ let blocks = parse_block_data_payload_parallel(payload, expected);
+ let gw = attr.block_grid_width.max(1) as usize;
+ for (bidx, raw) in blocks {
+ let Some(mask_tile) = decode_csp_tile_to_mask(&raw) else {
+ continue;
+ };
+ let col = (bidx % gw) as i32;
+ let row_i = (bidx / gw) as i32;
+ let tile_dx = col * TILE_SIZE as i32 + plan.mask_offset_x;
+ let tile_dy = row_i * TILE_SIZE as i32 + plan.mask_offset_y;
+
+ let x0 = (-tile_dx).max(0);
+ let y0 = (-tile_dy).max(0);
+ let x1 = (TILE_SIZE as i32)
+ .min(doc_w_i32 - tile_dx)
+ .min(attr.bitmap_width as i32 - col * TILE_SIZE as i32);
+ let y1 = (TILE_SIZE as i32)
+ .min(doc_h_i32 - tile_dy)
+ .min(attr.bitmap_height as i32 - row_i * TILE_SIZE as i32);
+ if x0 >= x1 || y0 >= y1 {
+ continue;
+ }
+ for sy in y0..y1 {
+ let dy = (tile_dy + sy) as usize;
+ let src_row = (sy as usize) * TILE_SIZE;
+ let dst_row = dy * (width as usize);
+ let s0 = src_row + x0 as usize;
+ let s1 = src_row + x1 as usize;
+ let d0 = dst_row + (tile_dx + x0) as usize;
+ gray[d0..d0 + (s1 - s0)].copy_from_slice(&mask_tile[s0..s1]);
+ }
+ }
+ }
+
+ RawMask {
+ enabled: plan.mask_enabled,
+ linked: plan.mask_linked,
+ default_color: default_val,
+ left: 0,
+ top: 0,
+ width,
+ height,
+ gray,
+ }
+ });
+
+ if plan.is_folder {
+ return AssembledLayer {
+ id: plan.id,
+ name: plan.name,
+ layer_type: "folder".to_string(),
+ visible: plan.visible,
+ opacity: plan.opacity,
+ blend_mode: plan.blend_mode,
+ locked: plan.locked,
+ alpha_locked: plan.alpha_locked,
+ clipped: plan.clipped,
+ collapsed: plan.collapsed,
+ parent_id: plan.parent_id,
+ solid_fill_hex: None,
+ tiles: Vec::new(),
+ mask,
+ };
+ }
+
+ let attr = plan
+ .render_offscreen
+ .as_ref()
+ .map(|ro| parse_offscreen_attribute(ro.attribute.as_deref(), width, height));
+
+ let mut tile_map: HashMap<(i32, i32), Vec<u8>> = HashMap::new();
+ if let (Some(ro), Some(a)) = (&plan.render_offscreen, &attr) {
+ if let Some(&payload) = exta_chunks.get(&ro.block_data_id) {
+ let expected =
+ (a.block_grid_width as usize).saturating_mul(a.block_grid_height as usize);
+ let blocks = parse_block_data_payload_parallel(payload, expected);
+ let gw = a.block_grid_width.max(1) as usize;
+ let valid_right = doc_w_i32.min(plan.offset_x + a.bitmap_width as i32);
+ let valid_bottom = doc_h_i32.min(plan.offset_y + a.bitmap_height as i32);
+
+ // Decode tiles in parallel
+ let decoded_tiles: Vec<(usize, Vec<u8>)> = blocks
+ .into_par_iter()
+ .filter_map(|(bidx, raw)| {
+ decode_csp_tile_to_rgba(&raw, a.default_fill).map(|rgba| (bidx, rgba))
+ })
+ .collect();
+
+ for (bidx, rgba) in decoded_tiles {
+ let col = (bidx % gw) as i32;
+ let row_i = (bidx / gw) as i32;
+ let tile_dx = col * TILE_SIZE as i32 + plan.offset_x;
+ let tile_dy = row_i * TILE_SIZE as i32 + plan.offset_y;
+ blit_offset_tile_into_map(
+ &mut tile_map,
+ &rgba,
+ tile_dx,
+ tile_dy,
+ valid_right,
+ valid_bottom,
+ );
+ }
+ }
+ }
+
+ let tiles: Vec<RawTile> = tile_map
+ .into_iter()
+ .map(|((tx, ty), rgba)| RawTile { tx, ty, rgba })
+ .collect();
+
+ let solid_fill_hex = if tiles.is_empty() {
+ extract_solid_fill_color(
+ plan.row,
+ attr.as_ref(),
+ &fill_by_layer_id,
+ plan.is_bottom_most_root,
+ )
+ } else {
+ None
+ };
+
+ AssembledLayer {
+ id: plan.id,
+ name: plan.name,
+ layer_type: "raster".to_string(),
+ visible: plan.visible,
+ opacity: plan.opacity,
+ blend_mode: plan.blend_mode,
+ locked: plan.locked,
+ alpha_locked: plan.alpha_locked,
+ clipped: plan.clipped,
+ collapsed: false,
+ parent_id: plan.parent_id,
+ solid_fill_hex,
+ tiles,
+ mask,
+ }
+ })
+ .collect();
+
+ pack_parsed_document(width, height, dpi, "color", preview, assembled)
+}
+
+// ---------------------------------------------------------------------------
+// Native .sut SQLite extractor (removes sql.js dependency from sutParser.ts)
+// ---------------------------------------------------------------------------
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SutMaterialRow {
+ pub pw_id: String,
+ pub original_path: String,
+ pub catalog_path: String,
+ pub file_data_offset: u32,
+ pub file_data_len: u32,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SutVariantBlobRef {
+ pub offset: u32,
+ pub len: u32,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SutExtractMeta {
+ pub node_name: Option<String>,
+ pub variant_id: Option<i64>,
+ pub variant_scalars: HashMap<String, serde_json::Value>,
+ pub variant_blobs: HashMap<String, SutVariantBlobRef>,
+ pub materials: Vec<SutMaterialRow>,
+}
+
+/// Extracts Node, Variant, and MaterialFile rows from a `.sut` brush file natively in Rust
+/// without needing WASM `sql.js`. Binary wire format:
+/// `[magic: "SUTD"][meta_json_len: u32 LE][meta_json][blob_section]`
+pub fn extract_sut_sqlite_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {
+ let chunks = parse_csp_chunks(bytes);
+ let sqlite_data = find_sqlite_data(&chunks, bytes)
+ .ok_or_else(|| "Invalid Clip Studio Paint file: No SQLite database header found in .sut".to_string())?;
+
+ let conn = open_readonly_mem_sqlite(sqlite_data)?;
+ let tables = get_table_names(&conn);
+
+ let mut node_name: Option<String> = None;
+ let mut variant_id: Option<i64> = None;
+ if tables.contains("Node") {
+ if let Ok(mut stmt) = conn.prepare("SELECT NodeName, NodeVariantId FROM Node LIMIT 1") {
+ let _ = stmt.query_row([], |row| {
+ if let Ok(Value::Text(s)) = row.get::<_, Value>(0) {
+ let trimmed = s.trim();
+ if !trimmed.is_empty() {
+ node_name = Some(trimmed.to_string());
+ }
+ }
+ if let Ok(v) = row.get::<_, Value>(1) {
+ match v {
+ Value::Integer(i) => variant_id = Some(i),
+ Value::Real(f) if f.is_finite() => variant_id = Some(f.trunc() as i64),
+ _ => {}
+ }
+ }
+ Ok(())
+ });
+ }
+ }
+
+ let mut blobs = Vec::<u8>::new();
+ let mut variant_scalars = HashMap::new();
+ let mut variant_blobs = HashMap::new();
+
+ if tables.contains("Variant") {
+ let query_res: rusqlite::Result<(Vec<String>, Vec<Value>)> = if let Some(vid) = variant_id {
+ conn.prepare("SELECT * FROM Variant WHERE _PW_ID = ?1 LIMIT 1")
+ .and_then(|mut s| {
+ let cols: Vec<String> = s.column_names().into_iter().map(String::from).collect();
+ let row = s.query_row([vid], |r| {
+ let mut vals = Vec::with_capacity(cols.len());
+ for i in 0..cols.len() {
+ vals.push(r.get::<_, Value>(i).unwrap_or(Value::Null));
+ }
+ Ok(vals)
+ })?;
+ Ok((cols, row))
+ })
+ } else {
+ Err(rusqlite::Error::QueryReturnedNoRows)
+ }
+ .or_else(|_| {
+ let mut s = conn.prepare("SELECT * FROM Variant LIMIT 1")?;
+ let cols: Vec<String> = s.column_names().into_iter().map(String::from).collect();
+ let row = s.query_row([], |r| {
+ let mut vals = Vec::with_capacity(cols.len());
+ for i in 0..cols.len() {
+ vals.push(r.get::<_, Value>(i).unwrap_or(Value::Null));
+ }
+ Ok(vals)
+ })?;
+ Ok((cols, row))
+ });
+
+ if let Ok((cols, vals)) = query_res {
+ for (cname, val) in cols.into_iter().zip(vals.into_iter()) {
+ match val {
+ Value::Null => {}
+ Value::Integer(i) => {
+ variant_scalars.insert(cname, serde_json::Value::from(i));
+ }
+ Value::Real(f) if f.is_finite() => {
+ variant_scalars.insert(cname, serde_json::Value::from(f));
+ }
+ Value::Text(t) => {
+ variant_scalars.insert(cname, serde_json::Value::from(t));
+ }
+ Value::Blob(b) => {
+ let off = u32::try_from(blobs.len())
+ .map_err(|_| "SUT blob payload exceeds 4 GB".to_string())?;
+ let len = u32::try_from(b.len())
+ .map_err(|_| "SUT blob item exceeds 4 GB".to_string())?;
+ blobs.extend_from_slice(&b);
+ variant_blobs.insert(cname, SutVariantBlobRef { offset: off, len });
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+
+ let mut materials = Vec::new();
+ if tables.contains("MaterialFile") {
+ if let Ok(mut stmt) =
+ conn.prepare("SELECT _PW_ID, OriginalPath, FileData, CatalogPath FROM MaterialFile")
+ {
+ if let Ok(rows) = stmt.query_map([], |r| {
+ let pw_id = match r.get::<_, Value>(0).unwrap_or(Value::Null) {
+ Value::Integer(i) => i.to_string(),
+ Value::Text(s) => s,
+ _ => String::new(),
+ };
+ let orig = match r.get::<_, Value>(1).unwrap_or(Value::Null) {
+ Value::Text(s) => s,
+ _ => String::new(),
+ };
+ let data = match r.get::<_, Value>(2).unwrap_or(Value::Null) {
+ Value::Blob(b) => b,
+ _ => Vec::new(),
+ };
+ let cat = match r.get::<_, Value>(3).unwrap_or(Value::Null) {
+ Value::Text(s) => s,
+ _ => String::new(),
+ };
+ Ok((pw_id, orig, data, cat))
+ }) {
+ for item in rows.flatten() {
+ let (pw_id, original_path, data, catalog_path) = item;
+ if data.is_empty() {
+ continue;
+ }
+ let off = u32::try_from(blobs.len())
+ .map_err(|_| "SUT material payload exceeds 4 GB".to_string())?;
+ let len = u32::try_from(data.len())
+ .map_err(|_| "SUT material exceeds 4 GB".to_string())?;
+ blobs.extend_from_slice(&data);
+ materials.push(SutMaterialRow {
+ pw_id,
+ original_path,
+ catalog_path,
+ file_data_offset: off,
+ file_data_len: len,
+ });
+ }
+ }
+ }
+ }
+
+ let meta = SutExtractMeta {
+ node_name,
+ variant_id,
+ variant_scalars,
+ variant_blobs,
+ materials,
+ };
+ let meta_json = serde_json::to_vec(&meta)
+ .map_err(|e| format!("Failed to serialize SUT metadata: {}", e))?;
+ let meta_len = u32::try_from(meta_json.len())
+ .map_err(|_| "SUT metadata exceeds 4 GB".to_string())?;
+
+ let mut out = Vec::with_capacity(8 + meta_json.len() + blobs.len());
+ out.extend_from_slice(b"SUTD");
+ out.extend_from_slice(&meta_len.to_le_bytes());
+ out.extend_from_slice(&meta_json);
+ out.extend_from_slice(&blobs);
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use flate2::write::ZlibEncoder;
+ use flate2::Compression;
+ use std::io::Write;
+
+ fn zlib_compress(data: &[u8]) -> Vec<u8> {
+ let mut enc = ZlibEncoder::new(Vec::new(), Compression::fast());
+ enc.write_all(data).unwrap();
+ enc.finish().unwrap()
+ }
+
+ fn build_chunk(name: &[u8; 4], data: &[u8]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(16 + data.len());
+ out.extend_from_slice(b"CHNK");
+ out.extend_from_slice(name);
+ out.extend_from_slice(&(data.len() as u64).to_be_bytes());
+ out.extend_from_slice(data);
+ out
+ }
+
+ fn build_exta(id: &str, payload: &[u8]) -> Vec<u8> {
+ let id_bytes = id.as_bytes();
+ let mut data = Vec::with_capacity(16 + id_bytes.len() + payload.len());
+ data.extend_from_slice(&(id_bytes.len() as u64).to_be_bytes());
+ data.extend_from_slice(id_bytes);
+ data.extend_from_slice(&(payload.len() as u64).to_be_bytes());
+ data.extend_from_slice(payload);
+ build_chunk(b"Exta", &data)
+ }
+
+ fn build_block_payload(tile_planes: &[u8]) -> Vec<u8> {
+ let compressed = zlib_compress(tile_planes);
+ let mut inner = Vec::new();
+ inner.extend_from_slice(&0u32.to_be_bytes()); // rawIndex
+ inner.extend_from_slice(&[0u8; 12]);
+ inner.extend_from_slice(&1u32.to_be_bytes()); // hasData
+ inner.extend_from_slice(&((compressed.len() + 4) as u32).to_be_bytes()); // outerLen
+ inner.extend_from_slice(&(compressed.len() as u32).to_le_bytes()); // innerLen
+ inner.extend_from_slice(&compressed);
+
+ let mut payload = Vec::new();
+ payload.extend_from_slice(tag_block_begin());
+ payload.extend_from_slice(&inner);
+ payload.extend_from_slice(tag_block_end());
+ payload
+ }
+
+ #[test]
+ fn test_parse_synthetic_clip_end_to_end() {
+ // Build an in-memory SQLite DB and serialize it
+ let conn = Connection::open_in_memory().unwrap();
+ conn.execute_batch(
+ "
+ CREATE TABLE Canvas (CanvasWidth REAL, CanvasHeight REAL, CanvasResolution REAL, CanvasRootFolder INTEGER);
+ CREATE TABLE Layer (
+ MainId INTEGER, LayerName TEXT, LayerFolder INTEGER, LayerFirstChildIndex INTEGER,
+ LayerNextIndex INTEGER, LayerType INTEGER, LayerComposite INTEGER,
+ LayerOpacity INTEGER, LayerVisibility INTEGER, LayerLock INTEGER,
+ LayerClip INTEGER, LayerRenderMipmap INTEGER, LayerOffsetX REAL, LayerOffsetY REAL
+ );
+ CREATE TABLE Mipmap (MainId INTEGER, BaseMipmapInfo INTEGER);
+ CREATE TABLE MipmapInfo (MainId INTEGER, Offscreen INTEGER, ThisScale REAL, NextIndex INTEGER);
+ CREATE TABLE Offscreen (MainId INTEGER, LayerId INTEGER, BlockData TEXT, Attribute BLOB);
+
+ INSERT INTO Canvas VALUES (512, 256, 600, 1);
+ INSERT INTO Layer VALUES (1, 'Root', 1, 2, 0, 0, 0, 256, 1, 0, 0, 0, 0, 0);
+ INSERT INTO Layer VALUES (2, 'Paper', 0, 0, 3, 1280, 0, 256, 1, 0, 0, 0, 0, 0);
+ INSERT INTO Layer VALUES (3, 'Ink', 0, 0, 0, 1, 2, 128, 1, 16, 1, 10, 0, 0);
+ INSERT INTO Mipmap VALUES (10, 20);
+ INSERT INTO MipmapInfo VALUES (20, 30, 1.0, 0);
+ INSERT INTO Offscreen VALUES (30, 3, 'extrnlid_ink', NULL);
+ ",
+ )
+ .unwrap();
+
+ let sqlite_bytes = conn.serialize(DatabaseName::Main).unwrap().to_vec();
+
+ // Build a 5-plane CSP tile with a red pixel at (3, 5)
+ let mut raw_tile = vec![0u8; TILE_PIXELS * 5];
+ let p = 5 * TILE_SIZE + 3;
+ raw_tile[p] = 200; // alpha
+ let ci = TILE_PIXELS + p * 4;
+ raw_tile[ci] = 10; // B
+ raw_tile[ci + 1] = 20; // G
+ raw_tile[ci + 2] = 240; // R
+
+ let exta = build_exta("extrnlid_ink", &build_block_payload(&raw_tile));
+ let sqli = build_chunk(b"SQLi", &sqlite_bytes);
+ let foot = build_chunk(b"Foot", &[]);
+
+ let mut clip = Vec::new();
+ clip.extend_from_slice(b"CSFCHUNK");
+ clip.extend_from_slice(&[0u8; 16]);
+ clip.extend_from_slice(&exta);
+ clip.extend_from_slice(&sqli);
+ clip.extend_from_slice(&foot);
+
+ let wire = parse_clip_to_binary(&clip).expect("parse_clip_to_binary failed");
+ assert_eq!(&wire[0..4], b"INKD");
+ let meta_len = u32::from_le_bytes(wire[8..12].try_into().unwrap()) as usize;
+ let meta: serde_json::Value = serde_json::from_slice(&wire[12..12 + meta_len]).unwrap();
+ assert_eq!(meta["width"], 512);
+ assert_eq!(meta["height"], 256);
+ assert_eq!(meta["dpi"], 600);
+ let layers = meta["layers"].as_array().unwrap();
+ assert_eq!(layers.len(), 2);
+ // Top-to-bottom order: Ink first, Paper second
+ assert_eq!(layers[0]["name"], "Ink");
+ assert_eq!(layers[0]["blendMode"], "multiply");
+ assert_eq!(layers[0]["alphaLocked"], true);
+ assert_eq!(layers[0]["clipped"], true);
+ let tiles = layers[0]["tiles"].as_array().unwrap();
+ assert_eq!(tiles.len(), 1);
+ let t0 = &tiles[0];
+ let blob_start = 12 + meta_len + t0["offset"].as_u64().unwrap() as usize;
+ let blob_len = t0["len"].as_u64().unwrap() as usize;
+ let decoded = lz4_flex::block::decompress(&wire[blob_start..blob_start + blob_len], BYTES_32BIT).unwrap();
+ let di = p * 4;
+ assert_eq!(&decoded[di..di + 4], &[240, 20, 10, 200]);
+
+ assert_eq!(layers[1]["name"], "Paper");
+ assert_eq!(layers[1]["solidFillHex"], "#ffffff");
+ }
+}
diff --git a/src-tauri/src/doc_wire.rs b/src-tauri/src/doc_wire.rs
new file mode 100644
index 0000000..167ca3e
--- /dev/null
+++ b/src-tauri/src/doc_wire.rs
@@ -0,0 +1,441 @@
+use rayon::prelude::*;
+use serde::Serialize;
+use std::collections::HashMap;
+
+pub const TILE_SIZE: usize = 256;
+pub const TILE_PIXELS: usize = TILE_SIZE * TILE_SIZE;
+pub const BYTES_32BIT: usize = TILE_PIXELS * 4;
+pub const MAX_CANVAS_DIM: u32 = 32768;
+
+pub const CODEC_RAW: u8 = 1;
+pub const CODEC_LZ4: u8 = 2;
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ParsedPreviewRef {
+ pub offset: u32,
+ pub len: u32,
+ pub mime: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ParsedTileRef {
+ pub tx: i32,
+ pub ty: i32,
+ pub codec: u8,
+ pub offset: u32,
+ pub len: u32,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ParsedMaskRef {
+ pub enabled: bool,
+ pub linked: bool,
+ pub default_color: u8,
+ pub left: i32,
+ pub top: i32,
+ pub width: u32,
+ pub height: u32,
+ pub codec: u8,
+ pub offset: u32,
+ pub len: u32,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ParsedLayerMeta {
+ pub id: String,
+ pub name: String,
+ #[serde(rename = "type")]
+ pub layer_type: String, // "raster" | "folder"
+ pub visible: bool,
+ pub opacity: f32,
+ pub blend_mode: String,
+ pub locked: bool,
+ pub alpha_locked: bool,
+ pub clipped: bool,
+ pub collapsed: bool,
+ pub parent_id: Option<String>,
+ pub solid_fill_hex: Option<String>,
+ pub tiles: Vec<ParsedTileRef>,
+ pub mask: Option<ParsedMaskRef>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ParsedDocumentMeta {
+ pub width: u32,
+ pub height: u32,
+ pub dpi: u32,
+ pub color_mode: String, // "color" | "grayscale"
+ pub preview: Option<ParsedPreviewRef>,
+ pub layers: Vec<ParsedLayerMeta>,
+}
+
+/// Raw uncompressed 256x256 RGBA tile before LZ4 packing.
+pub struct RawTile {
+ pub tx: i32,
+ pub ty: i32,
+ pub rgba: Vec<u8>,
+}
+
+/// Raw grayscale mask before LZ4 packing.
+pub struct RawMask {
+ pub enabled: bool,
+ pub linked: bool,
+ pub default_color: u8,
+ pub left: i32,
+ pub top: i32,
+ pub width: u32,
+ pub height: u32,
+ pub gray: Vec<u8>,
+}
+
+pub struct AssembledLayer {
+ pub id: String,
+ pub name: String,
+ pub layer_type: String,
+ pub visible: bool,
+ pub opacity: f32,
+ pub blend_mode: String,
+ pub locked: bool,
+ pub alpha_locked: bool,
+ pub clipped: bool,
+ pub collapsed: bool,
+ pub parent_id: Option<String>,
+ pub solid_fill_hex: Option<String>,
+ pub tiles: Vec<RawTile>,
+ pub mask: Option<RawMask>,
+}
+
+/// Slices a clipped RGBA sub-rectangle into sparse 256x256 RGBA tiles,
+/// skipping completely transparent tiles.
+pub fn slice_rgba_rect_to_tiles(
+ rgba: &[u8],
+ src_w: usize,
+ src_h: usize,
+ dx: i32,
+ dy: i32,
+ doc_w: i32,
+ doc_h: i32,
+) -> Vec<RawTile> {
+ if src_w == 0 || src_h == 0 || doc_w <= 0 || doc_h <= 0 {
+ return Vec::new();
+ }
+ let sx0 = (-dx).max(0) as usize;
+ let sy0 = (-dy).max(0) as usize;
+ let sx1 = (doc_w - dx).min(src_w as i32).max(0) as usize;
+ let sy1 = (doc_h - dy).min(src_h as i32).max(0) as usize;
+ if sx0 >= sx1 || sy0 >= sy1 {
+ return Vec::new();
+ }
+
+ let doc_x0 = dx + sx0 as i32;
+ let doc_y0 = dy + sy0 as i32;
+ let doc_x1 = dx + sx1 as i32;
+ let doc_y1 = dy + sy1 as i32;
+
+ let tx0 = doc_x0.div_euclid(TILE_SIZE as i32);
+ let ty0 = doc_y0.div_euclid(TILE_SIZE as i32);
+ let tx1 = (doc_x1 - 1).div_euclid(TILE_SIZE as i32);
+ let ty1 = (doc_y1 - 1).div_euclid(TILE_SIZE as i32);
+
+ let mut coords = Vec::with_capacity(((tx1 - tx0 + 1) * (ty1 - ty0 + 1)) as usize);
+ for ty in ty0..=ty1 {
+ for tx in tx0..=tx1 {
+ coords.push((tx, ty));
+ }
+ }
+
+ coords
+ .into_par_iter()
+ .filter_map(|(tx, ty)| {
+ let tile_doc_x = tx * TILE_SIZE as i32;
+ let tile_doc_y = ty * TILE_SIZE as i32;
+ let ix0 = doc_x0.max(tile_doc_x);
+ let iy0 = doc_y0.max(tile_doc_y);
+ let ix1 = doc_x1.min(tile_doc_x + TILE_SIZE as i32);
+ let iy1 = doc_y1.min(tile_doc_y + TILE_SIZE as i32);
+ if ix0 >= ix1 || iy0 >= iy1 {
+ return None;
+ }
+
+ let mut tile = vec![0u8; BYTES_32BIT];
+ let copy_w = (ix1 - ix0) as usize;
+ let copy_bytes = copy_w * 4;
+ let mut non_zero_alpha = false;
+
+ for y in iy0..iy1 {
+ let src_y = (y - dy) as usize;
+ let src_x = (ix0 - dx) as usize;
+ let dst_y = (y - tile_doc_y) as usize;
+ let dst_x = (ix0 - tile_doc_x) as usize;
+
+ let src_off = (src_y * src_w + src_x) * 4;
+ let dst_off = (dst_y * TILE_SIZE + dst_x) * 4;
+ let src_row = &rgba[src_off..src_off + copy_bytes];
+ tile[dst_off..dst_off + copy_bytes].copy_from_slice(src_row);
+
+ if !non_zero_alpha {
+ for chunk in src_row.chunks_exact(4) {
+ if chunk[3] != 0 {
+ non_zero_alpha = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if non_zero_alpha {
+ Some(RawTile { tx, ty, rgba: tile })
+ } else {
+ None
+ }
+ })
+ .collect()
+}
+
+/// Blits an already-decoded 256x256 tile (possibly with an arbitrary document offset) into a
+/// map of aligned document tiles.
+pub fn blit_offset_tile_into_map(
+ tile_map: &mut HashMap<(i32, i32), Vec<u8>>,
+ src_tile: &[u8],
+ tile_doc_x: i32,
+ tile_doc_y: i32,
+ valid_right: i32,
+ valid_bottom: i32,
+) {
+ let sx0 = (-tile_doc_x).max(0);
+ let sy0 = (-tile_doc_y).max(0);
+ let sx1 = (TILE_SIZE as i32).min(valid_right - tile_doc_x);
+ let sy1 = (TILE_SIZE as i32).min(valid_bottom - tile_doc_y);
+ if sx0 >= sx1 || sy0 >= sy1 {
+ return;
+ }
+
+ let doc_x0 = tile_doc_x + sx0;
+ let doc_y0 = tile_doc_y + sy0;
+ let doc_x1 = tile_doc_x + sx1;
+ let doc_y1 = tile_doc_y + sy1;
+
+ // Fast path: tile-aligned full 256x256 copy
+ if sx0 == 0
+ && sy0 == 0
+ && sx1 == TILE_SIZE as i32
+ && sy1 == TILE_SIZE as i32
+ && doc_x0.rem_euclid(TILE_SIZE as i32) == 0
+ && doc_y0.rem_euclid(TILE_SIZE as i32) == 0
+ {
+ let tx = doc_x0.div_euclid(TILE_SIZE as i32);
+ let ty = doc_y0.div_euclid(TILE_SIZE as i32);
+ tile_map.insert((tx, ty), src_tile[..BYTES_32BIT].to_vec());
+ return;
+ }
+
+ let tx0 = doc_x0.div_euclid(TILE_SIZE as i32);
+ let ty0 = doc_y0.div_euclid(TILE_SIZE as i32);
+ let tx1 = (doc_x1 - 1).div_euclid(TILE_SIZE as i32);
+ let ty1 = (doc_y1 - 1).div_euclid(TILE_SIZE as i32);
+
+ for ty in ty0..=ty1 {
+ let dst_tile_y = ty * TILE_SIZE as i32;
+ let iy0 = doc_y0.max(dst_tile_y);
+ let iy1 = doc_y1.min(dst_tile_y + TILE_SIZE as i32);
+ if iy0 >= iy1 {
+ continue;
+ }
+ for tx in tx0..=tx1 {
+ let dst_tile_x = tx * TILE_SIZE as i32;
+ let ix0 = doc_x0.max(dst_tile_x);
+ let ix1 = doc_x1.min(dst_tile_x + TILE_SIZE as i32);
+ if ix0 >= ix1 {
+ continue;
+ }
+ let entry = tile_map
+ .entry((tx, ty))
+ .or_insert_with(|| vec![0u8; BYTES_32BIT]);
+ let copy_bytes = ((ix1 - ix0) as usize) * 4;
+ for y in iy0..iy1 {
+ let src_y = (y - tile_doc_y) as usize;
+ let src_x = (ix0 - tile_doc_x) as usize;
+ let dst_y = (y - dst_tile_y) as usize;
+ let dst_x = (ix0 - dst_tile_x) as usize;
+ let src_off = (src_y * TILE_SIZE + src_x) * 4;
+ let dst_off = (dst_y * TILE_SIZE + dst_x) * 4;
+ entry[dst_off..dst_off + copy_bytes]
+ .copy_from_slice(&src_tile[src_off..src_off + copy_bytes]);
+ }
+ }
+ }
+}
+
+fn compress_lz4_or_raw(raw: &[u8]) -> (u8, Vec<u8>) {
+ let compressed = lz4_flex::block::compress(raw);
+ if compressed.len() <= raw.len() {
+ (CODEC_LZ4, compressed)
+ } else {
+ (CODEC_RAW, raw.to_vec())
+ }
+}
+
+/// Compresses all layer tiles and masks in parallel using Rayon + LZ4 block codec
+/// and packs the entire document into the compact `INKD` binary wire frame:
+/// `[magic: "INKD"][version: u32 LE = 1][meta_json_len: u32 LE][meta_json][blob_section]`
+pub fn pack_parsed_document(
+ width: u32,
+ height: u32,
+ dpi: u32,
+ color_mode: &str,
+ preview: Option<(Vec<u8>, String)>,
+ assembled_layers: Vec<AssembledLayer>,
+) -> Result<Vec<u8>, String> {
+ struct CompressedLayer {
+ layer: AssembledLayer,
+ compressed_tiles: Vec<(i32, i32, u8, Vec<u8>)>,
+ compressed_mask: Option<(bool, bool, u8, i32, i32, u32, u32, u8, Vec<u8>)>,
+ }
+
+ // Parallel compress across all layers & tiles
+ let compressed_layers: Vec<CompressedLayer> = assembled_layers
+ .into_par_iter()
+ .map(|mut layer| {
+ let tiles = std::mem::take(&mut layer.tiles);
+ let mask = layer.mask.take();
+
+ let compressed_tiles: Vec<(i32, i32, u8, Vec<u8>)> = tiles
+ .into_par_iter()
+ .map(|t| {
+ let (codec, bytes) = compress_lz4_or_raw(&t.rgba);
+ (t.tx, t.ty, codec, bytes)
+ })
+ .collect();
+
+ let compressed_mask = mask.map(|m| {
+ let (codec, bytes) = compress_lz4_or_raw(&m.gray);
+ (
+ m.enabled,
+ m.linked,
+ m.default_color,
+ m.left,
+ m.top,
+ m.width,
+ m.height,
+ codec,
+ bytes,
+ )
+ });
+
+ CompressedLayer {
+ layer,
+ compressed_tiles,
+ compressed_mask,
+ }
+ })
+ .collect();
+
+ let mut blob_section: Vec<u8> = Vec::new();
+
+ let preview_ref = if let Some((bytes, mime)) = preview {
+ let offset = u32::try_from(blob_section.len())
+ .map_err(|_| "Document binary payload exceeds 4 GB limit".to_string())?;
+ let len = u32::try_from(bytes.len())
+ .map_err(|_| "Preview payload exceeds 4 GB limit".to_string())?;
+ blob_section.extend_from_slice(&bytes);
+ Some(ParsedPreviewRef { offset, len, mime })
+ } else {
+ None
+ };
+
+ let mut layers_meta: Vec<ParsedLayerMeta> = Vec::with_capacity(compressed_layers.len());
+ for cl in compressed_layers {
+ let mut tile_refs = Vec::with_capacity(cl.compressed_tiles.len());
+ for (tx, ty, codec, bytes) in cl.compressed_tiles {
+ let offset = u32::try_from(blob_section.len())
+ .map_err(|_| "Document binary payload exceeds 4 GB limit".to_string())?;
+ let len = u32::try_from(bytes.len())
+ .map_err(|_| "Tile payload exceeds 4 GB limit".to_string())?;
+ blob_section.extend_from_slice(&bytes);
+ tile_refs.push(ParsedTileRef {
+ tx,
+ ty,
+ codec,
+ offset,
+ len,
+ });
+ }
+
+ let mask_ref = if let Some((
+ enabled,
+ linked,
+ default_color,
+ left,
+ top,
+ mw,
+ mh,
+ codec,
+ bytes,
+ )) = cl.compressed_mask
+ {
+ let offset = u32::try_from(blob_section.len())
+ .map_err(|_| "Document binary payload exceeds 4 GB limit".to_string())?;
+ let len = u32::try_from(bytes.len())
+ .map_err(|_| "Mask payload exceeds 4 GB limit".to_string())?;
+ blob_section.extend_from_slice(&bytes);
+ Some(ParsedMaskRef {
+ enabled,
+ linked,
+ default_color,
+ left,
+ top,
+ width: mw,
+ height: mh,
+ codec,
+ offset,
+ len,
+ })
+ } else {
+ None
+ };
+
+ layers_meta.push(ParsedLayerMeta {
+ id: cl.layer.id,
+ name: cl.layer.name,
+ layer_type: cl.layer.layer_type,
+ visible: cl.layer.visible,
+ opacity: cl.layer.opacity,
+ blend_mode: cl.layer.blend_mode,
+ locked: cl.layer.locked,
+ alpha_locked: cl.layer.alpha_locked,
+ clipped: cl.layer.clipped,
+ collapsed: cl.layer.collapsed,
+ parent_id: cl.layer.parent_id,
+ solid_fill_hex: cl.layer.solid_fill_hex,
+ tiles: tile_refs,
+ mask: mask_ref,
+ });
+ }
+
+ let meta = ParsedDocumentMeta {
+ width,
+ height,
+ dpi,
+ color_mode: color_mode.to_string(),
+ preview: preview_ref,
+ layers: layers_meta,
+ };
+
+ let meta_json = serde_json::to_vec(&meta)
+ .map_err(|e| format!("Failed to serialize parsed document metadata: {}", e))?;
+ let meta_len = u32::try_from(meta_json.len())
+ .map_err(|_| "Metadata JSON exceeds 4 GB limit".to_string())?;
+
+ let mut out = Vec::with_capacity(12 + meta_json.len() + blob_section.len());
+ out.extend_from_slice(b"INKD");
+ out.extend_from_slice(&1u32.to_le_bytes());
+ out.extend_from_slice(&meta_len.to_le_bytes());
+ out.extend_from_slice(&meta_json);
+ out.extend_from_slice(&blob_section);
+ Ok(out)
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 4790a59..dc6b3dd 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1,6 +1,11 @@
-mod server;
+mod clip_parser;
+mod doc_wire;
+mod psd_parser;
+mod raster_ops;
mod recovery;
mod scratch_disk;
+mod server;
+mod tablet_input;
mod timelapse;
use server::{
@@ -91,12 +96,12 @@ fn sanitize_id(raw: &str) -> String {
}
const ALLOWED_DOCUMENT_EXTS: &[&str] = &[
- "sora", "ink", "inkb", "psd", "psb", "clip", "csp", "sut", "png", "jpg", "jpeg", "webp", "bmp",
- "gif", "svg", "avif", "ico", "glb", "gltf", "obj",
+ "ink", "inkb", "psd", "psb", "clip", "csp", "sut", "png", "jpg", "jpeg", "webp", "bmp", "gif",
+ "svg", "avif", "ico", "glb", "gltf", "obj", "sora", // .sora: read-only legacy migrator
];
const DELETE_ALLOWED_EXTS: &[&str] = &[
- "sora", "ink", "psd", "psb", "clip", "csp", "png", "jpg", "jpeg", "webp", "bmp", "gif", "svg",
+ "ink", "psd", "psb", "clip", "csp", "png", "jpg", "jpeg", "webp", "bmp", "gif", "svg",
];
const MAX_READ_FILE_BYTES: u64 = 512 * 1024 * 1024; // 512 MB ceiling
@@ -533,6 +538,305 @@ async fn timelapse_export_ffmpeg(
Ok(tauri::ipc::Response::new(bytes))
}
+#[tauri::command]
+async fn parse_clip_file(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let body = raw_body(&request)?;
+ if body.len() as u64 > MAX_READ_FILE_BYTES {
+ return Err("CLIP file exceeds 512 MB safety limit".to_string());
+ }
+ let owned = body.to_vec();
+ let wire = tokio::task::spawn_blocking(move || clip_parser::parse_clip_to_binary(&owned))
+ .await
+ .map_err(|e| format!("CLIP parser worker failed: {}", e))??;
+ Ok(tauri::ipc::Response::new(wire))
+}
+
+#[tauri::command]
+async fn parse_sut_sqlite(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let body = raw_body(&request)?;
+ if body.len() as u64 > MAX_READ_FILE_BYTES {
+ return Err("SUT file exceeds 512 MB safety limit".to_string());
+ }
+ let owned = body.to_vec();
+ let wire = tokio::task::spawn_blocking(move || clip_parser::extract_sut_sqlite_binary(&owned))
+ .await
+ .map_err(|e| format!("SUT parser worker failed: {}", e))??;
+ Ok(tauri::ipc::Response::new(wire))
+}
+
+#[tauri::command]
+async fn parse_psd_file(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let body = raw_body(&request)?;
+ if body.len() as u64 > MAX_READ_FILE_BYTES {
+ return Err("PSD/PSB file exceeds 512 MB safety limit".to_string());
+ }
+ let owned = body.to_vec();
+ let wire = tokio::task::spawn_blocking(move || psd_parser::parse_psd_to_binary(&owned))
+ .await
+ .map_err(|e| format!("PSD parser worker failed: {}", e))??;
+ Ok(tauri::ipc::Response::new(wire))
+}
+
+#[tauri::command]
+async fn native_apply_filter(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let filter_type = header_str(&request, "x-filter-type")?;
+ let width: usize = header_parse(&request, "x-width")?;
+ let height: usize = header_parse(&request, "x-height")?;
+ let p_a: f32 = header_parse(&request, "x-param-a").unwrap_or(0.0);
+ let p_b: f32 = header_parse(&request, "x-param-b").unwrap_or(0.0);
+ let p_c: f32 = header_parse(&request, "x-param-c").unwrap_or(0.0);
+ let p_d: u32 = header_parse(&request, "x-param-d").unwrap_or(0);
+ let body = raw_body(&request)?;
+ if body.len() > raster_ops::MAX_RASTER_BYTES {
+ return Err("Filter payload exceeds raster safety ceiling".to_string());
+ }
+ let owned = body.to_vec();
+ let out = tokio::task::spawn_blocking(move || match filter_type.as_str() {
+ "gaussian-blur" => raster_ops::gaussian_blur_rgba(&owned, width, height, p_a),
+ "motion-blur" => raster_ops::motion_blur_rgba(&owned, width, height, p_a, p_b),
+ "unsharp-mask" => raster_ops::unsharp_mask_rgba(&owned, width, height, p_a, p_b, p_c),
+ "film-grain" => raster_ops::film_grain_rgba(
+ &owned,
+ width,
+ height,
+ p_a,
+ p_b.round().max(1.0) as u32,
+ p_c > 0.5,
+ p_d,
+ ),
+ other => Err(format!("Unsupported filter type: {}", other)),
+ })
+ .await
+ .map_err(|e| format!("Filter worker failed: {}", e))??;
+ Ok(tauri::ipc::Response::new(out))
+}
+
+#[tauri::command]
+async fn native_flood_fill(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let width: usize = header_parse(&request, "x-width")?;
+ let height: usize = header_parse(&request, "x-height")?;
+ let start_x: i32 = header_parse(&request, "x-start-x")?;
+ let start_y: i32 = header_parse(&request, "x-start-y")?;
+ let fill_packed: u32 = header_parse(&request, "x-fill-rgba")?;
+ let tolerance: f32 = header_parse(&request, "x-tolerance").unwrap_or(32.0);
+ let close_gap: u32 = header_parse(&request, "x-close-gap").unwrap_or(0);
+ let area_scale: i32 = header_parse(&request, "x-area-scale").unwrap_or(0);
+ let anti_alias: bool = header_parse::<u8>(&request, "x-anti-alias").unwrap_or(0) != 0;
+ let same_surface: bool = header_parse::<u8>(&request, "x-same-surface").unwrap_or(1) != 0;
+ let has_mask: bool = header_parse::<u8>(&request, "x-has-mask").unwrap_or(0) != 0;
+
+ let total_pixels = width
+ .checked_mul(height)
+ .ok_or_else(|| "FloodFill dimensions overflow".to_string())?;
+ let rgba_bytes = total_pixels
+ .checked_mul(4)
+ .ok_or_else(|| "FloodFill byte size overflow".to_string())?;
+ let expected = rgba_bytes
+ .checked_add(if same_surface { 0 } else { rgba_bytes })
+ .and_then(|n| n.checked_add(if has_mask { total_pixels } else { 0 }))
+ .ok_or_else(|| "FloodFill payload size overflow".to_string())?;
+
+ let body = raw_body(&request)?;
+ if body.len() != expected {
+ return Err("FloodFill binary payload size mismatch".to_string());
+ }
+ let owned = body.to_vec();
+ let params = raster_ops::FloodFillParams {
+ width,
+ height,
+ start_x,
+ start_y,
+ fill_rgba: [
+ ((fill_packed >> 24) & 0xff) as u8,
+ ((fill_packed >> 16) & 0xff) as u8,
+ ((fill_packed >> 8) & 0xff) as u8,
+ (fill_packed & 0xff) as u8,
+ ],
+ tolerance,
+ close_gap,
+ area_scale,
+ anti_alias,
+ same_surface,
+ };
+
+ let out = tokio::task::spawn_blocking(move || {
+ let ref_slice = &owned[..rgba_bytes];
+ let mut off = rgba_bytes;
+ let target_opt = if same_surface {
+ None
+ } else {
+ let s = &owned[off..off + rgba_bytes];
+ off += rgba_bytes;
+ Some(s)
+ };
+ let mask_opt = if has_mask {
+ Some(&owned[off..off + total_pixels])
+ } else {
+ None
+ };
+ raster_ops::flood_fill_rgba(ref_slice, target_opt, mask_opt, &params)
+ })
+ .await
+ .map_err(|e| format!("FloodFill worker failed: {}", e))??;
+
+ Ok(tauri::ipc::Response::new(out))
+}
+
+#[tauri::command]
+async fn native_liquify_step(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let roi_w: usize = header_parse(&request, "x-roi-w")?;
+ let roi_h: usize = header_parse(&request, "x-roi-h")?;
+ let min_x: f32 = header_parse(&request, "x-min-x")?;
+ let min_y: f32 = header_parse(&request, "x-min-y")?;
+ let cx: f32 = header_parse(&request, "x-cx")?;
+ let cy: f32 = header_parse(&request, "x-cy")?;
+ let ux: f32 = header_parse(&request, "x-ux").unwrap_or(0.0);
+ let uy: f32 = header_parse(&request, "x-uy").unwrap_or(0.0);
+ let v_len: f32 = header_parse(&request, "x-vlen").unwrap_or(0.0);
+ let radius: f32 = header_parse(&request, "x-radius")?;
+ let hardness: f32 = header_parse(&request, "x-hardness")?;
+ let strength: f32 = header_parse(&request, "x-strength")?;
+ let mode_u8: u8 = header_parse(&request, "x-mode")?;
+ let has_init: bool = header_parse::<u8>(&request, "x-has-init").unwrap_or(0) != 0;
+ let has_mask: bool = header_parse::<u8>(&request, "x-has-mask").unwrap_or(0) != 0;
+
+ let mode = raster_ops::LiquifyMode::from_u8(mode_u8)?;
+ let roi_pixels = roi_w
+ .checked_mul(roi_h)
+ .ok_or_else(|| "Liquify ROI dimensions overflow".to_string())?;
+ let roi_bytes = roi_pixels
+ .checked_mul(4)
+ .ok_or_else(|| "Liquify ROI byte size overflow".to_string())?;
+ let expected = roi_bytes
+ .checked_add(if has_init { roi_bytes } else { 0 })
+ .and_then(|n| n.checked_add(if has_mask { roi_pixels } else { 0 }))
+ .ok_or_else(|| "Liquify payload size overflow".to_string())?;
+
+ let body = raw_body(&request)?;
+ if body.len() != expected {
+ return Err("Liquify binary payload size mismatch".to_string());
+ }
+ let owned = body.to_vec();
+ let params = raster_ops::LiquifyStepParams {
+ roi_w,
+ roi_h,
+ min_x,
+ min_y,
+ cx,
+ cy,
+ ux,
+ uy,
+ v_len,
+ radius,
+ hardness,
+ strength,
+ mode,
+ };
+
+ let out = tokio::task::spawn_blocking(move || {
+ let src_roi = &owned[..roi_bytes];
+ let mut off = roi_bytes;
+ let init_opt = if has_init {
+ let s = &owned[off..off + roi_bytes];
+ off += roi_bytes;
+ Some(s)
+ } else {
+ None
+ };
+ let mask_opt = if has_mask {
+ Some(&owned[off..off + roi_pixels])
+ } else {
+ None
+ };
+ raster_ops::liquify_step_rgba(src_roi, init_opt, mask_opt, &params)
+ })
+ .await
+ .map_err(|e| format!("Liquify worker failed: {}", e))??;
+
+ Ok(tauri::ipc::Response::new(out))
+}
+
+#[tauri::command]
+async fn native_compress_tiles_lz4(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let owned = raw_body(&request)?.to_vec();
+ let out = tokio::task::spawn_blocking(move || raster_ops::compress_tiles_lz4_batch(&owned))
+ .await
+ .map_err(|e| format!("LZ4 compress worker failed: {}", e))??;
+ Ok(tauri::ipc::Response::new(out))
+}
+
+#[tauri::command]
+async fn native_decompress_tiles_lz4(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let owned = raw_body(&request)?.to_vec();
+ let out = tokio::task::spawn_blocking(move || raster_ops::decompress_tiles_lz4_batch(&owned))
+ .await
+ .map_err(|e| format!("LZ4 decompress worker failed: {}", e))??;
+ Ok(tauri::ipc::Response::new(out))
+}
+
+#[tauri::command]
+async fn native_flate_compress(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let op = header_str(&request, "x-op")?;
+ let level: u32 = header_parse(&request, "x-level").unwrap_or(1);
+ let owned = raw_body(&request)?.to_vec();
+ let out = tokio::task::spawn_blocking(move || raster_ops::flate_compress(&op, &owned, level))
+ .await
+ .map_err(|e| format!("Flate compress worker failed: {}", e))??;
+ Ok(tauri::ipc::Response::new(out))
+}
+
+#[tauri::command]
+async fn native_flate_decompress(
+ request: tauri::ipc::Request<'_>,
+) -> Result<tauri::ipc::Response, String> {
+ let op = header_str(&request, "x-op")?;
+ let max_out: usize = header_parse(&request, "x-max-output-bytes")
+ .unwrap_or(raster_ops::MAX_RASTER_BYTES);
+ let owned = raw_body(&request)?.to_vec();
+ let out =
+ tokio::task::spawn_blocking(move || raster_ops::flate_decompress(&op, &owned, max_out))
+ .await
+ .map_err(|e| format!("Flate decompress worker failed: {}", e))??;
+ Ok(tauri::ipc::Response::new(out))
+}
+
+#[tauri::command]
+fn tablet_start_input(
+ window: tauri::WebviewWindow,
+ mode: Option<String>,
+ on_samples: tauri::ipc::Channel<tauri::ipc::InvokeResponseBody>,
+) -> Result<tablet_input::TabletStatus, String> {
+ tablet_input::start_tablet_input(&window, mode.as_deref().unwrap_or("auto"), on_samples)
+}
+
+#[tauri::command]
+fn tablet_stop_input() {
+ tablet_input::stop_tablet_input();
+}
+
+#[tauri::command]
+fn tablet_get_status() -> tablet_input::TabletStatus {
+ tablet_input::get_tablet_status()
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
// Disable Windows 11 WebView2 Shell Handwriting / DirectInk overlay so stylus input on
@@ -608,13 +912,27 @@ pub fn run() {
timelapse_read_frame,
timelapse_clear,
timelapse_check_ffmpeg,
- timelapse_export_ffmpeg
+ timelapse_export_ffmpeg,
+ parse_clip_file,
+ parse_sut_sqlite,
+ parse_psd_file,
+ native_apply_filter,
+ native_flood_fill,
+ native_liquify_step,
+ native_compress_tiles_lz4,
+ native_decompress_tiles_lz4,
+ native_flate_compress,
+ native_flate_decompress,
+ tablet_start_input,
+ tablet_stop_input,
+ tablet_get_status
])
.build(tauri::generate_context!())
.expect("error while building tauri application");
app.run(|_app_handle, event| {
if let tauri::RunEvent::Exit = event {
+ tablet_input::stop_tablet_input();
server::shutdown_sync();
}
});
@@ -638,7 +956,7 @@ mod tests {
std::fs::create_dir_all(&allowed_dir).unwrap();
std::fs::create_dir_all(&outside_dir).unwrap();
- let inside_file = allowed_dir.join("art.sora");
+ let inside_file = allowed_dir.join("art.ink");
let outside_file = outside_dir.join("secret.png");
std::fs::write(&inside_file, b"ok").unwrap();
std::fs::write(&outside_file, b"secret").unwrap();
@@ -677,13 +995,13 @@ mod tests {
.is_err());
// Non-existent file outside allowed dir returns Access Denied (no existence oracle)
- let missing_outside = outside_dir.join("missing.sora");
+ let missing_outside = outside_dir.join("missing.ink");
assert!(validate_delete_path(missing_outside.to_str().unwrap(), &allowed_dirs)
.await
.is_err());
// Non-existent file inside allowed dir returns Ok(None)
- let missing_inside = allowed_dir.join("missing.sora");
+ let missing_inside = allowed_dir.join("missing.ink");
assert_eq!(
validate_delete_path(missing_inside.to_str().unwrap(), &allowed_dirs)
.await
diff --git a/src-tauri/src/psd_parser.rs b/src-tauri/src/psd_parser.rs
new file mode 100644
index 0000000..22933bd
--- /dev/null
+++ b/src-tauri/src/psd_parser.rs
@@ -0,0 +1,1250 @@
+use crate::doc_wire::{
+ pack_parsed_document, slice_rgba_rect_to_tiles, AssembledLayer, RawMask, MAX_CANVAS_DIM,
+};
+use flate2::read::ZlibDecoder;
+use rayon::prelude::*;
+use std::io::Read;
+
+const MAX_LAYERS: usize = 4096;
+const MAX_CHANNEL_BYTES: usize = 256 * 1024 * 1024; // 256 MB per channel safety cap
+
+struct Cursor<'a> {
+ data: &'a [u8],
+ pos: usize,
+}
+
+impl<'a> Cursor<'a> {
+ fn new(data: &'a [u8]) -> Self {
+ Self { data, pos: 0 }
+ }
+
+ fn remaining(&self) -> usize {
+ self.data.len().saturating_sub(self.pos)
+ }
+
+ fn read_bytes(&mut self, n: usize) -> Result<&'a [u8], String> {
+ let end = self
+ .pos
+ .checked_add(n)
+ .filter(|&e| e <= self.data.len())
+ .ok_or_else(|| "Unexpected EOF while reading PSD/PSB".to_string())?;
+ let slice = &self.data[self.pos..end];
+ self.pos = end;
+ Ok(slice)
+ }
+
+ fn skip(&mut self, n: usize) -> Result<(), String> {
+ let _ = self.read_bytes(n)?;
+ Ok(())
+ }
+
+ fn read_u8(&mut self) -> Result<u8, String> {
+ Ok(self.read_bytes(1)?[0])
+ }
+
+ fn read_u16(&mut self) -> Result<u16, String> {
+ let b = self.read_bytes(2)?;
+ Ok(u16::from_be_bytes([b[0], b[1]]))
+ }
+
+ fn read_i16(&mut self) -> Result<i16, String> {
+ let b = self.read_bytes(2)?;
+ Ok(i16::from_be_bytes([b[0], b[1]]))
+ }
+
+ fn read_u32(&mut self) -> Result<u32, String> {
+ let b = self.read_bytes(4)?;
+ Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
+ }
+
+ fn read_i32(&mut self) -> Result<i32, String> {
+ let b = self.read_bytes(4)?;
+ Ok(i32::from_be_bytes([b[0], b[1], b[2], b[3]]))
+ }
+
+ fn read_u64(&mut self) -> Result<u64, String> {
+ let b = self.read_bytes(8)?;
+ Ok(u64::from_be_bytes(b.try_into().unwrap()))
+ }
+
+ fn read_len(&mut self, is_psb: bool) -> Result<usize, String> {
+ if is_psb {
+ usize::try_from(self.read_u64()?)
+ .map_err(|_| "PSB length exceeds platform usize".to_string())
+ } else {
+ Ok(self.read_u32()? as usize)
+ }
+ }
+}
+
+pub fn map_psd_blend_key(key: &[u8; 4]) -> &'static str {
+ match key {
+ b"pass" => "pass-through",
+ b"norm" => "normal",
+ b"dark" => "darken",
+ b"mul " => "multiply",
+ b"idiv" => "color-burn",
+ b"lbrn" => "linear-burn",
+ b"dkCl" => "darker-color",
+ b"lite" => "lighten",
+ b"scrn" => "screen",
+ b"div " => "color-dodge",
+ b"lddg" => "add-glow",
+ b"lgCl" => "lighter-color",
+ b"over" => "overlay",
+ b"sLit" => "soft-light",
+ b"hLit" => "hard-light",
+ b"vLit" => "vivid-light",
+ b"lLit" => "linear-light",
+ b"pLit" => "pin-light",
+ b"hMix" => "hard-mix",
+ b"diff" => "difference",
+ b"smud" => "exclusion",
+ b"fsub" => "subtract",
+ b"fdiv" => "divide",
+ b"hue " => "hue",
+ b"sat " => "saturation",
+ b"colr" => "color",
+ b"lum " => "luminosity",
+ _ => "normal",
+ }
+}
+
+#[derive(Clone, Debug)]
+struct ChannelInfo {
+ id: i16,
+ data_len: usize,
+}
+
+#[derive(Clone, Debug)]
+struct PsdMaskRecord {
+ top: i32,
+ left: i32,
+ bottom: i32,
+ right: i32,
+ default_color: u8,
+ position_relative: bool,
+ disabled: bool,
+}
+
+#[derive(Clone, Debug)]
+struct PsdLayerRecord<'a> {
+ top: i32,
+ left: i32,
+ bottom: i32,
+ right: i32,
+ channels: Vec<ChannelInfo>,
+ channel_slices: Vec<(i16, &'a [u8])>,
+ blend_mode: &'static str,
+ opacity: u8,
+ clipping: bool,
+ hidden: bool,
+ transparency_protected: bool,
+ position_or_composite_locked: bool,
+ name: String,
+ section_divider: Option<(u32, Option<&'static str>)>, // (type: 1=open folder, 2=closed folder, 3=bounding end, blend)
+ mask: Option<PsdMaskRecord>,
+}
+
+/// Decodes PackBits RLE for a single scanline into `dst` (length = row_bytes).
+fn decode_packbits_row(src: &[u8], dst: &mut [u8]) -> Result<(), String> {
+ let mut si = 0usize;
+ let mut di = 0usize;
+ let dlen = dst.len();
+ while si < src.len() && di < dlen {
+ let header = src[si] as i8;
+ si += 1;
+ if header >= 0 {
+ let count = (header as usize) + 1;
+ let take = count.min(dlen - di);
+ if si + count > src.len() {
+ let avail = src.len().saturating_sub(si).min(take);
+ dst[di..di + avail].copy_from_slice(&src[si..si + avail]);
+ return Ok(());
+ }
+ dst[di..di + take].copy_from_slice(&src[si..si + take]);
+ si += count;
+ di += take;
+ } else if header != -128 {
+ let count = (1 - (header as i32)) as usize;
+ if si >= src.len() {
+ return Ok(());
+ }
+ let val = src[si];
+ si += 1;
+ let fill = count.min(dlen - di);
+ dst[di..di + fill].fill(val);
+ di += fill;
+ }
+ }
+ Ok(())
+}
+
+/// Un-predicts horizontal delta encoding in-place (PSD compression mode 3).
+fn unpredict_channel(buf: &mut [u8], width: usize, height: usize, depth: u16) {
+ match depth {
+ 8 => {
+ for y in 0..height {
+ let row = &mut buf[y * width..(y + 1) * width];
+ for x in 1..width {
+ row[x] = row[x].wrapping_add(row[x - 1]);
+ }
+ }
+ }
+ 16 => {
+ let row_bytes = width * 2;
+ for y in 0..height {
+ let row = &mut buf[y * row_bytes..(y + 1) * row_bytes];
+ let mut prev = u16::from_be_bytes([row[0], row[1]]);
+ for x in 1..width {
+ let i = x * 2;
+ let delta = u16::from_be_bytes([row[i], row[i + 1]]);
+ prev = prev.wrapping_add(delta);
+ let b = prev.to_be_bytes();
+ row[i] = b[0];
+ row[i + 1] = b[1];
+ }
+ }
+ }
+ 32 => {
+ // 32-bit float prediction in PSD stores delta-encoded bytes planar across 4 byte lanes per row
+ let row_bytes = width * 4;
+ let mut tmp = vec![0u8; row_bytes];
+ for y in 0..height {
+ let row = &mut buf[y * row_bytes..(y + 1) * row_bytes];
+ for i in 1..row_bytes {
+ row[i] = row[i].wrapping_add(row[i - 1]);
+ }
+ for x in 0..width {
+ tmp[x * 4] = row[x];
+ tmp[x * 4 + 1] = row[width + x];
+ tmp[x * 4 + 2] = row[2 * width + x];
+ tmp[x * 4 + 3] = row[3 * width + x];
+ }
+ row.copy_from_slice(&tmp);
+ }
+ }
+ _ => {}
+ }
+}
+
+/// Decodes a single PSD/PSB channel slice (starting with 2-byte compression ID) into 8-bit samples (`width * height`).
+fn decode_channel_to_u8(
+ slice: &[u8],
+ width: usize,
+ height: usize,
+ depth: u16,
+ is_psb: bool,
+) -> Result<Vec<u8>, String> {
+ let pixels = width
+ .checked_mul(height)
+ .ok_or_else(|| "PSD channel dimensions overflow".to_string())?;
+ if pixels == 0 {
+ return Ok(Vec::new());
+ }
+ if slice.len() < 2 {
+ return Ok(vec![0u8; pixels]);
+ }
+
+ let bytes_per_sample = match depth {
+ 8 => 1usize,
+ 16 => 2usize,
+ 32 => 4usize,
+ 1 => 1usize,
+ _ => return Err(format!("Unsupported PSD bit depth: {}", depth)),
+ };
+ let row_bytes = if depth == 1 {
+ width.div_ceil(8)
+ } else {
+ width
+ .checked_mul(bytes_per_sample)
+ .ok_or_else(|| "PSD row stride overflow".to_string())?
+ };
+ let raw_total = row_bytes
+ .checked_mul(height)
+ .ok_or_else(|| "PSD channel byte size overflow".to_string())?;
+ if raw_total > MAX_CHANNEL_BYTES {
+ return Err("PSD channel exceeds 256 MB safety ceiling".to_string());
+ }
+
+ let compression = u16::from_be_bytes([slice[0], slice[1]]);
+ let payload = &slice[2..];
+
+ let mut raw = vec![0u8; raw_total];
+ match compression {
+ 0 => {
+ // Raw uncompressed
+ let copy_len = raw_total.min(payload.len());
+ raw[..copy_len].copy_from_slice(&payload[..copy_len]);
+ }
+ 1 => {
+ // PackBits RLE: row byte counts followed by compressed scanlines
+ let count_size = if is_psb { 4usize } else { 2usize };
+ let counts_bytes = height
+ .checked_mul(count_size)
+ .ok_or_else(|| "PSD RLE header overflow".to_string())?;
+ if payload.len() < counts_bytes {
+ return Err("Truncated PSD RLE scanline table".to_string());
+ }
+ let mut data_pos = counts_bytes;
+ for y in 0..height {
+ let c_off = y * count_size;
+ let rle_len = if is_psb {
+ u32::from_be_bytes(payload[c_off..c_off + 4].try_into().unwrap()) as usize
+ } else {
+ u16::from_be_bytes([payload[c_off], payload[c_off + 1]]) as usize
+ };
+ if data_pos + rle_len > payload.len() {
+ break;
+ }
+ let row_src = &payload[data_pos..data_pos + rle_len];
+ decode_packbits_row(row_src, &mut raw[y * row_bytes..(y + 1) * row_bytes])?;
+ data_pos += rle_len;
+ }
+ }
+ 2 | 3 => {
+ // ZIP (2 = no prediction, 3 = horizontal prediction)
+ let mut dec = ZlibDecoder::new(payload);
+ let mut out = Vec::with_capacity(raw_total);
+ let mut limited = (&mut dec).take((raw_total as u64) + 1);
+ limited
+ .read_to_end(&mut out)
+ .map_err(|e| format!("Failed to inflate PSD ZIP channel: {}", e))?;
+ if out.len() > raw_total {
+ return Err("PSD ZIP channel exceeded expected dimensions".to_string());
+ }
+ let copy_len = out.len().min(raw_total);
+ raw[..copy_len].copy_from_slice(&out[..copy_len]);
+ if compression == 3 {
+ unpredict_channel(&mut raw, width, height, depth);
+ }
+ }
+ other => {
+ return Err(format!("Unsupported PSD channel compression: {}", other));
+ }
+ }
+
+ // Downconvert bit depth to u8
+ match depth {
+ 8 => Ok(raw),
+ 16 => {
+ let mut out = Vec::with_capacity(pixels);
+ for chunk in raw.chunks_exact(2) {
+ out.push(chunk[0]); // big-endian high byte == val >> 8
+ }
+ Ok(out)
+ }
+ 32 => {
+ let mut out = Vec::with_capacity(pixels);
+ for chunk in raw.chunks_exact(4) {
+ let f = f32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
+ let v = (f.clamp(0.0, 1.0) * 255.0).round() as u8;
+ out.push(v);
+ }
+ Ok(out)
+ }
+ 1 => {
+ let mut out = vec![0u8; pixels];
+ for y in 0..height {
+ let row = &raw[y * row_bytes..(y + 1) * row_bytes];
+ for x in 0..width {
+ let bit = (row[x >> 3] >> (7 - (x & 7))) & 1;
+ out[y * width + x] = if bit != 0 { 0 } else { 255 };
+ }
+ }
+ Ok(out)
+ }
+ _ => unreachable!(),
+ }
+}
+
+fn assemble_rgba_from_channels(
+ color_mode: u16,
+ width: usize,
+ height: usize,
+ channels: &[(i16, Vec<u8>)],
+) -> Vec<u8> {
+ let pixels = width * height;
+ let mut rgba = vec![0u8; pixels * 4];
+ let find_ch = |id: i16| -> Option<&[u8]> {
+ channels
+ .iter()
+ .find(|(cid, _)| *cid == id)
+ .map(|(_, v)| v.as_slice())
+ };
+ let ch_a = find_ch(-1);
+
+ match color_mode {
+ 1 => {
+ // Grayscale
+ let ch_g = find_ch(0);
+ for i in 0..pixels {
+ let g = ch_g.and_then(|c| c.get(i).copied()).unwrap_or(0);
+ let a = ch_a.and_then(|c| c.get(i).copied()).unwrap_or(255);
+ let di = i * 4;
+ rgba[di] = g;
+ rgba[di + 1] = g;
+ rgba[di + 2] = g;
+ rgba[di + 3] = a;
+ }
+ }
+ 4 => {
+ // CMYK (Photoshop stores inverted 0=100% ink, 255=0% ink)
+ let ch_c = find_ch(0);
+ let ch_m = find_ch(1);
+ let ch_y = find_ch(2);
+ let ch_k = find_ch(3);
+ for i in 0..pixels {
+ let c = ch_c.and_then(|v| v.get(i).copied()).unwrap_or(255) as u32;
+ let m = ch_m.and_then(|v| v.get(i).copied()).unwrap_or(255) as u32;
+ let y = ch_y.and_then(|v| v.get(i).copied()).unwrap_or(255) as u32;
+ let k = ch_k.and_then(|v| v.get(i).copied()).unwrap_or(255) as u32;
+ let a = ch_a.and_then(|v| v.get(i).copied()).unwrap_or(255);
+ let di = i * 4;
+ rgba[di] = ((c * k) / 255) as u8;
+ rgba[di + 1] = ((m * k) / 255) as u8;
+ rgba[di + 2] = ((y * k) / 255) as u8;
+ rgba[di + 3] = a;
+ }
+ }
+ _ => {
+ // RGB (3) and fallback
+ let ch_r = find_ch(0);
+ let ch_g = find_ch(1);
+ let ch_b = find_ch(2);
+ for i in 0..pixels {
+ let r = ch_r.and_then(|v| v.get(i).copied()).unwrap_or(0);
+ let g = ch_g.and_then(|v| v.get(i).copied()).unwrap_or(0);
+ let b = ch_b.and_then(|v| v.get(i).copied()).unwrap_or(0);
+ let a = ch_a.and_then(|v| v.get(i).copied()).unwrap_or(255);
+ let di = i * 4;
+ rgba[di] = r;
+ rgba[di + 1] = g;
+ rgba[di + 2] = b;
+ rgba[di + 3] = a;
+ }
+ }
+ }
+ rgba
+}
+
+fn parse_dpi_from_resources(res_bytes: &[u8]) -> u32 {
+ let mut cur = Cursor::new(res_bytes);
+ while cur.remaining() >= 12 {
+ let Ok(sig) = cur.read_bytes(4) else { break };
+ if sig != b"8BIM" {
+ break;
+ }
+ let Ok(res_id) = cur.read_u16() else { break };
+ let Ok(name_len) = cur.read_u8() else { break };
+ let padded_name = (name_len as usize) + if (name_len as usize) % 2 == 0 { 1 } else { 0 };
+ if cur.skip(padded_name).is_err() {
+ break;
+ }
+ let Ok(data_len) = cur.read_u32() else { break };
+ let data_len = data_len as usize;
+ let Ok(data) = cur.read_bytes(data_len) else {
+ break;
+ };
+ if data_len % 2 == 1 {
+ let _ = cur.skip(1);
+ }
+ // 0x03ED = ResolutionInfo (hRes fixed 16.16 big-endian)
+ if res_id == 0x03ED && data.len() >= 4 {
+ let hres_fixed = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
+ let dpi = ((hres_fixed as f64) / 65536.0).round() as u32;
+ if (1..=2400).contains(&dpi) {
+ return dpi;
+ }
+ }
+ }
+ 300
+}
+
+fn is_psb_64bit_tagged_block(key: &[u8; 4]) -> bool {
+ matches!(
+ key,
+ b"LMsk"
+ | b"Lr16"
+ | b"Lr32"
+ | b"Layr"
+ | b"Mt16"
+ | b"Mt32"
+ | b"Mtrn"
+ | b"Alph"
+ | b"FMsk"
+ | b"lnk2"
+ | b"FEid"
+ | b"FXid"
+ | b"PxSD"
+ )
+}
+
+fn parse_layer_records<'a>(
+ section: &'a [u8],
+ is_psb: bool,
+) -> Result<Vec<PsdLayerRecord<'a>>, String> {
+ if section.is_empty() {
+ return Ok(Vec::new());
+ }
+ let mut cur = Cursor::new(section);
+ let layer_info_len = cur.read_len(is_psb)?;
+ if layer_info_len == 0 || cur.remaining() < 2 {
+ return Ok(Vec::new());
+ }
+
+ let raw_count = cur.read_i16()?;
+ let layer_count = raw_count.unsigned_abs() as usize;
+ if layer_count > MAX_LAYERS {
+ return Err(format!(
+ "PSD layer count {} exceeds safety ceiling ({})",
+ layer_count, MAX_LAYERS
+ ));
+ }
+
+ let mut records = Vec::with_capacity(layer_count);
+
+ for _ in 0..layer_count {
+ let top = cur.read_i32()?;
+ let left = cur.read_i32()?;
+ let bottom = cur.read_i32()?;
+ let right = cur.read_i32()?;
+
+ let num_channels = cur.read_u16()? as usize;
+ if num_channels > 64 {
+ return Err("PSD layer has excessive channel count".to_string());
+ }
+ let mut channels = Vec::with_capacity(num_channels);
+ for _ in 0..num_channels {
+ let id = cur.read_i16()?;
+ let data_len = cur.read_len(is_psb)?;
+ channels.push(ChannelInfo { id, data_len });
+ }
+
+ let sig = cur.read_bytes(4)?;
+ if sig != b"8BIM" {
+ return Err("Invalid PSD layer blend signature".to_string());
+ }
+ let blend_key: [u8; 4] = cur.read_bytes(4)?.try_into().unwrap();
+ let blend_mode = map_psd_blend_key(&blend_key);
+ let opacity = cur.read_u8()?;
+ let clipping = cur.read_u8()? != 0;
+ let flags = cur.read_u8()?;
+ let _filler = cur.read_u8()?;
+
+ let transparency_protected = (flags & 0x01) != 0;
+ let hidden = (flags & 0x02) != 0;
+
+ let extra_len = cur.read_u32()? as usize;
+ let extra_bytes = cur.read_bytes(extra_len)?;
+ let mut ecur = Cursor::new(extra_bytes);
+
+ // 1. Layer Mask Data
+ let mask_len = ecur.read_u32()? as usize;
+ let mask_data = ecur.read_bytes(mask_len)?;
+ let mask = if mask_len >= 20 {
+ let m_top = i32::from_be_bytes(mask_data[0..4].try_into().unwrap());
+ let m_left = i32::from_be_bytes(mask_data[4..8].try_into().unwrap());
+ let m_bottom = i32::from_be_bytes(mask_data[8..12].try_into().unwrap());
+ let m_right = i32::from_be_bytes(mask_data[12..16].try_into().unwrap());
+ let default_color = mask_data[16];
+ let mflags = mask_data[17];
+ Some(PsdMaskRecord {
+ top: m_top,
+ left: m_left,
+ bottom: m_bottom,
+ right: m_right,
+ default_color,
+ position_relative: (mflags & 0x01) != 0,
+ disabled: (mflags & 0x02) != 0,
+ })
+ } else {
+ None
+ };
+
+ // 2. Blending Ranges (skip)
+ let blend_ranges_len = ecur.read_u32()? as usize;
+ ecur.skip(blend_ranges_len)?;
+
+ // 3. Layer Name (Pascal string padded to 4-byte boundary)
+ let name_len = ecur.read_u8()? as usize;
+ let name_bytes = ecur.read_bytes(name_len)?;
+ let mut name = String::from_utf8_lossy(name_bytes).to_string();
+ let total_name_field = 1 + name_len;
+ let pad = (4 - (total_name_field % 4)) % 4;
+ if pad > 0 {
+ let _ = ecur.skip(pad);
+ }
+
+ // 4. Additional Layer Info (Tagged Blocks: luni, lsct, lsdk, lspf)
+ let mut section_divider: Option<(u32, Option<&'static str>)> = None;
+ let mut position_or_composite_locked = false;
+ let mut extra_transparency_locked = false;
+
+ while ecur.remaining() >= 12 {
+ let Ok(tsig) = ecur.read_bytes(4) else { break };
+ if tsig != b"8BIM" && tsig != b"8B64" {
+ break;
+ }
+ let Ok(tkey_b) = ecur.read_bytes(4) else {
+ break;
+ };
+ let tkey: [u8; 4] = tkey_b.try_into().unwrap();
+ let block_len = if is_psb && is_psb_64bit_tagged_block(&tkey) {
+ match ecur.read_u64() {
+ Ok(v) => v as usize,
+ Err(_) => break,
+ }
+ } else {
+ match ecur.read_u32() {
+ Ok(v) => v as usize,
+ Err(_) => break,
+ }
+ };
+ let Ok(block) = ecur.read_bytes(block_len) else {
+ break;
+ };
+ // Tagged blocks inside extra layer info are padded to 2 or 4 bytes depending on writer;
+ // Photoshop aligns tagged blocks to even length (2 bytes) in most specs, or 4 bytes in some.
+ if block_len % 2 == 1 {
+ let _ = ecur.skip(1);
+ }
+ // If next 4 bytes aren't 8BIM/8B64 and skipping 2 bytes reveals 8BIM/8B64, realign
+ if ecur.remaining() >= 6 {
+ let peek = &ecur.data[ecur.pos..ecur.pos + 4];
+ if peek != b"8BIM" && peek != b"8B64" {
+ let peek2 = &ecur.data[ecur.pos + 2..ecur.pos + 6];
+ if peek2 == b"8BIM" || peek2 == b"8B64" {
+ let _ = ecur.skip(2);
+ }
+ }
+ }
+
+ match &tkey {
+ b"luni" => {
+ if block.len() >= 4 {
+ let char_count =
+ u32::from_be_bytes([block[0], block[1], block[2], block[3]]) as usize;
+ let max_chars = ((block.len() - 4) / 2).min(char_count);
+ let mut u16s = Vec::with_capacity(max_chars);
+ for i in 0..max_chars {
+ let off = 4 + i * 2;
+ u16s.push(u16::from_be_bytes([block[off], block[off + 1]]));
+ }
+ let decoded = String::from_utf16_lossy(&u16s)
+ .trim_end_matches('\0')
+ .to_string();
+ if !decoded.is_empty() {
+ name = decoded;
+ }
+ }
+ }
+ b"lsct" | b"lsdk" => {
+ if block.len() >= 4 {
+ let divider_type =
+ u32::from_be_bytes([block[0], block[1], block[2], block[3]]);
+ let folder_blend = if block.len() >= 12 && &block[4..8] == b"8BIM" {
+ let bk: [u8; 4] = block[8..12].try_into().unwrap();
+ Some(map_psd_blend_key(&bk))
+ } else {
+ None
+ };
+ section_divider = Some((divider_type, folder_blend));
+ }
+ }
+ b"lspf" => {
+ if block.len() >= 4 {
+ let prot = u32::from_be_bytes([block[0], block[1], block[2], block[3]]);
+ if (prot & 0x01) != 0 {
+ extra_transparency_locked = true;
+ }
+ if (prot & 0x02) != 0 || (prot & 0x04) != 0 {
+ position_or_composite_locked = true;
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+
+ records.push(PsdLayerRecord {
+ top,
+ left,
+ bottom,
+ right,
+ channels,
+ channel_slices: Vec::with_capacity(num_channels),
+ blend_mode,
+ opacity,
+ clipping,
+ hidden,
+ transparency_protected: transparency_protected || extra_transparency_locked,
+ position_or_composite_locked,
+ name,
+ section_divider,
+ mask,
+ });
+ }
+
+ // Read channel image data slices for each layer sequentially (zero-copy)
+ for rec in &mut records {
+ for ch in &rec.channels {
+ let slice = cur.read_bytes(ch.data_len)?;
+ rec.channel_slices.push((ch.id, slice));
+ }
+ }
+
+ Ok(records)
+}
+
+/// Decodes the flattened merged Image Data section (used when a PSD has 0 layers).
+fn decode_merged_composite(
+ image_data: &[u8],
+ width: usize,
+ height: usize,
+ channels_count: usize,
+ depth: u16,
+ color_mode: u16,
+ is_psb: bool,
+) -> Result<Vec<u8>, String> {
+ if image_data.len() < 2 {
+ return Err("Empty PSD Image Data section".to_string());
+ }
+ let compression = u16::from_be_bytes([image_data[0], image_data[1]]);
+ let payload = &image_data[2..];
+ let bytes_per_sample = match depth {
+ 8 => 1usize,
+ 16 => 2usize,
+ 32 => 4usize,
+ 1 => 1usize,
+ _ => return Err(format!("Unsupported PSD bit depth: {}", depth)),
+ };
+ let row_bytes = if depth == 1 {
+ width.div_ceil(8)
+ } else {
+ width * bytes_per_sample
+ };
+ let plane_bytes = row_bytes
+ .checked_mul(height)
+ .ok_or_else(|| "PSD composite size overflow".to_string())?;
+ let max_channels = channels_count.min(5);
+ let mut raw_planes: Vec<Vec<u8>> = vec![vec![0u8; plane_bytes]; max_channels];
+
+ match compression {
+ 0 => {
+ let mut off = 0usize;
+ for plane in &mut raw_planes {
+ let take = plane_bytes.min(payload.len().saturating_sub(off));
+ plane[..take].copy_from_slice(&payload[off..off + take]);
+ off += plane_bytes;
+ }
+ }
+ 1 => {
+ let count_size = if is_psb { 4usize } else { 2usize };
+ let total_rows = channels_count * height;
+ let counts_bytes = total_rows * count_size;
+ if payload.len() < counts_bytes {
+ return Err("Truncated PSD composite RLE header".to_string());
+ }
+ let mut data_pos = counts_bytes;
+ for c in 0..channels_count {
+ for y in 0..height {
+ let row_idx = c * height + y;
+ let c_off = row_idx * count_size;
+ let rle_len = if is_psb {
+ u32::from_be_bytes(payload[c_off..c_off + 4].try_into().unwrap()) as usize
+ } else {
+ u16::from_be_bytes([payload[c_off], payload[c_off + 1]]) as usize
+ };
+ if data_pos + rle_len > payload.len() {
+ break;
+ }
+ if c < max_channels {
+ decode_packbits_row(
+ &payload[data_pos..data_pos + rle_len],
+ &mut raw_planes[c][y * row_bytes..(y + 1) * row_bytes],
+ )?;
+ }
+ data_pos += rle_len;
+ }
+ }
+ }
+ 2 | 3 => {
+ let total_raw = plane_bytes * max_channels;
+ let mut dec = ZlibDecoder::new(payload);
+ let mut all = Vec::with_capacity(total_raw);
+ let mut limited = (&mut dec).take((total_raw as u64) + 1);
+ let _ = limited.read_to_end(&mut all);
+ for (c, plane) in raw_planes.iter_mut().enumerate() {
+ let start = c * plane_bytes;
+ if start < all.len() {
+ let take = plane_bytes.min(all.len() - start);
+ plane[..take].copy_from_slice(&all[start..start + take]);
+ if compression == 3 {
+ unpredict_channel(plane, width, height, depth);
+ }
+ }
+ }
+ }
+ other => return Err(format!("Unsupported PSD composite compression: {}", other)),
+ }
+
+ let pixels = width * height;
+ let convert_plane = |raw: &[u8]| -> Vec<u8> {
+ match depth {
+ 8 => raw.to_vec(),
+ 16 => raw.chunks_exact(2).map(|c| c[0]).collect(),
+ 32 => raw
+ .chunks_exact(4)
+ .map(|c| {
+ let f = f32::from_be_bytes([c[0], c[1], c[2], c[3]]);
+ (f.clamp(0.0, 1.0) * 255.0).round() as u8
+ })
+ .collect(),
+ 1 => {
+ let mut out = vec![0u8; pixels];
+ for y in 0..height {
+ let row = &raw[y * row_bytes..(y + 1) * row_bytes];
+ for x in 0..width {
+ let bit = (row[x >> 3] >> (7 - (x & 7))) & 1;
+ out[y * width + x] = if bit != 0 { 0 } else { 255 };
+ }
+ }
+ out
+ }
+ _ => vec![0u8; pixels],
+ }
+ };
+
+ let mut tagged: Vec<(i16, Vec<u8>)> = Vec::with_capacity(max_channels);
+ for (idx, plane) in raw_planes.into_iter().enumerate() {
+ let ch_id = match color_mode {
+ 1 => {
+ if idx == 0 {
+ 0
+ } else {
+ -1
+ }
+ }
+ 4 => {
+ if idx < 4 {
+ idx as i16
+ } else {
+ -1
+ }
+ }
+ _ => {
+ if idx < 3 {
+ idx as i16
+ } else {
+ -1
+ }
+ }
+ };
+ tagged.push((ch_id, convert_plane(&plane)));
+ }
+
+ Ok(assemble_rgba_from_channels(
+ color_mode, width, height, &tagged,
+ ))
+}
+
+/// Parses a Photoshop `.psd` or `.psb` file buffer natively in Rust with Rayon parallelism,
+/// returning the compact `INKD` binary wire frame with LZ4-compressed sparse 256x256 tiles.
+pub fn parse_psd_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {
+ let mut cur = Cursor::new(bytes);
+
+ // 1. File Header (26 bytes)
+ let sig = cur.read_bytes(4)?;
+ if sig != b"8BPS" {
+ return Err("Invalid PSD/PSB signature (expected 8BPS)".to_string());
+ }
+ let version = cur.read_u16()?;
+ let is_psb = match version {
+ 1 => false,
+ 2 => true,
+ _ => return Err(format!("Unsupported PSD version: {}", version)),
+ };
+ cur.skip(6)?; // reserved
+ let channels_count = cur.read_u16()? as usize;
+ let height = cur.read_u32()?;
+ let width = cur.read_u32()?;
+ let depth = cur.read_u16()?;
+ let color_mode = cur.read_u16()?;
+
+ if width == 0 || height == 0 || width > MAX_CANVAS_DIM || height > MAX_CANVAS_DIM {
+ return Err(format!(
+ "PSD dimensions {}x{} out of valid bounds (1..={})",
+ width, height, MAX_CANVAS_DIM
+ ));
+ }
+
+ // 2. Color Mode Data (skip)
+ let color_mode_len = cur.read_u32()? as usize;
+ cur.skip(color_mode_len)?;
+
+ // 3. Image Resources (extract DPI)
+ let resources_len = cur.read_u32()? as usize;
+ let resources_bytes = cur.read_bytes(resources_len)?;
+ let dpi = parse_dpi_from_resources(resources_bytes);
+
+ // 4. Layer and Mask Information
+ let layer_mask_len = cur.read_len(is_psb)?;
+ let layer_mask_bytes = cur.read_bytes(layer_mask_len)?;
+ let records = parse_layer_records(layer_mask_bytes, is_psb)?;
+
+ // 5. Image Data (composite fallback)
+ let image_data_bytes = &bytes[cur.pos..];
+
+ let ink_color_mode = if color_mode == 1 { "grayscale" } else { "color" };
+
+ // Build top-to-bottom Ink Studio layer hierarchy from PSD bottom-to-top records.
+ // In PSD, records are bottom-to-top:
+ // - Section divider type 3 ("</Layer group>") marks the BOTTOM of a folder
+ // - Children appear after it
+ // - Section divider type 1 (open folder) or 2 (closed folder) marks the TOP of the folder
+ // Iterating in REVERSE (top-to-bottom):
+ // - type 1 or 2 opens a folder (push folder ID onto stack)
+ // - type 3 closes the current folder (pop stack)
+ // - normal record emits a raster layer with parent = stack.last()
+ struct LayerPlan<'a> {
+ id: String,
+ parent_id: Option<String>,
+ is_folder: bool,
+ collapsed: bool,
+ blend_mode: &'static str,
+ rec: &'a PsdLayerRecord<'a>,
+ }
+
+ let mut plans: Vec<LayerPlan<'_>> = Vec::with_capacity(records.len());
+ let mut folder_stack: Vec<String> = Vec::new();
+ let mut seq = 0usize;
+
+ for rec in records.iter().rev() {
+ match rec.section_divider {
+ Some((1, folder_blend)) | Some((2, folder_blend)) => {
+ seq += 1;
+ let id = format!("psd-folder-{}", seq);
+ let parent_id = folder_stack.last().cloned();
+ let collapsed = matches!(rec.section_divider, Some((2, _)));
+ let blend = folder_blend.unwrap_or(rec.blend_mode);
+ plans.push(LayerPlan {
+ id: id.clone(),
+ parent_id,
+ is_folder: true,
+ collapsed,
+ blend_mode: blend,
+ rec,
+ });
+ folder_stack.push(id);
+ }
+ Some((3, _)) => {
+ folder_stack.pop();
+ }
+ _ => {
+ seq += 1;
+ let id = format!("psd-layer-{}", seq);
+ let parent_id = folder_stack.last().cloned();
+ plans.push(LayerPlan {
+ id,
+ parent_id,
+ is_folder: false,
+ collapsed: false,
+ blend_mode: rec.blend_mode,
+ rec,
+ });
+ }
+ }
+ }
+
+ // Parallel decode of all layers & masks via Rayon
+ let doc_w_i32 = width as i32;
+ let doc_h_i32 = height as i32;
+
+ let mut assembled: Vec<AssembledLayer> = plans
+ .into_par_iter()
+ .map(|plan| -> Result<AssembledLayer, String> {
+ let rec = plan.rec;
+
+ // Decode optional layer mask (channel ID -2)
+ let mask = if let Some(m) = &rec.mask {
+ let mw = (m.right - m.left).max(0) as usize;
+ let mh = (m.bottom - m.top).max(0) as usize;
+ let mut gray = vec![m.default_color; (width as usize) * (height as usize)];
+
+ if mw > 0 && mh > 0 {
+ if let Some((_, slice)) = rec.channel_slices.iter().find(|(cid, _)| *cid == -2)
+ {
+ let decoded_mask = decode_channel_to_u8(slice, mw, mh, depth, is_psb)?;
+ let sx0 = (-m.left).max(0) as usize;
+ let sy0 = (-m.top).max(0) as usize;
+ let sx1 = (doc_w_i32 - m.left).min(mw as i32).max(0) as usize;
+ let sy1 = (doc_h_i32 - m.top).min(mh as i32).max(0) as usize;
+ if sx0 < sx1 && sy0 < sy1 {
+ let copy_w = sx1 - sx0;
+ for sy in sy0..sy1 {
+ let dy = (m.top + sy as i32) as usize;
+ let dx = (m.left + sx0 as i32) as usize;
+ let src_off = sy * mw + sx0;
+ let dst_off = dy * (width as usize) + dx;
+ gray[dst_off..dst_off + copy_w]
+ .copy_from_slice(&decoded_mask[src_off..src_off + copy_w]);
+ }
+ }
+ }
+ }
+
+ Some(RawMask {
+ enabled: !m.disabled,
+ linked: !m.position_relative,
+ default_color: m.default_color,
+ left: 0,
+ top: 0,
+ width,
+ height,
+ gray,
+ })
+ } else {
+ None
+ };
+
+ let name = if rec.name.is_empty() {
+ if plan.is_folder {
+ "Folder".to_string()
+ } else {
+ "Layer".to_string()
+ }
+ } else {
+ rec.name.clone()
+ };
+
+ if plan.is_folder {
+ return Ok(AssembledLayer {
+ id: plan.id,
+ name,
+ layer_type: "folder".to_string(),
+ visible: !rec.hidden,
+ opacity: (rec.opacity as f32) / 255.0,
+ blend_mode: plan.blend_mode.to_string(),
+ locked: rec.position_or_composite_locked,
+ alpha_locked: rec.transparency_protected,
+ clipped: rec.clipping,
+ collapsed: plan.collapsed,
+ parent_id: plan.parent_id,
+ solid_fill_hex: None,
+ tiles: Vec::new(),
+ mask,
+ });
+ }
+
+ let lw = (rec.right - rec.left).max(0) as usize;
+ let lh = (rec.bottom - rec.top).max(0) as usize;
+
+ let tiles = if lw > 0 && lh > 0 {
+ let mut decoded_channels = Vec::with_capacity(rec.channel_slices.len());
+ for &(cid, slice) in &rec.channel_slices {
+ if cid == -2 || cid == -3 {
+ continue; // mask channel handled above
+ }
+ let ch_u8 = decode_channel_to_u8(slice, lw, lh, depth, is_psb)?;
+ decoded_channels.push((cid, ch_u8));
+ }
+ let rgba = assemble_rgba_from_channels(color_mode, lw, lh, &decoded_channels);
+ slice_rgba_rect_to_tiles(&rgba, lw, lh, rec.left, rec.top, doc_w_i32, doc_h_i32)
+ } else {
+ Vec::new()
+ };
+
+ Ok(AssembledLayer {
+ id: plan.id,
+ name,
+ layer_type: "raster".to_string(),
+ visible: !rec.hidden,
+ opacity: (rec.opacity as f32) / 255.0,
+ blend_mode: plan.blend_mode.to_string(),
+ locked: rec.position_or_composite_locked,
+ alpha_locked: rec.transparency_protected,
+ clipped: rec.clipping,
+ collapsed: false,
+ parent_id: plan.parent_id,
+ solid_fill_hex: None,
+ tiles,
+ mask,
+ })
+ })
+ .collect::<Result<Vec<_>, String>>()?;
+
+ // Flattened single-layer fallback when PSD has no layer records
+ if assembled.is_empty() && !image_data_bytes.is_empty() {
+ if let Ok(rgba) = decode_merged_composite(
+ image_data_bytes,
+ width as usize,
+ height as usize,
+ channels_count,
+ depth,
+ color_mode,
+ is_psb,
+ ) {
+ let tiles = slice_rgba_rect_to_tiles(
+ &rgba,
+ width as usize,
+ height as usize,
+ 0,
+ 0,
+ doc_w_i32,
+ doc_h_i32,
+ );
+ assembled.push(AssembledLayer {
+ id: "psd-layer-base-1".to_string(),
+ name: "Background".to_string(),
+ layer_type: "raster".to_string(),
+ visible: true,
+ opacity: 1.0,
+ blend_mode: "normal".to_string(),
+ locked: false,
+ alpha_locked: false,
+ clipped: false,
+ collapsed: false,
+ parent_id: None,
+ solid_fill_hex: None,
+ tiles,
+ mask: None,
+ });
+ }
+ }
+
+ pack_parsed_document(width, height, dpi, ink_color_mode, None, assembled)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::doc_wire::BYTES_32BIT;
+
+ #[test]
+ fn test_parse_minimal_psd_with_layer_and_folder() {
+ // Construct a minimal valid PSD v1 (4x4, RGB, 8-bit) with 1 folder containing 1 red 2x2 layer at (1, 1)
+ let mut psd = Vec::new();
+ // Header
+ psd.extend_from_slice(b"8BPS");
+ psd.extend_from_slice(&1u16.to_be_bytes()); // v1
+ psd.extend_from_slice(&[0u8; 6]);
+ psd.extend_from_slice(&4u16.to_be_bytes()); // 4 channels
+ psd.extend_from_slice(&4u32.to_be_bytes()); // height
+ psd.extend_from_slice(&4u32.to_be_bytes()); // width
+ psd.extend_from_slice(&8u16.to_be_bytes()); // depth
+ psd.extend_from_slice(&3u16.to_be_bytes()); // RGB
+
+ // Color Mode Data (empty)
+ psd.extend_from_slice(&0u32.to_be_bytes());
+
+ // Image Resources (DPI = 600 -> 600 << 16)
+ let mut res = Vec::new();
+ res.extend_from_slice(b"8BIM");
+ res.extend_from_slice(&0x03EDu16.to_be_bytes());
+ res.extend_from_slice(&[0u8, 0u8]); // empty pascal name + pad
+ res.extend_from_slice(&16u32.to_be_bytes());
+ res.extend_from_slice(&(600u32 << 16).to_be_bytes());
+ res.extend_from_slice(&[0u8; 12]);
+ psd.extend_from_slice(&(res.len() as u32).to_be_bytes());
+ psd.extend_from_slice(&res);
+
+ // Layer Info: 3 records (bottom-to-top):
+ // 0: folder end divider (type 3)
+ // 1: raster layer "RedDot" at (1,1)-(3,3), raw RGBA (255, 0, 0, 255)
+ // 2: folder open divider (type 1) "Group"
+ let mut linfo = Vec::new();
+ linfo.extend_from_slice(&3i16.to_be_bytes());
+
+ let write_divider = |out: &mut Vec<u8>, name: &str, div_type: u32| {
+ out.extend_from_slice(&[0u8; 16]); // empty rect
+ out.extend_from_slice(&0u16.to_be_bytes()); // 0 channels
+ out.extend_from_slice(b"8BIMpass");
+ out.push(255); // opacity
+ out.push(0); // clipping
+ out.push(0); // flags
+ out.push(0); // filler
+ let mut extra = Vec::new();
+ extra.extend_from_slice(&0u32.to_be_bytes()); // mask
+ extra.extend_from_slice(&0u32.to_be_bytes()); // blend ranges
+ extra.push(name.len() as u8);
+ extra.extend_from_slice(name.as_bytes());
+ let pad = (4 - ((1 + name.len()) % 4)) % 4;
+ extra.resize(extra.len() + pad, 0);
+ extra.extend_from_slice(b"8BIMlsct");
+ extra.extend_from_slice(&4u32.to_be_bytes());
+ extra.extend_from_slice(&div_type.to_be_bytes());
+ out.extend_from_slice(&(extra.len() as u32).to_be_bytes());
+ out.extend_from_slice(&extra);
+ };
+
+ // 0: folder end
+ write_divider(&mut linfo, "</Layer group>", 3);
+
+ // 1: raster layer 2x2 at (1,1)-(3,3)
+ linfo.extend_from_slice(&1i32.to_be_bytes()); // top
+ linfo.extend_from_slice(&1i32.to_be_bytes()); // left
+ linfo.extend_from_slice(&3i32.to_be_bytes()); // bottom
+ linfo.extend_from_slice(&3i32.to_be_bytes()); // right
+ linfo.extend_from_slice(&4u16.to_be_bytes()); // 4 channels
+ for cid in [-1i16, 0, 1, 2] {
+ linfo.extend_from_slice(&cid.to_be_bytes());
+ linfo.extend_from_slice(&6u32.to_be_bytes()); // 2-byte comp + 4 bytes raw
+ }
+ linfo.extend_from_slice(b"8BIMmul ");
+ linfo.push(128); // opacity ~0.5
+ linfo.push(1); // clipping
+ linfo.push(0); // flags
+ linfo.push(0);
+ let mut extra = Vec::new();
+ extra.extend_from_slice(&0u32.to_be_bytes());
+ extra.extend_from_slice(&0u32.to_be_bytes());
+ extra.push(6);
+ extra.extend_from_slice(b"RedDot");
+ extra.push(0); // pad to 8
+ linfo.extend_from_slice(&(extra.len() as u32).to_be_bytes());
+ linfo.extend_from_slice(&extra);
+
+ // 2: folder open
+ write_divider(&mut linfo, "Group", 1);
+
+ // Channel data for layer 1 (A=255, R=250, G=10, B=20)
+ for val in [255u8, 250, 10, 20] {
+ linfo.extend_from_slice(&0u16.to_be_bytes()); // raw
+ linfo.extend_from_slice(&[val; 4]);
+ }
+
+ let mut lm_sec = Vec::new();
+ lm_sec.extend_from_slice(&(linfo.len() as u32).to_be_bytes());
+ lm_sec.extend_from_slice(&linfo);
+ psd.extend_from_slice(&(lm_sec.len() as u32).to_be_bytes());
+ psd.extend_from_slice(&lm_sec);
+
+ // Empty merged image data
+ psd.extend_from_slice(&0u16.to_be_bytes());
+
+ let wire = parse_psd_to_binary(&psd).expect("parse_psd_to_binary failed");
+ assert_eq!(&wire[0..4], b"INKD");
+ let meta_len = u32::from_le_bytes(wire[8..12].try_into().unwrap()) as usize;
+ let meta: serde_json::Value = serde_json::from_slice(&wire[12..12 + meta_len]).unwrap();
+ assert_eq!(meta["width"], 4);
+ assert_eq!(meta["height"], 4);
+ assert_eq!(meta["dpi"], 600);
+ let layers = meta["layers"].as_array().unwrap();
+ assert_eq!(layers.len(), 2);
+ assert_eq!(layers[0]["type"], "folder");
+ assert_eq!(layers[0]["name"], "Group");
+ assert_eq!(layers[1]["type"], "raster");
+ assert_eq!(layers[1]["name"], "RedDot");
+ assert_eq!(layers[1]["parentId"], layers[0]["id"]);
+ assert_eq!(layers[1]["blendMode"], "multiply");
+ assert_eq!(layers[1]["clipped"], true);
+
+ let t0 = &layers[1]["tiles"][0];
+ let b_start = 12 + meta_len + t0["offset"].as_u64().unwrap() as usize;
+ let b_len = t0["len"].as_u64().unwrap() as usize;
+ let decoded = lz4_flex::block::decompress(&wire[b_start..b_start + b_len], BYTES_32BIT).unwrap();
+ let px_off = (1 * 256 + 1) * 4;
+ assert_eq!(&decoded[px_off..px_off + 4], &[250, 10, 20, 255]);
+ }
+}
diff --git a/src-tauri/src/raster_ops.rs b/src-tauri/src/raster_ops.rs
new file mode 100644
index 0000000..c362e88
--- /dev/null
+++ b/src-tauri/src/raster_ops.rs
@@ -0,0 +1,1350 @@
+use flate2::read::{DeflateDecoder, ZlibDecoder};
+use flate2::write::{DeflateEncoder, ZlibEncoder};
+use flate2::Compression;
+use rayon::prelude::*;
+use std::io::{Read, Write};
+
+pub const MAX_RASTER_BYTES: usize = 256 * 1024 * 1024; // 256 MB cap (e.g. 8192x8192 RGBA)
+pub const MAX_BATCH_TILES: usize = 4096;
+pub const MAX_TILE_BYTES: usize = 4 * 1024 * 1024;
+
+// ---------------------------------------------------------------------------
+// 1. Parallel Separable Gaussian Blur, Motion Blur, Unsharp Mask, Film Grain
+// ---------------------------------------------------------------------------
+
+fn boxes_for_gauss(sigma: f32, n: usize) -> Vec<usize> {
+ let nf = n as f32;
+ let w_ideal = ((12.0 * sigma * sigma / nf) + 1.0).sqrt();
+ let mut wl = w_ideal.floor() as i32;
+ if wl % 2 == 0 {
+ wl -= 1;
+ }
+ wl = wl.max(1);
+ let wu = wl + 2;
+
+ let wl_f = wl as f32;
+ let m_ideal =
+ (12.0 * sigma * sigma - nf * wl_f * wl_f - 4.0 * nf * wl_f - 3.0 * nf) / (-4.0 * wl_f - 4.0);
+ let m = m_ideal.round() as i32;
+
+ (0..n)
+ .map(|i| if (i as i32) < m { wl as usize } else { wu as usize })
+ .collect()
+}
+
+/// Parallel 1D horizontal sliding-window box blur on RGBA rows (O(W*H) independent of radius).
+fn box_blur_h_rgba(src: &[u8], dst: &mut [u8], w: usize, h: usize, r: usize) {
+ if r == 0 || w == 0 || h == 0 {
+ dst.copy_from_slice(src);
+ return;
+ }
+ let row_bytes = w * 4;
+ let inv = 1.0f32 / (r + r + 1) as f32;
+
+ dst.par_chunks_exact_mut(row_bytes)
+ .enumerate()
+ .for_each(|(y, dst_row)| {
+ let src_row = &src[y * row_bytes..(y + 1) * row_bytes];
+ let fv = [
+ src_row[0] as i32,
+ src_row[1] as i32,
+ src_row[2] as i32,
+ src_row[3] as i32,
+ ];
+ let last_off = (w - 1) * 4;
+ let lv = [
+ src_row[last_off] as i32,
+ src_row[last_off + 1] as i32,
+ src_row[last_off + 2] as i32,
+ src_row[last_off + 3] as i32,
+ ];
+
+ let mut acc = [
+ (r as i32 + 1) * fv[0],
+ (r as i32 + 1) * fv[1],
+ (r as i32 + 1) * fv[2],
+ (r as i32 + 1) * fv[3],
+ ];
+ for j in 0..r {
+ let idx = j.min(w - 1) * 4;
+ acc[0] += src_row[idx] as i32;
+ acc[1] += src_row[idx + 1] as i32;
+ acc[2] += src_row[idx + 2] as i32;
+ acc[3] += src_row[idx + 3] as i32;
+ }
+
+ let mut ri = r;
+ let mut li = 0usize;
+ let mut ti = 0usize;
+
+ // Left edge
+ let left_end = (r + 1).min(w);
+ for _ in 0..left_end {
+ let r_idx = ri.min(w - 1) * 4;
+ ri += 1;
+ acc[0] += src_row[r_idx] as i32 - fv[0];
+ acc[1] += src_row[r_idx + 1] as i32 - fv[1];
+ acc[2] += src_row[r_idx + 2] as i32 - fv[2];
+ acc[3] += src_row[r_idx + 3] as i32 - fv[3];
+ dst_row[ti] = (acc[0] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ dst_row[ti + 1] = (acc[1] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ dst_row[ti + 2] = (acc[2] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ dst_row[ti + 3] = (acc[3] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ ti += 4;
+ }
+
+ // Interior (no clamping branches)
+ if w > r * 2 + 1 {
+ for _ in (r + 1)..(w - r) {
+ let r_idx = ri * 4;
+ let l_idx = li * 4;
+ ri += 1;
+ li += 1;
+ acc[0] += src_row[r_idx] as i32 - src_row[l_idx] as i32;
+ acc[1] += src_row[r_idx + 1] as i32 - src_row[l_idx + 1] as i32;
+ acc[2] += src_row[r_idx + 2] as i32 - src_row[l_idx + 2] as i32;
+ acc[3] += src_row[r_idx + 3] as i32 - src_row[l_idx + 3] as i32;
+ dst_row[ti] = (acc[0] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ dst_row[ti + 1] = (acc[1] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ dst_row[ti + 2] = (acc[2] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ dst_row[ti + 3] = (acc[3] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ ti += 4;
+ }
+ }
+
+ // Right edge
+ let right_start = (r + 1).max(w.saturating_sub(r));
+ for _ in right_start..w {
+ let l_idx = li.min(w - 1) * 4;
+ li += 1;
+ acc[0] += lv[0] - src_row[l_idx] as i32;
+ acc[1] += lv[1] - src_row[l_idx + 1] as i32;
+ acc[2] += lv[2] - src_row[l_idx + 2] as i32;
+ acc[3] += lv[3] - src_row[l_idx + 3] as i32;
+ dst_row[ti] = (acc[0] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ dst_row[ti + 1] = (acc[1] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ dst_row[ti + 2] = (acc[2] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ dst_row[ti + 3] = (acc[3] as f32 * inv).round().clamp(0.0, 255.0) as u8;
+ ti += 4;
+ }
+ });
+}
+
+/// Cache-blocked parallel transpose of an RGBA image `(w x h) -> (h x w)`.
+/// Makes the vertical box blur pass 100% sequential in L1 cache.
+fn transpose_rgba(src: &[u8], dst: &mut [u8], w: usize, h: usize) {
+ const BLOCK: usize = 32;
+ let dst_row_bytes = h * 4;
+ // Partition output rows (x in 0..w) in blocks of BLOCK for Rayon parallelism
+ dst.par_chunks_mut(dst_row_bytes * BLOCK)
+ .enumerate()
+ .for_each(|(bx, dst_band)| {
+ let x0 = bx * BLOCK;
+ let x1 = (x0 + BLOCK).min(w);
+ let mut y0 = 0usize;
+ while y0 < h {
+ let y1 = (y0 + BLOCK).min(h);
+ for y in y0..y1 {
+ let src_row_off = y * w * 4;
+ for x in x0..x1 {
+ let s = src_row_off + x * 4;
+ let d = (x - x0) * dst_row_bytes + y * 4;
+ dst_band[d..d + 4].copy_from_slice(&src[s..s + 4]);
+ }
+ }
+ y0 = y1;
+ }
+ });
+}
+
+pub fn gaussian_blur_rgba(src: &[u8], w: usize, h: usize, radius: f32) -> Result<Vec<u8>, String> {
+ let expected = w
+ .checked_mul(h)
+ .and_then(|p| p.checked_mul(4))
+ .ok_or_else(|| "Image dimensions overflow".to_string())?;
+ if src.len() != expected || expected > MAX_RASTER_BYTES {
+ return Err("Invalid RGBA buffer size for Gaussian blur".to_string());
+ }
+ if w == 0 || h == 0 {
+ return Ok(Vec::new());
+ }
+ let r = radius.clamp(0.1, 200.0);
+ let bxs = boxes_for_gauss(r, 3);
+
+ let mut cur = src.to_vec();
+ let mut tmp = vec![0u8; expected];
+ let mut trans_a = vec![0u8; expected];
+ let mut trans_b = vec![0u8; expected];
+
+ // All 3 horizontal passes sequentially on (w x h) -> transpose ONCE -> 3 horizontal passes on (h x w) -> transpose back!
+ // Because 1D box blurs commute (H1*V1*H2*V2*H3*V3 == H1*H2*H3 * V1*V2*V3), we only transpose TWICE instead of 6 times!
+ for &b in &bxs {
+ let br = (b.saturating_sub(1)) / 2;
+ box_blur_h_rgba(&cur, &mut tmp, w, h, br);
+ std::mem::swap(&mut cur, &mut tmp);
+ }
+
+ transpose_rgba(&cur, &mut trans_a, w, h);
+
+ for &b in &bxs {
+ let br = (b.saturating_sub(1)) / 2;
+ box_blur_h_rgba(&trans_a, &mut trans_b, h, w, br);
+ std::mem::swap(&mut trans_a, &mut trans_b);
+ }
+
+ transpose_rgba(&trans_a, &mut cur, h, w);
+ Ok(cur)
+}
+
+pub fn motion_blur_rgba(
+ src: &[u8],
+ w: usize,
+ h: usize,
+ distance: f32,
+ angle_deg: f32,
+) -> Result<Vec<u8>, String> {
+ let expected = w
+ .checked_mul(h)
+ .and_then(|p| p.checked_mul(4))
+ .ok_or_else(|| "Image dimensions overflow".to_string())?;
+ if src.len() != expected || expected > MAX_RASTER_BYTES {
+ return Err("Invalid RGBA buffer size for Motion blur".to_string());
+ }
+ if w == 0 || h == 0 {
+ return Ok(Vec::new());
+ }
+
+ let dist = distance.clamp(1.0, 200.0);
+ let rad = angle_deg.to_radians();
+ let cos_a = rad.cos();
+ let sin_a = rad.sin();
+ let half_steps = (dist * 0.5).floor().max(1.0) as i32;
+ let num_samples = (half_steps * 2 + 1) as f32;
+ let inv_samples = 1.0f32 / num_samples;
+ let step_scale = dist / num_samples;
+
+ let offsets: Vec<(i32, i32)> = (-half_steps..=half_steps)
+ .map(|s| {
+ let f = (s as f32) * step_scale;
+ ((cos_a * f).round() as i32, (sin_a * f).round() as i32)
+ })
+ .collect();
+
+ let mut dst = vec![0u8; expected];
+ let row_bytes = w * 4;
+ let max_x = (w - 1) as i32;
+ let max_y = (h - 1) as i32;
+
+ dst.par_chunks_exact_mut(row_bytes)
+ .enumerate()
+ .for_each(|(y, dst_row)| {
+ let yi = y as i32;
+ for x in 0..w {
+ let xi = x as i32;
+ let mut acc_r = 0u32;
+ let mut acc_g = 0u32;
+ let mut acc_b = 0u32;
+ let mut acc_a = 0u32;
+ for &(dx, dy) in &offsets {
+ let sx = (xi + dx).clamp(0, max_x) as usize;
+ let sy = (yi + dy).clamp(0, max_y) as usize;
+ let idx = (sy * w + sx) * 4;
+ acc_r += src[idx] as u32;
+ acc_g += src[idx + 1] as u32;
+ acc_b += src[idx + 2] as u32;
+ acc_a += src[idx + 3] as u32;
+ }
+ let out_i = x * 4;
+ dst_row[out_i] = (acc_r as f32 * inv_samples).round().clamp(0.0, 255.0) as u8;
+ dst_row[out_i + 1] = (acc_g as f32 * inv_samples).round().clamp(0.0, 255.0) as u8;
+ dst_row[out_i + 2] = (acc_b as f32 * inv_samples).round().clamp(0.0, 255.0) as u8;
+ dst_row[out_i + 3] = (acc_a as f32 * inv_samples).round().clamp(0.0, 255.0) as u8;
+ }
+ });
+
+ Ok(dst)
+}
+
+pub fn unsharp_mask_rgba(
+ src: &[u8],
+ w: usize,
+ h: usize,
+ radius: f32,
+ amount: f32,
+ threshold: f32,
+) -> Result<Vec<u8>, String> {
+ let blurred = gaussian_blur_rgba(src, w, h, radius)?;
+ let safe_thresh = threshold.max(0.0) as i32;
+ let mut dst = vec![0u8; src.len()];
+ let row_bytes = w * 4;
+
+ dst.par_chunks_exact_mut(row_bytes)
+ .enumerate()
+ .for_each(|(y, dst_row)| {
+ let base = y * row_bytes;
+ let s_row = &src[base..base + row_bytes];
+ let b_row = &blurred[base..base + row_bytes];
+ for x in 0..w {
+ let i = x * 4;
+ let dr = s_row[i] as i32 - b_row[i] as i32;
+ let dg = s_row[i + 1] as i32 - b_row[i + 1] as i32;
+ let db = s_row[i + 2] as i32 - b_row[i + 2] as i32;
+ let max_d = dr.abs().max(dg.abs()).max(db.abs());
+ if max_d >= safe_thresh {
+ dst_row[i] = (s_row[i] as f32 + dr as f32 * amount)
+ .round()
+ .clamp(0.0, 255.0) as u8;
+ dst_row[i + 1] = (s_row[i + 1] as f32 + dg as f32 * amount)
+ .round()
+ .clamp(0.0, 255.0) as u8;
+ dst_row[i + 2] = (s_row[i + 2] as f32 + db as f32 * amount)
+ .round()
+ .clamp(0.0, 255.0) as u8;
+ } else {
+ dst_row[i] = s_row[i];
+ dst_row[i + 1] = s_row[i + 1];
+ dst_row[i + 2] = s_row[i + 2];
+ }
+ dst_row[i + 3] = s_row[i + 3];
+ }
+ });
+
+ Ok(dst)
+}
+
+#[inline]
+fn mulberry32_hash(seed: u32) -> f32 {
+ let s = seed.wrapping_add(0x6d2b_79f5);
+ let mut t = (s ^ (s >> 15)).wrapping_mul(1 | s);
+ t = (t.wrapping_add((t ^ (t >> 7)).wrapping_mul(61 | t))) ^ t;
+ ((t ^ (t >> 14)) as f32) / 4_294_967_296.0
+}
+
+pub fn film_grain_rgba(
+ src: &[u8],
+ w: usize,
+ h: usize,
+ intensity: f32,
+ size: u32,
+ monochromatic: bool,
+ seed: u32,
+) -> Result<Vec<u8>, String> {
+ let expected = w
+ .checked_mul(h)
+ .and_then(|p| p.checked_mul(4))
+ .ok_or_else(|| "Image dimensions overflow".to_string())?;
+ if src.len() != expected || expected > MAX_RASTER_BYTES {
+ return Err("Invalid RGBA buffer size for Film grain".to_string());
+ }
+ if w == 0 || h == 0 {
+ return Ok(Vec::new());
+ }
+
+ let scale = (intensity / 100.0) * 128.0;
+ let grain_size = size.clamp(1, 10) as usize;
+ let blocks_w = w.div_ceil(grain_size);
+ let row_bytes = w * 4;
+ let mut dst = vec![0u8; expected];
+
+ // Per-block stateless hash PRNG enables lock-free Rayon parallelism with deterministic output
+ dst.par_chunks_exact_mut(row_bytes)
+ .enumerate()
+ .for_each(|(y, dst_row)| {
+ let src_row = &src[y * row_bytes..(y + 1) * row_bytes];
+ let by = y / grain_size;
+ let b_row = by * blocks_w;
+ for x in 0..w {
+ let i = x * 4;
+ let a = src_row[i + 3];
+ if a == 0 {
+ dst_row[i + 3] = 0;
+ continue;
+ }
+ let bx = x / grain_size;
+ let block_id = ((b_row + bx) as u32)
+ .wrapping_mul(0x9e37_79b9)
+ .wrapping_add(seed);
+ if monochromatic {
+ let noise = (mulberry32_hash(block_id) * 2.0 - 1.0) * scale;
+ dst_row[i] = (src_row[i] as f32 + noise).round().clamp(0.0, 255.0) as u8;
+ dst_row[i + 1] = (src_row[i + 1] as f32 + noise).round().clamp(0.0, 255.0) as u8;
+ dst_row[i + 2] = (src_row[i + 2] as f32 + noise).round().clamp(0.0, 255.0) as u8;
+ } else {
+ let nr = (mulberry32_hash(block_id) * 2.0 - 1.0) * scale;
+ let ng = (mulberry32_hash(block_id.wrapping_add(1)) * 2.0 - 1.0) * scale;
+ let nb = (mulberry32_hash(block_id.wrapping_add(2)) * 2.0 - 1.0) * scale;
+ dst_row[i] = (src_row[i] as f32 + nr).round().clamp(0.0, 255.0) as u8;
+ dst_row[i + 1] = (src_row[i + 1] as f32 + ng).round().clamp(0.0, 255.0) as u8;
+ dst_row[i + 2] = (src_row[i + 2] as f32 + nb).round().clamp(0.0, 255.0) as u8;
+ }
+ dst_row[i + 3] = a;
+ }
+ });
+
+ Ok(dst)
+}
+
+// ---------------------------------------------------------------------------
+// 2. Parallel Morphological Ops + Scanline Flood Fill
+// ---------------------------------------------------------------------------
+
+fn dilate_binary_mask_par(mask: &[u8], w: usize, h: usize, radius: usize) -> Vec<u8> {
+ if radius == 0 {
+ return mask.to_vec();
+ }
+ let r = radius as isize;
+ let mut horiz = vec![0u8; w * h];
+ horiz
+ .par_chunks_exact_mut(w)
+ .enumerate()
+ .for_each(|(y, h_row)| {
+ let m_row = &mask[y * w..(y + 1) * w];
+ let mut last = -1_000_000isize;
+ for x in 0..w {
+ if m_row[x] != 0 {
+ last = x as isize;
+ }
+ if (x as isize) - last <= r {
+ h_row[x] = 1;
+ }
+ }
+ last = 1_000_000isize;
+ for x in (0..w).rev() {
+ if m_row[x] != 0 {
+ last = x as isize;
+ }
+ if last - (x as isize) <= r {
+ h_row[x] = 1;
+ }
+ }
+ });
+
+ let mut out = vec![0u8; w * h];
+ // Parallel by column chunks (strided writes avoided via row-parallel sliding count!)
+ // Actually: vertical dilation on a binary mask = pixel (x,y) is 1 iff any horiz[x, y-r..=y+r] == 1.
+ // Row-parallel sliding window over columns: compute prefix sums per column or chunk columns.
+ // For binary masks, row-parallel over y reading horiz[y0..=y1] is cache-friendly & lock-free:
+ out.par_chunks_exact_mut(w)
+ .enumerate()
+ .for_each(|(y, out_row)| {
+ let y0 = y.saturating_sub(radius);
+ let y1 = (y + radius).min(h - 1);
+ for yy in y0..=y1 {
+ let h_row = &horiz[yy * w..(yy + 1) * w];
+ for x in 0..w {
+ out_row[x] |= h_row[x];
+ }
+ }
+ });
+ out
+}
+
+fn erode_binary_mask_par(mask: &[u8], w: usize, h: usize, radius: usize) -> Vec<u8> {
+ if radius == 0 {
+ return mask.to_vec();
+ }
+ let r = radius as isize;
+ let mut horiz = vec![0u8; w * h];
+ horiz
+ .par_chunks_exact_mut(w)
+ .enumerate()
+ .for_each(|(y, h_row)| {
+ let m_row = &mask[y * w..(y + 1) * w];
+ let mut last_zero = -1_000_000isize;
+ for x in 0..w {
+ if m_row[x] == 0 {
+ last_zero = x as isize;
+ }
+ if (x as isize) - last_zero > r {
+ h_row[x] = 1;
+ }
+ }
+ last_zero = 1_000_000isize;
+ for x in (0..w).rev() {
+ if m_row[x] == 0 {
+ last_zero = x as isize;
+ }
+ if last_zero - (x as isize) <= r {
+ h_row[x] = 0;
+ }
+ }
+ });
+
+ let mut out = vec![1u8; w * h];
+ out.par_chunks_exact_mut(w)
+ .enumerate()
+ .for_each(|(y, out_row)| {
+ let y0 = y.saturating_sub(radius);
+ let y1 = (y + radius).min(h - 1);
+ for yy in y0..=y1 {
+ let h_row = &horiz[yy * w..(yy + 1) * w];
+ for x in 0..w {
+ out_row[x] &= h_row[x];
+ }
+ }
+ });
+ out
+}
+
+pub struct FloodFillParams {
+ pub width: usize,
+ pub height: usize,
+ pub start_x: i32,
+ pub start_y: i32,
+ pub fill_rgba: [u8; 4],
+ pub tolerance: f32,
+ pub close_gap: u32,
+ pub area_scale: i32,
+ pub anti_alias: bool,
+ pub same_surface: bool,
+}
+
+/// Executes flood fill and returns compact binary response:
+/// `[modified: u8][min_x: i32 LE][min_y: i32 LE][dirty_w: i32 LE][dirty_h: i32 LE][dirty_rgba_bytes]`
+pub fn flood_fill_rgba(
+ ref_rgba: &[u8],
+ target_rgba_opt: Option<&[u8]>,
+ selection_mask: Option<&[u8]>,
+ params: &FloodFillParams,
+) -> Result<Vec<u8>, String> {
+ let w = params.width;
+ let h = params.height;
+ let total_pixels = w
+ .checked_mul(h)
+ .ok_or_else(|| "FloodFill dimensions overflow".to_string())?;
+ let expected_bytes = total_pixels
+ .checked_mul(4)
+ .ok_or_else(|| "FloodFill byte size overflow".to_string())?;
+ if ref_rgba.len() != expected_bytes || expected_bytes > MAX_RASTER_BYTES {
+ return Err("Invalid reference RGBA buffer for flood fill".to_string());
+ }
+ let target_src = target_rgba_opt.unwrap_or(ref_rgba);
+ if target_src.len() != expected_bytes {
+ return Err("Invalid target RGBA buffer for flood fill".to_string());
+ }
+ if let Some(sm) = selection_mask {
+ if sm.len() != total_pixels {
+ return Err("Invalid selection mask length for flood fill".to_string());
+ }
+ }
+
+ let no_op = || -> Vec<u8> { vec![0u8; 17] };
+
+ if w == 0 || h == 0 {
+ return Ok(no_op());
+ }
+ if params.start_x < 0
+ || params.start_x >= w as i32
+ || params.start_y < 0
+ || params.start_y >= h as i32
+ {
+ return Ok(no_op());
+ }
+ let px = params.start_x as usize;
+ let py = params.start_y as usize;
+ let seed_p = py * w + px;
+
+ if let Some(sm) = selection_mask {
+ if sm[seed_p] == 0 {
+ return Ok(no_op());
+ }
+ }
+
+ let seed_i = seed_p * 4;
+ let sr = ref_rgba[seed_i] as i32;
+ let sg = ref_rgba[seed_i + 1] as i32;
+ let sb = ref_rgba[seed_i + 2] as i32;
+ let sa = ref_rgba[seed_i + 3] as i32;
+
+ let close_gap = params.close_gap.min(20) as usize;
+ let area_scale = params.area_scale.clamp(-20, 20);
+ let [fr, fg, fb, fa] = params.fill_rgba;
+
+ if params.same_surface
+ && area_scale == 0
+ && (sr - fr as i32).abs() <= 2
+ && (sg - fg as i32).abs() <= 2
+ && (sb - fb as i32).abs() <= 2
+ && (sa - fa as i32).abs() <= 2
+ {
+ return Ok(no_op());
+ }
+
+ let max_tol_4 = ((params.tolerance / 100.0) * 255.0 * 4.0) as i32;
+
+ // Optional parallel Close Gap morphological barrier mask
+ let barrier_mask: Option<Vec<u8>> = if close_gap > 0 {
+ let mut raw_barrier = vec![0u8; total_pixels];
+ raw_barrier
+ .par_chunks_exact_mut(w)
+ .enumerate()
+ .for_each(|(y, row)| {
+ let base = y * w * 4;
+ for x in 0..w {
+ let i = base + x * 4;
+ let diff4 = (ref_rgba[i] as i32 - sr).abs()
+ + (ref_rgba[i + 1] as i32 - sg).abs()
+ + (ref_rgba[i + 2] as i32 - sb).abs()
+ + (ref_rgba[i + 3] as i32 - sa).abs();
+ if diff4 > max_tol_4 {
+ row[x] = 1;
+ }
+ }
+ });
+ let closing_r = close_gap.div_ceil(2).max(1);
+ let dilated = dilate_binary_mask_par(&raw_barrier, w, h, closing_r);
+ let mut closed = erode_binary_mask_par(&dilated, w, h, closing_r);
+ closed
+ .par_iter_mut()
+ .zip(raw_barrier.par_iter())
+ .for_each(|(c, &rb)| {
+ if rb != 0 {
+ *c = 1;
+ }
+ });
+ closed[seed_p] = raw_barrier[seed_p];
+ Some(closed)
+ } else {
+ None
+ };
+
+ let matches_seed = |x: usize, y: usize| -> bool {
+ let p = y * w + x;
+ if let Some(sm) = selection_mask {
+ if sm[p] == 0 {
+ return false;
+ }
+ }
+ if let Some(ref bm) = barrier_mask {
+ return bm[p] == 0;
+ }
+ let i = p * 4;
+ let diff4 = (ref_rgba[i] as i32 - sr).abs()
+ + (ref_rgba[i + 1] as i32 - sg).abs()
+ + (ref_rgba[i + 2] as i32 - sb).abs()
+ + (ref_rgba[i + 3] as i32 - sa).abs();
+ diff4 <= max_tol_4
+ };
+
+ let mut visited = vec![0u8; total_pixels];
+ let mut stack: Vec<(usize, usize)> = Vec::with_capacity(4096);
+ stack.push((px, py));
+
+ let mut min_x = px;
+ let mut max_x = px;
+ let mut min_y = py;
+ let mut max_y = py;
+
+ while let Some((cur_x, cur_y)) = stack.pop() {
+ let row_off = cur_y * w;
+ if visited[row_off + cur_x] != 0 {
+ continue;
+ }
+ let mut x1 = cur_x;
+ while x1 > 0 && visited[row_off + x1 - 1] == 0 && matches_seed(x1 - 1, cur_y) {
+ x1 -= 1;
+ }
+ if visited[row_off + x1] != 0 || !matches_seed(x1, cur_y) {
+ continue;
+ }
+ let mut x2 = cur_x;
+ while x2 + 1 < w && visited[row_off + x2 + 1] == 0 && matches_seed(x2 + 1, cur_y) {
+ x2 += 1;
+ }
+
+ min_x = min_x.min(x1);
+ max_x = max_x.max(x2);
+ min_y = min_y.min(cur_y);
+ max_y = max_y.max(cur_y);
+
+ let mut span_above = false;
+ let mut span_below = false;
+ for x in x1..=x2 {
+ visited[row_off + x] = 1;
+ if cur_y > 0 {
+ let above_ok = visited[(cur_y - 1) * w + x] == 0 && matches_seed(x, cur_y - 1);
+ if !span_above && above_ok {
+ stack.push((x, cur_y - 1));
+ span_above = true;
+ } else if span_above && !above_ok {
+ span_above = false;
+ }
+ }
+ if cur_y + 1 < h {
+ let below_ok = visited[(cur_y + 1) * w + x] == 0 && matches_seed(x, cur_y + 1);
+ if !span_below && below_ok {
+ stack.push((x, cur_y + 1));
+ span_below = true;
+ } else if span_below && !below_ok {
+ span_below = false;
+ }
+ }
+ }
+ }
+
+ // Area scaling (expand with line-art centerline guard, or shrink via parallel erosion)
+ let mut final_mask = visited;
+ if area_scale > 0 {
+ let get_line_strength = |p: usize| -> f32 {
+ let i = p * 4;
+ let a = ref_rgba[i + 3] as f32 / 255.0;
+ let luma = (0.299 * ref_rgba[i] as f32
+ + 0.587 * ref_rgba[i + 1] as f32
+ + 0.114 * ref_rgba[i + 2] as f32)
+ / 255.0;
+ a * (1.0 - luma * 0.85)
+ };
+
+ let mut frontier: Vec<usize> = Vec::new();
+ for y in min_y..=max_y {
+ let row_off = y * w;
+ for x in min_x..=max_x {
+ let p = row_off + x;
+ if final_mask[p] == 0 {
+ continue;
+ }
+ if (x > 0 && final_mask[p - 1] == 0)
+ || (x + 1 < w && final_mask[p + 1] == 0)
+ || (y > 0 && final_mask[p - w] == 0)
+ || (y + 1 < h && final_mask[p + w] == 0)
+ {
+ frontier.push(p);
+ }
+ }
+ }
+
+ for _ in 0..(area_scale as usize) {
+ if frontier.is_empty() {
+ break;
+ }
+ let mut next_frontier = Vec::new();
+ for &p in &frontier {
+ let x = p % w;
+ let y = p / w;
+ let cur_str = get_line_strength(p);
+ let neighbors: [Option<(usize, usize)>; 4] = [
+ if x > 0 { Some((x - 1, y)) } else { None },
+ if x + 1 < w { Some((x + 1, y)) } else { None },
+ if y > 0 { Some((x, y - 1)) } else { None },
+ if y + 1 < h { Some((x, y + 1)) } else { None },
+ ];
+ for nb in neighbors.into_iter().flatten() {
+ let (nx, ny) = nb;
+ let np = ny * w + nx;
+ if final_mask[np] != 0 {
+ continue;
+ }
+ let n_str = get_line_strength(np);
+ if cur_str > 0.55 && n_str < cur_str - 0.05 {
+ continue;
+ }
+ final_mask[np] = 1;
+ next_frontier.push(np);
+ min_x = min_x.min(nx);
+ max_x = max_x.max(nx);
+ min_y = min_y.min(ny);
+ max_y = max_y.max(ny);
+ }
+ }
+ frontier = next_frontier;
+ }
+ } else if area_scale < 0 {
+ final_mask = erode_binary_mask_par(&final_mask, w, h, area_scale.unsigned_abs() as usize);
+ }
+
+ if params.anti_alias {
+ min_x = min_x.saturating_sub(1);
+ min_y = min_y.saturating_sub(1);
+ max_x = (max_x + 1).min(w - 1);
+ max_y = (max_y + 1).min(h - 1);
+ }
+
+ let dirty_w = max_x - min_x + 1;
+ let dirty_h = max_y - min_y + 1;
+ let mut dirty_rgba = vec![0u8; dirty_w * dirty_h * 4];
+ let dirty_row_bytes = dirty_w * 4;
+ let anti_alias = params.anti_alias;
+
+ // Parallel composite of only the dirty bounding box
+ dirty_rgba
+ .par_chunks_exact_mut(dirty_row_bytes)
+ .enumerate()
+ .for_each(|(ry, out_row)| {
+ let y = min_y + ry;
+ let row_off = y * w;
+ let src_start = (row_off + min_x) * 4;
+ out_row.copy_from_slice(&target_src[src_start..src_start + dirty_row_bytes]);
+
+ for rx in 0..dirty_w {
+ let x = min_x + rx;
+ let p = row_off + x;
+ if let Some(sm) = selection_mask {
+ if sm[p] == 0 {
+ continue;
+ }
+ }
+ let ti = rx * 4;
+ if final_mask[p] != 0 {
+ out_row[ti] = fr;
+ out_row[ti + 1] = fg;
+ out_row[ti + 2] = fb;
+ out_row[ti + 3] = fa;
+ } else if anti_alias {
+ let mut n = 0u32;
+ if x > 0 && final_mask[p - 1] != 0 {
+ n += 1;
+ }
+ if x + 1 < w && final_mask[p + 1] != 0 {
+ n += 1;
+ }
+ if y > 0 && final_mask[p - w] != 0 {
+ n += 1;
+ }
+ if y + 1 < h && final_mask[p + w] != 0 {
+ n += 1;
+ }
+ if n >= 2 {
+ let blend_a = (n as f32 / 4.0) * (fa as f32 / 255.0) * 0.5;
+ let dst_a = out_row[ti + 3] as f32 / 255.0;
+ let out_a = blend_a + dst_a * (1.0 - blend_a);
+ if out_a > 0.0 {
+ let inv = 1.0 / out_a;
+ let k = dst_a * (1.0 - blend_a);
+ out_row[ti] =
+ ((fr as f32 * blend_a + out_row[ti] as f32 * k) * inv)
+ .round()
+ .clamp(0.0, 255.0) as u8;
+ out_row[ti + 1] =
+ ((fg as f32 * blend_a + out_row[ti + 1] as f32 * k) * inv)
+ .round()
+ .clamp(0.0, 255.0) as u8;
+ out_row[ti + 2] =
+ ((fb as f32 * blend_a + out_row[ti + 2] as f32 * k) * inv)
+ .round()
+ .clamp(0.0, 255.0) as u8;
+ out_row[ti + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
+ }
+ }
+ }
+ }
+ });
+
+ let mut resp = Vec::with_capacity(17 + dirty_rgba.len());
+ resp.push(1u8); // modified = true
+ resp.extend_from_slice(&(min_x as i32).to_le_bytes());
+ resp.extend_from_slice(&(min_y as i32).to_le_bytes());
+ resp.extend_from_slice(&(dirty_w as i32).to_le_bytes());
+ resp.extend_from_slice(&(dirty_h as i32).to_le_bytes());
+ resp.extend_from_slice(&dirty_rgba);
+ Ok(resp)
+}
+
+// ---------------------------------------------------------------------------
+// 3. Parallel Bilinear Liquify Step
+// ---------------------------------------------------------------------------
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum LiquifyMode {
+ Push = 0,
+ PushLeft = 1,
+ PushRight = 2,
+ Expand = 3,
+ Pinch = 4,
+ TwirlCw = 5,
+ TwirlCcw = 6,
+ Reconstruct = 7,
+}
+
+impl LiquifyMode {
+ pub fn from_u8(v: u8) -> Result<Self, String> {
+ match v {
+ 0 => Ok(Self::Push),
+ 1 => Ok(Self::PushLeft),
+ 2 => Ok(Self::PushRight),
+ 3 => Ok(Self::Expand),
+ 4 => Ok(Self::Pinch),
+ 5 => Ok(Self::TwirlCw),
+ 6 => Ok(Self::TwirlCcw),
+ 7 => Ok(Self::Reconstruct),
+ _ => Err(format!("Unknown liquify mode code: {}", v)),
+ }
+ }
+}
+
+pub struct LiquifyStepParams {
+ pub roi_w: usize,
+ pub roi_h: usize,
+ pub min_x: f32,
+ pub min_y: f32,
+ pub cx: f32,
+ pub cy: f32,
+ pub ux: f32,
+ pub uy: f32,
+ pub v_len: f32,
+ pub radius: f32,
+ pub hardness: f32,
+ pub strength: f32,
+ pub mode: LiquifyMode,
+}
+
+pub fn liquify_step_rgba(
+ src_roi: &[u8],
+ init_roi: Option<&[u8]>,
+ sel_mask_roi: Option<&[u8]>,
+ p: &LiquifyStepParams,
+) -> Result<Vec<u8>, String> {
+ let roi_pixels = p
+ .roi_w
+ .checked_mul(p.roi_h)
+ .ok_or_else(|| "Liquify ROI dimensions overflow".to_string())?;
+ let roi_bytes = roi_pixels
+ .checked_mul(4)
+ .ok_or_else(|| "Liquify ROI byte size overflow".to_string())?;
+ if src_roi.len() != roi_bytes || roi_bytes > MAX_RASTER_BYTES {
+ return Err("Invalid source ROI buffer for liquify".to_string());
+ }
+ if let Some(init) = init_roi {
+ if init.len() != roi_bytes {
+ return Err("Invalid initial ROI buffer for liquify reconstruct".to_string());
+ }
+ }
+ if let Some(mask) = sel_mask_roi {
+ if mask.len() != roi_pixels {
+ return Err("Invalid selection ROI mask for liquify".to_string());
+ }
+ }
+
+ let mut dst = src_roi.to_vec();
+ let radius = p.radius.max(1.0);
+ let radius_sq = radius * radius;
+ let inv_radius = 1.0 / radius;
+ let twirl_base = if p.mode == LiquifyMode::TwirlCw {
+ p.strength * 0.45
+ } else {
+ -p.strength * 0.45
+ };
+ let row_bytes = p.roi_w * 4;
+ let max_sx = (p.roi_w as f32) - 1.0001;
+ let max_sy = (p.roi_h as f32) - 1.0001;
+
+ dst.par_chunks_exact_mut(row_bytes)
+ .enumerate()
+ .for_each(|(ry, dst_row)| {
+ let py = p.min_y + ry as f32;
+ let dy = py - p.cy;
+ let dy_sq = dy * dy;
+ if dy_sq >= radius_sq {
+ return;
+ }
+ let mask_row_off = ry * p.roi_w;
+
+ for rx in 0..p.roi_w {
+ let px = p.min_x + rx as f32;
+ let dx = px - p.cx;
+ let dist_sq = dx * dx + dy_sq;
+ if dist_sq >= radius_sq {
+ continue;
+ }
+ if let Some(m) = sel_mask_roi {
+ if m[mask_row_off + rx] == 0 {
+ continue;
+ }
+ }
+ let u = dist_sq.sqrt() * inv_radius;
+ if u >= 1.0 {
+ continue;
+ }
+ let t = 1.0 - u * u;
+ let weight = (1.0 - p.hardness) * (t * t) + p.hardness * t;
+ if weight <= 0.0 {
+ continue;
+ }
+
+ let di = rx * 4;
+ if p.mode == LiquifyMode::Reconstruct {
+ if let Some(init) = init_roi {
+ let alpha = (p.strength * weight * 0.35).min(1.0);
+ let inv_a = 1.0 - alpha;
+ let ii = ry * row_bytes + di;
+ dst_row[di] =
+ (dst_row[di] as f32 * inv_a + init[ii] as f32 * alpha).round() as u8;
+ dst_row[di + 1] =
+ (dst_row[di + 1] as f32 * inv_a + init[ii + 1] as f32 * alpha).round()
+ as u8;
+ dst_row[di + 2] =
+ (dst_row[di + 2] as f32 * inv_a + init[ii + 2] as f32 * alpha).round()
+ as u8;
+ dst_row[di + 3] =
+ (dst_row[di + 3] as f32 * inv_a + init[ii + 3] as f32 * alpha).round()
+ as u8;
+ }
+ continue;
+ }
+
+ let (src_x, src_y) = match p.mode {
+ LiquifyMode::Push => {
+ let amt = p.v_len * p.strength * weight;
+ (px - p.ux * amt, py - p.uy * amt)
+ }
+ LiquifyMode::PushLeft => {
+ let amt = p.v_len.max(1.5) * p.strength * weight;
+ (px + p.uy * amt, py - p.ux * amt)
+ }
+ LiquifyMode::PushRight => {
+ let amt = p.v_len.max(1.5) * p.strength * weight;
+ (px - p.uy * amt, py + p.ux * amt)
+ }
+ LiquifyMode::Expand => {
+ let factor = p.strength * weight * 0.3;
+ (p.cx + dx * (1.0 - factor), p.cy + dy * (1.0 - factor))
+ }
+ LiquifyMode::Pinch => {
+ let factor = p.strength * weight * 0.3;
+ (p.cx + dx * (1.0 + factor), p.cy + dy * (1.0 + factor))
+ }
+ LiquifyMode::TwirlCw | LiquifyMode::TwirlCcw => {
+ let (sin_t, cos_t) = (twirl_base * weight).sin_cos();
+ (p.cx + dx * cos_t + dy * sin_t, p.cy - dx * sin_t + dy * cos_t)
+ }
+ LiquifyMode::Reconstruct => unreachable!(),
+ };
+
+ let lsx = (src_x - p.min_x).clamp(0.0, max_sx);
+ let lsy = (src_y - p.min_y).clamp(0.0, max_sy);
+ let x0 = lsx as usize;
+ let y0 = lsy as usize;
+ let x1 = (x0 + 1).min(p.roi_w - 1);
+ let y1 = (y0 + 1).min(p.roi_h - 1);
+ let fx = lsx - x0 as f32;
+ let fy = lsy - y0 as f32;
+
+ let w00 = (1.0 - fx) * (1.0 - fy);
+ let w10 = fx * (1.0 - fy);
+ let w01 = (1.0 - fx) * fy;
+ let w11 = fx * fy;
+
+ let i00 = (y0 * p.roi_w + x0) * 4;
+ let i10 = (y0 * p.roi_w + x1) * 4;
+ let i01 = (y1 * p.roi_w + x0) * 4;
+ let i11 = (y1 * p.roi_w + x1) * 4;
+
+ dst_row[di] = (w00 * src_roi[i00] as f32
+ + w10 * src_roi[i10] as f32
+ + w01 * src_roi[i01] as f32
+ + w11 * src_roi[i11] as f32)
+ .round() as u8;
+ dst_row[di + 1] = (w00 * src_roi[i00 + 1] as f32
+ + w10 * src_roi[i10 + 1] as f32
+ + w01 * src_roi[i01 + 1] as f32
+ + w11 * src_roi[i11 + 1] as f32)
+ .round() as u8;
+ dst_row[di + 2] = (w00 * src_roi[i00 + 2] as f32
+ + w10 * src_roi[i10 + 2] as f32
+ + w01 * src_roi[i01 + 2] as f32
+ + w11 * src_roi[i11 + 2] as f32)
+ .round() as u8;
+ dst_row[di + 3] = (w00 * src_roi[i00 + 3] as f32
+ + w10 * src_roi[i10 + 3] as f32
+ + w01 * src_roi[i01 + 3] as f32
+ + w11 * src_roi[i11 + 3] as f32)
+ .round() as u8;
+ }
+ });
+
+ Ok(dst)
+}
+
+// ---------------------------------------------------------------------------
+// 4. Parallel Batch Tile Compression (LZ4 Raw Block + Flate2 Zlib/Deflate)
+// ---------------------------------------------------------------------------
+
+/// Input frame: `[count: u32 LE][len: u32 LE, raw_bytes]...`
+/// Output frame: `[count: u32 LE][codec: u8 (1=raw, 2=lz4), out_len: u32 LE, bytes]...`
+pub fn compress_tiles_lz4_batch(body: &[u8]) -> Result<Vec<u8>, String> {
+ if body.len() < 4 {
+ return Err("Truncated tile compress batch header".to_string());
+ }
+ let count = u32::from_le_bytes(body[0..4].try_into().unwrap()) as usize;
+ if count > MAX_BATCH_TILES {
+ return Err("Tile compress batch exceeds safety ceiling".to_string());
+ }
+
+ let mut slices: Vec<&[u8]> = Vec::with_capacity(count);
+ let mut off = 4usize;
+ for _ in 0..count {
+ if off + 4 > body.len() {
+ return Err("Truncated tile length in compress batch".to_string());
+ }
+ let len = u32::from_le_bytes(body[off..off + 4].try_into().unwrap()) as usize;
+ off += 4;
+ if len > MAX_TILE_BYTES || off + len > body.len() {
+ return Err("Invalid or truncated tile payload in compress batch".to_string());
+ }
+ slices.push(&body[off..off + len]);
+ off += len;
+ }
+
+ let results: Vec<(u8, Vec<u8>)> = slices
+ .into_par_iter()
+ .map(|raw| {
+ let comp = lz4_flex::block::compress(raw);
+ if comp.len() <= raw.len() {
+ (2u8, comp)
+ } else {
+ (1u8, raw.to_vec())
+ }
+ })
+ .collect();
+
+ let total_out: usize = 4 + results.iter().map(|(_, b)| 5 + b.len()).sum::<usize>();
+ let mut out = Vec::with_capacity(total_out);
+ out.extend_from_slice(&(count as u32).to_le_bytes());
+ for (codec, bytes) in results {
+ out.push(codec);
+ out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
+ out.extend_from_slice(&bytes);
+ }
+ Ok(out)
+}
+
+/// Input frame: `[count: u32 LE][codec: u8 (1=raw, 2=lz4), expected_len: u32 LE, comp_len: u32 LE, bytes]...`
+/// Output frame: `[count: u32 LE][raw_len: u32 LE, raw_bytes]...`
+pub fn decompress_tiles_lz4_batch(body: &[u8]) -> Result<Vec<u8>, String> {
+ if body.len() < 4 {
+ return Err("Truncated tile decompress batch header".to_string());
+ }
+ let count = u32::from_le_bytes(body[0..4].try_into().unwrap()) as usize;
+ if count > MAX_BATCH_TILES {
+ return Err("Tile decompress batch exceeds safety ceiling".to_string());
+ }
+
+ let mut items: Vec<(u8, usize, &[u8])> = Vec::with_capacity(count);
+ let mut off = 4usize;
+ for _ in 0..count {
+ if off + 9 > body.len() {
+ return Err("Truncated tile record header in decompress batch".to_string());
+ }
+ let codec = body[off];
+ let expected_len = u32::from_le_bytes(body[off + 1..off + 5].try_into().unwrap()) as usize;
+ let comp_len = u32::from_le_bytes(body[off + 5..off + 9].try_into().unwrap()) as usize;
+ off += 9;
+ if expected_len > MAX_TILE_BYTES || off + comp_len > body.len() {
+ return Err("Invalid or oversized tile payload in decompress batch".to_string());
+ }
+ items.push((codec, expected_len, &body[off..off + comp_len]));
+ off += comp_len;
+ }
+
+ let decoded: Vec<Vec<u8>> = items
+ .into_par_iter()
+ .map(|(codec, expected_len, data)| match codec {
+ 1 => {
+ if data.len() != expected_len {
+ Err("Raw tile length mismatch".to_string())
+ } else {
+ Ok(data.to_vec())
+ }
+ }
+ 2 => lz4_flex::block::decompress(data, expected_len)
+ .map_err(|e| format!("LZ4 block decompress failed: {}", e)),
+ _ => Err(format!("Unsupported tile codec: {}", codec)),
+ })
+ .collect::<Result<Vec<_>, String>>()?;
+
+ let total_out: usize = 4 + decoded.iter().map(|b| 4 + b.len()).sum::<usize>();
+ let mut out = Vec::with_capacity(total_out);
+ out.extend_from_slice(&(count as u32).to_le_bytes());
+ for raw in decoded {
+ out.extend_from_slice(&(raw.len() as u32).to_le_bytes());
+ out.extend_from_slice(&raw);
+ }
+ Ok(out)
+}
+
+pub fn flate_compress(op: &str, data: &[u8], level: u32) -> Result<Vec<u8>, String> {
+ let comp = Compression::new(level.min(9));
+ match op {
+ "deflate" => {
+ let mut enc = DeflateEncoder::new(Vec::new(), comp);
+ enc.write_all(data).map_err(|e| e.to_string())?;
+ enc.finish().map_err(|e| e.to_string())
+ }
+ "zlib" => {
+ let mut enc = ZlibEncoder::new(Vec::new(), comp);
+ enc.write_all(data).map_err(|e| e.to_string())?;
+ enc.finish().map_err(|e| e.to_string())
+ }
+ _ => Err(format!("Unknown compression op: {}", op)),
+ }
+}
+
+pub fn flate_decompress(
+ op: &str,
+ data: &[u8],
+ max_output_bytes: usize,
+) -> Result<Vec<u8>, String> {
+ let cap = max_output_bytes.min(MAX_RASTER_BYTES);
+ let mut out = Vec::new();
+ match op {
+ "inflate" => {
+ let mut dec = DeflateDecoder::new(data);
+ let mut limited = (&mut dec).take((cap as u64) + 1);
+ limited.read_to_end(&mut out).map_err(|e| e.to_string())?;
+ }
+ "unzlib" => {
+ let mut dec = ZlibDecoder::new(data);
+ let mut limited = (&mut dec).take((cap as u64) + 1);
+ limited.read_to_end(&mut out).map_err(|e| e.to_string())?;
+ }
+ _ => return Err(format!("Unknown decompression op: {}", op)),
+ }
+ if out.len() > cap {
+ return Err(format!(
+ "Decompressed payload exceeds safety ceiling ({} bytes)",
+ cap
+ ));
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_gaussian_blur_preserves_solid_and_blurs_impulse() {
+ let w = 32;
+ let h = 32;
+ let mut solid = vec![0u8; w * h * 4];
+ for px in solid.chunks_exact_mut(4) {
+ px.copy_from_slice(&[100, 150, 200, 255]);
+ }
+ let out = gaussian_blur_rgba(&solid, w, h, 3.0).unwrap();
+ assert_eq!(&out[0..4], &[100, 150, 200, 255]);
+
+ let mut impulse = vec![0u8; w * h * 4];
+ let mid = (16 * w + 16) * 4;
+ impulse[mid..mid + 4].copy_from_slice(&[255, 255, 255, 255]);
+ let blurred = gaussian_blur_rgba(&impulse, w, h, 2.0).unwrap();
+ assert!(blurred[mid] > 0 && blurred[mid] < 255);
+ assert!(blurred[(16 * w + 17) * 4] > 0);
+ }
+
+ #[test]
+ fn test_flood_fill_close_gap_and_bounds() {
+ let w = 40;
+ let h = 40;
+ let mut ref_img = vec![0u8; w * h * 4];
+ // Draw a black box from (10,10)..(30,30) with a 2px gap at (20..22, 10)
+ for x in 10..=30 {
+ if x == 20 || x == 21 {
+ continue;
+ }
+ for y in [10, 30] {
+ let i = (y * w + x) * 4;
+ ref_img[i + 3] = 255;
+ }
+ }
+ for y in 10..=30 {
+ for x in [10, 30] {
+ let i = (y * w + x) * 4;
+ ref_img[i + 3] = 255;
+ }
+ }
+
+ // With close_gap = 4, fill at (20, 20) stays trapped inside the box!
+ let resp = flood_fill_rgba(
+ &ref_img,
+ None,
+ None,
+ &FloodFillParams {
+ width: w,
+ height: h,
+ start_x: 20,
+ start_y: 20,
+ fill_rgba: [255, 0, 0, 255],
+ tolerance: 10.0,
+ close_gap: 4,
+ area_scale: 0,
+ anti_alias: false,
+ same_surface: true,
+ },
+ )
+ .unwrap();
+ assert_eq!(resp[0], 1);
+ let min_x = i32::from_le_bytes(resp[1..5].try_into().unwrap());
+ let min_y = i32::from_le_bytes(resp[5..9].try_into().unwrap());
+ let dw = i32::from_le_bytes(resp[9..13].try_into().unwrap());
+ let dh = i32::from_le_bytes(resp[13..17].try_into().unwrap());
+ assert!(min_x >= 10 && min_y >= 10 && dw <= 21 && dh <= 21);
+ }
+
+ #[test]
+ fn test_liquify_push_displaces_pixels() {
+ let w = 32;
+ let h = 32;
+ let mut roi = vec![0u8; w * h * 4];
+ let c = (16 * w + 16) * 4;
+ roi[c..c + 4].copy_from_slice(&[255, 0, 0, 255]);
+
+ let out = liquify_step_rgba(
+ &roi,
+ None,
+ None,
+ &LiquifyStepParams {
+ roi_w: w,
+ roi_h: h,
+ min_x: 0.0,
+ min_y: 0.0,
+ cx: 16.0,
+ cy: 16.0,
+ ux: 1.0,
+ uy: 0.0,
+ v_len: 4.0,
+ radius: 10.0,
+ hardness: 0.5,
+ strength: 1.0,
+ mode: LiquifyMode::Push,
+ },
+ )
+ .unwrap();
+ // Pixel should have moved right (+x)
+ let shifted = (16 * w + 19) * 4;
+ assert!(out[shifted] > 0 || out[(16 * w + 18) * 4] > 0);
+ }
+
+ #[test]
+ fn test_parallel_lz4_tile_batch_roundtrip() {
+ let t1 = vec![0xAAu8; 65536];
+ let t2: Vec<u8> = (0..262144).map(|i| (i % 251) as u8).collect();
+ let mut req = Vec::new();
+ req.extend_from_slice(&2u32.to_le_bytes());
+ req.extend_from_slice(&(t1.len() as u32).to_le_bytes());
+ req.extend_from_slice(&t1);
+ req.extend_from_slice(&(t2.len() as u32).to_le_bytes());
+ req.extend_from_slice(&t2);
+
+ let comp = compress_tiles_lz4_batch(&req).unwrap();
+ // Build decompress request
+ let count = u32::from_le_bytes(comp[0..4].try_into().unwrap());
+ assert_eq!(count, 2);
+ let mut off = 4usize;
+ let mut dec_req = Vec::new();
+ dec_req.extend_from_slice(&2u32.to_le_bytes());
+ for expected in [t1.len(), t2.len()] {
+ let codec = comp[off];
+ let clen = u32::from_le_bytes(comp[off + 1..off + 5].try_into().unwrap()) as usize;
+ off += 5;
+ dec_req.push(codec);
+ dec_req.extend_from_slice(&(expected as u32).to_le_bytes());
+ dec_req.extend_from_slice(&(clen as u32).to_le_bytes());
+ dec_req.extend_from_slice(&comp[off..off + clen]);
+ off += clen;
+ }
+ let dec = decompress_tiles_lz4_batch(&dec_req).unwrap();
+ let len1 = u32::from_le_bytes(dec[4..8].try_into().unwrap()) as usize;
+ assert_eq!(&dec[8..8 + len1], t1.as_slice());
+ let len2 = u32::from_le_bytes(dec[8 + len1..12 + len1].try_into().unwrap()) as usize;
+ assert_eq!(&dec[12 + len1..12 + len1 + len2], t2.as_slice());
+ }
+}
diff --git a/src-tauri/src/server.rs b/src-tauri/src/server.rs
index 88bf169..7f5305c 100644
--- a/src-tauri/src/server.rs
+++ b/src-tauri/src/server.rs
@@ -12,7 +12,7 @@ use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
- collections::HashMap,
+ collections::{HashMap, HashSet, VecDeque},
net::{SocketAddr, UdpSocket},
path::PathBuf,
process::Stdio,
@@ -23,7 +23,7 @@ use std::{
time::Instant,
};
use tokio::io::{AsyncBufReadExt, BufReader};
-use tokio::sync::{mpsc, oneshot, Notify, OwnedSemaphorePermit, RwLock, Semaphore};
+use tokio::sync::{mpsc, oneshot, Notify, OwnedSemaphorePermit, Semaphore};
use tower_http::cors::{AllowOrigin, CorsLayer};
#[cfg(windows)]
@@ -34,6 +34,40 @@ const MAX_WS_MESSAGE_BYTES: usize = 8 * 1024 * 1024; // 8 MB
const MAX_CONCURRENT_CLIENTS: usize = 16;
const WS_PING_INTERVAL_SECS: u64 = 25;
+// Binary wire protocol constants (must stay aligned with src/services/multiplayerService.ts)
+const BINARY_MAGIC_0: u8 = 0x49; // 'I'
+const BINARY_MAGIC_1: u8 = 0x4e; // 'N'
+const BINARY_HEADER_BYTES: usize = 11;
+
+const CODE_STROKE_START: u8 = 0x01;
+const CODE_STROKE_CHUNK: u8 = 0x02;
+const CODE_STROKE_FINISH: u8 = 0x03;
+const CODE_TILE_DELTA: u8 = 0x04;
+const CODE_CURSOR_MOVE: u8 = 0x05;
+const CODE_SELECTIVE_UNDO: u8 = 0x06;
+const CODE_BRUSH_ASSET_DATA: u8 = 0x07;
+const CODE_BRUSH_ASSET_REQUEST: u8 = 0x08;
+const CODE_LAYER_MASK_DATA: u8 = 0x09;
+
+const TILE_CODEC_EMPTY: u8 = 0;
+const TILE_CODEC_RAW: u8 = 1;
+const TILE_CODEC_LZ4: u8 = 2;
+const TILE_PACKET_HEADER_BYTES: usize = 14;
+const MAX_TILE_COORD: i32 = 4096;
+
+const MASK_FLAG_FULL_REPLACE: u8 = 0x01;
+const MAX_SYNC_CANVAS_DIM: u32 = 16384;
+
+// Server-side state ceilings (prevent memory exhaustion from rogue or buggy peers)
+const MAX_SYNC_LAYERS: usize = 512;
+const MAX_SYNC_VECTOR_STROKES: usize = 20_000;
+const MAX_OP_LOG_ENTRIES: usize = 4096;
+const MAX_OP_LOG_BYTES: usize = 64 * 1024 * 1024; // 64 MB
+const MAX_STORED_TILES: usize = 16_384;
+const MAX_TILE_STORE_BYTES: usize = 256 * 1024 * 1024; // 256 MB
+const MAX_MASK_PACKETS_PER_LAYER: usize = 128;
+const MAX_MASK_STORE_BYTES: usize = 32 * 1024 * 1024; // 32 MB
+
// Per-client message and bandwidth token bucket limits.
// Burst headroom accommodates progressive tile streaming on room join.
const CLIENT_MSG_BURST: f64 = 1000.0;
@@ -41,24 +75,1872 @@ const CLIENT_MSG_REFILL_PER_SEC: f64 = 400.0;
const CLIENT_BYTES_BURST: f64 = 32.0 * 1024.0 * 1024.0;
const CLIENT_BYTES_REFILL_PER_SEC: f64 = 16.0 * 1024.0 * 1024.0;
-// Connection upgrade rate limit to deter token brute-force / connection floods.
-const CONNECT_BURST: f64 = 30.0;
-const CONNECT_REFILL_PER_SEC: f64 = 5.0;
+// Connection upgrade rate limit to deter token brute-force / connection floods.
+const CONNECT_BURST: f64 = 30.0;
+const CONNECT_REFILL_PER_SEC: f64 = 5.0;
+
+// Pinned official Cloudflare release for explicit verified installation.
+pub const PINNED_CLOUDFLARED_VERSION: &str = "2026.11.1";
+pub const PINNED_CLOUDFLARED_URL: &str =
+ "https://github.com/cloudflare/cloudflared/releases/download/2026.11.1/cloudflared-windows-amd64.exe";
+pub const PINNED_CLOUDFLARED_SHA256: &str =
+ "341deda3db5ec498a0482254d6c38c0b7cf01a30c37bb5dd95d2216d08955e35";
+const MAX_CLOUDFLARED_BYTES: u64 = 100 * 1024 * 1024; // 100 MB ceiling
+
+static NEXT_CLIENT_ID: AtomicUsize = AtomicUsize::new(1);
+
+#[derive(Clone)]
+struct ClientHandle {
+ tx: mpsc::Sender<Message>,
+ kick: Arc<Notify>,
+ /// False while a full snapshot / catch-up sync is in flight so live
+ /// broadcasts never interleave out of order before the snapshot lands.
+ live: bool,
+ sync_in_progress: bool,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum PeerRole {
+ Host,
+ Editor,
+ Viewer,
+}
+
+impl PeerRole {
+ fn as_str(self) -> &'static str {
+ match self {
+ PeerRole::Host => "host",
+ PeerRole::Editor => "editor",
+ PeerRole::Viewer => "viewer",
+ }
+ }
+
+ fn from_guest_str(s: &str) -> Option<Self> {
+ match s {
+ "editor" => Some(PeerRole::Editor),
+ "viewer" => Some(PeerRole::Viewer),
+ _ => None,
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+struct PeerRecord {
+ client_id: usize,
+ id: String,
+ name: String,
+ is_host: bool,
+ role: PeerRole,
+ raw: serde_json::Map<String, serde_json::Value>,
+}
+
+#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
+struct TileKey {
+ layer_id: String,
+ tile_x: i32,
+ tile_y: i32,
+}
+
+#[derive(Clone)]
+enum OpPayload {
+ Text(Arc<String>),
+ Binary(Arc<Vec<u8>>),
+}
+
+impl OpPayload {
+ fn byte_len(&self) -> usize {
+ match self {
+ OpPayload::Text(s) => s.len(),
+ OpPayload::Binary(b) => b.len(),
+ }
+ }
+
+ fn to_message(&self) -> Message {
+ match self {
+ OpPayload::Text(s) => Message::Text((**s).clone()),
+ OpPayload::Binary(b) => Message::Binary((**b).clone()),
+ }
+ }
+}
+
+#[derive(Clone)]
+struct OpLogEntry {
+ seq: u64,
+ sender_client_id: Option<usize>,
+ payload: OpPayload,
+}
+
+#[derive(Clone)]
+struct DocumentSnapshot {
+ initialized: bool,
+ dimensions: serde_json::Value,
+ color_mode: String,
+ layers: Vec<serde_json::Map<String, serde_json::Value>>,
+ perspective_ruler: serde_json::Value,
+ straight_ruler: serde_json::Value,
+ animation_timeline: serde_json::Value,
+}
+
+impl Default for DocumentSnapshot {
+ fn default() -> Self {
+ Self {
+ initialized: false,
+ dimensions: serde_json::json!({ "width": 1920, "height": 1080 }),
+ color_mode: "color".to_string(),
+ layers: Vec::new(),
+ perspective_ruler: serde_json::Value::Null,
+ straight_ruler: serde_json::Value::Null,
+ animation_timeline: serde_json::Value::Null,
+ }
+ }
+}
+
+struct SnapshotSyncPlan {
+ snapshot_seq: u64,
+ join_accepted: Option<String>,
+ doc_sync_response: String,
+ tiles: Vec<Arc<Vec<u8>>>,
+ masks: Vec<Arc<Vec<u8>>>,
+}
+
+enum SyncPlan {
+ Full(SnapshotSyncPlan),
+ Incremental {
+ join_accepted: Option<String>,
+ since_seq: u64,
+ },
+}
+
+enum HandleTextOutcome {
+ None,
+ PeerRegistered(String),
+ StartSync {
+ peer_id: Option<String>,
+ plan: SyncPlan,
+ },
+}
+
+struct RoomState {
+ room_name: String,
+ seq: u64,
+ clients: HashMap<usize, ClientHandle>,
+ peers: HashMap<usize, PeerRecord>,
+ /// Persistent role assignment per peerId across reconnects (prevents viewer bypass via reconnect).
+ peer_roles: HashMap<String, PeerRole>,
+ /// Permanently banned peerIds for this room session.
+ banned_peer_ids: HashSet<String>,
+ host_client_id: Option<usize>,
+ host_peer_id: Option<String>,
+ doc: DocumentSnapshot,
+ tiles: HashMap<TileKey, Arc<Vec<u8>>>,
+ tile_store_bytes: usize,
+ masks: HashMap<String, Vec<Arc<Vec<u8>>>>,
+ mask_store_bytes: usize,
+ op_log: VecDeque<OpLogEntry>,
+ op_log_bytes: usize,
+ /// Highest `seq` evicted from `op_log` or replaced by a full document seed.
+ /// Incremental replay from `since_seq` is safe iff `since_seq >= op_log_floor && since_seq <= seq`.
+ op_log_floor: u64,
+}
+
+impl RoomState {
+ fn new(room_name: String) -> Self {
+ Self {
+ room_name,
+ seq: 0,
+ clients: HashMap::new(),
+ peers: HashMap::new(),
+ peer_roles: HashMap::new(),
+ banned_peer_ids: HashSet::new(),
+ host_client_id: None,
+ host_peer_id: None,
+ doc: DocumentSnapshot::default(),
+ tiles: HashMap::new(),
+ tile_store_bytes: 0,
+ masks: HashMap::new(),
+ mask_store_bytes: 0,
+ op_log: VecDeque::new(),
+ op_log_bytes: 0,
+ op_log_floor: 0,
+ }
+ }
+
+ #[inline]
+ fn is_host_client(&self, client_id: usize) -> bool {
+ self.host_client_id == Some(client_id)
+ }
+
+ #[inline]
+ fn client_role(&self, client_id: usize) -> PeerRole {
+ if self.is_host_client(client_id) {
+ return PeerRole::Host;
+ }
+ self.peers
+ .get(&client_id)
+ .map(|p| p.role)
+ .unwrap_or(PeerRole::Editor)
+ }
+
+ #[inline]
+ fn client_peer_id(&self, client_id: usize) -> Option<&str> {
+ self.peers.get(&client_id).map(|p| p.id.as_str())
+ }
+
+ fn send_direct(&self, client_id: usize, msg: Message) {
+ if let Some(c) = self.clients.get(&client_id) {
+ let _ = c.tx.try_send(msg);
+ }
+ }
+
+ fn send_access_denied(&self, client_id: usize, code: &str, reason: &str, target_peer_id: Option<&str>) {
+ let mut payload = serde_json::json!({
+ "type": "ACCESS_DENIED",
+ "code": code,
+ "reason": reason,
+ });
+ if let Some(pid) = target_peer_id {
+ payload["targetPeerId"] = serde_json::Value::String(pid.to_string());
+ }
+ self.send_direct(client_id, Message::Text(payload.to_string()));
+ }
+
+ fn can_mutate_canvas(&self, client_id: usize) -> Result<(), (&'static str, &'static str)> {
+ if self.client_role(client_id) == PeerRole::Viewer {
+ return Err(("VIEWER_READONLY", "Viewers have read-only access"));
+ }
+ Ok(())
+ }
+
+ fn can_modify_layer(
+ &self,
+ client_id: usize,
+ layer_id: &str,
+ ) -> Result<(), (&'static str, String)> {
+ let role = self.client_role(client_id);
+ if role == PeerRole::Viewer {
+ return Err(("VIEWER_READONLY", "Viewers have read-only access".to_string()));
+ }
+ if role == PeerRole::Host {
+ return Ok(());
+ }
+ let sender_peer_id = self.client_peer_id(client_id);
+ if let Some(layer) = self
+ .doc
+ .layers
+ .iter()
+ .find(|l| layer_id_of(l) == Some(layer_id))
+ {
+ if let Some(reserved_by) = layer.get("reservedByPeerId").and_then(value_to_peer_id) {
+ if sender_peer_id != Some(reserved_by.as_str()) {
+ let owner_name = layer
+ .get("reservedByPeerName")
+ .and_then(|v| v.as_str())
+ .unwrap_or("its owner");
+ return Err((
+ "LAYER_LOCKED",
+ format!("Layer is locked by {}", owner_name),
+ ));
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn collect_layer_subtree_ids(&self, root_id: &str) -> HashSet<String> {
+ let mut deleted: HashSet<String> = HashSet::new();
+ deleted.insert(root_id.to_string());
+ loop {
+ let mut added_any = false;
+ for l in &self.doc.layers {
+ let Some(lid) = layer_id_of(l) else {
+ continue;
+ };
+ if deleted.contains(lid) {
+ continue;
+ }
+ if let Some(pid) = l.get("parentId").and_then(|v| v.as_str()) {
+ if deleted.contains(pid) {
+ deleted.insert(lid.to_string());
+ added_any = true;
+ }
+ }
+ }
+ if !added_any {
+ break;
+ }
+ }
+ deleted
+ }
+
+ fn can_delete_layer(
+ &self,
+ client_id: usize,
+ layer_id: &str,
+ ) -> Result<(), (&'static str, String)> {
+ let role = self.client_role(client_id);
+ if role == PeerRole::Viewer {
+ return Err(("VIEWER_READONLY", "Viewers cannot delete layers".to_string()));
+ }
+ if role == PeerRole::Host {
+ return Ok(());
+ }
+ let sender_peer_id = self.client_peer_id(client_id);
+ let target_ids = self.collect_layer_subtree_ids(layer_id);
+ for layer in &self.doc.layers {
+ let Some(lid) = layer_id_of(layer) else {
+ continue;
+ };
+ if !target_ids.contains(lid) {
+ continue;
+ }
+ let lname = layer
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Layer");
+ if let Some(reserved_by) = layer.get("reservedByPeerId").and_then(value_to_peer_id) {
+ if sender_peer_id != Some(reserved_by.as_str()) {
+ let lock_name = layer
+ .get("reservedByPeerName")
+ .and_then(|v| v.as_str())
+ .unwrap_or("another user");
+ return Err((
+ "LAYER_LOCKED",
+ format!("Cannot delete \"{}\" — locked by {}", lname, lock_name),
+ ));
+ }
+ }
+ if let Some(owner_id) = layer.get("ownerPeerId").and_then(value_to_peer_id) {
+ if sender_peer_id != Some(owner_id.as_str()) {
+ let owner_name = layer
+ .get("ownerPeerName")
+ .and_then(|v| v.as_str())
+ .unwrap_or("another user");
+ return Err((
+ "NOT_OWNER",
+ format!("Cannot delete \"{}\" — owned by {}", lname, owner_name),
+ ));
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn release_peer_locks(&mut self, target_peer_id: &str) {
+ let mut unlocked_ids: Vec<String> = Vec::new();
+ for layer in &mut self.doc.layers {
+ let matches_lock = layer
+ .get("reservedByPeerId")
+ .and_then(value_to_peer_id)
+ .map_or(false, |id| id == target_peer_id);
+ if matches_lock {
+ layer.remove("reservedByPeerId");
+ layer.remove("reservedByPeerName");
+ if let Some(lid) = layer_id_of(layer) {
+ unlocked_ids.push(lid.to_string());
+ }
+ }
+ }
+ for lid in unlocked_ids {
+ let seq = self.next_seq();
+ let upd = serde_json::json!({
+ "type": "LAYER_UPDATE",
+ "seq": seq,
+ "layerId": lid,
+ "patch": {},
+ "clearedFields": ["reservedByPeerId", "reservedByPeerName"],
+ });
+ let text = Arc::new(upd.to_string());
+ self.push_op_log(seq, None, OpPayload::Text(Arc::clone(&text)));
+ self.broadcast_live(None, Message::Text((*text).clone()));
+ }
+ }
+
+ fn kick_clients_for_peer(&mut self, target_peer_id: &str, code: &str, reason: &str) {
+ let matching_cids: Vec<usize> = self
+ .peers
+ .iter()
+ .filter(|(_, p)| p.id == target_peer_id)
+ .map(|(&cid, _)| cid)
+ .collect();
+ for cid in matching_cids {
+ self.send_access_denied(cid, code, reason, Some(target_peer_id));
+ if let Some(removed) = self.clients.remove(&cid) {
+ removed.kick.notify_one();
+ }
+ self.peers.remove(&cid);
+ }
+ }
+
+ #[inline]
+ fn next_seq(&mut self) -> u64 {
+ self.seq = self.seq.saturating_add(1);
+ self.seq
+ }
+
+ fn push_op_log(&mut self, seq: u64, sender_client_id: Option<usize>, payload: OpPayload) {
+ let size = payload.byte_len();
+ if size > MAX_OP_LOG_BYTES {
+ self.op_log.clear();
+ self.op_log_bytes = 0;
+ self.op_log_floor = seq;
+ return;
+ }
+ while !self.op_log.is_empty()
+ && (self.op_log.len() >= MAX_OP_LOG_ENTRIES
+ || self.op_log_bytes.saturating_add(size) > MAX_OP_LOG_BYTES)
+ {
+ if let Some(evicted) = self.op_log.pop_front() {
+ self.op_log_bytes = self.op_log_bytes.saturating_sub(evicted.payload.byte_len());
+ self.op_log_floor = self.op_log_floor.max(evicted.seq);
+ }
+ }
+ self.op_log_bytes = self.op_log_bytes.saturating_add(size);
+ self.op_log.push_back(OpLogEntry {
+ seq,
+ sender_client_id,
+ payload,
+ });
+ }
+
+ fn broadcast_live(&mut self, sender_id: Option<usize>, msg: Message) {
+ let mut slow_ids: Vec<usize> = Vec::new();
+ for (&id, peer) in self.clients.iter() {
+ if Some(id) == sender_id || !peer.live {
+ continue;
+ }
+ if peer.tx.try_send(msg.clone()).is_err() {
+ slow_ids.push(id);
+ }
+ }
+ for id in slow_ids {
+ if let Some(removed) = self.clients.remove(&id) {
+ removed.kick.notify_one();
+ }
+ }
+ }
+
+ fn prune_layer_tiles(&mut self, layer_id: &str) {
+ let mut freed = 0usize;
+ self.tiles.retain(|k, v| {
+ if k.layer_id == layer_id {
+ freed = freed.saturating_add(v.len());
+ false
+ } else {
+ true
+ }
+ });
+ self.tile_store_bytes = self.tile_store_bytes.saturating_sub(freed);
+ }
+
+ fn prune_layer_masks(&mut self, layer_id: &str) {
+ if let Some(removed) = self.masks.remove(layer_id) {
+ let freed: usize = removed.iter().map(|p| p.len()).sum();
+ self.mask_store_bytes = self.mask_store_bytes.saturating_sub(freed);
+ }
+ }
+
+ fn prune_orphaned_layer_data(&mut self) {
+ let live_ids: HashSet<&str> = self
+ .doc
+ .layers
+ .iter()
+ .filter_map(layer_id_of)
+ .collect();
+ let masked_ids: HashSet<&str> = self
+ .doc
+ .layers
+ .iter()
+ .filter(|l| l.get("hasMask").and_then(|v| v.as_bool()).unwrap_or(false))
+ .filter_map(layer_id_of)
+ .collect();
+
+ let mut freed_tiles = 0usize;
+ self.tiles.retain(|k, v| {
+ if live_ids.contains(k.layer_id.as_str()) {
+ true
+ } else {
+ freed_tiles = freed_tiles.saturating_add(v.len());
+ false
+ }
+ });
+ self.tile_store_bytes = self.tile_store_bytes.saturating_sub(freed_tiles);
+
+ let mut freed_masks = 0usize;
+ self.masks.retain(|lid, packets| {
+ if live_ids.contains(lid.as_str()) && masked_ids.contains(lid.as_str()) {
+ true
+ } else {
+ freed_masks = freed_masks.saturating_add(packets.iter().map(|p| p.len()).sum::<usize>());
+ false
+ }
+ });
+ self.mask_store_bytes = self.mask_store_bytes.saturating_sub(freed_masks);
+ }
+
+ fn apply_doc_sync_response(&mut self, obj: &serde_json::Map<String, serde_json::Value>) -> bool {
+ let Some(layers_val) = obj.get("layers").and_then(|v| v.as_array()) else {
+ return false;
+ };
+ let Some(dims_obj) = obj.get("dimensions").and_then(|v| v.as_object()) else {
+ return false;
+ };
+ let w = dims_obj.get("width").and_then(|v| v.as_f64()).unwrap_or(0.0);
+ let h = dims_obj.get("height").and_then(|v| v.as_f64()).unwrap_or(0.0);
+ if !w.is_finite()
+ || !h.is_finite()
+ || w < 1.0
+ || h < 1.0
+ || w > MAX_SYNC_CANVAS_DIM as f64
+ || h > MAX_SYNC_CANVAS_DIM as f64
+ {
+ return false;
+ }
+
+ let sanitized_layers = sanitize_layer_tree_objects(layers_val);
+ if sanitized_layers.is_empty() {
+ return false;
+ }
+
+ let color_mode = match obj.get("colorMode").and_then(|v| v.as_str()) {
+ Some("grayscale") => "grayscale".to_string(),
+ Some("monochrome") => "monochrome".to_string(),
+ _ => "color".to_string(),
+ };
+
+ self.doc.dimensions = serde_json::Value::Object(dims_obj.clone());
+ self.doc.color_mode = color_mode;
+ self.doc.layers = sanitized_layers;
+ self.doc.perspective_ruler = obj
+ .get("perspectiveRuler")
+ .cloned()
+ .unwrap_or(serde_json::Value::Null);
+ self.doc.straight_ruler = obj
+ .get("straightRuler")
+ .cloned()
+ .unwrap_or(serde_json::Value::Null);
+ self.doc.animation_timeline = obj
+ .get("animationTimeline")
+ .cloned()
+ .unwrap_or(serde_json::Value::Null);
+ self.doc.initialized = true;
+ self.prune_orphaned_layer_data();
+ true
+ }
+
+ fn ensure_guest_layer(&mut self, peer: &PeerRecord, client_id: usize) -> Option<String> {
+ let layer_id = format!("layer-{}-1", peer.id);
+ if self
+ .doc
+ .layers
+ .iter()
+ .any(|l| layer_id_of(l) == Some(layer_id.as_str()))
+ {
+ return Some(layer_id);
+ }
+ if self.doc.layers.len() >= MAX_SYNC_LAYERS {
+ return None;
+ }
+
+ let layer_name = next_collab_layer_name(&peer.name, &self.doc.layers);
+ let mut layer_obj = serde_json::Map::new();
+ layer_obj.insert("id".to_string(), serde_json::Value::String(layer_id.clone()));
+ layer_obj.insert("name".to_string(), serde_json::Value::String(layer_name));
+ layer_obj.insert("type".to_string(), serde_json::Value::String("raster".to_string()));
+ layer_obj.insert("visible".to_string(), serde_json::Value::Bool(true));
+ layer_obj.insert("opacity".to_string(), serde_json::json!(1.0));
+ layer_obj.insert("blendMode".to_string(), serde_json::Value::String("normal".to_string()));
+ layer_obj.insert("locked".to_string(), serde_json::Value::Bool(false));
+ layer_obj.insert("parentId".to_string(), serde_json::Value::Null);
+ layer_obj.insert("ownerPeerId".to_string(), serde_json::Value::String(peer.id.clone()));
+ layer_obj.insert("ownerPeerName".to_string(), serde_json::Value::String(peer.name.clone()));
+
+ self.doc.layers.insert(0, layer_obj.clone());
+
+ let seq = self.next_seq();
+ let layer_add = serde_json::json!({
+ "type": "LAYER_ADD",
+ "seq": seq,
+ "layerId": layer_id,
+ "layerItem": serde_json::Value::Object(layer_obj),
+ "insertIndex": 0,
+ });
+ let text = Arc::new(layer_add.to_string());
+ self.push_op_log(seq, Some(client_id), OpPayload::Text(Arc::clone(&text)));
+ self.broadcast_live(Some(client_id), Message::Text((*text).clone()));
+
+ Some(layer_id)
+ }
+
+ fn build_join_accepted_json(
+ &self,
+ client_id: usize,
+ target_peer_id: &str,
+ assigned_layer_id: Option<&str>,
+ assigned_role: PeerRole,
+ is_reconnect: bool,
+ seq: u64,
+ ) -> String {
+ let other_peers: Vec<serde_json::Value> = self
+ .peers
+ .values()
+ .filter(|p| p.client_id != client_id)
+ .map(|p| serde_json::Value::Object(p.raw.clone()))
+ .collect();
+ let host_id = self.host_peer_id.clone().unwrap_or_default();
+ serde_json::json!({
+ "type": "JOIN_ACCEPTED",
+ "seq": seq,
+ "serverSeq": seq,
+ "targetPeerId": target_peer_id,
+ "roomName": self.room_name,
+ "peers": other_peers,
+ "hostId": host_id,
+ "docDimensions": self.doc.dimensions,
+ "colorMode": self.doc.color_mode,
+ "assignedLayerId": assigned_layer_id,
+ "assignedRole": assigned_role.as_str(),
+ "isReconnect": is_reconnect,
+ })
+ .to_string()
+ }
+
+ fn build_full_sync_plan(
+ &mut self,
+ client_id: usize,
+ target_peer_id: &str,
+ assigned_layer_id: Option<String>,
+ include_join_accepted: bool,
+ is_reconnect: bool,
+ ) -> SyncPlan {
+ if let Some(c) = self.clients.get_mut(&client_id) {
+ c.live = false;
+ c.sync_in_progress = true;
+ }
+
+ let snapshot_seq = self.seq;
+ let assigned_role = self.client_role(client_id);
+ let join_accepted = if include_join_accepted {
+ Some(self.build_join_accepted_json(
+ client_id,
+ target_peer_id,
+ assigned_layer_id.as_deref(),
+ assigned_role,
+ is_reconnect,
+ snapshot_seq,
+ ))
+ } else {
+ None
+ };
+
+ let layers_json: Vec<serde_json::Value> = self
+ .doc
+ .layers
+ .iter()
+ .cloned()
+ .map(serde_json::Value::Object)
+ .collect();
+ let doc_sync_response = serde_json::json!({
+ "type": "DOC_SYNC_RESPONSE",
+ "seq": snapshot_seq,
+ "targetPeerId": target_peer_id,
+ "roomName": self.room_name,
+ "assignedLayerId": assigned_layer_id,
+ "dimensions": self.doc.dimensions,
+ "colorMode": self.doc.color_mode,
+ "layers": layers_json,
+ "perspectiveRuler": self.doc.perspective_ruler,
+ "straightRuler": self.doc.straight_ruler,
+ "animationTimeline": self.doc.animation_timeline,
+ })
+ .to_string();
+
+ let mut tile_entries: Vec<(&TileKey, &Arc<Vec<u8>>)> = self.tiles.iter().collect();
+ tile_entries.sort_by(|(ka, _), (kb, _)| ka.cmp(kb));
+ let tiles: Vec<Arc<Vec<u8>>> = tile_entries
+ .into_iter()
+ .map(|(_, v)| Arc::clone(v))
+ .collect();
+
+ let mut mask_entries: Vec<(&String, &Vec<Arc<Vec<u8>>>)> = self.masks.iter().collect();
+ mask_entries.sort_by(|(ka, _), (kb, _)| ka.cmp(kb));
+ let mut masks = Vec::new();
+ for (_, pkts) in mask_entries {
+ for pkt in pkts {
+ masks.push(Arc::clone(pkt));
+ }
+ }
+
+ SyncPlan::Full(SnapshotSyncPlan {
+ snapshot_seq,
+ join_accepted,
+ doc_sync_response,
+ tiles,
+ masks,
+ })
+ }
+
+ fn apply_layer_add(&mut self, obj: &serde_json::Map<String, serde_json::Value>) {
+ if self.doc.layers.len() >= MAX_SYNC_LAYERS {
+ return;
+ }
+ let Some(item_obj) = obj.get("layerItem").and_then(|v| v.as_object()) else {
+ return;
+ };
+ let Some(clean) = sanitize_layer_object(item_obj) else {
+ return;
+ };
+ let Some(new_id) = layer_id_of(&clean) else {
+ return;
+ };
+ if self.doc.layers.iter().any(|l| layer_id_of(l) == Some(new_id)) {
+ return;
+ }
+
+ if let Some(idx) = obj.get("insertIndex").and_then(|v| v.as_u64()) {
+ let pos = (idx as usize).min(self.doc.layers.len());
+ self.doc.layers.insert(pos, clean);
+ } else if let Some(bg_idx) = self
+ .doc
+ .layers
+ .iter()
+ .position(|l| layer_id_of(l).map_or(false, is_background_layer_id))
+ {
+ self.doc.layers.insert(bg_idx, clean);
+ } else {
+ self.doc.layers.push(clean);
+ }
+ }
+
+ fn apply_layer_delete(&mut self, obj: &serde_json::Map<String, serde_json::Value>) {
+ let Some(target_id) = obj.get("layerId").and_then(|v| v.as_str()) else {
+ return;
+ };
+ if target_id.is_empty() || target_id.len() > 256 {
+ return;
+ }
+
+ // Collect target + all transitive children (matching computeBatchDeleteLayers)
+ let mut deleted: HashSet<String> = HashSet::new();
+ deleted.insert(target_id.to_string());
+ loop {
+ let mut added_any = false;
+ for l in &self.doc.layers {
+ let Some(lid) = layer_id_of(l) else {
+ continue;
+ };
+ if deleted.contains(lid) {
+ continue;
+ }
+ if let Some(pid) = l.get("parentId").and_then(|v| v.as_str()) {
+ if deleted.contains(pid) {
+ deleted.insert(lid.to_string());
+ added_any = true;
+ }
+ }
+ }
+ if !added_any {
+ break;
+ }
+ }
+
+ self.doc
+ .layers
+ .retain(|l| layer_id_of(l).map_or(true, |id| !deleted.contains(id)));
+ for del_id in &deleted {
+ self.prune_layer_tiles(del_id);
+ self.prune_layer_masks(del_id);
+ }
+ }
+
+ fn apply_layer_clear(&mut self, obj: &serde_json::Map<String, serde_json::Value>) {
+ let Some(layer_id) = obj.get("layerId").and_then(|v| v.as_str()) else {
+ return;
+ };
+ if layer_id.is_empty() || layer_id.len() > 256 {
+ return;
+ }
+ if let Some(layer) = self
+ .doc
+ .layers
+ .iter_mut()
+ .find(|l| layer_id_of(l) == Some(layer_id))
+ {
+ if layer.get("type").and_then(|v| v.as_str()) == Some("vector") {
+ layer.insert("vectorStrokes".to_string(), serde_json::Value::Array(Vec::new()));
+ }
+ }
+ if !is_background_layer_id(layer_id) {
+ self.prune_layer_tiles(layer_id);
+ }
+ }
+
+ fn apply_layer_update(&mut self, obj: &serde_json::Map<String, serde_json::Value>) {
+ let Some(layer_id) = obj.get("layerId").and_then(|v| v.as_str()) else {
+ return;
+ };
+ let mut mask_removed = false;
+ if let Some(layer) = self
+ .doc
+ .layers
+ .iter_mut()
+ .find(|l| layer_id_of(l) == Some(layer_id))
+ {
+ if let Some(patch) = obj.get("patch").and_then(|v| v.as_object()) {
+ for (k, v) in patch {
+ if is_forbidden_json_key(k) || k == "id" {
+ continue;
+ }
+ if k == "hasMask" && v.as_bool() == Some(false) {
+ mask_removed = true;
+ }
+ layer.insert(k.clone(), v.clone());
+ }
+ }
+ if let Some(cleared) = obj.get("clearedFields").and_then(|v| v.as_array()) {
+ for field in cleared.iter().take(64) {
+ if let Some(fname) = field.as_str() {
+ if fname == "id" || is_forbidden_json_key(fname) {
+ continue;
+ }
+ if fname == "hasMask" {
+ mask_removed = true;
+ }
+ layer.remove(fname);
+ }
+ }
+ }
+ }
+ if mask_removed {
+ self.prune_layer_masks(layer_id);
+ }
+ }
+
+ fn handle_text_object(
+ &mut self,
+ client_id: usize,
+ mut obj: serde_json::Map<String, serde_json::Value>,
+ ) -> HandleTextOutcome {
+ let Some(msg_type) = obj
+ .get("type")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string())
+ else {
+ return HandleTextOutcome::None;
+ };
+
+ match msg_type.as_str() {
+ "JOIN_REQUEST" => {
+ let Some(mut peer) = parse_peer_from_join(&obj, client_id) else {
+ return HandleTextOutcome::None;
+ };
+
+ // Reject banned peerIds immediately before registering or leaking room state
+ if self.banned_peer_ids.contains(&peer.id) {
+ self.send_access_denied(
+ client_id,
+ "BANNED",
+ "You are banned from this room",
+ Some(&peer.id),
+ );
+ if let Some(removed) = self.clients.remove(&client_id) {
+ removed.kick.notify_one();
+ }
+ return HandleTextOutcome::None;
+ }
+
+ // Prevent host-claim hijacking while the real host is briefly disconnected
+ let is_host_claim = peer.is_host
+ && (self.host_peer_id.is_none()
+ || self.host_peer_id.as_deref() == Some(peer.id.as_str()))
+ && (self.host_client_id.is_none() || self.host_client_id == Some(client_id));
+
+ let assigned_role = if is_host_claim {
+ PeerRole::Host
+ } else {
+ match self.peer_roles.get(&peer.id).copied() {
+ Some(PeerRole::Viewer) => PeerRole::Viewer,
+ _ => {
+ self.peer_roles.insert(peer.id.clone(), PeerRole::Editor);
+ PeerRole::Editor
+ }
+ }
+ };
+
+ peer.is_host = is_host_claim;
+ peer.role = assigned_role;
+ peer.raw
+ .insert("isHost".to_string(), serde_json::Value::Bool(is_host_claim));
+ peer.raw.insert(
+ "role".to_string(),
+ serde_json::Value::String(assigned_role.as_str().to_string()),
+ );
+
+ if is_host_claim {
+ self.host_client_id = Some(client_id);
+ self.host_peer_id = Some(peer.id.clone());
+ }
+ self.peers.insert(client_id, peer.clone());
+
+ let is_reconnect = obj
+ .get("isReconnect")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ let since_seq = obj.get("sinceSeq").and_then(|v| v.as_u64());
+
+ if is_host_claim {
+ if is_reconnect && self.doc.initialized {
+ if let Some(s) = since_seq {
+ if s >= self.op_log_floor && s <= self.seq {
+ if let Some(c) = self.clients.get_mut(&client_id) {
+ c.live = false;
+ c.sync_in_progress = true;
+ }
+ return HandleTextOutcome::StartSync {
+ peer_id: Some(peer.id),
+ plan: SyncPlan::Incremental {
+ join_accepted: None,
+ since_seq: s,
+ },
+ };
+ }
+ if s < self.op_log_floor {
+ let plan = self.build_full_sync_plan(
+ client_id,
+ &peer.id,
+ None,
+ false,
+ true,
+ );
+ return HandleTextOutcome::StartSync {
+ peer_id: Some(peer.id),
+ plan,
+ };
+ }
+ }
+ }
+ return HandleTextOutcome::PeerRegistered(peer.id);
+ }
+
+ if self.doc.initialized {
+ let already_syncing = self
+ .clients
+ .get(&client_id)
+ .map_or(true, |c| c.sync_in_progress);
+ if already_syncing {
+ return HandleTextOutcome::PeerRegistered(peer.id);
+ }
+
+ let assigned_layer_id = if assigned_role == PeerRole::Viewer {
+ None
+ } else {
+ self.ensure_guest_layer(&peer, client_id)
+ };
+
+ let join_seq = self.next_seq();
+ let peer_joined = serde_json::json!({
+ "type": "PEER_JOINED",
+ "seq": join_seq,
+ "peer": serde_json::Value::Object(peer.raw.clone()),
+ });
+ let pj_text = Arc::new(peer_joined.to_string());
+ self.push_op_log(
+ join_seq,
+ Some(client_id),
+ OpPayload::Text(Arc::clone(&pj_text)),
+ );
+ self.broadcast_live(Some(client_id), Message::Text((*pj_text).clone()));
+
+ // Incremental catch-up by seq on reconnect when op_log still covers since_seq
+ if is_reconnect {
+ if let Some(s) = since_seq {
+ if s >= self.op_log_floor && s <= self.seq {
+ let join_acc = self.build_join_accepted_json(
+ client_id,
+ &peer.id,
+ assigned_layer_id.as_deref(),
+ assigned_role,
+ true,
+ self.seq,
+ );
+ if let Some(c) = self.clients.get_mut(&client_id) {
+ c.live = false;
+ c.sync_in_progress = true;
+ }
+ return HandleTextOutcome::StartSync {
+ peer_id: Some(peer.id),
+ plan: SyncPlan::Incremental {
+ join_accepted: Some(join_acc),
+ since_seq: s,
+ },
+ };
+ }
+ }
+ }
+
+ let plan = self.build_full_sync_plan(
+ client_id,
+ &peer.id,
+ assigned_layer_id,
+ true,
+ is_reconnect,
+ );
+ return HandleTextOutcome::StartSync {
+ peer_id: Some(peer.id),
+ plan,
+ };
+ }
+
+ // Fallback when host has not yet seeded the server snapshot
+ let seq = self.next_seq();
+ obj.insert("seq".to_string(), serde_json::Value::from(seq));
+ let text = serde_json::Value::Object(obj).to_string();
+ self.broadcast_live(Some(client_id), Message::Text(text));
+ HandleTextOutcome::PeerRegistered(peer.id)
+ }
+
+ "DOC_SYNC_REQUEST" => {
+ if self.doc.initialized {
+ let already_syncing = self
+ .clients
+ .get(&client_id)
+ .map_or(true, |c| c.sync_in_progress);
+ if already_syncing {
+ return HandleTextOutcome::None;
+ }
+
+ if let Some(since_seq) = obj.get("sinceSeq").and_then(|v| v.as_u64()) {
+ if since_seq >= self.op_log_floor && since_seq <= self.seq {
+ if let Some(c) = self.clients.get_mut(&client_id) {
+ c.live = false;
+ c.sync_in_progress = true;
+ }
+ return HandleTextOutcome::StartSync {
+ peer_id: None,
+ plan: SyncPlan::Incremental {
+ join_accepted: None,
+ since_seq,
+ },
+ };
+ }
+ }
+
+ let target_peer_id = obj
+ .get("targetPeerId")
+ .and_then(value_to_peer_id)
+ .or_else(|| self.peers.get(&client_id).map(|p| p.id.clone()))
+ .unwrap_or_default();
+ let plan = self.build_full_sync_plan(
+ client_id,
+ &target_peer_id,
+ None,
+ false,
+ false,
+ );
+ return HandleTextOutcome::StartSync {
+ peer_id: None,
+ plan,
+ };
+ }
+
+ // Fallback relay when server snapshot is not initialized
+ let seq = self.next_seq();
+ obj.insert("seq".to_string(), serde_json::Value::from(seq));
+ let text = serde_json::Value::Object(obj).to_string();
+ self.broadcast_live(Some(client_id), Message::Text(text));
+ HandleTextOutcome::None
+ }
+
+ "PEER_ROLE_UPDATE" => {
+ if !self.is_host_client(client_id) {
+ self.send_access_denied(
+ client_id,
+ "FORBIDDEN",
+ "Only the Host can change participant roles",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ let Some(target_peer_id) = obj.get("targetPeerId").and_then(value_to_peer_id)
+ else {
+ return HandleTextOutcome::None;
+ };
+ if self.host_peer_id.as_deref() == Some(target_peer_id.as_str()) {
+ return HandleTextOutcome::None;
+ }
+ let Some(role_str) = obj.get("role").and_then(|v| v.as_str()) else {
+ return HandleTextOutcome::None;
+ };
+ let Some(next_role) = PeerRole::from_guest_str(role_str) else {
+ return HandleTextOutcome::None;
+ };
+ self.peer_roles.insert(target_peer_id.clone(), next_role);
+ for peer in self.peers.values_mut() {
+ if peer.id == target_peer_id {
+ peer.role = next_role;
+ peer.raw.insert(
+ "role".to_string(),
+ serde_json::Value::String(next_role.as_str().to_string()),
+ );
+ }
+ }
+ obj.insert(
+ "role".to_string(),
+ serde_json::Value::String(next_role.as_str().to_string()),
+ );
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "PEER_KICK" => {
+ if !self.is_host_client(client_id) {
+ self.send_access_denied(
+ client_id,
+ "FORBIDDEN",
+ "Only the Host can kick participants",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ let Some(target_peer_id) = obj.get("targetPeerId").and_then(value_to_peer_id)
+ else {
+ return HandleTextOutcome::None;
+ };
+ if self.host_peer_id.as_deref() == Some(target_peer_id.as_str()) {
+ return HandleTextOutcome::None;
+ }
+ let reason = obj
+ .get("reason")
+ .and_then(|v| v.as_str())
+ .map(|s| s.trim().chars().take(256).collect::<String>())
+ .filter(|s| !s.is_empty())
+ .unwrap_or_else(|| "You were kicked by the host".to_string());
+
+ self.release_peer_locks(&target_peer_id);
+ self.kick_clients_for_peer(&target_peer_id, "KICKED", &reason);
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "PEER_BAN" => {
+ if !self.is_host_client(client_id) {
+ self.send_access_denied(
+ client_id,
+ "FORBIDDEN",
+ "Only the Host can ban participants",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ let Some(target_peer_id) = obj.get("targetPeerId").and_then(value_to_peer_id)
+ else {
+ return HandleTextOutcome::None;
+ };
+ if self.host_peer_id.as_deref() == Some(target_peer_id.as_str()) {
+ return HandleTextOutcome::None;
+ }
+ let reason = obj
+ .get("reason")
+ .and_then(|v| v.as_str())
+ .map(|s| s.trim().chars().take(256).collect::<String>())
+ .filter(|s| !s.is_empty())
+ .unwrap_or_else(|| "You have been banned from this room".to_string());
+
+ self.banned_peer_ids.insert(target_peer_id.clone());
+ self.release_peer_locks(&target_peer_id);
+ self.kick_clients_for_peer(&target_peer_id, "BANNED", &reason);
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "PEER_UNBAN" => {
+ if !self.is_host_client(client_id) {
+ self.send_access_denied(
+ client_id,
+ "FORBIDDEN",
+ "Only the Host can unban participants",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ if let Some(target_peer_id) = obj.get("targetPeerId").and_then(value_to_peer_id) {
+ self.banned_peer_ids.remove(&target_peer_id);
+ self.commit_and_broadcast_text(client_id, obj, false);
+ }
+ HandleTextOutcome::None
+ }
+
+ "DOC_SYNC_RESPONSE" => {
+ if let Err((code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, code, reason, None);
+ return HandleTextOutcome::None;
+ }
+ let can_seed = !self.doc.initialized || self.host_client_id == Some(client_id);
+ let seeded = if can_seed {
+ self.apply_doc_sync_response(&obj)
+ } else {
+ false
+ };
+
+ let target = obj
+ .get("targetPeerId")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if target.is_empty() || target == "__server__" {
+ if seeded {
+ let seq = self.next_seq();
+ // Snapshot replaces prior baseline; clients behind `seq` need full sync
+ self.op_log.clear();
+ self.op_log_bytes = 0;
+ self.op_log_floor = seq;
+ }
+ return HandleTextOutcome::None;
+ }
+
+ // Only host (or initial unseeded responder) may broadcast DOC_SYNC_RESPONSE
+ if !can_seed {
+ return HandleTextOutcome::None;
+ }
+
+ let seq = self.next_seq();
+ if seeded {
+ self.op_log_floor = self.op_log_floor.max(seq);
+ }
+ obj.insert("seq".to_string(), serde_json::Value::from(seq));
+ let text = serde_json::Value::Object(obj).to_string();
+ self.broadcast_live(Some(client_id), Message::Text(text));
+ HandleTextOutcome::None
+ }
+
+ "LAYER_ADD" => {
+ if let Err((code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, code, reason, None);
+ return HandleTextOutcome::None;
+ }
+ // Stamp authoritative ownerPeerId for non-host editors so ownership cannot be spoofed
+ if !self.is_host_client(client_id) {
+ if let Some(peer) = self.peers.get(&client_id).cloned() {
+ if let Some(item) = obj.get_mut("layerItem").and_then(|v| v.as_object_mut())
+ {
+ item.insert(
+ "ownerPeerId".to_string(),
+ serde_json::Value::String(peer.id),
+ );
+ item.insert(
+ "ownerPeerName".to_string(),
+ serde_json::Value::String(peer.name),
+ );
+ }
+ }
+ }
+ self.apply_layer_add(&obj);
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
-// Pinned official Cloudflare release for explicit verified installation.
-pub const PINNED_CLOUDFLARED_VERSION: &str = "2026.11.1";
-pub const PINNED_CLOUDFLARED_URL: &str =
- "https://github.com/cloudflare/cloudflared/releases/download/2026.11.1/cloudflared-windows-amd64.exe";
-pub const PINNED_CLOUDFLARED_SHA256: &str =
- "341deda3db5ec498a0482254d6c38c0b7cf01a30c37bb5dd95d2216d08955e35";
-const MAX_CLOUDFLARED_BYTES: u64 = 100 * 1024 * 1024; // 100 MB ceiling
+ "LAYER_DELETE" => {
+ if let Some(layer_id) = obj.get("layerId").and_then(|v| v.as_str()) {
+ if let Err((code, reason)) = self.can_delete_layer(client_id, layer_id) {
+ self.send_access_denied(client_id, code, &reason, None);
+ return HandleTextOutcome::None;
+ }
+ } else {
+ return HandleTextOutcome::None;
+ }
+ self.apply_layer_delete(&obj);
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
-static NEXT_CLIENT_ID: AtomicUsize = AtomicUsize::new(1);
+ "LAYER_CLEAR" => {
+ if let Some(layer_id) = obj.get("layerId").and_then(|v| v.as_str()) {
+ if let Err((code, reason)) = self.can_modify_layer(client_id, layer_id) {
+ self.send_access_denied(client_id, code, &reason, None);
+ return HandleTextOutcome::None;
+ }
+ } else {
+ return HandleTextOutcome::None;
+ }
+ self.apply_layer_clear(&obj);
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
-#[derive(Clone)]
-struct ClientHandle {
- tx: mpsc::Sender<Message>,
- kick: Arc<Notify>,
+ "LAYER_RENAME" => {
+ let Some(layer_id) = obj.get("layerId").and_then(|v| v.as_str()).map(|s| s.to_string()) else {
+ return HandleTextOutcome::None;
+ };
+ if let Err((code, reason)) = self.can_modify_layer(client_id, &layer_id) {
+ self.send_access_denied(client_id, code, &reason, None);
+ return HandleTextOutcome::None;
+ }
+ if let Some(new_name) = obj.get("newName").and_then(|v| v.as_str()) {
+ let safe_name: String = new_name.chars().take(256).collect();
+ if let Some(layer) = self
+ .doc
+ .layers
+ .iter_mut()
+ .find(|l| layer_id_of(l) == Some(layer_id.as_str()))
+ {
+ layer.insert("name".to_string(), serde_json::Value::String(safe_name));
+ }
+ }
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "LAYER_VISIBILITY" => {
+ let Some(layer_id) = obj.get("layerId").and_then(|v| v.as_str()).map(|s| s.to_string()) else {
+ return HandleTextOutcome::None;
+ };
+ if let Err((code, reason)) = self.can_modify_layer(client_id, &layer_id) {
+ self.send_access_denied(client_id, code, &reason, None);
+ return HandleTextOutcome::None;
+ }
+ if let Some(visible) = obj.get("visible").and_then(|v| v.as_bool()) {
+ if let Some(layer) = self
+ .doc
+ .layers
+ .iter_mut()
+ .find(|l| layer_id_of(l) == Some(layer_id.as_str()))
+ {
+ layer.insert("visible".to_string(), serde_json::Value::Bool(visible));
+ }
+ }
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "LAYER_OPACITY" => {
+ let Some(layer_id) = obj.get("layerId").and_then(|v| v.as_str()).map(|s| s.to_string()) else {
+ return HandleTextOutcome::None;
+ };
+ if let Err((code, reason)) = self.can_modify_layer(client_id, &layer_id) {
+ self.send_access_denied(client_id, code, &reason, None);
+ return HandleTextOutcome::None;
+ }
+ if let Some(opacity) = obj.get("opacity").and_then(|v| v.as_f64()) {
+ if opacity.is_finite() {
+ let clamped = opacity.clamp(0.0, 1.0);
+ if let Some(layer) = self
+ .doc
+ .layers
+ .iter_mut()
+ .find(|l| layer_id_of(l) == Some(layer_id.as_str()))
+ {
+ layer.insert("opacity".to_string(), serde_json::json!(clamped));
+ }
+ }
+ }
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "LAYER_UPDATE" => {
+ let Some(layer_id) = obj.get("layerId").and_then(|v| v.as_str()).map(|s| s.to_string()) else {
+ return HandleTextOutcome::None;
+ };
+ if let Err((code, reason)) = self.can_modify_layer(client_id, &layer_id) {
+ self.send_access_denied(client_id, code, &reason, None);
+ return HandleTextOutcome::None;
+ }
+ if !self.is_host_client(client_id) {
+ let sender_peer_id = self.client_peer_id(client_id).map(|s| s.to_string());
+ let existing = self
+ .doc
+ .layers
+ .iter()
+ .find(|l| layer_id_of(l) == Some(layer_id.as_str()));
+ if let Some(layer) = existing {
+ let existing_owner = layer.get("ownerPeerId").and_then(value_to_peer_id);
+ let patch = obj.get("patch").and_then(|v| v.as_object());
+ let cleared = obj.get("clearedFields").and_then(|v| v.as_array());
+ let clears_field = |name: &str| {
+ cleared.map_or(false, |arr| {
+ arr.iter().any(|v| v.as_str() == Some(name))
+ })
+ };
+ // Non-host cannot reassign or strip another user's ownership
+ let touches_owner = patch.map_or(false, |p| p.contains_key("ownerPeerId"))
+ || clears_field("ownerPeerId");
+ if touches_owner
+ && existing_owner.is_some()
+ && existing_owner.as_deref() != sender_peer_id.as_deref()
+ {
+ self.send_access_denied(
+ client_id,
+ "NOT_OWNER",
+ "Cannot modify ownership of another user's layer",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ // Non-host can only lock a layer they own (or unowned) and only under their own peerId
+ if let Some(new_lock) = patch
+ .and_then(|p| p.get("reservedByPeerId"))
+ .and_then(value_to_peer_id)
+ {
+ if sender_peer_id.as_deref() != Some(new_lock.as_str()) {
+ self.send_access_denied(
+ client_id,
+ "FORBIDDEN",
+ "Cannot lock layer under another peer ID",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ if existing_owner.is_some()
+ && existing_owner.as_deref() != sender_peer_id.as_deref()
+ {
+ self.send_access_denied(
+ client_id,
+ "NOT_OWNER",
+ "Only the layer owner or Host can lock this layer",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ }
+ }
+ }
+ self.apply_layer_update(&obj);
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "LAYER_TREE_SYNC" => {
+ if let Err((code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, code, reason, None);
+ return HandleTextOutcome::None;
+ }
+ if let Some(layers_arr) = obj.get("layers").and_then(|v| v.as_array()) {
+ let sanitized = sanitize_layer_tree_objects(layers_arr);
+ if !sanitized.is_empty() {
+ if !self.is_host_client(client_id) {
+ let sender_peer_id = self.client_peer_id(client_id);
+ let incoming_by_id: HashMap<&str, &serde_json::Map<String, serde_json::Value>> =
+ sanitized
+ .iter()
+ .filter_map(|l| layer_id_of(l).map(|id| (id, l)))
+ .collect();
+ for existing in &self.doc.layers {
+ let Some(eid) = layer_id_of(existing) else {
+ continue;
+ };
+ let existing_lock =
+ existing.get("reservedByPeerId").and_then(value_to_peer_id);
+ let existing_owner =
+ existing.get("ownerPeerId").and_then(value_to_peer_id);
+ match incoming_by_id.get(eid) {
+ None => {
+ if existing_lock.is_some()
+ && existing_lock.as_deref() != sender_peer_id
+ {
+ self.send_access_denied(
+ client_id,
+ "LAYER_LOCKED",
+ "Cannot delete a layer locked by another user",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ if existing_owner.is_some()
+ && existing_owner.as_deref() != sender_peer_id
+ {
+ self.send_access_denied(
+ client_id,
+ "NOT_OWNER",
+ "Cannot delete another user's layer",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ }
+ Some(next_layer) => {
+ if existing_lock.is_some()
+ && existing_lock.as_deref() != sender_peer_id
+ {
+ let next_lock = next_layer
+ .get("reservedByPeerId")
+ .and_then(value_to_peer_id);
+ if next_lock != existing_lock {
+ self.send_access_denied(
+ client_id,
+ "LAYER_LOCKED",
+ "Cannot unlock another user's layer",
+ None,
+ );
+ return HandleTextOutcome::None;
+ }
+ }
+ }
+ }
+ }
+ }
+ self.doc.layers = sanitized;
+ self.prune_orphaned_layer_data();
+ }
+ }
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "PERSPECTIVE_RULER_SYNC" => {
+ if let Err((code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, code, reason, None);
+ return HandleTextOutcome::None;
+ }
+ if let Some(ruler) = obj.get("perspectiveRuler") {
+ self.doc.perspective_ruler = ruler.clone();
+ }
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "STRAIGHT_RULER_SYNC" => {
+ if let Err((code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, code, reason, None);
+ return HandleTextOutcome::None;
+ }
+ if let Some(ruler) = obj.get("straightRuler") {
+ self.doc.straight_ruler = ruler.clone();
+ }
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "ANIMATION_SYNC" => {
+ if let Err((code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, code, reason, None);
+ return HandleTextOutcome::None;
+ }
+ if let Some(tl) = obj.get("animationTimeline") {
+ self.doc.animation_timeline = tl.clone();
+ }
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "CANVAS_RESIZE" => {
+ if let Err((code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, code, reason, None);
+ return HandleTextOutcome::None;
+ }
+ if let Some(dims) = obj.get("dimensions").and_then(|v| v.as_object()) {
+ let w = dims.get("width").and_then(|v| v.as_f64()).unwrap_or(0.0);
+ let h = dims.get("height").and_then(|v| v.as_f64()).unwrap_or(0.0);
+ if w.is_finite()
+ && h.is_finite()
+ && w >= 1.0
+ && h >= 1.0
+ && w <= MAX_SYNC_CANVAS_DIM as f64
+ && h <= MAX_SYNC_CANVAS_DIM as f64
+ {
+ self.doc.dimensions = serde_json::Value::Object(dims.clone());
+ }
+ }
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ "PEER_LEFT" => {
+ self.peers.remove(&client_id);
+ if self.host_client_id == Some(client_id) {
+ self.host_client_id = None;
+ }
+ self.commit_and_broadcast_text(client_id, obj, true);
+ HandleTextOutcome::None
+ }
+
+ // Ephemeral messages: monotonic seq stamped, broadcast immediately, not logged
+ "CURSOR_MOVE" | "CANVAS_PING" => {
+ self.commit_and_broadcast_text(client_id, obj, false);
+ HandleTextOutcome::None
+ }
+
+ // Any other valid JSON protocol message (e.g. JOIN_ACCEPTED, PEER_JOINED fallback)
+ _ => {
+ self.commit_and_broadcast_text(client_id, obj, false);
+ HandleTextOutcome::None
+ }
+ }
+ }
+
+ fn commit_and_broadcast_text(
+ &mut self,
+ client_id: usize,
+ mut obj: serde_json::Map<String, serde_json::Value>,
+ record_in_log: bool,
+ ) {
+ let seq = self.next_seq();
+ obj.insert("seq".to_string(), serde_json::Value::from(seq));
+ let text = Arc::new(serde_json::Value::Object(obj).to_string());
+ if record_in_log {
+ self.push_op_log(seq, Some(client_id), OpPayload::Text(Arc::clone(&text)));
+ }
+ self.broadcast_live(Some(client_id), Message::Text((*text).clone()));
+ }
+
+ fn handle_binary_frame(&mut self, client_id: usize, mut bin: Vec<u8>) {
+ if bin.len() < BINARY_HEADER_BYTES || bin.len() > MAX_WS_MESSAGE_BYTES {
+ return;
+ }
+ if bin[0] != BINARY_MAGIC_0 || bin[1] != BINARY_MAGIC_1 {
+ return;
+ }
+ let code = bin[2];
+ if !(CODE_STROKE_START..=CODE_LAYER_MASK_DATA).contains(&code) {
+ return;
+ }
+ let payload_len = u32::from_le_bytes([bin[7], bin[8], bin[9], bin[10]]) as usize;
+ if BINARY_HEADER_BYTES.saturating_add(payload_len) != bin.len() {
+ return;
+ }
+
+ // Validate structured binary payloads BEFORE allocating seq or mutating state
+ enum ParsedBinary {
+ Tile {
+ key: TileKey,
+ is_empty: bool,
+ },
+ Mask {
+ layer_id: String,
+ is_full_replace: bool,
+ },
+ StrokeFinish,
+ SelectiveUndo,
+ LoggedOther,
+ Ephemeral,
+ }
+
+ let parsed = match code {
+ CODE_TILE_DELTA => {
+ let Some((key, _version, is_empty)) =
+ parse_tile_delta_header(&bin[BINARY_HEADER_BYTES..])
+ else {
+ return;
+ };
+ if let Err((denial_code, reason)) = self.can_modify_layer(client_id, &key.layer_id)
+ {
+ self.send_access_denied(client_id, denial_code, &reason, None);
+ return;
+ }
+ ParsedBinary::Tile { key, is_empty }
+ }
+ CODE_LAYER_MASK_DATA => {
+ let Some((layer_id, is_full_replace)) =
+ parse_mask_data_header(&bin[BINARY_HEADER_BYTES..])
+ else {
+ return;
+ };
+ if let Err((denial_code, reason)) = self.can_modify_layer(client_id, &layer_id) {
+ self.send_access_denied(client_id, denial_code, &reason, None);
+ return;
+ }
+ ParsedBinary::Mask {
+ layer_id,
+ is_full_replace,
+ }
+ }
+ CODE_STROKE_FINISH => {
+ if let Err((denial_code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, denial_code, reason, None);
+ return;
+ }
+ if let Ok(val) = serde_json::from_slice::<serde_json::Value>(&bin[BINARY_HEADER_BYTES..]) {
+ if let Some(lid) = val.get("layerId").and_then(|v| v.as_str()) {
+ if let Err((denial_code, reason)) = self.can_modify_layer(client_id, lid) {
+ self.send_access_denied(client_id, denial_code, &reason, None);
+ return;
+ }
+ }
+ }
+ ParsedBinary::StrokeFinish
+ }
+ CODE_SELECTIVE_UNDO => {
+ if let Err((denial_code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, denial_code, reason, None);
+ return;
+ }
+ ParsedBinary::SelectiveUndo
+ }
+ CODE_STROKE_START => {
+ if let Err((denial_code, reason)) = self.can_mutate_canvas(client_id) {
+ self.send_access_denied(client_id, denial_code, reason, None);
+ return;
+ }
+ if let Ok(val) = serde_json::from_slice::<serde_json::Value>(&bin[BINARY_HEADER_BYTES..]) {
+ if let Some(lid) = val.get("layerId").and_then(|v| v.as_str()) {
+ if let Err((denial_code, reason)) = self.can_modify_layer(client_id, lid) {
+ self.send_access_denied(client_id, denial_code, &reason, None);
+ return;
+ }
+ }
+ }
+ ParsedBinary::LoggedOther
+ }
+ CODE_STROKE_CHUNK => {
+ if self.can_mutate_canvas(client_id).is_err() {
+ return;
+ }
+ ParsedBinary::Ephemeral
+ }
+ CODE_BRUSH_ASSET_DATA => {
+ if self.can_mutate_canvas(client_id).is_err() {
+ return;
+ }
+ ParsedBinary::LoggedOther
+ }
+ CODE_CURSOR_MOVE | CODE_BRUSH_ASSET_REQUEST => ParsedBinary::Ephemeral,
+ _ => return,
+ };
+
+ // Stamp authoritative server monotonic seq into bytes [3..7]
+ let seq = self.next_seq();
+ bin[3..7].copy_from_slice(&(seq as u32).to_le_bytes());
+ let pkt = Arc::new(bin);
+
+ let record_in_log = match parsed {
+ ParsedBinary::Tile { key, is_empty } => {
+ if is_empty {
+ if let Some(old) = self.tiles.remove(&key) {
+ self.tile_store_bytes = self.tile_store_bytes.saturating_sub(old.len());
+ }
+ } else {
+ let pkt_len = pkt.len();
+ let old_len = self.tiles.get(&key).map_or(0, |t| t.len());
+ let next_bytes = self
+ .tile_store_bytes
+ .saturating_sub(old_len)
+ .saturating_add(pkt_len);
+ let within_count =
+ self.tiles.contains_key(&key) || self.tiles.len() < MAX_STORED_TILES;
+ if within_count && next_bytes <= MAX_TILE_STORE_BYTES {
+ self.tile_store_bytes = next_bytes;
+ self.tiles.insert(key, Arc::clone(&pkt));
+ }
+ }
+ true
+ }
+ ParsedBinary::Mask {
+ layer_id,
+ is_full_replace,
+ } => {
+ let pkt_len = pkt.len();
+ if is_full_replace {
+ self.prune_layer_masks(&layer_id);
+ if self.mask_store_bytes.saturating_add(pkt_len) <= MAX_MASK_STORE_BYTES {
+ self.mask_store_bytes = self.mask_store_bytes.saturating_add(pkt_len);
+ self.masks.insert(layer_id, vec![Arc::clone(&pkt)]);
+ }
+ } else {
+ let entry = self.masks.entry(layer_id).or_default();
+ if entry.len() < MAX_MASK_PACKETS_PER_LAYER
+ && self.mask_store_bytes.saturating_add(pkt_len) <= MAX_MASK_STORE_BYTES
+ {
+ self.mask_store_bytes = self.mask_store_bytes.saturating_add(pkt_len);
+ entry.push(Arc::clone(&pkt));
+ }
+ }
+ true
+ }
+ ParsedBinary::StrokeFinish => {
+ self.apply_vector_stroke_finish(&pkt[BINARY_HEADER_BYTES..]);
+ true
+ }
+ ParsedBinary::SelectiveUndo => {
+ self.apply_vector_selective_undo(&pkt[BINARY_HEADER_BYTES..]);
+ true
+ }
+ ParsedBinary::LoggedOther => true,
+ ParsedBinary::Ephemeral => false,
+ };
+
+ if record_in_log {
+ self.push_op_log(seq, Some(client_id), OpPayload::Binary(Arc::clone(&pkt)));
+ }
+ self.broadcast_live(Some(client_id), Message::Binary((*pkt).clone()));
+ }
+
+ fn apply_vector_stroke_finish(&mut self, payload: &[u8]) {
+ let Ok(val) = serde_json::from_slice::<serde_json::Value>(payload) else {
+ return;
+ };
+ let Some(vector_stroke) = val.get("vectorStroke").filter(|v| v.is_object()) else {
+ return;
+ };
+ let Some(layer_id) = val.get("layerId").and_then(|v| v.as_str()) else {
+ return;
+ };
+ if let Some(layer) = self
+ .doc
+ .layers
+ .iter_mut()
+ .find(|l| layer_id_of(l) == Some(layer_id))
+ {
+ if layer.get("type").and_then(|v| v.as_str()) == Some("vector") {
+ let strokes = layer
+ .entry("vectorStrokes".to_string())
+ .or_insert_with(|| serde_json::Value::Array(Vec::new()));
+ if let Some(arr) = strokes.as_array_mut() {
+ if arr.len() < MAX_SYNC_VECTOR_STROKES {
+ arr.push(vector_stroke.clone());
+ }
+ }
+ }
+ }
+ }
+
+ fn apply_vector_selective_undo(&mut self, payload: &[u8]) {
+ let Ok(val) = serde_json::from_slice::<serde_json::Value>(payload) else {
+ return;
+ };
+ let Some(stroke_id) = val.get("strokeId").and_then(|v| v.as_str()) else {
+ return;
+ };
+ for layer in &mut self.doc.layers {
+ if let Some(arr) = layer
+ .get_mut("vectorStrokes")
+ .and_then(|v| v.as_array_mut())
+ {
+ for st in arr.iter_mut() {
+ if st.get("id").and_then(|v| v.as_str()) == Some(stroke_id) {
+ if let Some(obj) = st.as_object_mut() {
+ obj.insert("deleted".to_string(), serde_json::Value::Bool(true));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ fn disconnect_client(&mut self, client_id: usize, fallback_peer_id: Option<String>) {
+ self.clients.remove(&client_id);
+ let removed_peer = self.peers.remove(&client_id);
+ if self.host_client_id == Some(client_id) {
+ self.host_client_id = None;
+ }
+
+ let peer_id = removed_peer.map(|p| p.id).or(fallback_peer_id);
+ let seq = self.next_seq();
+ let leave_msg = match &peer_id {
+ Some(pid) => serde_json::json!({
+ "type": "PEER_DISCONNECTED",
+ "seq": seq,
+ "peerId": pid,
+ "clientId": client_id,
+ }),
+ None => serde_json::json!({
+ "type": "PEER_DISCONNECTED",
+ "seq": seq,
+ "clientId": client_id,
+ }),
+ };
+ let text = Arc::new(leave_msg.to_string());
+ if peer_id.is_some() {
+ self.push_op_log(seq, None, OpPayload::Text(Arc::clone(&text)));
+ }
+ self.broadcast_live(None, Message::Text((*text).clone()));
+ }
}
struct TokenBucket {
@@ -101,7 +1983,7 @@ pub struct AppState {
pub local_ip: String,
pub port: u16,
pub tunnel_origin: Arc<std::sync::RwLock<Option<String>>>,
- clients: Arc<RwLock<HashMap<usize, ClientHandle>>>,
+ room: Arc<std::sync::Mutex<RoomState>>,
client_slots: Arc<Semaphore>,
connect_limiter: Arc<std::sync::Mutex<TokenBucket>>,
}
@@ -638,7 +2520,7 @@ pub async fn start_embedded_server(
local_ip: local_ip.clone(),
port,
tunnel_origin: Arc::clone(&tunnel_origin),
- clients: Arc::new(RwLock::new(HashMap::new())),
+ room: Arc::new(std::sync::Mutex::new(RoomState::new(room_name.clone()))),
client_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_CLIENTS)),
connect_limiter: Arc::new(std::sync::Mutex::new(TokenBucket::new(
CONNECT_BURST,
@@ -747,7 +2629,7 @@ pub fn shutdown_sync() {
pub async fn get_server_status() -> ServerInfo {
let manager = get_server_manager().lock().await;
if let (Some(info), Some(state)) = (&manager.current_info, &manager.state) {
- let count = state.clients.read().await.len();
+ let count = state.room.lock().map(|r| r.clients.len()).unwrap_or(0);
let mut updated = info.clone();
updated.peer_count = count;
updated
@@ -820,66 +2702,444 @@ async fn ws_handler(
}
}
- // 3. Constant-time room token verification
- let provided = extract_auth_token(&query, &headers);
- let token_valid = provided.map_or(false, |tok| {
- constant_time_eq(tok.as_bytes(), state.room_token.as_bytes())
- });
- if !token_valid {
- return (StatusCode::UNAUTHORIZED, "Unauthorized").into_response();
+ // 3. Constant-time room token verification
+ let provided = extract_auth_token(&query, &headers);
+ let token_valid = provided.map_or(false, |tok| {
+ constant_time_eq(tok.as_bytes(), state.room_token.as_bytes())
+ });
+ if !token_valid {
+ return (StatusCode::UNAUTHORIZED, "Unauthorized").into_response();
+ }
+
+ // 4. Enforce strict concurrent client ceiling atomically before upgrade
+ let Ok(permit) = Arc::clone(&state.client_slots).try_acquire_owned() else {
+ return (StatusCode::SERVICE_UNAVAILABLE, "Room is full").into_response();
+ };
+
+ ws.max_message_size(MAX_WS_MESSAGE_BYTES)
+ .max_frame_size(MAX_WS_MESSAGE_BYTES)
+ .on_upgrade(move |socket| handle_socket(socket, state, permit))
+}
+
+#[inline]
+fn is_forbidden_json_key(k: &str) -> bool {
+ k == "__proto__" || k == "constructor" || k == "prototype"
+}
+
+#[inline]
+fn is_background_layer_id(id: &str) -> bool {
+ id == "layer-bg" || id.starts_with("layer-bg")
+}
+
+#[inline]
+fn layer_id_of(layer: &serde_json::Map<String, serde_json::Value>) -> Option<&str> {
+ layer.get("id").and_then(|v| v.as_str())
+}
+
+fn value_to_peer_id(val: &serde_json::Value) -> Option<String> {
+ let s = match val {
+ serde_json::Value::String(s) => s.trim().to_string(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => return None,
+ };
+ if s.is_empty() || s.len() > 128 {
+ return None;
+ }
+ Some(s)
+}
+
+fn parse_peer_from_join(
+ obj: &serde_json::Map<String, serde_json::Value>,
+ client_id: usize,
+) -> Option<PeerRecord> {
+ let peer_obj = obj.get("peer")?.as_object()?;
+ let id = value_to_peer_id(peer_obj.get("id")?)?;
+ let name: String = peer_obj
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Guest")
+ .trim()
+ .chars()
+ .take(64)
+ .collect();
+ let name = if name.is_empty() {
+ "Guest".to_string()
+ } else {
+ name
+ };
+ let color: String = peer_obj
+ .get("color")
+ .and_then(|v| v.as_str())
+ .unwrap_or("#38bdf8")
+ .trim()
+ .chars()
+ .take(32)
+ .collect();
+ let is_host = peer_obj
+ .get("isHost")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ let mut raw = serde_json::Map::new();
+ raw.insert("id".to_string(), serde_json::Value::String(id.clone()));
+ raw.insert("name".to_string(), serde_json::Value::String(name.clone()));
+ raw.insert(
+ "color".to_string(),
+ serde_json::Value::String(if color.is_empty() {
+ "#38bdf8".to_string()
+ } else {
+ color.clone()
+ }),
+ );
+ raw.insert("isHost".to_string(), serde_json::Value::Bool(is_host));
+ let initial_role = if is_host {
+ PeerRole::Host
+ } else {
+ PeerRole::Editor
+ };
+ raw.insert(
+ "role".to_string(),
+ serde_json::Value::String(initial_role.as_str().to_string()),
+ );
+
+ Some(PeerRecord {
+ client_id,
+ id,
+ name,
+ is_host,
+ role: initial_role,
+ raw,
+ })
+}
+
+fn sanitize_layer_object(
+ raw: &serde_json::Map<String, serde_json::Value>,
+) -> Option<serde_json::Map<String, serde_json::Value>> {
+ let id = raw.get("id")?.as_str()?.trim();
+ if id.is_empty() || id.len() > 256 {
+ return None;
+ }
+ let mut out = serde_json::Map::with_capacity(raw.len());
+ for (k, v) in raw {
+ if is_forbidden_json_key(k) {
+ continue;
+ }
+ out.insert(k.clone(), v.clone());
+ }
+ out.insert("id".to_string(), serde_json::Value::String(id.to_string()));
+ Some(out)
+}
+
+fn sanitize_layer_tree_objects(
+ raw_layers: &[serde_json::Value],
+) -> Vec<serde_json::Map<String, serde_json::Value>> {
+ let mut out: Vec<serde_json::Map<String, serde_json::Value>> =
+ Vec::with_capacity(raw_layers.len().min(MAX_SYNC_LAYERS));
+ let mut seen: HashSet<String> = HashSet::new();
+
+ for val in raw_layers.iter().take(MAX_SYNC_LAYERS) {
+ let Some(obj) = val.as_object() else {
+ continue;
+ };
+ let Some(clean) = sanitize_layer_object(obj) else {
+ continue;
+ };
+ let id = layer_id_of(&clean).unwrap_or("").to_string();
+ if id.is_empty() || !seen.insert(id) {
+ continue;
+ }
+ out.push(clean);
+ }
+
+ // Break dangling parentId references and cycles
+ let id_to_parent: HashMap<String, Option<String>> = out
+ .iter()
+ .filter_map(|l| {
+ let id = layer_id_of(l)?.to_string();
+ let pid = l
+ .get("parentId")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(|s| s.to_string());
+ Some((id, pid))
+ })
+ .collect();
+
+ for layer in &mut out {
+ let Some(id) = layer_id_of(layer).map(|s| s.to_string()) else {
+ continue;
+ };
+ let Some(mut cur_parent) = layer
+ .get("parentId")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(|s| s.to_string())
+ else {
+ continue;
+ };
+ if !id_to_parent.contains_key(&cur_parent) {
+ layer.insert("parentId".to_string(), serde_json::Value::Null);
+ continue;
+ }
+ let mut visited: HashSet<String> = HashSet::new();
+ visited.insert(id);
+ loop {
+ if !visited.insert(cur_parent.clone()) {
+ layer.insert("parentId".to_string(), serde_json::Value::Null);
+ break;
+ }
+ match id_to_parent.get(&cur_parent).and_then(|p| p.as_ref()) {
+ Some(next_parent) => cur_parent = next_parent.clone(),
+ None => break,
+ }
+ }
+ }
+
+ out
+}
+
+fn next_collab_layer_name(
+ username: &str,
+ layers: &[serde_json::Map<String, serde_json::Value>],
+) -> String {
+ let clean = username.trim();
+ let base = if clean.is_empty() { "User" } else { clean };
+ let base_lower = base.to_lowercase();
+ let mut max_num: u32 = 0;
+
+ for l in layers {
+ let Some(name) = l.get("name").and_then(|v| v.as_str()) else {
+ continue;
+ };
+ let lower = name.to_lowercase();
+ if let Some(rest) = lower.strip_prefix(&base_lower) {
+ let trimmed = rest.trim();
+ if trimmed.is_empty() {
+ max_num = max_num.max(1);
+ } else if trimmed.bytes().all(|b| b.is_ascii_digit()) {
+ if let Ok(n) = trimmed.parse::<u32>() {
+ max_num = max_num.max(n);
+ }
+ }
+ }
+ }
+
+ format!("{} {}", base, max_num.saturating_add(1))
+}
+
+fn parse_tile_delta_header(payload: &[u8]) -> Option<(TileKey, u32, bool)> {
+ if payload.len() < 2 {
+ return None;
+ }
+ let layer_id_len = u16::from_le_bytes([payload[0], payload[1]]) as usize;
+ if layer_id_len == 0
+ || layer_id_len > 256
+ || 2 + layer_id_len + TILE_PACKET_HEADER_BYTES > payload.len()
+ {
+ return None;
+ }
+ let layer_id = std::str::from_utf8(&payload[2..2 + layer_id_len]).ok()?;
+ let hdr = &payload[2 + layer_id_len..];
+ let tile_x = i32::from_le_bytes([hdr[0], hdr[1], hdr[2], hdr[3]]);
+ let tile_y = i32::from_le_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]);
+ let format_code = hdr[8];
+ let version = u32::from_le_bytes([hdr[9], hdr[10], hdr[11], hdr[12]]);
+ let codec = hdr[13];
+
+ if !(0..MAX_TILE_COORD).contains(&tile_x) || !(0..MAX_TILE_COORD).contains(&tile_y) {
+ return None;
+ }
+ if !matches!(format_code, 1 | 2 | 4) {
+ return None;
+ }
+ if !matches!(codec, TILE_CODEC_EMPTY | TILE_CODEC_RAW | TILE_CODEC_LZ4) {
+ return None;
+ }
+ let body_len = hdr.len() - TILE_PACKET_HEADER_BYTES;
+ if codec == TILE_CODEC_EMPTY && body_len != 0 {
+ return None;
}
- // 4. Enforce strict concurrent client ceiling atomically before upgrade
- let Ok(permit) = Arc::clone(&state.client_slots).try_acquire_owned() else {
- return (StatusCode::SERVICE_UNAVAILABLE, "Room is full").into_response();
- };
-
- ws.max_message_size(MAX_WS_MESSAGE_BYTES)
- .max_frame_size(MAX_WS_MESSAGE_BYTES)
- .on_upgrade(move |socket| handle_socket(socket, state, permit))
+ Some((
+ TileKey {
+ layer_id: layer_id.to_string(),
+ tile_x,
+ tile_y,
+ },
+ version,
+ codec == TILE_CODEC_EMPTY,
+ ))
}
-async fn broadcast_message(state: &AppState, sender_id: Option<usize>, msg: Message) {
- let mut slow_clients: Vec<(usize, Arc<Notify>)> = Vec::new();
- {
- let clients = state.clients.read().await;
- for (&id, peer) in clients.iter() {
- if Some(id) == sender_id {
- continue;
- }
- if peer.tx.try_send(msg.clone()).is_err() {
- slow_clients.push((id, Arc::clone(&peer.kick)));
- }
- }
+fn parse_mask_data_header(payload: &[u8]) -> Option<(String, bool)> {
+ if payload.len() < 19 {
+ return None;
+ }
+ let layer_id_len = u16::from_le_bytes([payload[0], payload[1]]) as usize;
+ if layer_id_len == 0 || layer_id_len > 256 || 2 + layer_id_len + 17 > payload.len() {
+ return None;
}
+ let layer_id = std::str::from_utf8(&payload[2..2 + layer_id_len]).ok()?;
+ let hdr = &payload[2 + layer_id_len..];
+ let flags = hdr[0];
+ let x = u32::from_le_bytes([hdr[1], hdr[2], hdr[3], hdr[4]]);
+ let y = u32::from_le_bytes([hdr[5], hdr[6], hdr[7], hdr[8]]);
+ let width = u32::from_le_bytes([hdr[9], hdr[10], hdr[11], hdr[12]]);
+ let height = u32::from_le_bytes([hdr[13], hdr[14], hdr[15], hdr[16]]);
- if !slow_clients.is_empty() {
- let mut clients = state.clients.write().await;
- for (id, kick) in slow_clients {
- clients.remove(&id);
- kick.notify_one();
- }
+ if x > MAX_SYNC_CANVAS_DIM
+ || y > MAX_SYNC_CANVAS_DIM
+ || width == 0
+ || height == 0
+ || width > MAX_SYNC_CANVAS_DIM
+ || height > MAX_SYNC_CANVAS_DIM
+ {
+ return None;
}
+
+ Some((layer_id.to_string(), (flags & MASK_FLAG_FULL_REPLACE) != 0))
}
+#[cfg(test)]
fn extract_peer_id_from_join(text: &str) -> Option<String> {
if !text.contains("JOIN_REQUEST") {
return None;
}
let val: serde_json::Value = serde_json::from_str(text).ok()?;
- if val.get("type")?.as_str()? != "JOIN_REQUEST" {
+ let obj = val.as_object()?;
+ if obj.get("type")?.as_str()? != "JOIN_REQUEST" {
return None;
}
- let peer_id = val.get("peer")?.get("id")?;
- let id_str = match peer_id {
- serde_json::Value::String(s) => s.trim().to_string(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => return None,
+ value_to_peer_id(obj.get("peer")?.get("id")?)
+}
+
+async fn run_client_sync_task(
+ state: AppState,
+ client_id: usize,
+ tx: mpsc::Sender<Message>,
+ plan: SyncPlan,
+) {
+ let mut cursor_seq = match plan {
+ SyncPlan::Full(snap) => {
+ if let Some(join_acc) = snap.join_accepted {
+ if tx.send(Message::Text(join_acc)).await.is_err() {
+ return;
+ }
+ }
+ if tx.send(Message::Text(snap.doc_sync_response)).await.is_err() {
+ return;
+ }
+ for tile_pkt in snap.tiles {
+ if tx.send(Message::Binary((*tile_pkt).clone())).await.is_err() {
+ return;
+ }
+ }
+ for mask_pkt in snap.masks {
+ if tx.send(Message::Binary((*mask_pkt).clone())).await.is_err() {
+ return;
+ }
+ }
+ snap.snapshot_seq
+ }
+ SyncPlan::Incremental {
+ join_accepted,
+ since_seq,
+ } => {
+ if let Some(join_acc) = join_accepted {
+ if tx.send(Message::Text(join_acc)).await.is_err() {
+ return;
+ }
+ }
+ since_seq
+ }
};
- if id_str.is_empty() || id_str.len() > 128 {
- return None;
+
+ // Tail catch-up loop: drain op_log entries > cursor_seq until caught up, then flip to live atomically
+ loop {
+ enum CatchUpStep {
+ Done,
+ Evicted,
+ SendBatch(Vec<Message>),
+ }
+
+ let step = {
+ let mut room = state.room.lock().unwrap_or_else(|e| e.into_inner());
+ if !room.clients.contains_key(&client_id) {
+ return;
+ }
+ if cursor_seq < room.op_log_floor {
+ if let Some(removed) = room.clients.remove(&client_id) {
+ removed.kick.notify_one();
+ }
+ CatchUpStep::Evicted
+ } else {
+ let pending: Vec<(u64, Message)> = room
+ .op_log
+ .iter()
+ .filter(|e| e.seq > cursor_seq && e.sender_client_id != Some(client_id))
+ .map(|e| (e.seq, e.payload.to_message()))
+ .collect();
+
+ if pending.is_empty() {
+ if let Some(c) = room.clients.get_mut(&client_id) {
+ c.live = true;
+ c.sync_in_progress = false;
+ }
+ CatchUpStep::Done
+ } else if pending.len() <= 64 {
+ let mut all_enqueued = true;
+ if let Some(c) = room.clients.get_mut(&client_id) {
+ for (s, msg) in pending {
+ if c.tx.try_send(msg).is_err() {
+ all_enqueued = false;
+ break;
+ }
+ cursor_seq = s;
+ }
+ if all_enqueued {
+ c.live = true;
+ c.sync_in_progress = false;
+ }
+ }
+ if all_enqueued {
+ CatchUpStep::Done
+ } else {
+ let after = cursor_seq;
+ let batch: Vec<Message> = room
+ .op_log
+ .iter()
+ .filter(|e| e.seq > after && e.sender_client_id != Some(client_id))
+ .map(|e| {
+ cursor_seq = e.seq;
+ e.payload.to_message()
+ })
+ .collect();
+ CatchUpStep::SendBatch(batch)
+ }
+ } else {
+ let batch: Vec<Message> = pending
+ .into_iter()
+ .map(|(s, m)| {
+ cursor_seq = s;
+ m
+ })
+ .collect();
+ CatchUpStep::SendBatch(batch)
+ }
+ }
+ };
+
+ match step {
+ CatchUpStep::Done | CatchUpStep::Evicted => break,
+ CatchUpStep::SendBatch(batch) => {
+ for msg in batch {
+ if tx.send(msg).await.is_err() {
+ return;
+ }
+ }
+ }
+ }
}
- Some(id_str)
}
async fn handle_socket(socket: WebSocket, state: AppState, _permit: OwnedSemaphorePermit) {
@@ -889,16 +3149,20 @@ async fn handle_socket(socket: WebSocket, state: AppState, _permit: OwnedSemapho
let (tx, mut rx) = mpsc::channel::<Message>(CLIENT_CHANNEL_CAPACITY);
let kick = Arc::new(Notify::new());
- // Register new client
- {
- state.clients.write().await.insert(
+ // Register client and read current server sequence atomically
+ let current_seq = {
+ let mut room = state.room.lock().unwrap_or_else(|e| e.into_inner());
+ room.clients.insert(
client_id,
ClientHandle {
tx: tx.clone(),
kick: Arc::clone(&kick),
+ live: true,
+ sync_in_progress: false,
},
);
- }
+ room.seq
+ };
// Spawn task to forward internal bounded channel messages to WebSocket sender
let forward_task = tokio::spawn(async move {
@@ -909,14 +3173,16 @@ async fn handle_socket(socket: WebSocket, state: AppState, _permit: OwnedSemapho
}
});
- // Notify client of room assignment
+ // Notify client of room assignment and current authoritative sequence
let welcome_msg = serde_json::json!({
"type": "ROOM_INFO",
"clientId": client_id,
"roomName": state.room_name,
+ "serverSeq": current_seq,
});
if tx.try_send(Message::Text(welcome_msg.to_string())).is_err() {
- state.clients.write().await.remove(&client_id);
+ let mut room = state.room.lock().unwrap_or_else(|e| e.into_inner());
+ room.clients.remove(&client_id);
forward_task.abort();
return;
}
@@ -930,7 +3196,6 @@ async fn handle_socket(socket: WebSocket, state: AppState, _permit: OwnedSemapho
tokio::time::interval(tokio::time::Duration::from_secs(WS_PING_INTERVAL_SECS));
ping_interval.tick().await;
- // Broadcast loop for incoming WebSocket messages from this client
loop {
tokio::select! {
_ = kick.notified() => break,
@@ -953,12 +3218,34 @@ async fn handle_socket(socket: WebSocket, state: AppState, _permit: OwnedSemapho
{
break;
}
- if known_peer_id.is_none() {
- if let Some(pid) = extract_peer_id_from_join(&text) {
- known_peer_id = Some(pid);
+ // Parse outside the room lock to minimize contention
+ let Ok(serde_json::Value::Object(obj)) = serde_json::from_str(&text) else {
+ continue;
+ };
+ let outcome = {
+ let mut room = state.room.lock().unwrap_or_else(|e| e.into_inner());
+ room.handle_text_object(client_id, obj)
+ };
+ match outcome {
+ HandleTextOutcome::None => {}
+ HandleTextOutcome::PeerRegistered(pid) => {
+ if known_peer_id.is_none() {
+ known_peer_id = Some(pid);
+ }
+ }
+ HandleTextOutcome::StartSync { peer_id, plan } => {
+ if known_peer_id.is_none() {
+ if let Some(pid) = peer_id {
+ known_peer_id = Some(pid);
+ }
+ }
+ let sync_state = state.clone();
+ let sync_tx = tx.clone();
+ tokio::spawn(async move {
+ run_client_sync_task(sync_state, client_id, sync_tx, plan).await;
+ });
}
}
- broadcast_message(&state, Some(client_id), Message::Text(text)).await;
}
Message::Binary(bin) => {
let len = bin.len();
@@ -968,7 +3255,8 @@ async fn handle_socket(socket: WebSocket, state: AppState, _permit: OwnedSemapho
{
break;
}
- broadcast_message(&state, Some(client_id), Message::Binary(bin)).await;
+ let mut room = state.room.lock().unwrap_or_else(|e| e.into_inner());
+ room.handle_binary_frame(client_id, bin);
}
Message::Ping(payload) => {
let _ = tx.try_send(Message::Pong(payload));
@@ -980,25 +3268,12 @@ async fn handle_socket(socket: WebSocket, state: AppState, _permit: OwnedSemapho
}
}
- // Client disconnected or evicted
+ // Client disconnected or evicted: remove from room, emit sequenced PEER_DISCONNECTED
+ forward_task.abort();
{
- state.clients.write().await.remove(&client_id);
+ let mut room = state.room.lock().unwrap_or_else(|e| e.into_inner());
+ room.disconnect_client(client_id, known_peer_id);
}
- forward_task.abort();
-
- // Broadcast user left event with both peerId and clientId so peers never turn into ghosts
- let leave_msg = match known_peer_id {
- Some(pid) => serde_json::json!({
- "type": "PEER_DISCONNECTED",
- "peerId": pid,
- "clientId": client_id,
- }),
- None => serde_json::json!({
- "type": "PEER_DISCONNECTED",
- "clientId": client_id,
- }),
- };
- broadcast_message(&state, None, Message::Text(leave_msg.to_string())).await;
}
fn urlencoding_encode(s: &str) -> String {
@@ -1103,7 +3378,7 @@ mod tests {
local_ip: "127.0.0.1".to_string(),
port: 0,
tunnel_origin: Arc::new(std::sync::RwLock::new(None)),
- clients: Arc::new(RwLock::new(HashMap::new())),
+ room: Arc::new(std::sync::Mutex::new(RoomState::new("Test".to_string()))),
client_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_CLIENTS)),
connect_limiter: Arc::new(std::sync::Mutex::new(TokenBucket::new(
CONNECT_BURST,
@@ -1180,4 +3455,851 @@ mod tests {
server_task.abort();
}
+
+ fn make_tile_packet(
+ layer_id: &str,
+ tile_x: i32,
+ tile_y: i32,
+ version: u32,
+ codec: u8,
+ tile_body: &[u8],
+ ) -> Vec<u8> {
+ let lid = layer_id.as_bytes();
+ let payload_len = 2 + lid.len() + TILE_PACKET_HEADER_BYTES + tile_body.len();
+ let mut pkt = Vec::with_capacity(BINARY_HEADER_BYTES + payload_len);
+ pkt.push(BINARY_MAGIC_0);
+ pkt.push(BINARY_MAGIC_1);
+ pkt.push(CODE_TILE_DELTA);
+ pkt.extend_from_slice(&999u32.to_le_bytes()); // spoofed client lamport/seq
+ pkt.extend_from_slice(&(payload_len as u32).to_le_bytes());
+ pkt.extend_from_slice(&(lid.len() as u16).to_le_bytes());
+ pkt.extend_from_slice(lid);
+ pkt.extend_from_slice(&tile_x.to_le_bytes());
+ pkt.extend_from_slice(&tile_y.to_le_bytes());
+ pkt.push(4); // color-32bit
+ pkt.extend_from_slice(&version.to_le_bytes());
+ pkt.push(codec);
+ pkt.extend_from_slice(tile_body);
+ pkt
+ }
+
+ fn make_mask_packet(layer_id: &str, flags: u8, w: u32, h: u32, body: &[u8]) -> Vec<u8> {
+ let lid = layer_id.as_bytes();
+ let payload_len = 2 + lid.len() + 17 + body.len();
+ let mut pkt = Vec::with_capacity(BINARY_HEADER_BYTES + payload_len);
+ pkt.push(BINARY_MAGIC_0);
+ pkt.push(BINARY_MAGIC_1);
+ pkt.push(CODE_LAYER_MASK_DATA);
+ pkt.extend_from_slice(&1u32.to_le_bytes());
+ pkt.extend_from_slice(&(payload_len as u32).to_le_bytes());
+ pkt.extend_from_slice(&(lid.len() as u16).to_le_bytes());
+ pkt.extend_from_slice(lid);
+ pkt.push(flags);
+ pkt.extend_from_slice(&0u32.to_le_bytes()); // x
+ pkt.extend_from_slice(&0u32.to_le_bytes()); // y
+ pkt.extend_from_slice(&w.to_le_bytes());
+ pkt.extend_from_slice(&h.to_le_bytes());
+ pkt.extend_from_slice(body);
+ pkt
+ }
+
+ fn register_test_client(room: &mut RoomState, client_id: usize) -> mpsc::Receiver<Message> {
+ let (tx, rx) = mpsc::channel(64);
+ room.clients.insert(
+ client_id,
+ ClientHandle {
+ tx,
+ kick: Arc::new(Notify::new()),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+ rx
+ }
+
+ #[test]
+ fn test_monotonic_seq_overwrites_spoofed_seq_and_orders_concurrent_edits() {
+ let mut room = RoomState::new("Room".to_string());
+ let mut rx_host = register_test_client(&mut room, 1);
+ let mut rx_guest = register_test_client(&mut room, 2);
+
+ // Host registers & seeds doc
+ let join_host = serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "host-1", "name": "Host", "color": "#fff", "isHost": true }
+ });
+ room.handle_text_object(1, join_host.as_object().unwrap().clone());
+
+ let seed = serde_json::json!({
+ "type": "DOC_SYNC_RESPONSE",
+ "targetPeerId": "__server__",
+ "dimensions": { "width": 1000, "height": 800 },
+ "colorMode": "color",
+ "layers": [
+ { "id": "l1", "name": "Layer 1", "type": "raster", "visible": true, "opacity": 1.0, "blendMode": "normal", "locked": false, "parentId": null }
+ ]
+ });
+ room.handle_text_object(1, seed.as_object().unwrap().clone());
+ assert!(room.doc.initialized);
+ let seed_seq = room.seq;
+ assert_eq!(seed_seq, 1);
+
+ // Concurrent edits with spoofed seq values
+ let edit1 = serde_json::json!({
+ "type": "LAYER_OPACITY",
+ "layerId": "l1",
+ "opacity": 0.4,
+ "seq": 99999
+ });
+ room.handle_text_object(1, edit1.as_object().unwrap().clone());
+
+ let edit2 = serde_json::json!({
+ "type": "LAYER_OPACITY",
+ "layerId": "l1",
+ "opacity": 0.75,
+ "seq": 1
+ });
+ room.handle_text_object(2, edit2.as_object().unwrap().clone());
+
+ // Binary tile with spoofed seq 999
+ let tile_pkt = make_tile_packet("l1", 1, 2, 5, TILE_CODEC_LZ4, &[1, 2, 3, 4]);
+ room.handle_binary_frame(1, tile_pkt);
+
+ // Verify strict monotonic server seq assignment
+ let Message::Text(g_msg1) = rx_guest.try_recv().unwrap() else {
+ panic!("expected text");
+ };
+ let v1: serde_json::Value = serde_json::from_str(&g_msg1).unwrap();
+ assert_eq!(v1["seq"].as_u64(), Some(2));
+
+ let Message::Text(h_msg2) = rx_host.try_recv().unwrap() else {
+ panic!("expected text");
+ };
+ let v2: serde_json::Value = serde_json::from_str(&h_msg2).unwrap();
+ assert_eq!(v2["seq"].as_u64(), Some(3));
+
+ let Message::Binary(g_bin) = rx_guest.try_recv().unwrap() else {
+ panic!("expected binary");
+ };
+ let stamped_seq = u32::from_le_bytes([g_bin[3], g_bin[4], g_bin[5], g_bin[6]]);
+ assert_eq!(stamped_seq, 4);
+
+ // Final canonical layer opacity on server reflects edit2 (seq=3)
+ assert_eq!(room.doc.layers[0]["opacity"].as_f64(), Some(0.75));
+ assert_eq!(room.tiles.len(), 1);
+ assert_eq!(room.op_log.len(), 3);
+ }
+
+ #[tokio::test]
+ async fn test_new_peer_syncs_directly_from_server_without_blocking_host() {
+ let state = AppState {
+ room_name: "Studio".to_string(),
+ room_token: Arc::new("tok".to_string()),
+ local_ip: "127.0.0.1".to_string(),
+ port: 0,
+ tunnel_origin: Arc::new(std::sync::RwLock::new(None)),
+ room: Arc::new(std::sync::Mutex::new(RoomState::new("Studio".to_string()))),
+ client_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_CLIENTS)),
+ connect_limiter: Arc::new(std::sync::Mutex::new(TokenBucket::new(
+ CONNECT_BURST,
+ CONNECT_REFILL_PER_SEC,
+ ))),
+ };
+
+ let mut rx_host;
+ let mut rx_guest;
+ let guest_tx;
+ let sync_plan;
+
+ {
+ let mut room = state.room.lock().unwrap();
+ rx_host = register_test_client(&mut room, 1);
+
+ // Host joins and seeds document + tiles + mask
+ room.handle_text_object(
+ 1,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "host-1", "name": "Host", "color": "#111", "isHost": true }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ room.handle_text_object(
+ 1,
+ serde_json::json!({
+ "type": "DOC_SYNC_RESPONSE",
+ "targetPeerId": "__server__",
+ "dimensions": { "width": 1440, "height": 900 },
+ "colorMode": "color",
+ "layers": [
+ { "id": "l1", "name": "Host 1", "type": "raster", "visible": true, "opacity": 1.0, "blendMode": "normal", "locked": false, "parentId": null, "hasMask": true },
+ { "id": "layer-bg", "name": "Background", "type": "raster", "visible": true, "opacity": 1.0, "blendMode": "normal", "locked": false, "parentId": null }
+ ]
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ // Tile v1 then overwritten by v2; tile (0,1) created then tombstoned
+ room.handle_binary_frame(1, make_tile_packet("l1", 0, 0, 1, TILE_CODEC_LZ4, &[10, 20]));
+ room.handle_binary_frame(1, make_tile_packet("l1", 0, 0, 2, TILE_CODEC_LZ4, &[30, 40, 50]));
+ room.handle_binary_frame(1, make_tile_packet("l1", 0, 1, 1, TILE_CODEC_LZ4, &[99]));
+ room.handle_binary_frame(1, make_tile_packet("l1", 0, 1, 2, TILE_CODEC_EMPTY, &[]));
+ // Mask solid fill
+ room.handle_binary_frame(1, make_mask_packet("l1", MASK_FLAG_FULL_REPLACE | 0x04, 1440, 900, &[255]));
+
+ // Guest connects and sends JOIN_REQUEST
+ rx_guest = register_test_client(&mut room, 2);
+ guest_tx = room.clients.get(&2).unwrap().tx.clone();
+ let outcome = room.handle_text_object(
+ 2,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "guest-2", "name": "Bob", "color": "#222", "isHost": false }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ sync_plan = match outcome {
+ HandleTextOutcome::StartSync { plan, .. } => plan,
+ _ => panic!("expected server-direct StartSync"),
+ };
+
+ // Simulate concurrent host edit arriving WHILE guest sync is in flight!
+ room.handle_text_object(
+ 1,
+ serde_json::json!({
+ "type": "LAYER_RENAME",
+ "layerId": "l1",
+ "newName": "Renamed During Sync"
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ }
+
+ // Host must NEVER receive JOIN_REQUEST (only LAYER_ADD + PEER_JOINED)
+ let mut host_types = Vec::new();
+ while let Ok(Message::Text(t)) = rx_host.try_recv() {
+ let v: serde_json::Value = serde_json::from_str(&t).unwrap();
+ host_types.push(v["type"].as_str().unwrap().to_string());
+ }
+ assert_eq!(host_types, vec!["LAYER_ADD", "PEER_JOINED"]);
+
+ // Run server direct sync task to completion
+ run_client_sync_task(state.clone(), 2, guest_tx, sync_plan).await;
+
+ // Guest receives: JOIN_ACCEPTED -> DOC_SYNC_RESPONSE -> 1 latest tile (v2) -> 1 mask -> tail LAYER_RENAME!
+ let Message::Text(m1) = rx_guest.try_recv().unwrap() else { panic!("expected JOIN_ACCEPTED") };
+ let j1: serde_json::Value = serde_json::from_str(&m1).unwrap();
+ assert_eq!(j1["type"], "JOIN_ACCEPTED");
+ assert_eq!(j1["assignedLayerId"], "layer-guest-2-1");
+ assert_eq!(j1["hostId"], "host-1");
+
+ let Message::Text(m2) = rx_guest.try_recv().unwrap() else { panic!("expected DOC_SYNC_RESPONSE") };
+ let j2: serde_json::Value = serde_json::from_str(&m2).unwrap();
+ assert_eq!(j2["type"], "DOC_SYNC_RESPONSE");
+ assert_eq!(j2["layers"].as_array().unwrap().len(), 3);
+ assert_eq!(j2["layers"][0]["id"], "layer-guest-2-1");
+
+ let Message::Binary(b_tile) = rx_guest.try_recv().unwrap() else { panic!("expected BINARY_TILE") };
+ assert_eq!(b_tile[2], CODE_TILE_DELTA);
+ let (_, ver, is_empty) = parse_tile_delta_header(&b_tile[BINARY_HEADER_BYTES..]).unwrap();
+ assert_eq!(ver, 2); // latest version, tombstone (0,1) excluded
+ assert!(!is_empty);
+
+ let Message::Binary(b_mask) = rx_guest.try_recv().unwrap() else { panic!("expected BINARY_MASK") };
+ assert_eq!(b_mask[2], CODE_LAYER_MASK_DATA);
+
+ // Tail op arrived during sync is replayed in order AFTER snapshot
+ let Message::Text(m_tail) = rx_guest.try_recv().unwrap() else { panic!("expected tail LAYER_RENAME") };
+ let j_tail: serde_json::Value = serde_json::from_str(&m_tail).unwrap();
+ assert_eq!(j_tail["type"], "LAYER_RENAME");
+ assert_eq!(j_tail["newName"], "Renamed During Sync");
+ assert!(rx_guest.try_recv().is_err());
+ assert!(state.room.lock().unwrap().clients.get(&2).unwrap().live);
+ }
+
+ #[tokio::test]
+ async fn test_incremental_doc_sync_request_and_security_guards() {
+ let state = AppState {
+ room_name: "SecRoom".to_string(),
+ room_token: Arc::new("tok".to_string()),
+ local_ip: "127.0.0.1".to_string(),
+ port: 0,
+ tunnel_origin: Arc::new(std::sync::RwLock::new(None)),
+ room: Arc::new(std::sync::Mutex::new(RoomState::new("SecRoom".to_string()))),
+ client_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_CLIENTS)),
+ connect_limiter: Arc::new(std::sync::Mutex::new(TokenBucket::new(
+ CONNECT_BURST,
+ CONNECT_REFILL_PER_SEC,
+ ))),
+ };
+
+ let mut rx_guest;
+ let guest_tx;
+ let inc_plan;
+
+ {
+ let mut room = state.room.lock().unwrap();
+ let _rx_host = register_test_client(&mut room, 1);
+ rx_guest = register_test_client(&mut room, 2);
+ guest_tx = room.clients.get(&2).unwrap().tx.clone();
+
+ room.handle_text_object(
+ 1,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "host-1", "name": "Host", "color": "#000", "isHost": true }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ room.handle_text_object(
+ 1,
+ serde_json::json!({
+ "type": "DOC_SYNC_RESPONSE",
+ "targetPeerId": "__server__",
+ "dimensions": { "width": 512, "height": 512 },
+ "colorMode": "color",
+ "layers": [
+ { "id": "f1", "name": "Folder", "type": "folder", "parentId": null },
+ { "id": "c1", "name": "Child", "type": "raster", "parentId": "f1" }
+ ]
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ let baseline_seq = room.seq;
+
+ // Rogue guest attempts to hijack host and overwrite document snapshot -> must fail
+ room.handle_text_object(
+ 2,
+ serde_json::json!({
+ "type": "DOC_SYNC_RESPONSE",
+ "targetPeerId": "__server__",
+ "dimensions": { "width": 10, "height": 10 },
+ "colorMode": "monochrome",
+ "layers": [{ "id": "evil", "name": "Evil", "type": "raster", "parentId": null }]
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert_eq!(room.doc.layers.len(), 2);
+ assert_eq!(room.doc.layers[0]["id"], "f1");
+
+ // Host adds tile on child, then deletes parent folder -> subtree + tile pruned
+ room.handle_binary_frame(1, make_tile_packet("c1", 0, 0, 1, TILE_CODEC_LZ4, &[7, 8]));
+ assert_eq!(room.tiles.len(), 1);
+ room.handle_text_object(
+ 1,
+ serde_json::json!({ "type": "LAYER_DELETE", "layerId": "f1" })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert!(room.doc.layers.is_empty());
+ assert!(room.tiles.is_empty());
+
+ // Drain guest's live messages before testing incremental replay
+ while rx_guest.try_recv().is_ok() {}
+
+ // Guest asks for incremental catch-up from baseline_seq
+ let outcome = room.handle_text_object(
+ 2,
+ serde_json::json!({
+ "type": "DOC_SYNC_REQUEST",
+ "targetPeerId": "guest-2",
+ "sinceSeq": baseline_seq
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ inc_plan = match outcome {
+ HandleTextOutcome::StartSync {
+ plan:
+ SyncPlan::Incremental {
+ join_accepted,
+ since_seq,
+ },
+ ..
+ } => {
+ assert_eq!(since_seq, baseline_seq);
+ SyncPlan::Incremental {
+ join_accepted,
+ since_seq,
+ }
+ }
+ _ => panic!("expected Incremental sync plan"),
+ };
+ }
+
+ run_client_sync_task(state.clone(), 2, guest_tx, inc_plan).await;
+
+ // Replays exact 2 ops since baseline_seq: BINARY_TILE then LAYER_DELETE
+ let Message::Binary(b1) = rx_guest.try_recv().unwrap() else { panic!("expected tile op") };
+ assert_eq!(b1[2], CODE_TILE_DELTA);
+ let Message::Text(t2) = rx_guest.try_recv().unwrap() else { panic!("expected delete op") };
+ let j2: serde_json::Value = serde_json::from_str(&t2).unwrap();
+ assert_eq!(j2["type"], "LAYER_DELETE");
+ assert!(rx_guest.try_recv().is_err());
+ }
+
+ fn make_test_app_state() -> AppState {
+ AppState {
+ room_name: "TestRoom".to_string(),
+ room_token: Arc::new("tok".to_string()),
+ local_ip: "127.0.0.1".to_string(),
+ port: 30303,
+ tunnel_origin: Arc::new(std::sync::RwLock::new(None)),
+ room: Arc::new(std::sync::Mutex::new(RoomState::new("TestRoom".to_string()))),
+ client_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_CLIENTS)),
+ connect_limiter: Arc::new(std::sync::Mutex::new(TokenBucket::new(
+ CONNECT_BURST,
+ CONNECT_REFILL_PER_SEC,
+ ))),
+ }
+ }
+
+ #[tokio::test]
+ async fn test_reconnect_catchup_by_seq_and_host_hijack_prevention() {
+ let state = make_test_app_state();
+ let (host_tx, _rx_host) = mpsc::channel::<Message>(64);
+ let (guest_tx, mut rx_guest) = mpsc::channel::<Message>(64);
+ let (reconn_tx, mut rx_reconn) = mpsc::channel::<Message>(64);
+
+ let guest_baseline_seq: u64;
+ {
+ let mut room = state.room.lock().unwrap();
+ room.clients.insert(
+ 1,
+ ClientHandle {
+ tx: host_tx.clone(),
+ kick: Arc::new(Notify::new()),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+ room.handle_text_object(
+ 1,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "host-1", "name": "Host", "color": "#fff", "isHost": true }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ room.handle_text_object(
+ 1,
+ serde_json::json!({
+ "type": "DOC_SYNC_RESPONSE",
+ "targetPeerId": "__server__",
+ "dimensions": { "width": 512, "height": 512 },
+ "colorMode": "color",
+ "layers": [
+ { "id": "layer-host", "name": "Host 1", "type": "raster", "visible": true, "opacity": 1.0, "blendMode": "normal", "locked": false, "parentId": null, "ownerPeerId": "host-1", "ownerPeerName": "Host" }
+ ]
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+
+ // Guest joins initially
+ room.clients.insert(
+ 2,
+ ClientHandle {
+ tx: guest_tx.clone(),
+ kick: Arc::new(Notify::new()),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+ let _ = room.handle_text_object(
+ 2,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "guest-a", "name": "Alice", "color": "#0f0", "isHost": false }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ // Mark guest live and snapshot baseline seq
+ if let Some(c) = room.clients.get_mut(&2) {
+ c.live = true;
+ c.sync_in_progress = false;
+ }
+ guest_baseline_seq = room.seq;
+
+ // Guest disconnects temporarily
+ room.disconnect_client(2, Some("guest-a".to_string()));
+ // Host also disconnects temporarily to test hijack prevention
+ room.disconnect_client(1, Some("host-1".to_string()));
+
+ // Attacker tries to claim isHost:true while real host is disconnected
+ room.clients.insert(
+ 3,
+ ClientHandle {
+ tx: reconn_tx.clone(),
+ kick: Arc::new(Notify::new()),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+ let _ = room.handle_text_object(
+ 3,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "attacker", "name": "Evil", "color": "#f00", "isHost": true }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert_eq!(room.host_peer_id.as_deref(), Some("host-1"));
+ assert_ne!(room.host_client_id, Some(3));
+ assert_eq!(room.client_role(3), PeerRole::Editor);
+ room.disconnect_client(3, Some("attacker".to_string()));
+
+ // Real host reconnects and produces a tile + layer rename while guest-a is offline
+ room.clients.insert(
+ 4,
+ ClientHandle {
+ tx: host_tx.clone(),
+ kick: Arc::new(Notify::new()),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+ room.handle_text_object(
+ 4,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "host-1", "name": "Host", "color": "#fff", "isHost": true },
+ "isReconnect": true,
+ "sinceSeq": guest_baseline_seq
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert_eq!(room.host_client_id, Some(4));
+
+ room.handle_binary_frame(4, make_tile_packet("layer-host", 0, 0, 7, TILE_CODEC_RAW, &[1, 2, 3, 4]));
+ room.handle_text_object(
+ 4,
+ serde_json::json!({
+ "type": "LAYER_RENAME",
+ "layerId": "layer-host",
+ "newName": "Inked"
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ }
+
+ // Now guest-a reconnects with isReconnect: true and sinceSeq = guest_baseline_seq
+ let plan = {
+ let mut room = state.room.lock().unwrap();
+ room.clients.insert(
+ 5,
+ ClientHandle {
+ tx: reconn_tx.clone(),
+ kick: Arc::new(Notify::new()),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+ let outcome = room.handle_text_object(
+ 5,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "guest-a", "name": "Alice", "color": "#0f0", "isHost": false },
+ "isReconnect": true,
+ "sinceSeq": guest_baseline_seq
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ match outcome {
+ HandleTextOutcome::StartSync {
+ plan:
+ SyncPlan::Incremental {
+ join_accepted,
+ since_seq,
+ },
+ ..
+ } => {
+ assert!(join_accepted.is_some());
+ assert_eq!(since_seq, guest_baseline_seq);
+ SyncPlan::Incremental {
+ join_accepted,
+ since_seq,
+ }
+ }
+ _ => panic!("expected Incremental catch-up on reconnect"),
+ }
+ };
+
+ while rx_reconn.try_recv().is_ok() {}
+ while rx_guest.try_recv().is_ok() {}
+
+ run_client_sync_task(state.clone(), 5, reconn_tx, plan).await;
+
+ let mut saw_join_accepted = false;
+ let mut saw_tile = false;
+ let mut saw_rename = false;
+ while let Ok(msg) = rx_reconn.try_recv() {
+ match msg {
+ Message::Text(t) => {
+ let v: serde_json::Value = serde_json::from_str(&t).unwrap();
+ if v["type"] == "JOIN_ACCEPTED" {
+ assert_eq!(v["isReconnect"], true);
+ saw_join_accepted = true;
+ } else if v["type"] == "LAYER_RENAME" && v["newName"] == "Inked" {
+ saw_rename = true;
+ }
+ }
+ Message::Binary(b) => {
+ if b.len() > 2 && b[2] == CODE_TILE_DELTA {
+ saw_tile = true;
+ }
+ }
+ _ => {}
+ }
+ }
+ assert!(saw_join_accepted);
+ assert!(saw_tile);
+ assert!(saw_rename);
+ }
+
+ #[test]
+ fn test_roles_owner_lock_delete_protection_and_kick_ban() {
+ let mut room = RoomState::new("ModRoom".to_string());
+ let (host_tx, _rx_host) = mpsc::channel::<Message>(64);
+ let (alice_tx, mut rx_alice) = mpsc::channel::<Message>(64);
+ let (bob_tx, mut rx_bob) = mpsc::channel::<Message>(64);
+
+ let alice_kick = Arc::new(Notify::new());
+ let bob_kick = Arc::new(Notify::new());
+
+ room.clients.insert(
+ 1,
+ ClientHandle {
+ tx: host_tx,
+ kick: Arc::new(Notify::new()),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+ room.clients.insert(
+ 2,
+ ClientHandle {
+ tx: alice_tx,
+ kick: Arc::clone(&alice_kick),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+ room.clients.insert(
+ 3,
+ ClientHandle {
+ tx: bob_tx,
+ kick: Arc::clone(&bob_kick),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+
+ // Register Host, Alice (editor), Bob (editor)
+ room.handle_text_object(
+ 1,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "host-1", "name": "Host", "color": "#fff", "isHost": true }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ room.handle_text_object(
+ 1,
+ serde_json::json!({
+ "type": "DOC_SYNC_RESPONSE",
+ "targetPeerId": "__server__",
+ "dimensions": { "width": 512, "height": 512 },
+ "colorMode": "color",
+ "layers": [
+ { "id": "layer-alice", "name": "Alice 1", "type": "raster", "visible": true, "opacity": 1.0, "blendMode": "normal", "locked": false, "parentId": null, "ownerPeerId": "alice", "ownerPeerName": "Alice" },
+ { "id": "layer-bob", "name": "Bob 1", "type": "raster", "visible": true, "opacity": 1.0, "blendMode": "normal", "locked": false, "parentId": null, "ownerPeerId": "bob", "ownerPeerName": "Bob" }
+ ]
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ room.handle_text_object(
+ 2,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "alice", "name": "Alice", "color": "#0f0", "isHost": false }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ room.handle_text_object(
+ 3,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "bob", "name": "Bob", "color": "#00f", "isHost": false }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ // Flip to live
+ room.clients.get_mut(&2).unwrap().live = true;
+ room.clients.get_mut(&2).unwrap().sync_in_progress = false;
+ room.clients.get_mut(&3).unwrap().live = true;
+ room.clients.get_mut(&3).unwrap().sync_in_progress = false;
+ while rx_alice.try_recv().is_ok() {}
+ while rx_bob.try_recv().is_ok() {}
+
+ // 1. Bob cannot delete Alice's layer (protection against accidental deletion)
+ room.handle_text_object(
+ 3,
+ serde_json::json!({ "type": "LAYER_DELETE", "layerId": "layer-alice" })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert!(room.doc.layers.iter().any(|l| layer_id_of(l) == Some("layer-alice")));
+ let Message::Text(denied_txt) = rx_bob.try_recv().unwrap() else { panic!("expected denied") };
+ let denied_json: serde_json::Value = serde_json::from_str(&denied_txt).unwrap();
+ assert_eq!(denied_json["type"], "ACCESS_DENIED");
+ assert_eq!(denied_json["code"], "NOT_OWNER");
+
+ // 2. Bob also cannot delete Alice's layer via LAYER_TREE_SYNC
+ room.handle_text_object(
+ 3,
+ serde_json::json!({
+ "type": "LAYER_TREE_SYNC",
+ "layers": [
+ { "id": "layer-bob", "name": "Bob 1", "type": "raster", "visible": true, "opacity": 1.0, "blendMode": "normal", "locked": false, "parentId": null, "ownerPeerId": "bob" }
+ ]
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert!(room.doc.layers.iter().any(|l| layer_id_of(l) == Some("layer-alice")));
+ while rx_bob.try_recv().is_ok() {}
+
+ // 3. Alice locks her layer by owner -> Bob cannot paint tiles or rename or unlock it
+ room.handle_text_object(
+ 2,
+ serde_json::json!({
+ "type": "LAYER_UPDATE",
+ "layerId": "layer-alice",
+ "patch": { "reservedByPeerId": "alice", "reservedByPeerName": "Alice" }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ while rx_bob.try_recv().is_ok() {}
+
+ room.handle_binary_frame(3, make_tile_packet("layer-alice", 0, 0, 1, TILE_CODEC_RAW, &[9, 9, 9]));
+ assert!(room.tiles.is_empty());
+ let Message::Text(lock_denied) = rx_bob.try_recv().unwrap() else { panic!("expected lock denied") };
+ assert_eq!(serde_json::from_str::<serde_json::Value>(&lock_denied).unwrap()["code"], "LAYER_LOCKED");
+
+ // 4. Non-host cannot demote someone else
+ room.handle_text_object(
+ 3,
+ serde_json::json!({ "type": "PEER_ROLE_UPDATE", "targetPeerId": "alice", "role": "viewer" })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert_eq!(room.client_role(2), PeerRole::Editor);
+ while rx_bob.try_recv().is_ok() {}
+
+ // 5. Host demotes Bob to Viewer -> Bob cannot draw even on his own layer, and Viewer persists across reconnect
+ room.handle_text_object(
+ 1,
+ serde_json::json!({ "type": "PEER_ROLE_UPDATE", "targetPeerId": "bob", "role": "viewer" })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert_eq!(room.client_role(3), PeerRole::Viewer);
+ while rx_bob.try_recv().is_ok() {}
+
+ room.handle_binary_frame(3, make_tile_packet("layer-bob", 0, 0, 2, TILE_CODEC_RAW, &[7, 7, 7]));
+ assert!(room.tiles.is_empty());
+ let Message::Text(viewer_denied) = rx_bob.try_recv().unwrap() else { panic!("expected viewer denied") };
+ assert_eq!(serde_json::from_str::<serde_json::Value>(&viewer_denied).unwrap()["code"], "VIEWER_READONLY");
+
+ // 6. Host bans Alice -> releases Alice's layer lock, removes Alice, blocks Alice rejoin until unban
+ room.handle_text_object(
+ 1,
+ serde_json::json!({ "type": "PEER_BAN", "targetPeerId": "alice", "reason": "Griefing" })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert!(room.banned_peer_ids.contains("alice"));
+ assert!(!room.clients.contains_key(&2));
+ let alice_layer = room.doc.layers.iter().find(|l| layer_id_of(l) == Some("layer-alice")).unwrap();
+ assert!(alice_layer.get("reservedByPeerId").is_none());
+
+ // Alice tries to rejoin while banned -> immediately denied & removed
+ let (alice2_tx, mut rx_alice2) = mpsc::channel::<Message>(16);
+ room.clients.insert(
+ 9,
+ ClientHandle {
+ tx: alice2_tx,
+ kick: Arc::new(Notify::new()),
+ live: true,
+ sync_in_progress: false,
+ },
+ );
+ room.handle_text_object(
+ 9,
+ serde_json::json!({
+ "type": "JOIN_REQUEST",
+ "peer": { "id": "alice", "name": "Alice", "color": "#0f0", "isHost": false }
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert!(!room.clients.contains_key(&9));
+ let Message::Text(ban_msg) = rx_alice2.try_recv().unwrap() else { panic!("expected ban denial") };
+ assert_eq!(serde_json::from_str::<serde_json::Value>(&ban_msg).unwrap()["code"], "BANNED");
+
+ // Host unbans Alice -> allowed to rejoin
+ room.handle_text_object(
+ 1,
+ serde_json::json!({ "type": "PEER_UNBAN", "targetPeerId": "alice" })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ assert!(!room.banned_peer_ids.contains("alice"));
+ }
}
diff --git a/src-tauri/src/tablet_input.rs b/src-tauri/src/tablet_input.rs
new file mode 100644
index 0000000..6d42691
--- /dev/null
+++ b/src-tauri/src/tablet_input.rs
@@ -0,0 +1,1103 @@
+use serde::Serialize;
+use tauri::ipc::{Channel, InvokeResponseBody};
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TabletStatus {
+ pub active: bool,
+ pub backend: String, // "wintab" | "windows-ink" | "none"
+ pub wintab_available: bool,
+ pub windows_ink_available: bool,
+ pub device_name: Option<String>,
+ pub max_pressure: u32,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct TabletSample {
+ pub client_x: f32,
+ pub client_y: f32,
+ pub pressure: f32,
+ pub tilt_x: f32,
+ pub tilt_y: f32,
+ pub twist: f32,
+ pub timestamp_ms: f64,
+ pub buttons: u16,
+ pub phase: u8, // 0=hover, 1=down, 2=move/drag, 3=up, 4=leave
+ pub backend: u8, // 1=wintab, 2=windows-ink
+}
+
+pub const SAMPLE_WIRE_BYTES: usize = 36;
+
+/// Packs a slice of TabletSamples into a raw little-endian binary frame:
+/// `[count: u32 LE][sample_0: 36 bytes]...[sample_N-1: 36 bytes]`
+pub fn pack_tablet_samples(samples: &[TabletSample]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(4 + samples.len() * SAMPLE_WIRE_BYTES);
+ out.extend_from_slice(&(samples.len() as u32).to_le_bytes());
+ for s in samples {
+ out.extend_from_slice(&s.client_x.to_le_bytes());
+ out.extend_from_slice(&s.client_y.to_le_bytes());
+ out.extend_from_slice(&s.pressure.to_le_bytes());
+ out.extend_from_slice(&s.tilt_x.to_le_bytes());
+ out.extend_from_slice(&s.tilt_y.to_le_bytes());
+ out.extend_from_slice(&s.twist.to_le_bytes());
+ out.extend_from_slice(&s.timestamp_ms.to_le_bytes());
+ out.extend_from_slice(&s.buttons.to_le_bytes());
+ out.push(s.phase);
+ out.push(s.backend);
+ }
+ out
+}
+
+#[cfg(target_os = "windows")]
+mod win_impl {
+ use super::*;
+ use std::ffi::c_void;
+ use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
+ use std::sync::{LazyLock, Mutex};
+ use std::thread::JoinHandle;
+ use windows_sys::Win32::Foundation::{FreeLibrary, BOOL, HWND, LPARAM, LRESULT, POINT, WPARAM};
+ use windows_sys::Win32::Graphics::Gdi::ScreenToClient;
+ use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
+ use windows_sys::Win32::System::Performance::{
+ QueryPerformanceCounter, QueryPerformanceFrequency,
+ };
+ use windows_sys::Win32::System::Threading::{
+ GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,
+ };
+ use windows_sys::Win32::UI::HiDpi::GetDpiForWindow;
+ use windows_sys::Win32::UI::Input::Pointer::{
+ GetPointerPenInfoHistory, GetPointerType, POINTER_FLAG_FIRSTBUTTON,
+ POINTER_FLAG_INCONTACT, POINTER_FLAG_SECONDBUTTON, POINTER_PEN_INFO,
+ };
+
+ const PEN_FLAG_BARREL: u32 = 0x0000_0001;
+ const PEN_FLAG_INVERTED: u32 = 0x0000_0002;
+ const PEN_FLAG_ERASER: u32 = 0x0000_0004;
+ const PEN_MASK_PRESSURE: u32 = 0x0000_0001;
+ const PEN_MASK_ROTATION: u32 = 0x0000_0002;
+ const PEN_MASK_TILT_X: u32 = 0x0000_0004;
+ const PEN_MASK_TILT_Y: u32 = 0x0000_0008;
+ use windows_sys::Win32::UI::Shell::{
+ DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass,
+ };
+ use windows_sys::Win32::UI::WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, EnumChildWindows,
+ GetForegroundWindow, GetMessageW, GetSystemMetrics, PostThreadMessageW, RegisterClassW,
+ TranslateMessage, HWND_MESSAGE, MSG, PT_PEN, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN,
+ SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, WM_POINTERDOWN, WM_POINTERENTER, WM_POINTERLEAVE,
+ WM_POINTERUP, WM_POINTERUPDATE, WM_QUIT, WNDCLASSW,
+ };
+
+ // --- WinTab ABI constants & types ---
+ const WTI_INTERFACE: u32 = 1;
+ const IFC_WINTABID: u32 = 1;
+ const WTI_DEFSYSCTX: u32 = 4;
+ const WTI_DEVICES: u32 = 100;
+ const DVC_NAME: u32 = 1;
+ const DVC_NPRESSURE: u32 = 15;
+ const DVC_ORIENTATION: u32 = 17;
+
+ const CXO_SYSTEM: u32 = 0x0001;
+ const CXO_PEN: u32 = 0x0002;
+ const CXO_MESSAGES: u32 = 0x0004;
+
+ const PK_STATUS: u32 = 0x0002;
+ const PK_TIME: u32 = 0x0004;
+ const PK_CURSOR: u32 = 0x0020;
+ const PK_BUTTONS: u32 = 0x0040;
+ const PK_X: u32 = 0x0080;
+ const PK_Y: u32 = 0x0100;
+ const PK_NORMAL_PRESSURE: u32 = 0x0400;
+ const PK_ORIENTATION: u32 = 0x1000;
+
+ const PACKET_DATA_MASK: u32 = PK_STATUS
+ | PK_TIME
+ | PK_CURSOR
+ | PK_BUTTONS
+ | PK_X
+ | PK_Y
+ | PK_NORMAL_PRESSURE
+ | PK_ORIENTATION;
+
+ const TPS_PROXIMITY: u32 = 0x0001;
+ const TPS_INVERT: u32 = 0x0010;
+ const WT_PACKET: u32 = 0x7FF0;
+ const WT_PROXIMITY: u32 = 0x7FF5;
+
+ type HCTX = *mut c_void;
+
+ #[repr(C)]
+ #[derive(Clone, Copy)]
+ struct Axis {
+ ax_min: i32,
+ ax_max: i32,
+ ax_units: u32,
+ ax_resolution: u32,
+ }
+
+ #[repr(C)]
+ #[derive(Clone, Copy)]
+ struct Orientation {
+ or_azimuth: i32,
+ or_altitude: i32,
+ or_twist: i32,
+ }
+
+ #[repr(C)]
+ #[derive(Clone, Copy)]
+ struct LogContextW {
+ lc_name: [u16; 40],
+ lc_options: u32,
+ lc_status: u32,
+ lc_locks: u32,
+ lc_msg_base: u32,
+ lc_device: u32,
+ lc_pkt_rate: u32,
+ lc_pkt_data: u32,
+ lc_pkt_mode: u32,
+ lc_move_mask: u32,
+ lc_btn_dn_mask: u32,
+ lc_btn_up_mask: u32,
+ lc_in_org_x: i32,
+ lc_in_org_y: i32,
+ lc_in_org_z: i32,
+ lc_in_ext_x: i32,
+ lc_in_ext_y: i32,
+ lc_in_ext_z: i32,
+ lc_out_org_x: i32,
+ lc_out_org_y: i32,
+ lc_out_org_z: i32,
+ lc_out_ext_x: i32,
+ lc_out_ext_y: i32,
+ lc_out_ext_z: i32,
+ lc_sens_x: u32,
+ lc_sens_y: u32,
+ lc_sens_z: u32,
+ lc_sys_mode: i32,
+ lc_sys_org_x: i32,
+ lc_sys_org_y: i32,
+ lc_sys_ext_x: i32,
+ lc_sys_ext_y: i32,
+ lc_sys_sens_x: u32,
+ lc_sys_sens_y: u32,
+ }
+
+ #[repr(C)]
+ #[derive(Clone, Copy)]
+ struct WtPacket {
+ pk_status: u32,
+ pk_time: u32,
+ pk_cursor: u32,
+ pk_buttons: u32,
+ pk_x: i32,
+ pk_y: i32,
+ pk_normal_pressure: u32,
+ pk_orientation: Orientation,
+ }
+
+ type FnWTInfoW = unsafe extern "system" fn(u32, u32, *mut c_void) -> u32;
+ type FnWTOpenW = unsafe extern "system" fn(HWND, *mut LogContextW, BOOL) -> HCTX;
+ type FnWTClose = unsafe extern "system" fn(HCTX) -> BOOL;
+ type FnWTPacketsGet = unsafe extern "system" fn(HCTX, i32, *mut c_void) -> i32;
+ type FnWTOverlap = unsafe extern "system" fn(HCTX, BOOL) -> BOOL;
+ type FnWTQueueSizeSet = unsafe extern "system" fn(HCTX, i32) -> BOOL;
+
+ struct WintabLib {
+ module: *mut c_void,
+ wt_info: FnWTInfoW,
+ wt_open: FnWTOpenW,
+ wt_close: FnWTClose,
+ wt_packets_get: FnWTPacketsGet,
+ wt_overlap: Option<FnWTOverlap>,
+ wt_queue_size_set: Option<FnWTQueueSizeSet>,
+ }
+
+ unsafe impl Send for WintabLib {}
+ unsafe impl Sync for WintabLib {}
+
+ impl WintabLib {
+ unsafe fn load() -> Option<Self> {
+ let wide: Vec<u16> = "wintab32.dll\0".encode_utf16().collect();
+ let module = LoadLibraryW(wide.as_ptr());
+ if module.is_null() {
+ return None;
+ }
+ let wt_info = GetProcAddress(module, b"WTInfoW\0".as_ptr())?;
+ let wt_open = GetProcAddress(module, b"WTOpenW\0".as_ptr())?;
+ let wt_close = GetProcAddress(module, b"WTClose\0".as_ptr())?;
+ let wt_packets_get = GetProcAddress(module, b"WTPacketsGet\0".as_ptr())?;
+ let wt_overlap = GetProcAddress(module, b"WTOverlap\0".as_ptr());
+ let wt_queue_size_set = GetProcAddress(module, b"WTQueueSizeSet\0".as_ptr());
+
+ Some(Self {
+ module,
+ wt_info: std::mem::transmute(wt_info),
+ wt_open: std::mem::transmute(wt_open),
+ wt_close: std::mem::transmute(wt_close),
+ wt_packets_get: std::mem::transmute(wt_packets_get),
+ wt_overlap: wt_overlap.map(|f| std::mem::transmute(f)),
+ wt_queue_size_set: wt_queue_size_set.map(|f| std::mem::transmute(f)),
+ })
+ }
+ }
+
+ impl Drop for WintabLib {
+ fn drop(&mut self) {
+ if !self.module.is_null() {
+ unsafe {
+ FreeLibrary(self.module);
+ }
+ }
+ }
+ }
+
+ fn qpc_now_ms() -> f64 {
+ static FREQ: LazyLock<f64> = LazyLock::new(|| unsafe {
+ let mut f = 0i64;
+ QueryPerformanceFrequency(&mut f);
+ if f > 0 {
+ f as f64 / 1000.0
+ } else {
+ 1.0
+ }
+ });
+ unsafe {
+ let mut now = 0i64;
+ QueryPerformanceCounter(&mut now);
+ (now as f64) / *FREQ
+ }
+ }
+
+ fn screen_to_css_client(main_hwnd: HWND, sx: i32, sy: i32) -> (f32, f32) {
+ unsafe {
+ let mut pt = POINT { x: sx, y: sy };
+ ScreenToClient(main_hwnd, &mut pt);
+ let dpi = GetDpiForWindow(main_hwnd);
+ let scale = if dpi > 0 { (dpi as f32) / 96.0 } else { 1.0 };
+ (pt.x as f32 / scale, pt.y as f32 / scale)
+ }
+ }
+
+ fn wintab_orientation_to_tilt(
+ ori: Orientation,
+ az_max: i32,
+ alt_max: i32,
+ twist_max: i32,
+ ) -> (f32, f32, f32) {
+ let mut tilt_x = 0.0f32;
+ let mut tilt_y = 0.0f32;
+ if az_max > 0 && alt_max > 0 {
+ let az = (ori.or_azimuth as f64 / az_max as f64) * std::f64::consts::TAU;
+ let alt = (ori.or_altitude.abs() as f64 / alt_max as f64)
+ * std::f64::consts::FRAC_PI_2;
+ let sin_alt = alt.sin().max(1e-5);
+ let cos_alt = alt.cos();
+ tilt_x = (az.sin() * cos_alt).atan2(sin_alt).to_degrees() as f32;
+ tilt_y = (-az.cos() * cos_alt).atan2(sin_alt).to_degrees() as f32;
+ }
+ let twist = if twist_max > 0 {
+ ((ori.or_twist as f64 / twist_max as f64) * 360.0).rem_euclid(360.0) as f32
+ } else {
+ 0.0
+ };
+ (tilt_x.clamp(-90.0, 90.0), tilt_y.clamp(-90.0, 90.0), twist)
+ }
+
+ // --- Shared active channel & state ---
+ struct ActiveSink {
+ channel: Channel<InvokeResponseBody>,
+ }
+
+ static ACTIVE_SINK: LazyLock<Mutex<Option<ActiveSink>>> = LazyLock::new(|| Mutex::new(None));
+ static SUBCLASSED_HWNDS: LazyLock<Mutex<Vec<isize>>> = LazyLock::new(|| Mutex::new(Vec::new()));
+ static WINTAB_RUNNING: AtomicBool = AtomicBool::new(false);
+ static WINTAB_THREAD_ID: AtomicIsize = AtomicIsize::new(0);
+ static WINTAB_THREAD: LazyLock<Mutex<Option<JoinHandle<()>>>> =
+ LazyLock::new(|| Mutex::new(None));
+ static CURRENT_STATUS: LazyLock<Mutex<TabletStatus>> = LazyLock::new(|| {
+ Mutex::new(TabletStatus {
+ active: false,
+ backend: "none".to_string(),
+ wintab_available: false,
+ windows_ink_available: true,
+ device_name: None,
+ max_pressure: 1024,
+ })
+ });
+
+ const SUBCLASS_ID: usize = 0x494E_4B54; // "INKT"
+
+ fn send_samples(samples: &[TabletSample]) {
+ if samples.is_empty() {
+ return;
+ }
+ let packed = pack_tablet_samples(samples);
+ if let Ok(guard) = ACTIVE_SINK.lock() {
+ if let Some(sink) = guard.as_ref() {
+ let _ = sink.channel.send(InvokeResponseBody::Raw(packed));
+ }
+ }
+ }
+
+ // --- Windows Ink WM_POINTER subclass callback ---
+ unsafe extern "system" fn ink_subclass_proc(
+ hwnd: HWND,
+ msg: u32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+ _uid_subclass: usize,
+ dw_ref_data: usize,
+ ) -> LRESULT {
+ let _ = std::panic::catch_unwind(|| {
+ let phase = match msg {
+ WM_POINTERDOWN => Some(1u8),
+ WM_POINTERUPDATE => Some(2u8),
+ WM_POINTERUP => Some(3u8),
+ WM_POINTERENTER => Some(0u8),
+ WM_POINTERLEAVE => Some(4u8),
+ _ => None,
+ };
+
+ if let Some(phase_code) = phase {
+ let pointer_id = (wparam & 0xFFFF) as u32;
+ let mut ptype = 0i32;
+ if GetPointerType(pointer_id, &mut ptype) != 0 && ptype == PT_PEN {
+ let main_hwnd = dw_ref_data as HWND;
+ let mut count: u32 = 64;
+ let mut history: [POINTER_PEN_INFO; 64] = std::mem::zeroed();
+ if GetPointerPenInfoHistory(pointer_id, &mut count, history.as_mut_ptr()) != 0
+ && count > 0
+ {
+ let n = (count as usize).min(64);
+ let ts_now = qpc_now_ms();
+ let mut samples = Vec::with_capacity(n);
+
+ // History is reverse chronological (0 = newest), emit oldest -> newest
+ for idx in (0..n).rev() {
+ let info = &history[idx];
+ let pinfo = &info.pointerInfo;
+ let (cx, cy) = screen_to_css_client(
+ main_hwnd,
+ pinfo.ptPixelLocationRaw.x,
+ pinfo.ptPixelLocationRaw.y,
+ );
+
+ let in_contact = (pinfo.pointerFlags & POINTER_FLAG_INCONTACT) != 0;
+ let pressure = if (info.penMask & PEN_MASK_PRESSURE) != 0 {
+ (info.pressure as f32 / 1024.0).clamp(0.0, 1.0)
+ } else if in_contact {
+ 0.5
+ } else {
+ 0.0
+ };
+
+ let tilt_x = if (info.penMask & PEN_MASK_TILT_X) != 0 {
+ (info.tiltX as f32).clamp(-90.0, 90.0)
+ } else {
+ 0.0
+ };
+ let tilt_y = if (info.penMask & PEN_MASK_TILT_Y) != 0 {
+ (info.tiltY as f32).clamp(-90.0, 90.0)
+ } else {
+ 0.0
+ };
+ let twist = if (info.penMask & PEN_MASK_ROTATION) != 0 {
+ (info.rotation as f32).rem_euclid(360.0)
+ } else {
+ 0.0
+ };
+
+ let mut buttons: u16 = 0;
+ if in_contact || (pinfo.pointerFlags & POINTER_FLAG_FIRSTBUTTON) != 0 {
+ buttons |= 1;
+ }
+ if (info.penFlags & PEN_FLAG_BARREL) != 0
+ || (pinfo.pointerFlags & POINTER_FLAG_SECONDBUTTON) != 0
+ {
+ buttons |= 2;
+ }
+ if (info.penFlags & (PEN_FLAG_ERASER | PEN_FLAG_INVERTED)) != 0 {
+ buttons |= 8;
+ }
+
+ let sample_phase = if idx == 0 {
+ phase_code
+ } else if in_contact {
+ 2
+ } else {
+ 0
+ };
+
+ samples.push(TabletSample {
+ client_x: cx,
+ client_y: cy,
+ pressure,
+ tilt_x,
+ tilt_y,
+ twist,
+ timestamp_ms: ts_now,
+ buttons,
+ phase: sample_phase,
+ backend: 2,
+ });
+ }
+
+ send_samples(&samples);
+ }
+ }
+ }
+ });
+
+ DefSubclassProc(hwnd, msg, wparam, lparam)
+ }
+
+ unsafe extern "system" fn enum_child_install_subclass(hwnd: HWND, lparam: LPARAM) -> BOOL {
+ let main_hwnd = lparam as usize;
+ if SetWindowSubclass(hwnd, Some(ink_subclass_proc), SUBCLASS_ID, main_hwnd) != 0 {
+ if let Ok(mut list) = SUBCLASSED_HWNDS.lock() {
+ let raw = hwnd as isize;
+ if !list.contains(&raw) {
+ list.push(raw);
+ }
+ }
+ }
+ 1 // continue enumeration
+ }
+
+ fn install_windows_ink_hooks(main_hwnd: HWND) -> Result<(), String> {
+ uninstall_windows_ink_hooks();
+ unsafe {
+ let main_ref = main_hwnd as usize;
+ if SetWindowSubclass(main_hwnd, Some(ink_subclass_proc), SUBCLASS_ID, main_ref) != 0 {
+ if let Ok(mut list) = SUBCLASSED_HWNDS.lock() {
+ list.push(main_hwnd as isize);
+ }
+ }
+ // Also hook WebView2 child HWNDs (Chrome_WidgetWin_1 / Chrome_RenderWidgetHostHWND)
+ EnumChildWindows(main_hwnd, Some(enum_child_install_subclass), main_ref as LPARAM);
+ }
+ Ok(())
+ }
+
+ fn uninstall_windows_ink_hooks() {
+ let hwnds = {
+ let Ok(mut list) = SUBCLASSED_HWNDS.lock() else {
+ return;
+ };
+ std::mem::take(&mut *list)
+ };
+ for raw in hwnds {
+ unsafe {
+ RemoveWindowSubclass(raw as HWND, Some(ink_subclass_proc), SUBCLASS_ID);
+ }
+ }
+ }
+
+ // --- WinTab dedicated high-priority message-window thread ---
+ struct WintabRuntime {
+ lib: WintabLib,
+ hctx: HCTX,
+ main_hwnd: HWND,
+ max_pressure: u32,
+ az_max: i32,
+ alt_max: i32,
+ twist_max: i32,
+ out_org_x: i32,
+ out_org_y: i32,
+ out_ext_x: i32,
+ out_ext_y: i32,
+ sys_org_x: i32,
+ sys_org_y: i32,
+ sys_ext_x: i32,
+ sys_ext_y: i32,
+ was_down: bool,
+ }
+
+ thread_local! {
+ static WT_RT: std::cell::RefCell<Option<WintabRuntime>> = const { std::cell::RefCell::new(None) };
+ }
+
+ unsafe extern "system" fn wintab_wnd_proc(
+ hwnd: HWND,
+ msg: u32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+ ) -> LRESULT {
+ let _ = std::panic::catch_unwind(|| {
+ if msg == WT_PACKET {
+ WT_RT.with(|cell| {
+ let mut borrow = cell.borrow_mut();
+ let Some(rt) = borrow.as_mut() else { return };
+
+ // Keep WinTab context on top when our window is focused
+ if let Some(overlap) = rt.lib.wt_overlap {
+ let fg = GetForegroundWindow();
+ if fg == rt.main_hwnd {
+ overlap(rt.hctx, 1);
+ }
+ }
+
+ let mut buf: [WtPacket; 64] = std::mem::zeroed();
+ let n = (rt.lib.wt_packets_get)(rt.hctx, 64, buf.as_mut_ptr() as *mut c_void);
+ if n <= 0 {
+ return;
+ }
+
+ let ts_now = qpc_now_ms();
+ let mut samples = Vec::with_capacity(n as usize);
+ let denom_p = (rt.max_pressure.max(1)) as f32;
+
+ for pkt in &buf[..n as usize] {
+ // Map WinTab output space -> virtual screen pixels -> main HWND CSS pixels
+ let nx = if rt.out_ext_x != 0 {
+ (pkt.pk_x - rt.out_org_x) as f64 / (rt.out_ext_x as f64)
+ } else {
+ 0.0
+ };
+ let ny = if rt.out_ext_y != 0 {
+ (pkt.pk_y - rt.out_org_y) as f64 / (rt.out_ext_y as f64)
+ } else {
+ 0.0
+ };
+ let sx = rt.sys_org_x + (nx * rt.sys_ext_x as f64).round() as i32;
+ let sy = rt.sys_org_y + (ny * rt.sys_ext_y as f64).round() as i32;
+ let (cx, cy) = screen_to_css_client(rt.main_hwnd, sx, sy);
+
+ let pressure = (pkt.pk_normal_pressure as f32 / denom_p).clamp(0.0, 1.0);
+ let (tilt_x, tilt_y, twist) = wintab_orientation_to_tilt(
+ pkt.pk_orientation,
+ rt.az_max,
+ rt.alt_max,
+ rt.twist_max,
+ );
+
+ let tip_down = pressure > 0.001 || (pkt.pk_buttons & 1) != 0;
+ let mut buttons: u16 = 0;
+ if tip_down {
+ buttons |= 1;
+ }
+ if (pkt.pk_buttons & 2) != 0 {
+ buttons |= 2;
+ }
+ if (pkt.pk_buttons & 4) != 0 {
+ buttons |= 4;
+ }
+ if (pkt.pk_status & TPS_INVERT) != 0 {
+ buttons |= 8;
+ }
+
+ let phase = if (pkt.pk_status & TPS_PROXIMITY) != 0 {
+ rt.was_down = false;
+ 4
+ } else if tip_down && !rt.was_down {
+ rt.was_down = true;
+ 1
+ } else if tip_down && rt.was_down {
+ 2
+ } else if !tip_down && rt.was_down {
+ rt.was_down = false;
+ 3
+ } else {
+ 0
+ };
+
+ samples.push(TabletSample {
+ client_x: cx,
+ client_y: cy,
+ pressure,
+ tilt_x,
+ tilt_y,
+ twist,
+ timestamp_ms: ts_now,
+ buttons,
+ phase,
+ backend: 1,
+ });
+ }
+
+ send_samples(&samples);
+ });
+ } else if msg == WT_PROXIMITY {
+ let entering = (lparam & 0xFFFF) != 0;
+ if !entering {
+ WT_RT.with(|cell| {
+ if let Some(rt) = cell.borrow_mut().as_mut() {
+ rt.was_down = false;
+ }
+ });
+ send_samples(&[TabletSample {
+ client_x: 0.0,
+ client_y: 0.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: qpc_now_ms(),
+ buttons: 0,
+ phase: 4,
+ backend: 1,
+ }]);
+ }
+ }
+ });
+ DefWindowProcW(hwnd, msg, wparam, lparam)
+ }
+
+ pub fn probe_wintab() -> (bool, Option<String>, u32) {
+ unsafe {
+ let Some(lib) = WintabLib::load() else {
+ return (false, None, 1024);
+ };
+ let id_len = (lib.wt_info)(WTI_INTERFACE, IFC_WINTABID, std::ptr::null_mut());
+ if id_len == 0 {
+ return (false, None, 1024);
+ }
+ let mut name_buf = [0u16; 128];
+ let name_bytes = (lib.wt_info)(
+ WTI_DEVICES,
+ DVC_NAME,
+ name_buf.as_mut_ptr() as *mut c_void,
+ );
+ let device_name = if name_bytes > 0 {
+ let chars = (name_bytes as usize / 2).min(name_buf.len());
+ let s = String::from_utf16_lossy(&name_buf[..chars])
+ .trim_end_matches('\0')
+ .to_string();
+ if s.is_empty() { None } else { Some(s) }
+ } else {
+ Some("WinTab Digitizer".to_string())
+ };
+
+ let mut p_axis: Axis = std::mem::zeroed();
+ let max_p = if (lib.wt_info)(
+ WTI_DEVICES,
+ DVC_NPRESSURE,
+ &mut p_axis as *mut Axis as *mut c_void,
+ ) > 0
+ && p_axis.ax_max > 0
+ {
+ p_axis.ax_max as u32
+ } else {
+ 1024
+ };
+ (true, device_name, max_p)
+ }
+ }
+
+ fn start_wintab_thread(main_hwnd: isize) -> Result<(Option<String>, u32), String> {
+ stop_wintab_thread();
+ let (tx, rx) = std::sync::mpsc::channel::<Result<(Option<String>, u32), String>>();
+ WINTAB_RUNNING.store(true, Ordering::SeqCst);
+
+ let handle = std::thread::Builder::new()
+ .name("inkstudio-wintab".to_string())
+ .spawn(move || unsafe {
+ SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
+ let tid = windows_sys::Win32::System::Threading::GetCurrentThreadId();
+ WINTAB_THREAD_ID.store(tid as isize, Ordering::SeqCst);
+
+ let Some(lib) = WintabLib::load() else {
+ let _ = tx.send(Err("wintab32.dll not available".to_string()));
+ WINTAB_RUNNING.store(false, Ordering::SeqCst);
+ return;
+ };
+
+ let mut lc: LogContextW = std::mem::zeroed();
+ if (lib.wt_info)(
+ WTI_DEFSYSCTX,
+ 0,
+ &mut lc as *mut LogContextW as *mut c_void,
+ ) == 0
+ {
+ let _ = tx.send(Err("WinTab driver reported no default system context".to_string()));
+ WINTAB_RUNNING.store(false, Ordering::SeqCst);
+ return;
+ }
+
+ let mut name_buf = [0u16; 128];
+ let nbytes = (lib.wt_info)(
+ WTI_DEVICES,
+ DVC_NAME,
+ name_buf.as_mut_ptr() as *mut c_void,
+ );
+ let device_name = if nbytes > 0 {
+ let chars = (nbytes as usize / 2).min(name_buf.len());
+ let s = String::from_utf16_lossy(&name_buf[..chars])
+ .trim_end_matches('\0')
+ .to_string();
+ if s.is_empty() { None } else { Some(s) }
+ } else {
+ Some("WinTab Digitizer".to_string())
+ };
+
+ let mut p_axis: Axis = std::mem::zeroed();
+ let max_pressure = if (lib.wt_info)(
+ WTI_DEVICES,
+ DVC_NPRESSURE,
+ &mut p_axis as *mut Axis as *mut c_void,
+ ) > 0
+ && p_axis.ax_max > 0
+ {
+ p_axis.ax_max as u32
+ } else {
+ 1024
+ };
+
+ let mut ori_axes: [Axis; 3] = std::mem::zeroed();
+ let has_ori = (lib.wt_info)(
+ WTI_DEVICES,
+ DVC_ORIENTATION,
+ ori_axes.as_mut_ptr() as *mut c_void,
+ ) > 0;
+ let (az_max, alt_max, twist_max) = if has_ori {
+ (ori_axes[0].ax_max, ori_axes[1].ax_max, ori_axes[2].ax_max)
+ } else {
+ (0, 0, 0)
+ };
+
+ // Configure virtual desktop mapping
+ let vx = GetSystemMetrics(SM_XVIRTUALSCREEN);
+ let vy = GetSystemMetrics(SM_YVIRTUALSCREEN);
+ let vw = GetSystemMetrics(SM_CXVIRTUALSCREEN).max(1);
+ let vh = GetSystemMetrics(SM_CYVIRTUALSCREEN).max(1);
+
+ lc.lc_options |= CXO_SYSTEM | CXO_PEN | CXO_MESSAGES;
+ lc.lc_pkt_data = PACKET_DATA_MASK;
+ lc.lc_pkt_mode = 0;
+ lc.lc_move_mask = PACKET_DATA_MASK;
+ lc.lc_btn_dn_mask = u32::MAX;
+ lc.lc_btn_up_mask = u32::MAX;
+ lc.lc_out_org_x = 0;
+ lc.lc_out_org_y = 0;
+ lc.lc_out_ext_x = vw;
+ lc.lc_out_ext_y = -vh; // top-down Y matching Win32 screen coords
+ lc.lc_sys_org_x = vx;
+ lc.lc_sys_org_y = vy;
+ lc.lc_sys_ext_x = vw;
+ lc.lc_sys_ext_y = vh;
+
+ // Register lightweight message-only window class
+ let class_name: Vec<u16> = "InkStudioWinTabSink\0".encode_utf16().collect();
+ let wc = WNDCLASSW {
+ style: 0,
+ lpfnWndProc: Some(wintab_wnd_proc),
+ cbClsExtra: 0,
+ cbWndExtra: 0,
+ hInstance: std::ptr::null_mut(),
+ hIcon: std::ptr::null_mut(),
+ hCursor: std::ptr::null_mut(),
+ hbrBackground: std::ptr::null_mut(),
+ lpszMenuName: std::ptr::null(),
+ lpszClassName: class_name.as_ptr(),
+ };
+ RegisterClassW(&wc);
+
+ let msg_hwnd = CreateWindowExW(
+ 0,
+ class_name.as_ptr(),
+ class_name.as_ptr(),
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ HWND_MESSAGE,
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ std::ptr::null(),
+ );
+ if msg_hwnd.is_null() {
+ let _ = tx.send(Err("Failed to create WinTab message window".to_string()));
+ WINTAB_RUNNING.store(false, Ordering::SeqCst);
+ return;
+ }
+
+ let hctx = (lib.wt_open)(msg_hwnd, &mut lc, 1);
+ if hctx.is_null() {
+ DestroyWindow(msg_hwnd);
+ let _ = tx.send(Err("WTOpenW failed to open WinTab context".to_string()));
+ WINTAB_RUNNING.store(false, Ordering::SeqCst);
+ return;
+ }
+
+ if let Some(qset) = lib.wt_queue_size_set {
+ qset(hctx, 128);
+ }
+
+ WT_RT.with(|cell| {
+ *cell.borrow_mut() = Some(WintabRuntime {
+ lib,
+ hctx,
+ main_hwnd: main_hwnd as HWND,
+ max_pressure,
+ az_max,
+ alt_max,
+ twist_max,
+ out_org_x: lc.lc_out_org_x,
+ out_org_y: lc.lc_out_org_y,
+ out_ext_x: lc.lc_out_ext_x,
+ out_ext_y: lc.lc_out_ext_y,
+ sys_org_x: lc.lc_sys_org_x,
+ sys_org_y: lc.lc_sys_org_y,
+ sys_ext_x: lc.lc_sys_ext_x,
+ sys_ext_y: lc.lc_sys_ext_y,
+ was_down: false,
+ });
+ });
+
+ let _ = tx.send(Ok((device_name, max_pressure)));
+
+ let mut msg: MSG = std::mem::zeroed();
+ while WINTAB_RUNNING.load(Ordering::Relaxed)
+ && GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0
+ {
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+
+ WT_RT.with(|cell| {
+ if let Some(rt) = cell.borrow_mut().take() {
+ (rt.lib.wt_close)(rt.hctx);
+ }
+ });
+ DestroyWindow(msg_hwnd);
+ WINTAB_THREAD_ID.store(0, Ordering::SeqCst);
+ WINTAB_RUNNING.store(false, Ordering::SeqCst);
+ })
+ .map_err(|e| format!("Failed to spawn WinTab thread: {}", e))?;
+
+ let init_res = rx
+ .recv_timeout(std::time::Duration::from_secs(2))
+ .map_err(|_| "WinTab initialization timed out".to_string())?;
+
+ match init_res {
+ Ok(info) => {
+ if let Ok(mut guard) = WINTAB_THREAD.lock() {
+ *guard = Some(handle);
+ }
+ Ok(info)
+ }
+ Err(e) => {
+ let _ = handle.join();
+ Err(e)
+ }
+ }
+ }
+
+ fn stop_wintab_thread() {
+ WINTAB_RUNNING.store(false, Ordering::SeqCst);
+ let tid = WINTAB_THREAD_ID.load(Ordering::SeqCst);
+ if tid != 0 {
+ unsafe {
+ PostThreadMessageW(tid as u32, WM_QUIT, 0, 0);
+ }
+ }
+ if let Ok(mut guard) = WINTAB_THREAD.lock() {
+ if let Some(handle) = guard.take() {
+ let _ = handle.join();
+ }
+ }
+ }
+
+ pub fn start(
+ window: &tauri::WebviewWindow,
+ mode: &str,
+ channel: Channel<InvokeResponseBody>,
+ ) -> Result<TabletStatus, String> {
+ stop();
+
+ let hwnd = window
+ .hwnd()
+ .map_err(|e| format!("Failed to acquire window HWND: {}", e))?;
+ let main_hwnd_raw = hwnd.0 as isize;
+
+ {
+ let mut sink = ACTIVE_SINK
+ .lock()
+ .map_err(|_| "Failed to lock tablet sink".to_string())?;
+ *sink = Some(ActiveSink { channel });
+ }
+
+ let (wt_avail, _, _) = probe_wintab();
+
+ let (chosen_backend, device_name, max_pressure) = match mode {
+ "wintab" => {
+ let (dev, mp) = start_wintab_thread(main_hwnd_raw)?;
+ ("wintab".to_string(), dev, mp)
+ }
+ "windows-ink" => {
+ install_windows_ink_hooks(hwnd.0 as HWND)?;
+ (
+ "windows-ink".to_string(),
+ Some("Windows Ink Digitizer".to_string()),
+ 1024,
+ )
+ }
+ "off" | "pointer-events" => {
+ stop();
+ return Ok(get_status());
+ }
+ _ => {
+ // "auto": prefer WinTab if driver + tablet context opens, else Windows Ink WM_POINTER
+ if wt_avail {
+ match start_wintab_thread(main_hwnd_raw) {
+ Ok((dev, mp)) => ("wintab".to_string(), dev, mp),
+ Err(_) => {
+ install_windows_ink_hooks(hwnd.0 as HWND)?;
+ (
+ "windows-ink".to_string(),
+ Some("Windows Ink Digitizer".to_string()),
+ 1024,
+ )
+ }
+ }
+ } else {
+ install_windows_ink_hooks(hwnd.0 as HWND)?;
+ (
+ "windows-ink".to_string(),
+ Some("Windows Ink Digitizer".to_string()),
+ 1024,
+ )
+ }
+ }
+ };
+
+ let status = TabletStatus {
+ active: true,
+ backend: chosen_backend,
+ wintab_available: wt_avail,
+ windows_ink_available: true,
+ device_name,
+ max_pressure,
+ };
+ if let Ok(mut st) = CURRENT_STATUS.lock() {
+ *st = status.clone();
+ }
+ Ok(status)
+ }
+
+ pub fn stop() {
+ stop_wintab_thread();
+ uninstall_windows_ink_hooks();
+ if let Ok(mut sink) = ACTIVE_SINK.lock() {
+ *sink = None;
+ }
+ if let Ok(mut st) = CURRENT_STATUS.lock() {
+ st.active = false;
+ st.backend = "none".to_string();
+ }
+ }
+
+ pub fn get_status() -> TabletStatus {
+ if let Ok(st) = CURRENT_STATUS.lock() {
+ if st.active {
+ return st.clone();
+ }
+ }
+ let (wt_avail, dev, mp) = probe_wintab();
+ TabletStatus {
+ active: false,
+ backend: "none".to_string(),
+ wintab_available: wt_avail,
+ windows_ink_available: true,
+ device_name: dev,
+ max_pressure: mp,
+ }
+ }
+}
+
+#[cfg(not(target_os = "windows"))]
+mod fallback_impl {
+ use super::*;
+
+ pub fn start(
+ _window: &tauri::WebviewWindow,
+ _mode: &str,
+ _channel: Channel<InvokeResponseBody>,
+ ) -> Result<TabletStatus, String> {
+ Ok(get_status())
+ }
+
+ pub fn stop() {}
+
+ pub fn get_status() -> TabletStatus {
+ TabletStatus {
+ active: false,
+ backend: "none".to_string(),
+ wintab_available: false,
+ windows_ink_available: false,
+ device_name: None,
+ max_pressure: 1024,
+ }
+ }
+}
+
+pub fn start_tablet_input(
+ window: &tauri::WebviewWindow,
+ mode: &str,
+ channel: Channel<InvokeResponseBody>,
+) -> Result<TabletStatus, String> {
+ #[cfg(target_os = "windows")]
+ {
+ win_impl::start(window, mode, channel)
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ fallback_impl::start(window, mode, channel)
+ }
+}
+
+pub fn stop_tablet_input() {
+ #[cfg(target_os = "windows")]
+ win_impl::stop();
+ #[cfg(not(target_os = "windows"))]
+ fallback_impl::stop();
+}
+
+pub fn get_tablet_status() -> TabletStatus {
+ #[cfg(target_os = "windows")]
+ {
+ win_impl::get_status()
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ fallback_impl::get_status()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_pack_tablet_samples_binary_layout() {
+ let s = TabletSample {
+ client_x: 123.5,
+ client_y: 456.25,
+ pressure: 0.75,
+ tilt_x: -15.0,
+ tilt_y: 30.0,
+ twist: 90.0,
+ timestamp_ms: 123456.789,
+ buttons: 9,
+ phase: 2,
+ backend: 1,
+ };
+ let buf = pack_tablet_samples(&[s]);
+ assert_eq!(buf.len(), 4 + SAMPLE_WIRE_BYTES);
+ assert_eq!(u32::from_le_bytes(buf[0..4].try_into().unwrap()), 1);
+ assert_eq!(f32::from_le_bytes(buf[4..8].try_into().unwrap()), 123.5);
+ assert_eq!(f32::from_le_bytes(buf[8..12].try_into().unwrap()), 456.25);
+ assert_eq!(f32::from_le_bytes(buf[12..16].try_into().unwrap()), 0.75);
+ assert_eq!(f32::from_le_bytes(buf[16..20].try_into().unwrap()), -15.0);
+ assert_eq!(f32::from_le_bytes(buf[20..24].try_into().unwrap()), 30.0);
+ assert_eq!(f32::from_le_bytes(buf[24..28].try_into().unwrap()), 90.0);
+ assert_eq!(
+ f64::from_le_bytes(buf[28..36].try_into().unwrap()),
+ 123456.789
+ );
+ assert_eq!(u16::from_le_bytes(buf[36..38].try_into().unwrap()), 9);
+ assert_eq!(buf[38], 2);
+ assert_eq!(buf[39], 1);
+ }
+}
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 7429202..3d60b5e 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -38,7 +38,7 @@
"licenseFile": "../LICENSE",
"fileAssociations": [
{
- "ext": ["sora", "ink"],
+ "ext": ["ink"],
"name": "Ink Studio Project",
"description": "Ink Studio Project File",
"role": "Editor"
diff --git a/src/App.tsx b/src/App.tsx
index 5ba8360..d2aa8fd 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -9,7 +9,7 @@ import { screenToCanvas } from './utils/canvasUtils';
import { createDefaultPageFrame } from './utils/frameEngine';
import { AutoAction, AutoActionExecutionContext, executeAutoAction } from './utils/autoActionEngine';
import { globalTimelapseManager } from './utils/timelapseEngine';
-import { globalTileGrid, parseTileKey } from './utils/tileEngine';
+import { globalTileGrid, TileSnapshotEntry } from './utils/tileEngine';
import { documentStore } from './utils/documentStore';
import { multiplayerService } from './services/multiplayerService';
import { updaterService } from './services/updaterService';
@@ -66,7 +66,7 @@ export function App() {
const strokeCanvasRef = draftCanvasRef;
const selectiveUndoRef = useRef<(peerId?: string | number, strokeId?: string) => unknown>(() => {});
const pushHistoryStepRef = useRef<PushHistoryStepFn | null>(null);
- const getActiveCanvasRef = useRef<() => HTMLCanvasElement | null>(() => null);
+ const resetHistoryRef = useRef<((targetDocumentId?: string) => void) | null>(null);
const flushPendingHistoryTasksRef = useRef<() => void>(() => {});
const showToast = uiStoreActions.showToast;
@@ -115,10 +115,8 @@ export function App() {
collapsed: false,
parentId: null,
};
- const canvas = document.createElement('canvas');
- canvas.width = dimensions.width;
- canvas.height = dimensions.height;
- layerMgr.registerLayerCanvas(newLayerId, canvas);
+ activeTileGrid.setLayerFormat(newLayerId, 'color-32bit');
+ activeTileGrid.markLayerIngested(newLayerId);
layerMgr.setLayers((prev) => [newCelLayer, ...prev]);
layerMgr.setActiveLayerId(newLayerId);
@@ -127,7 +125,7 @@ export function App() {
handleUpdateAnimationTimeline(setFrameCel(currentTl, frameIndex, newLayerId));
showToast(`Cel added for frame ${frameIndex + 1}`);
},
- [activeAnimationTimeline, dimensions, handleUpdateAnimationTimeline, layerMgr, showToast]
+ [activeAnimationTimeline, activeTileGrid, handleUpdateAnimationTimeline, layerMgr, showToast]
);
const handleDeleteAnimationCel = useCallback(
@@ -146,6 +144,10 @@ export function App() {
activeDocumentId,
});
+ const stableResetHistory = useCallback((targetDocumentId?: string) => {
+ resetHistoryRef.current?.(targetDocumentId);
+ }, []);
+
// Multiplayer & Collaborative Layer Sync
const collab = useCollabSync({
hasOpenDocument,
@@ -154,19 +156,27 @@ export function App() {
layers: layerMgr.layers,
activeLayerId: layerMgr.activeLayerId,
selectedLayerIds: layerMgr.selectedLayerIds,
- layerCanvasesRef: layerMgr.layerCanvasesRef,
- materializeLayerCanvas: layerMgr.materializeLayerCanvas,
+ perspectiveRuler,
+ straightRuler,
+ animationTimeline: activeAnimationTimeline,
pushHistoryStepRef,
selectiveUndoRef,
resetZoomAndCenter: nav.resetZoomAndCenter,
+ resetHistory: stableResetHistory,
+ setLayers: layerMgr.setLayers,
setActiveLayerId: layerMgr.setActiveLayerId,
+ toggleLock: layerMgr.toggleLock,
addLayer: layerMgr.addLayer,
addRemoteLayer: layerMgr.addRemoteLayer,
deleteLayer: layerMgr.deleteLayer,
deleteRemoteLayer: layerMgr.deleteRemoteLayer,
+ applyRemoteLayerUpdate: layerMgr.applyRemoteLayerUpdate,
+ applyRemoteLayerTree: layerMgr.applyRemoteLayerTree,
+ applyRemoteMaskData: layerMgr.applyRemoteMaskData,
deleteSelectedLayers: layerMgr.deleteSelectedLayers,
groupSelectedLayers: layerMgr.groupSelectedLayers,
syncRemoteDocument: layerMgr.syncRemoteDocument,
+ resizeCanvas: layerMgr.resizeCanvas,
renameLayer: layerMgr.renameLayer,
toggleVisibility: layerMgr.toggleVisibility,
setOpacity: layerMgr.setOpacity,
@@ -175,7 +185,6 @@ export function App() {
showToast,
});
- const stableGetActiveCanvas = useCallback(() => getActiveCanvasRef.current(), []);
const stableFlushPendingHistoryTasks = useCallback(
() => flushPendingHistoryTasksRef.current(),
[]
@@ -195,10 +204,6 @@ export function App() {
activeLayer: layerMgr.activeLayer,
activeLayerId: layerMgr.activeLayerId,
selectedLayerIds: layerMgr.selectedLayerIds,
- layerCanvasesRef: layerMgr.layerCanvasesRef,
- layerSourceCanvasesRef: layerMgr.layerSourceCanvasesRef,
- getActiveCanvas: stableGetActiveCanvas,
- materializeLayerCanvas: layerMgr.materializeLayerCanvas,
tileGrid: activeTileGrid,
flushPendingHistoryTasks: stableFlushPendingHistoryTasks,
updateLayerThumbnail: layerMgr.updateLayerThumbnail,
@@ -258,7 +263,13 @@ export function App() {
const drawing = useCanvasDrawing({
dimensions,
colorMode,
- disabled: !hasOpenDocument || nav.isSpaceDown || nav.isPanning || nav.isRotating || nav.isZoomDragging,
+ disabled:
+ !hasOpenDocument ||
+ nav.isSpaceDown ||
+ nav.isPanning ||
+ nav.isRotating ||
+ nav.isZoomDragging ||
+ ((collab.isConnected || collab.isReconnecting) && collab.myRole === 'viewer'),
viewportRef: nav.viewportRef,
pan: nav.pan,
zoom: nav.zoom,
@@ -269,13 +280,12 @@ export function App() {
activeLayerId: layerMgr.activeLayerId,
activeSessionId: activeDocumentId,
tileGrid: activeTileGrid,
- materializeLayerCanvas: layerMgr.materializeLayerCanvas,
- activeLayerLocked: layerMgr.activeLayer?.locked ?? false,
+ activeLayerLocked:
+ (layerMgr.activeLayer?.locked ?? false) ||
+ ((collab.isConnected || collab.isReconnecting) && !collab.canEditActiveLayer),
activeLayerVisible: layerMgr.activeLayer
? layerMgr.isLayerEffectivelyVisible(layerMgr.activeLayer)
: true,
- layerCanvasesRef: layerMgr.layerCanvasesRef,
- layerSourceCanvasesRef: layerMgr.layerSourceCanvasesRef,
layers: hasOpenDocument ? layerMgr.layers : [],
onUpdateLayerThumbnail: layerMgr.updateLayerThumbnail,
isMaskMode: activeEditTarget === 'mask',
@@ -294,7 +304,7 @@ export function App() {
selectiveUndoRef.current = drawing.selectiveUndo;
pushHistoryStepRef.current = drawing.pushHistoryStep;
- getActiveCanvasRef.current = drawing.getActiveCanvas;
+ resetHistoryRef.current = drawing.resetHistory;
flushPendingHistoryTasksRef.current = drawing.flushPendingHistoryTasks;
const handleUndo = useCallback(() => {
@@ -305,30 +315,12 @@ export function App() {
if (collab.isConnected && collab.myPeer.id) {
void drawing.selectiveUndo('local').then((undone) => {
if (!undone || !multiplayerService.isConnected()) return;
- if (undone.strokeId) {
- multiplayerService.sendSelectiveUndo(undone.strokeId);
- } else if (undone.tileDeltas && undone.tileDeltas.length > 0) {
+ if (undone.syncedRemotely) return;
+ if (undone.tileDeltas && undone.tileDeltas.length > 0) {
const grid = documentStore.getActiveTileGrid();
- for (const delta of undone.tileDeltas) {
- const { layerId, tileX, tileY } = parseTileKey(delta.key);
- const tile = grid.getTile(layerId, tileX, tileY, 0);
- if (tile) {
- multiplayerService.sendTileDelta(layerId, tile);
- } else {
- multiplayerService.sendTileDelta(layerId, {
- layerId,
- tileX,
- tileY,
- format: delta.format,
- data: null,
- dirty: true,
- version: 0,
- isPagedToDisk: false,
- lastAccessTimestamp: Date.now(),
- lod: 0,
- });
- }
- }
+ multiplayerService.sendTileDeltas(undone.tileDeltas, grid, { force: true });
+ } else if (undone.strokeId) {
+ multiplayerService.sendSelectiveUndo(undone.strokeId);
}
});
} else {
@@ -364,20 +356,16 @@ export function App() {
activeLayerId: layerMgr.activeLayerId,
selectedLayerIds: layerMgr.selectedLayerIds,
selection: selectionTools.selection,
- layerCanvasesRef: layerMgr.layerCanvasesRef,
- layerSourceCanvasesRef: layerMgr.layerSourceCanvasesRef,
- materializeLayerCanvas: layerMgr.materializeLayerCanvas,
flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,
isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
getEffectiveOpacity: layerMgr.getEffectiveOpacity,
- getActiveCanvas: drawing.getActiveCanvas,
getCanvasCoords,
setActiveLayerId: layerMgr.setActiveLayerId,
upsertTextLayer: layerMgr.upsertTextLayer,
upsertBalloonLayer: layerMgr.upsertBalloonLayer,
createFrameFolder: layerMgr.createFrameFolder,
divideFrameFolder: layerMgr.divideFrameFolder,
- deleteLayer: layerMgr.deleteLayer,
+ deleteLayer: collab.handleDeleteLayer,
updateLayerThumbnail: layerMgr.updateLayerThumbnail,
pushHistoryStep: drawing.pushHistoryStep,
showToast,
@@ -387,8 +375,8 @@ export function App() {
const vectorTools = useVectorDrawing({
activeLayer: layerMgr.activeLayer,
activeLayerId: layerMgr.activeLayerId,
+ dimensions,
colorMode,
- getActiveCanvas: drawing.getActiveCanvas,
getCanvasCoords,
updateLayerThumbnail: layerMgr.updateLayerThumbnail,
pushHistoryStep: drawing.pushHistoryStep,
@@ -404,12 +392,7 @@ export function App() {
activeLayer: layerMgr.activeLayer,
activeLayerId: layerMgr.activeLayerId,
selection: selectionTools.selection,
- layerCanvasesRef: layerMgr.layerCanvasesRef,
- layerSourceCanvasesRef: layerMgr.layerSourceCanvasesRef,
- materializeLayerCanvas: layerMgr.materializeLayerCanvas,
- releaseLayerCanvas: layerMgr.releaseLayerCanvas,
setActiveLayerId: layerMgr.setActiveLayerId,
- getActiveCanvas: drawing.getActiveCanvas,
updateLayerThumbnail: layerMgr.updateLayerThumbnail,
handleCommitFloatingSelection: selectionTools.handleCommitFloatingSelection,
pushHistoryStepRef,
@@ -430,7 +413,6 @@ export function App() {
layers: layerMgr.layers,
activeLayer: layerMgr.activeLayer,
activeLayerId: layerMgr.activeLayerId,
- layerCanvasesRef: layerMgr.layerCanvasesRef,
getEffectiveOpacity: layerMgr.getEffectiveOpacity,
isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
setActiveLayerId: layerMgr.setActiveLayerId,
@@ -442,7 +424,7 @@ export function App() {
resizeCanvas: layerMgr.resizeCanvas,
copyLayer: layerMgr.copyLayer,
pasteLayer: layerMgr.pasteLayer,
- deleteLayer: layerMgr.deleteLayer,
+ deleteLayer: collab.handleDeleteLayer,
pasteLayerFromFile: layerMgr.pasteLayerFromFile,
resetZoomAndCenter: nav.resetZoomAndCenter,
resetHistory: drawing.resetHistory,
@@ -563,7 +545,7 @@ export function App() {
if (!hasOpenDocument) return;
autoActionStoreActions.setIsPlaying(true);
let currentLayerId = layerMgr.activeLayerId;
- let groupStartBefore: ImageData | null = null;
+ let groupStartSnapshot: Map<string, TileSnapshotEntry> | null = null;
let groupTargetLayerId = currentLayerId;
const ctx: AutoActionExecutionContext = {
@@ -586,7 +568,7 @@ export function App() {
return folder.id;
},
duplicateLayer: (id) => layerMgr.duplicateLayer(id),
- deleteLayer: (id) => layerMgr.deleteLayer(id),
+ deleteLayer: (id) => collab.handleDeleteLayer(id),
renameLayer: (id, name) => layerMgr.renameLayer(id, name),
setBlendMode: (id, blendMode) => layerMgr.setBlendMode(id, blendMode),
setOpacity: (id, opacity) => layerMgr.setOpacity(id, opacity),
@@ -616,28 +598,20 @@ export function App() {
if (opts?.angle !== undefined) layerMgr.setToneAngle(id, opts.angle);
},
fillLayer: (id, color) => {
- const canvas = layerMgr.materializeLayerCanvas(id);
- if (!canvas) return;
- const c2d = canvas.getContext('2d');
- if (!c2d) return;
- if (!groupStartBefore) {
- groupStartBefore = c2d.getImageData(0, 0, canvas.width, canvas.height);
+ if (!groupStartSnapshot) {
+ groupStartSnapshot = activeTileGrid.snapshotLayerTiles(id);
groupTargetLayerId = id;
}
- c2d.save();
- c2d.fillStyle = color;
- c2d.fillRect(0, 0, canvas.width, canvas.height);
- c2d.restore();
- activeTileGrid.ingestCanvas(id, canvas, 'color-32bit');
+ activeTileGrid.fillLayerSolidColor(id, dimensions.width, dimensions.height, color, 'color-32bit');
activeTileGrid.notifyChange(true);
layerMgr.updateLayerThumbnail(id, true);
},
clearLayer: (id) => {
- activeTileGrid.clearLayer(id);
- const canvas = layerMgr.layerCanvasesRef.current.get(id);
- if (canvas) {
- canvas.getContext('2d')?.clearRect(0, 0, canvas.width, canvas.height);
+ if (!groupStartSnapshot) {
+ groupStartSnapshot = activeTileGrid.snapshotLayerTiles(id);
+ groupTargetLayerId = id;
}
+ activeTileGrid.clearLayer(id);
activeTileGrid.notifyChange(true);
layerMgr.updateLayerThumbnail(id, true);
},
@@ -657,19 +631,18 @@ export function App() {
docLifecycle.handleExportImage();
},
endHistoryGroup: (label) => {
- const targetCanvas = groupTargetLayerId
- ? layerMgr.layerCanvasesRef.current.get(groupTargetLayerId)
- : null;
- const afterImg =
- groupStartBefore && targetCanvas
- ? targetCanvas.getContext('2d')?.getImageData(0, 0, targetCanvas.width, targetCanvas.height) ?? null
- : null;
+ const targetId = groupTargetLayerId || currentLayerId;
+ const tileDeltas = groupStartSnapshot
+ ? activeTileGrid.computeDeltasFromSnapshot(groupStartSnapshot, targetId)
+ : undefined;
drawing.pushHistoryStep(
'auto-action',
label,
- groupStartBefore,
- afterImg,
- groupTargetLayerId || currentLayerId
+ null,
+ null,
+ targetId,
+ undefined,
+ tileDeltas && tileDeltas.length > 0 ? tileDeltas : undefined
);
},
};
@@ -762,6 +735,19 @@ export function App() {
const tool = useToolStore.getState().tool;
const pt = getCanvasCoords(e);
+ // Collaborative role & owner-lock guard on canvas mutations
+ if ((collab.isConnected || collab.isReconnecting) && tool !== 'pipette') {
+ if (collab.myRole === 'viewer') {
+ showToast('Viewers have read-only access');
+ return;
+ }
+ const editPerm = collab.canEditLayerById(layerMgr.activeLayerId);
+ if (!editPerm.allowed) {
+ showToast(editPerm.reason || 'Layer is locked by its owner');
+ return;
+ }
+ }
+
if (tool === 'brush' || tool === 'eraser') {
const curLayer = layerMgr.activeLayer;
if (curLayer?.type === 'text' || curLayer?.type === 'balloon') {
@@ -787,7 +773,21 @@ export function App() {
if (selectionTools.handleSelectionPointerDown(e, pt)) return;
shapeFillTools.handleShapeFillPointerDown(e, pt);
},
- [hasOpenDocument, getCanvasCoords, selectionTools, drawing, vectorTools, shapeFillTools]
+ [
+ hasOpenDocument,
+ getCanvasCoords,
+ selectionTools,
+ drawing,
+ vectorTools,
+ shapeFillTools,
+ collab.isConnected,
+ collab.isReconnecting,
+ collab.myRole,
+ collab.canEditLayerById,
+ layerMgr.activeLayer,
+ layerMgr.activeLayerId,
+ showToast,
+ ]
);
const handlePointerMove = useCallback(
@@ -880,7 +880,7 @@ export function App() {
handleOpenLayerStylesModal: tonalActions.handleOpenLayerStylesModal,
toggleLayerColor: layerMgr.toggleLayerColor,
handleConvertLayer: tonalActions.handleConvertLayer,
- deleteLayer: layerMgr.deleteLayer,
+ deleteLayer: collab.handleDeleteLayer,
handleApplyFilter: handleRecordedApplyFilter,
zoomIn: nav.zoomIn,
zoomOut: nav.zoomOut,
@@ -935,8 +935,6 @@ export function App() {
layers: layerMgr.layers,
activeLayerId: layerMgr.activeLayerId,
tileGrid: activeTileGrid,
- layerCanvasesRef: layerMgr.layerCanvasesRef,
- registerLayerCanvas: layerMgr.registerLayerCanvas,
getEffectiveOpacity: layerMgr.getEffectiveOpacity,
isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
interactionRef: drawing.interactionRef,
@@ -989,8 +987,6 @@ export function App() {
handlePointerUp,
layerMgr.layers,
layerMgr.activeLayerId,
- layerMgr.layerCanvasesRef,
- layerMgr.registerLayerCanvas,
layerMgr.getEffectiveOpacity,
layerMgr.isLayerEffectivelyVisible,
layerMgr.setActiveLayerId,
@@ -1064,6 +1060,7 @@ export function App() {
handleClearActiveLayer={collab.handleClearActiveLayer}
handleMergeDown={handleMergeDown}
isCollabConnected={collab.isConnected}
+ isCollabReconnecting={collab.isReconnecting}
collabPeerCount={collab.peers.length + 1}
onOpenCollabModal={handleOpenCollabModal}
handleTriggerOpenFile={docLifecycle.handleTriggerOpenFile}
@@ -1086,7 +1083,8 @@ export function App() {
handleToggleVisibility={collab.handleToggleVisibility}
handleSetOpacity={handleRecordedSetOpacity}
setBlendMode={handleRecordedSetBlendMode}
- toggleLock={layerMgr.toggleLock}
+ toggleLock={collab.handleToggleLock}
+ toggleOwnerLock={collab.handleToggleOwnerLock}
toggleAlphaLock={layerMgr.toggleAlphaLock}
toggleClipping={handleRecordedToggleClipping}
toggleCollapse={layerMgr.toggleCollapse}
@@ -1123,7 +1121,6 @@ export function App() {
<DocumentLifecycleManager
layers={layerMgr.layers}
activeLayerId={layerMgr.activeLayerId}
- layerCanvasesRef={layerMgr.layerCanvasesRef}
needsAdaptiveFitRef={docLifecycle.needsAdaptiveFitRef}
pendingFitDimsRef={docLifecycle.pendingFitDimsRef}
resetToNewCanvas={layerMgr.resetToNewCanvas}
@@ -1182,7 +1179,6 @@ export function App() {
<ModalHost
layers={layerMgr.layers}
activeLayer={layerMgr.activeLayer}
- layerCanvasesRef={layerMgr.layerCanvasesRef}
getEffectiveOpacity={layerMgr.getEffectiveOpacity}
isLayerEffectivelyVisible={layerMgr.isLayerEffectivelyVisible}
handleCreateNewCanvas={docLifecycle.handleCreateNewCanvas}
@@ -1201,14 +1197,22 @@ export function App() {
setIsHostModalOpen={collab.setIsHostModalOpen}
isCollabHost={collab.isHost}
isCollabConnected={collab.isConnected}
+ collabConnectionStatus={collab.connectionStatus}
+ collabReconnectAttempt={collab.reconnectAttempt}
+ collabMyRole={collab.myRole}
collabHostInfo={collab.hostInfo}
collabPeers={collab.peers}
+ collabBannedPeerIds={collab.bannedPeerIds}
collabMyPeer={collab.myPeer}
updateMyName={collab.updateMyName}
handleStartHosting={collab.handleStartHosting}
stopHosting={collab.stopHosting}
joinByInviteUrl={collab.joinByInviteUrl}
leaveRoom={collab.leaveRoom}
+ onSetPeerRole={collab.setPeerRole}
+ onKickPeer={collab.kickPeer}
+ onBanPeer={collab.banPeer}
+ onUnbanPeer={collab.unbanPeer}
clipboardInvite={collab.clipboardInvite}
setClipboardInvite={collab.setClipboardInvite}
webLandingInvite={collab.webLandingInvite}
diff --git a/src/components/AnimationTimeline.tsx b/src/components/AnimationTimeline.tsx
index 6ba5452..30b0f44 100644
--- a/src/components/AnimationTimeline.tsx
+++ b/src/components/AnimationTimeline.tsx
@@ -9,6 +9,8 @@ import {
X,
} from 'lucide-react';
import { AnimationTimeline as TimelineData, LayerItem, AnimationExportFormat } from '../types/editor';
+import { SparseTileGrid } from '../utils/tileEngine';
+import { documentStore } from '../utils/documentStore';
import {
exportAnimationToGif,
exportAnimationToApng,
@@ -21,7 +23,7 @@ export interface AnimationTimelineProps {
timeline: TimelineData;
onChangeTimeline: (timeline: TimelineData) => void;
layers: LayerItem[];
- layerCanvasesMap?: Map<string, HTMLCanvasElement>;
+ tileGrid?: SparseTileGrid;
dimensions: { width: number; height: number };
onAddCel: (frameIndex: number) => void;
onDeleteCel: (frameIndex: number) => void;
@@ -33,7 +35,7 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
timeline,
onChangeTimeline,
layers,
- layerCanvasesMap = new Map(),
+ tileGrid,
dimensions,
onAddCel,
onDeleteCel,
@@ -191,18 +193,20 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
let blob: Blob;
let filename = `animation_${Date.now()}`;
+ const grid = tileGrid ?? documentStore.getActiveTileGrid();
+ const emptyMap = new Map<string, HTMLCanvasElement>();
if (exportFormat === 'gif') {
- blob = await exportAnimationToGif(timeline, layers, layerCanvasesMap, dimensions, onProgress);
+ blob = await exportAnimationToGif(timeline, layers, emptyMap, dimensions, onProgress, grid);
filename += '.gif';
} else if (exportFormat === 'apng') {
- blob = await exportAnimationToApng(timeline, layers, layerCanvasesMap, dimensions, onProgress);
+ blob = await exportAnimationToApng(timeline, layers, emptyMap, dimensions, onProgress, grid);
filename += '.png';
} else if (exportFormat === 'webm' || exportFormat === 'mp4') {
- blob = await exportAnimationToVideo(timeline, layers, layerCanvasesMap, dimensions, onProgress);
+ blob = await exportAnimationToVideo(timeline, layers, emptyMap, dimensions, onProgress, grid);
filename += exportFormat === 'mp4' ? '.mp4' : '.webm';
} else {
- blob = await exportAnimationToPngZip(timeline, layers, layerCanvasesMap, dimensions, onProgress);
+ blob = await exportAnimationToPngZip(timeline, layers, emptyMap, dimensions, onProgress, grid);
filename += '.zip';
}
diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsx
index 6010c6f..358a070 100644
--- a/src/components/AppShell.tsx
+++ b/src/components/AppShell.tsx
@@ -77,8 +77,6 @@ interface CanvasAreaContainerProps {
layers: LayerItem[];
activeLayerId: string;
tileGrid: SparseTileGrid;
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- registerLayerCanvas: (id: string, canvas: HTMLCanvasElement | null) => void;
getEffectiveOpacity: (layer: LayerItem) => number;
isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
interactionRef: React.RefObject<HTMLDivElement | null>;
@@ -223,8 +221,6 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((prop
activeLayerId={props.activeLayerId}
colorMode={colorMode}
tileGrid={props.tileGrid}
- layerCanvasesRef={props.layerCanvasesRef}
- registerLayerCanvas={props.registerLayerCanvas}
getEffectiveOpacity={props.getEffectiveOpacity}
isLayerEffectivelyVisible={props.isLayerEffectivelyVisible}
interactionRef={props.interactionRef}
@@ -364,6 +360,7 @@ export interface AppShellProps {
handleClearActiveLayer: () => void;
handleMergeDown: () => void;
isCollabConnected: boolean;
+ isCollabReconnecting?: boolean;
collabPeerCount: number;
onOpenCollabModal: () => void;
// Welcome props
@@ -390,6 +387,7 @@ export interface AppShellProps {
handleSetOpacity: (id: string, opacity: number) => void;
setBlendMode: (id: string, blendMode: BlendMode) => void;
toggleLock: (id: string) => void;
+ toggleOwnerLock?: (id: string) => void;
toggleAlphaLock: (id: string) => void;
toggleClipping: (id: string) => void;
toggleCollapse: (id: string) => void;
@@ -460,6 +458,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
handleClearActiveLayer,
handleMergeDown,
isCollabConnected,
+ isCollabReconnecting,
collabPeerCount,
onOpenCollabModal,
handleTriggerOpenFile,
@@ -483,6 +482,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
handleSetOpacity,
setBlendMode,
toggleLock,
+ toggleOwnerLock,
toggleAlphaLock,
toggleClipping,
toggleCollapse,
@@ -755,6 +755,8 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
onSetOpacity: handleSetOpacity,
onSetBlendMode: setBlendMode,
onToggleLock: toggleLock,
+ onToggleOwnerLock: toggleOwnerLock,
+ isCollabActive: Boolean(isCollabConnected || isCollabReconnecting),
onToggleAlphaLock: toggleAlphaLock,
onToggleClipping: toggleClipping,
onToggleCollapse: toggleCollapse,
@@ -823,6 +825,9 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
handleSetOpacity,
setBlendMode,
toggleLock,
+ toggleOwnerLock,
+ isCollabConnected,
+ isCollabReconnecting,
toggleAlphaLock,
toggleClipping,
toggleCollapse,
@@ -881,7 +886,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
<input
ref={fileInputRef}
type="file"
- accept=".png,.jpg,.jpeg,.webp,.bmp,.gif,.svg,.psd,.psb,.clip,.csp,.lip,.sora,.ink,.inkb,.sut"
+ accept=".ink,.psd,.psb,.clip,.csp,.lip,.png,.jpg,.jpeg,.webp,.bmp,.gif,.svg,.inkb,.sut,.sora"
onChange={handleFileInputChange}
className="hidden"
/>
@@ -929,6 +934,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
onRenameDocument={handleRenameDocument}
commandHandlers={commandHandlers}
isCollabConnected={isCollabConnected}
+ isCollabReconnecting={isCollabReconnecting}
collabPeerCount={collabPeerCount}
onOpenCollabModal={onOpenCollabModal}
onOpenSettings={handleOpenSettings}
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index 8c9cd1c..8009aa5 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -1,326 +1,65 @@
-import React, { useState, useEffect, useRef, useMemo } from 'react';
-import {
- CanvasDimensions,
- BrushSettings,
- LayerItem,
- CanvasSelection,
- TransformSession,
- TextSettings,
- ToolType,
- LiquifySettings,
- SpeechBalloon,
- SoftProofSettings,
- CanvasColorMode,
- ShapeDragPreview,
-} from '../types/editor';
-import { buildShapeSvgPaths, isOpenShape, resolveShapeFillColor } from '../utils/shapeEngine';
-import { ROTATE_CURSOR_CSS, CanvasNavigationHandle } from '../hooks/useCanvasNavigation';
-import { SelectionOverlay } from './SelectionOverlay';
-import { TransformOverlay } from './TransformOverlay';
-import { TextEditorOverlay } from './TextEditorOverlay';
-import { SpeechBalloonOverlay } from './SpeechBalloonOverlay';
-import { SmartphoneViewportSimulator } from './SmartphoneViewportSimulator';
-import { PerspectiveRulerOverlay } from './PerspectiveRulerOverlay';
-import { StraightRulerOverlay } from './StraightRulerOverlay';
-import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../types/perspective';
-import { Local3DContainer } from './Local3DContainer';
-import { ViewportCompositor } from '../utils/compositor';
-import { SparseTileGrid, globalTileGrid } from '../utils/tileEngine';
-import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../utils/brushOutline';
-import { preloadTipImage } from '../utils/brushStorage';
-import { Smartphone, Archive } from 'lucide-react';
-import { AnimationTimeline } from './AnimationTimeline';
-import { AnimationTimeline as AnimationTimelineType } from '../types/editor';
-import { getOnionSkinFrames } from '../utils/animationEngine';
+import React, { useState, useRef } from 'react';
+import { globalTileGrid } from '../utils/tileEngine';
import { FloatingBrushPill } from './FloatingBrushPill';
-import { screenToCanvas } from '../utils/canvasUtils';
-import {
- resolveHeldKeyModifierAction,
- resolvePointerModifierAction,
-} from '../utils/shortcutManager';
-import { toolStoreActions, useToolStore, useUiStore } from '../stores';
import { ModifierAction } from '../types/settings';
-
-const PIPETTE_CURSOR_CSS = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cg stroke='%23000000' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3Cg stroke='%23ffffff' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3C/svg%3E") 2 22, crosshair`;
-
-interface CanvasAreaProps {
- viewportRef: React.RefObject<HTMLDivElement | null>;
- dimensions: CanvasDimensions;
- brushSettings: BrushSettings;
- onUpdateBrushSettings: (newSettings: Partial<BrushSettings>) => void;
- zoom: number;
- pan: { x: number; y: number };
- rotation: number;
- flipX?: boolean;
- flipY?: boolean;
- navigation?: CanvasNavigationHandle;
- isSpaceDown: boolean;
- isShiftDown: boolean;
- isRotateModifier: boolean;
- isPanning: boolean;
- isRotating: boolean;
- isZoomDragging?: boolean;
- onStartPan: (e: React.PointerEvent) => void;
- onStartRotate: (e: React.PointerEvent) => void;
- onStartZoomDrag?: (e: React.PointerEvent) => void;
- onSampleColor?: (pt: { x: number; y: number }) => void;
- onUndo?: () => void;
- onRedo?: () => void;
- onFlipHorizontal?: () => void;
- isHovering: boolean;
- cursorPos: { x: number; y: number } | null;
- onPointerDown: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[]) => void;
- onPointerMove: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[], predicted?: PointerEvent[]) => void;
- onPointerUp: (e: React.PointerEvent<HTMLElement>) => void;
- predictedCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
- onPointerEnter: () => void;
- onPointerLeave: () => void;
- layers: LayerItem[];
- layerCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- registerLayerCanvas: (id: string, canvas: HTMLCanvasElement | null) => void;
- getEffectiveOpacity: (layer: LayerItem) => number;
- isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
- interactionRef: React.RefObject<HTMLDivElement | null>;
- showCheckerboard?: boolean;
- hasOpenDocument?: boolean;
- draftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
- strokeCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
- peers?: import('../types/multiplayer').CollabPeer[];
- activePings?: Array<{ id: string; x: number; y: number; color: string; name: string }>;
- remoteDraftCanvasesRef?: React.MutableRefObject<Map<string | number, HTMLCanvasElement>>;
- tool?: ToolType;
- selection?: CanvasSelection | null;
- onDeselect?: () => void;
- onTransformSelection?: () => void;
- onFillScreentone?: () => void;
- onFillColor?: () => void;
- onClearSelection?: () => void;
- onInvertSelection?: () => void;
- onExpandSelection?: (pixels: number) => void;
- onContractSelection?: (pixels: number) => void;
- onFeatherSelection?: (radius: number) => void;
- transformSession?: TransformSession | null;
- onUpdateTransformSession?: (updater: (prev: TransformSession) => TransformSession) => void;
- onApplyTransform?: () => void;
- onCancelTransform?: () => void;
- textSession?: { x: number; y: number; settings: TextSettings } | null;
- onUpdateTextSettings?: (updater: (prev: TextSettings) => TextSettings) => void;
- onMoveTextSession?: (x: number, y: number) => void;
- onConfirmText?: () => void;
- onCancelText?: () => void;
- perspectiveRuler?: PerspectiveRuler | null;
- onUpdatePerspectiveRuler?: (ruler: PerspectiveRuler | null) => void;
- straightRuler?: StraightRuler | null;
- onUpdateStraightRuler?: (ruler: StraightRuler | null) => void;
- activeLockedAxis?: ConstraintAxis | null;
- isDrawing?: boolean;
- is3DLayerOpen?: boolean;
- initial3DFile?: File | null;
- onClose3DLayer?: () => void;
- onInsertRasterLayer?: (layer: LayerItem, canvas: HTMLCanvasElement) => void;
- onBake3DSuccess?: (layer: LayerItem) => void;
- liquifySettings?: LiquifySettings;
- onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;
- primaryColor?: string;
- onSwapColors?: () => void;
- showCursorCoordinates?: boolean;
- showPressureInStatusBar?: boolean;
- isWebtoonMode?: boolean;
- onToggleWebtoonMode?: () => void;
- onOpenWebtoonExport?: () => void;
- activeBalloon?: SpeechBalloon | null;
- onUpdateBalloon?: (updater: (prev: SpeechBalloon) => SpeechBalloon) => void;
- onConfirmBalloon?: () => void;
- onDeleteBalloon?: () => void;
- frameDragPreview?: { mode: 'create' | 'divide'; start: { x: number; y: number }; end: { x: number; y: number } } | null;
- shapeDragPreview?: ShapeDragPreview | null;
- secondaryColor?: string;
- animationTimeline?: AnimationTimelineType | null;
- onUpdateAnimationTimeline?: (timeline: AnimationTimelineType) => void;
- onAddAnimationCel?: (frameIndex: number) => void;
- onDeleteAnimationCel?: (frameIndex: number) => void;
- onSelectCelLayer?: (layerId: string) => void;
- softProofSettings?: SoftProofSettings;
- onViewportReady?: (viewport: HTMLDivElement) => void;
- activeLayerId?: string;
- colorMode?: CanvasColorMode;
- tileGrid?: SparseTileGrid;
- isExternalFileDropActive?: boolean;
-}
-
-export function extractCoalescedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {
- const native = e.nativeEvent;
- if (!native) return [];
- // Per W3C Pointer Events spec, pointerdown represents a single contact event;
- // some Windows/WebView2 stylus drivers emit stale or DPI-offset coalesced packets on pointerdown.
- if (native.type === 'pointerdown') {
- return [native];
- }
- if (typeof native.getCoalescedEvents === 'function') {
- try {
- const coalesced = native.getCoalescedEvents();
- if (coalesced && coalesced.length > 0) {
- const last = coalesced[coalesced.length - 1];
- // Guard against Chromium/WebView2 Windows Ink DPI coordinate-space mismatch where
- // getCoalescedEvents() diverges from the dispatching PointerEvent's clientX/clientY.
- if (
- last &&
- Number.isFinite(last.clientX) &&
- Number.isFinite(last.clientY) &&
- Math.hypot(last.clientX - native.clientX, last.clientY - native.clientY) <= 1.5
- ) {
- return coalesced as unknown as PointerEvent[];
- }
- }
- } catch {}
- }
- return [native];
-}
-
-function extractPredictedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {
- const native = e.nativeEvent;
- if (native && typeof native.getPredictedEvents === 'function') {
- try {
- const predicted = native.getPredictedEvents();
- if (predicted && predicted.length > 0) {
- return predicted as unknown as PointerEvent[];
- }
- } catch {}
- }
- return [];
-}
-
-function formatArtboardTransform(
- pan: { x: number; y: number },
- zoom: number,
- rotation: number,
- flipX: boolean,
- flipY: boolean,
- dimensions: CanvasDimensions
-): string {
- const sx = (flipX ? -1 : 1) * zoom;
- const sy = (flipY ? -1 : 1) * zoom;
- return `translate3d(${pan.x}px, ${pan.y}px, 0) rotate(${rotation}deg) scale(${sx}, ${sy}) translate3d(${-dimensions.width / 2}px, ${-dimensions.height / 2}px, 0)`;
-}
-
-function formatCursorRingTransform(
- x: number,
- y: number,
- rotation: number,
- flipX: boolean,
- flipY: boolean,
- tipAngleDeg: number
-): string {
- const fx = flipX ? -1 : 1;
- const fy = flipY ? -1 : 1;
- return `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%) rotate(${rotation}deg) scale(${fx}, ${fy}) rotate(${tipAngleDeg}deg)`;
-}
-
-export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
- viewportRef,
- onViewportReady,
- dimensions,
- brushSettings,
- onUpdateBrushSettings,
- zoom,
- pan,
- rotation,
- flipX = false,
- flipY = false,
- navigation,
- isSpaceDown,
- isRotateModifier,
- isPanning,
- isRotating,
- isZoomDragging = false,
- onStartPan,
- onStartRotate,
- onStartZoomDrag,
- onSampleColor,
- onUndo,
- onRedo,
- onFlipHorizontal,
- isWebtoonMode = false,
- onToggleWebtoonMode,
- onOpenWebtoonExport,
- activeBalloon = null,
- onUpdateBalloon,
- onConfirmBalloon,
- onDeleteBalloon,
- frameDragPreview = null,
- shapeDragPreview = null,
- secondaryColor = '#ffffff',
- isHovering: _isHovering,
- cursorPos: _cursorPos,
- onPointerDown,
- onPointerMove,
- onPointerUp,
- onPointerEnter,
- onPointerLeave,
- layers,
- layerCanvasesRef,
- registerLayerCanvas: _registerLayerCanvas,
- getEffectiveOpacity: _getEffectiveOpacity,
- isLayerEffectivelyVisible: _isLayerEffectivelyVisible,
- interactionRef,
- showCheckerboard = true,
- hasOpenDocument = true,
- draftCanvasRef,
- strokeCanvasRef,
- predictedCanvasRef,
- peers = [],
- activePings = [],
- remoteDraftCanvasesRef,
- tool = 'brush',
- selection = null,
- onDeselect,
- onTransformSelection,
- onFillScreentone,
- onFillColor,
- onClearSelection,
- onInvertSelection,
- onExpandSelection,
- onContractSelection,
- onFeatherSelection,
- transformSession = null,
- onUpdateTransformSession,
- onApplyTransform,
- onCancelTransform,
- textSession = null,
- onUpdateTextSettings,
- onMoveTextSession,
- onConfirmText,
- onCancelText,
- perspectiveRuler = null,
- onUpdatePerspectiveRuler,
- straightRuler = null,
- onUpdateStraightRuler,
- activeLockedAxis = null,
- isDrawing = false,
- is3DLayerOpen = false,
- initial3DFile = null,
- onClose3DLayer,
- onInsertRasterLayer,
- onBake3DSuccess,
- liquifySettings,
- onUpdateLiquifySettings,
- primaryColor = '#000000',
- onSwapColors,
- showCursorCoordinates = false,
- showPressureInStatusBar = false,
- animationTimeline = null,
- onUpdateAnimationTimeline,
- onAddAnimationCel,
- onDeleteAnimationCel,
- onSelectCelLayer,
- softProofSettings,
- activeLayerId,
- colorMode = 'color',
- tileGrid = globalTileGrid,
- isExternalFileDropActive = false,
-}) => {
- const tileGridRef = useRef<SparseTileGrid>(tileGrid);
- tileGridRef.current = tileGrid;
+import {
+ CanvasAreaProps,
+ extractCoalescedEvents,
+ getCursorStyle,
+} from './canvasArea/types';
+import { useCanvasEffects } from './canvasArea/useCanvasEffects';
+import { useCompositorViewport } from './canvasArea/useCompositorViewport';
+import { useCanvasPointerHandlers } from './canvasArea/useCanvasPointerHandlers';
+import { CanvasArtboardOverlays } from './canvasArea/CanvasArtboardOverlays';
+import { CanvasViewportHud } from './canvasArea/CanvasViewportHud';
+
+export { extractCoalescedEvents };
+
+export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {
+ const {
+ viewportRef,
+ onViewportReady,
+ dimensions,
+ brushSettings,
+ onUpdateBrushSettings,
+ zoom,
+ pan,
+ rotation,
+ flipX = false,
+ flipY = false,
+ navigation,
+ isSpaceDown,
+ isRotateModifier,
+ isPanning,
+ isRotating,
+ isZoomDragging = false,
+ onStartPan,
+ onStartRotate,
+ onStartZoomDrag,
+ onSampleColor,
+ onUndo,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+ layers,
+ showCheckerboard = true,
+ hasOpenDocument = true,
+ draftCanvasRef,
+ strokeCanvasRef,
+ predictedCanvasRef,
+ tool = 'brush',
+ liquifySettings,
+ onUpdateLiquifySettings,
+ primaryColor = '#000000',
+ onSwapColors,
+ showCursorCoordinates = false,
+ showPressureInStatusBar = false,
+ animationTimeline = null,
+ softProofSettings,
+ activeLayerId,
+ colorMode = 'color',
+ tileGrid = globalTileGrid,
+ } = props;
const effectiveDraftCanvasRef = draftCanvasRef || strokeCanvasRef;
const localPredictedCanvasRef = useRef<HTMLCanvasElement | null>(null);
@@ -329,51 +68,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
const activeLayer = layers.find((l) => l.id === activeLayerId);
const isMonochromeActive = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome' || brushSettings.antiAlias === 0;
- // Resolve tip image and extract vector outline silhouette
- const activeTipImage = resolveBrushTipImage(brushSettings);
- const [tipOutline, setTipOutline] = useState<TipOutline | null>(() => {
- return activeTipImage ? getBrushTipOutline(activeTipImage) : null;
- });
-
- useEffect(() => {
- let isCancelled = false;
-
- if (activeTipImage) {
- if (activeTipImage.complete && activeTipImage.naturalWidth > 0) {
- setTipOutline(getBrushTipOutline(activeTipImage));
- } else {
- const handleLoad = () => {
- if (!isCancelled) {
- setTipOutline(getBrushTipOutline(activeTipImage));
- }
- };
- activeTipImage.addEventListener('load', handleLoad, { once: true });
- }
- return () => {
- isCancelled = true;
- };
- }
-
- if (brushSettings.customTipDataUrl) {
- preloadTipImage(brushSettings.customTipDataUrl)
- .then((img) => {
- if (!isCancelled) {
- setTipOutline(getBrushTipOutline(img));
- }
- })
- .catch(() => {
- if (!isCancelled) {
- setTipOutline(null);
- }
- });
- return () => {
- isCancelled = true;
- };
- }
-
- setTipOutline(null);
- }, [activeTipImage, brushSettings.customTipDataUrl, brushSettings.preset]);
-
// Dynamic cursor dimensions according to brush tip shape, aspect ratio, and thickness
const liveCamera = navigation
? navigation.getCameraState()
@@ -384,939 +78,135 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
const liveFlipX = liveCamera.flipX;
const liveFlipY = liveCamera.flipY;
- const isCustomTip = Boolean(tipOutline && (tool === 'brush' || tool === 'eraser'));
- const isSquare = brushSettings.preset === 'square-digital' && !tipOutline;
- const tipAspect = isCustomTip && tipOutline ? tipOutline.height / tipOutline.width : 1.0;
-
- const activeToolSize = tool === 'liquify' && liquifySettings ? liquifySettings.size : brushSettings.size;
- const cursorBaseWidth = Math.max(4, activeToolSize * liveZoom);
- const thicknessRatio = tool === 'brush' ? (brushSettings.thickness ?? 1.0) : 1.0;
- const thicknessVertical = Boolean(brushSettings.thicknessVertical && tool === 'brush');
- const tipAngleDeg = tool === 'brush' ? (brushSettings.customTipAngle ?? 0) : 0;
-
- const cursorWidth = thicknessVertical
- ? Math.max(2, cursorBaseWidth * thicknessRatio)
- : cursorBaseWidth;
- const cursorHeight = thicknessVertical
- ? Math.max(2, cursorBaseWidth * tipAspect)
- : Math.max(2, cursorBaseWidth * tipAspect * thicknessRatio);
-
- // Brush tip rotation: tip angle relative to canvas + viewport canvas rotation
- const totalAngleDeg = tipAngleDeg + liveRotation;
- const cursorConfigRef = useRef({
- activeToolSize,
- tipAspect,
- thicknessRatio,
- thicknessVertical,
- tipAngleDeg,
- rotation: liveRotation,
- flipX: liveFlipX,
- flipY: liveFlipY,
- });
- cursorConfigRef.current = {
- activeToolSize,
- tipAspect,
- thicknessRatio,
- thicknessVertical,
- tipAngleDeg,
- rotation: liveRotation,
- flipX: liveFlipX,
- flipY: liveFlipY,
- };
- const lastPointerPosRef = useRef<{ x: number; y: number } | null>(null);
-
// Dynamic on-canvas brush resizing via configured modifier (default Ctrl + Alt + Drag or Shift + Alt + Drag)
const [heldModifierAction, setHeldModifierAction] = useState<ModifierAction>('none');
const [isResizingBrush, setIsResizingBrush] = useState(false);
const [quickPalettePos, setQuickPalettePos] = useState<{ x: number; y: number } | null>(null);
- const tempEraserPrevToolRef = useRef<ToolType | null>(null);
const resizeOriginRef = useRef<{ clientX: number; clientY: number }>({ clientX: 0, clientY: 0 });
const resizeStartSettingsRef = useRef<{ size: number; hardness: number }>({
size: brushSettings.size,
hardness: brushSettings.hardness ?? 1.0,
});
- // Zero-latency direct DOM cursor preview element & artboard container
const artboardRef = useRef<HTMLDivElement | null>(null);
- const cursorRingRef = useRef<HTMLDivElement | null>(null);
- const pointerStatRef = useRef<HTMLDivElement | null>(null);
-
- useEffect(() => {
- if (!showCursorCoordinates && !showPressureInStatusBar) return;
- let rafId = 0;
- const handlePointerStat = (e: Event) => {
- const detail = (e as CustomEvent).detail;
- cancelAnimationFrame(rafId);
- rafId = requestAnimationFrame(() => {
- const el = pointerStatRef.current;
- if (!el || !detail) return;
- const parts: string[] = [];
- if (showCursorCoordinates && detail.x !== null && detail.x !== undefined) {
- parts.push(`${detail.x}, ${detail.y}`);
- }
- if (showPressureInStatusBar && detail.pressure > 0) {
- parts.push(`${Math.round(detail.pressure * 100)}%`);
- }
- el.textContent = parts.join(' · ');
- });
- };
- window.addEventListener('canvas-pointer-stat', handlePointerStat);
- return () => {
- window.removeEventListener('canvas-pointer-stat', handlePointerStat);
- cancelAnimationFrame(rafId);
- };
- }, [showCursorCoordinates, showPressureInStatusBar]);
-
- // Update cursor rotation/flip in-place when viewport rotates/flips or brush tip angle changes while hovering
- useEffect(() => {
- const ring = cursorRingRef.current;
- const pos = lastPointerPosRef.current;
- if (ring && pos && ring.style.display !== 'none') {
- const cfg = cursorConfigRef.current;
- ring.style.transform = formatCursorRingTransform(
- pos.x,
- pos.y,
- cfg.rotation,
- cfg.flipX,
- cfg.flipY,
- cfg.tipAngleDeg
- );
- }
- }, [tipAngleDeg, liveRotation, liveFlipX, liveFlipY]);
-
- useEffect(() => {
- const viewport = viewportRef.current;
- if (!viewport) return;
-
- let cachedRect: DOMRect | null = viewport.getBoundingClientRect();
- const updateRect = () => {
- if (viewport) cachedRect = viewport.getBoundingClientRect();
- };
-
- window.addEventListener('resize', updateRect);
- window.addEventListener('scroll', updateRect, true);
- const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updateRect) : null;
- ro?.observe(viewport);
-
- const updateCursorRingPos = (e: PointerEvent, forceRefreshRect: boolean = false) => {
- const ring = cursorRingRef.current;
- if (!ring) return;
-
- if (
- isSpaceDown ||
- isPanning ||
- isRotating ||
- isZoomDragging ||
- isRotateModifier ||
- isResizingBrush ||
- heldModifierAction === 'brush-size' ||
- heldModifierAction === 'pan' ||
- heldModifierAction === 'rotate' ||
- heldModifierAction === 'zoom-drag' ||
- (tool !== 'brush' && tool !== 'eraser' && tool !== 'liquify' && tool !== 'select-pen' && tool !== 'select-eraser')
- ) {
- ring.style.display = 'none';
- return;
- }
-
- if (forceRefreshRect || !cachedRect) updateRect();
- if (!cachedRect) return;
-
- const x = e.clientX - cachedRect.left;
- const y = e.clientY - cachedRect.top;
-
- if (x < 0 || x > cachedRect.width || y < 0 || y > cachedRect.height) {
- ring.style.display = 'none';
- return;
- }
-
- lastPointerPosRef.current = { x, y };
- const cfg = cursorConfigRef.current;
- ring.style.transform = formatCursorRingTransform(
- x,
- y,
- cfg.rotation,
- cfg.flipX,
- cfg.flipY,
- cfg.tipAngleDeg
- );
- if (ring.style.display !== 'block') {
- ring.style.display = 'block';
- }
- };
-
- const handleWindowPointerMove = (e: PointerEvent) => {
- updateCursorRingPos(e, false);
- };
-
- const handleViewportPointerEnterOrDown = (e: PointerEvent) => {
- updateCursorRingPos(e, true);
- };
-
- const handlePointerLeave = () => {
- lastPointerPosRef.current = null;
- if (cursorRingRef.current) {
- cursorRingRef.current.style.display = 'none';
- }
- };
-
- viewport.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
- viewport.addEventListener('pointerdown', handleViewportPointerEnterOrDown, { passive: true });
- viewport.addEventListener('pointerenter', handleViewportPointerEnterOrDown, { passive: true });
- viewport.addEventListener('pointerleave', handlePointerLeave, { passive: true });
- return () => {
- window.removeEventListener('resize', updateRect);
- window.removeEventListener('scroll', updateRect, true);
- ro?.disconnect();
- viewport.removeEventListener('pointermove', handleWindowPointerMove);
- viewport.removeEventListener('pointerdown', handleViewportPointerEnterOrDown);
- viewport.removeEventListener('pointerenter', handleViewportPointerEnterOrDown);
- viewport.removeEventListener('pointerleave', handlePointerLeave);
- };
- }, [isSpaceDown, isPanning, isRotating, isZoomDragging, isRotateModifier, isResizingBrush, heldModifierAction, viewportRef, tool, hasOpenDocument]);
-
- // Compute colored onion skin frames and active cel isolation for animation
- const onionSkinFrames = useMemo(() => {
- if (!animationTimeline || !animationTimeline.onionSkin?.enabled) return [];
- return getOnionSkinFrames(animationTimeline);
- }, [animationTimeline]);
-
- const effectiveLayers = useMemo(() => {
- if (!animationTimeline) return layers;
- const currentCelId = animationTimeline.cels[animationTimeline.currentFrame];
- const allCelIds = new Set(Object.values(animationTimeline.cels));
- return layers.map((layer) => {
- if (allCelIds.has(layer.id)) {
- return {
- ...layer,
- visible: layer.id === currentCelId && layer.visible,
- };
- }
- return layer;
- });
- }, [layers, animationTimeline]);
+ const {
+ tipOutline,
+ isCustomTip,
+ isSquare,
+ cursorWidth,
+ cursorHeight,
+ totalAngleDeg,
+ cursorConfigRef,
+ lastPointerPosRef,
+ cursorRingRef,
+ pointerStatRef,
+ } = useCanvasEffects({
+ viewportRef,
+ brushSettings,
+ onUpdateBrushSettings,
+ liquifySettings,
+ onUpdateLiquifySettings,
+ tool,
+ liveZoom,
+ liveRotation,
+ liveFlipX,
+ liveFlipY,
+ isSpaceDown,
+ isPanning,
+ isRotating,
+ isZoomDragging,
+ isRotateModifier,
+ hasOpenDocument,
+ showCursorCoordinates,
+ showPressureInStatusBar,
+ heldModifierAction,
+ setHeldModifierAction,
+ isResizingBrush,
+ setIsResizingBrush,
+ quickPalettePos,
+ setQuickPalettePos,
+ resizeOriginRef,
+ resizeStartSettingsRef,
+ });
- // Unified GPU Viewport Compositor
- const viewportCanvasRef = useRef<HTMLCanvasElement | null>(null);
- const compositorRef = useRef<ViewportCompositor | null>(null);
- const viewportCssSizeRef = useRef<{ width: number; height: number } | null>(null);
- const renderParamsRef = useRef({
- effectiveLayers,
- pan: livePan,
- zoom: liveZoom,
- rotation: liveRotation,
- flipX: liveFlipX,
- flipY: liveFlipY,
- dimensions,
- showCheckerboard,
- onionSkinFrames,
- softProofSettings,
- activeLayerId,
- brushOpacity: brushSettings.opacity ?? 1.0,
+ const { viewportCanvasRef } = useCompositorViewport({
+ viewportRef,
+ onViewportReady,
+ artboardRef,
+ cursorRingRef,
+ cursorConfigRef,
+ lastPointerPosRef,
effectiveDraftCanvasRef,
- });
- renderParamsRef.current = {
- effectiveLayers,
- pan: livePan,
- zoom: liveZoom,
- rotation: liveRotation,
- flipX: liveFlipX,
- flipY: liveFlipY,
+ effectivePredictedCanvasRef,
+ navigation,
+ layers,
+ animationTimeline,
+ pan,
+ zoom,
+ rotation,
+ flipX,
+ flipY,
+ livePan,
+ liveZoom,
+ liveRotation,
+ liveFlipX,
+ liveFlipY,
dimensions,
showCheckerboard,
- onionSkinFrames,
+ hasOpenDocument,
softProofSettings,
activeLayerId,
- brushOpacity: brushSettings.opacity ?? 1.0,
- effectiveDraftCanvasRef,
- };
-
- const buildCompositorOptions = (rp: typeof renderParamsRef.current, dpr: number) => {
- const vCanvas = viewportCanvasRef.current;
- const cssSize = viewportCssSizeRef.current;
- if (vCanvas && compositorRef.current && cssSize && cssSize.width > 0 && cssSize.height > 0) {
- const expectedW = Math.max(1, Math.round(cssSize.width * dpr));
- const expectedH = Math.max(1, Math.round(cssSize.height * dpr));
- if (vCanvas.width !== expectedW || vCanvas.height !== expectedH) {
- compositorRef.current.resize(expectedW, expectedH);
- const predCanvas = rp.effectiveDraftCanvasRef ? effectivePredictedCanvasRef?.current : null;
- if (predCanvas && (predCanvas.width !== expectedW || predCanvas.height !== expectedH)) {
- predCanvas.width = expectedW;
- predCanvas.height = expectedH;
- }
- }
- }
- const draftCanvas = rp.effectiveDraftCanvasRef?.current ?? null;
- const draftVersion = draftCanvas ? ((draftCanvas as any).__draftVersion ?? 0) : 0;
- const draftSpace = ((draftCanvas as any)?.__draftSpace as 'document' | 'viewport' | undefined) ?? 'viewport';
- const draftDocRect = (draftCanvas as any)?.__draftDocRect ?? null;
- const draftMonochrome = Boolean((draftCanvas as any)?.__draftMonochrome);
- return {
- dimensions: rp.dimensions,
- showCheckerboard: rp.showCheckerboard,
- devicePixelRatio: dpr,
- onionSkinFrames: rp.onionSkinFrames,
- softProof: rp.softProofSettings,
- activeLayerId: rp.activeLayerId ?? null,
- activeDraftLayerId: rp.activeLayerId ?? null,
- activeDraftCanvas: draftCanvas,
- activeDraftDirtyRect: draftSpace === 'document' ? draftDocRect : null,
- activeDraftVersion: draftVersion,
- activeDraftSpace: draftSpace,
- activeDraftOpacity: rp.brushOpacity,
- activeDraftMonochrome: draftMonochrome,
- };
- };
-
- // Direct zero-React-rerender camera subscription for smooth 60-240Hz pan, zoom, rotation, and view flip
- useEffect(() => {
- if (!navigation) return;
- return navigation.subscribeCamera((cam) => {
- const rp = renderParamsRef.current;
- rp.pan = cam.pan;
- rp.zoom = cam.zoom;
- rp.rotation = cam.rotation;
- rp.flipX = cam.flipX;
- rp.flipY = cam.flipY;
-
- const cfg = cursorConfigRef.current;
- cfg.rotation = cam.rotation;
- cfg.flipX = cam.flipX;
- cfg.flipY = cam.flipY;
-
- const artboard = artboardRef.current;
- if (artboard) {
- artboard.style.transform = formatArtboardTransform(
- cam.pan,
- cam.zoom,
- cam.rotation,
- cam.flipX,
- cam.flipY,
- rp.dimensions
- );
- }
-
- const ring = cursorRingRef.current;
- if (ring) {
- const baseW = Math.max(4, cfg.activeToolSize * cam.zoom);
- const cW = cfg.thicknessVertical
- ? Math.max(2, baseW * cfg.thicknessRatio)
- : baseW;
- const cH = cfg.thicknessVertical
- ? Math.max(2, baseW * cfg.tipAspect)
- : Math.max(2, baseW * cfg.tipAspect * cfg.thicknessRatio);
- ring.style.width = `${cW}px`;
- ring.style.height = `${cH}px`;
- const pos = lastPointerPosRef.current;
- if (pos && ring.style.display !== 'none') {
- ring.style.transform = formatCursorRingTransform(
- pos.x,
- pos.y,
- cam.rotation,
- cam.flipX,
- cam.flipY,
- cfg.tipAngleDeg
- );
- }
- }
-
- if (viewportCanvasRef.current && !compositorRef.current) {
- compositorRef.current = new ViewportCompositor(viewportCanvasRef.current);
- }
- if (compositorRef.current) {
- const dpr = window.devicePixelRatio || 1;
- compositorRef.current.render(
- rp.effectiveLayers,
- {
- pan: cam.pan,
- zoom: cam.zoom,
- rotation: cam.rotation,
- flipX: cam.flipX,
- flipY: cam.flipY,
- },
- rp.dimensions,
- tileGridRef.current,
- buildCompositorOptions(rp, dpr)
- );
- }
- });
- }, [navigation]);
-
- // Synchronize viewport and draft overlay canvas resolution with the screen viewport
- useEffect(() => {
- let dprMql: MediaQueryList | null = null;
-
- const updateCanvasSizes = () => {
- const viewport = viewportRef.current;
- if (!viewport) return;
- const rect = viewport.getBoundingClientRect();
- if (rect.width > 0 && rect.height > 0) {
- viewportCssSizeRef.current = { width: rect.width, height: rect.height };
- }
- const dpr = window.devicePixelRatio || 1;
- const w = Math.max(1, Math.round(rect.width * dpr));
- const h = Math.max(1, Math.round(rect.height * dpr));
-
- const draftCanvas = effectiveDraftCanvasRef?.current;
- if (
- draftCanvas &&
- (draftCanvas as any).__draftSpace !== 'document' &&
- (draftCanvas.width !== w || draftCanvas.height !== h)
- ) {
- draftCanvas.width = w;
- draftCanvas.height = h;
- (draftCanvas as any).__draftHasContent = false;
- (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
- }
-
- const predCanvas = effectivePredictedCanvasRef?.current;
- if (predCanvas && (predCanvas.width !== w || predCanvas.height !== h)) {
- predCanvas.width = w;
- predCanvas.height = h;
- }
-
- const vCanvas = viewportCanvasRef.current;
- if (vCanvas) {
- if (compositorRef.current && compositorRef.current.getCanvas() !== vCanvas) {
- compositorRef.current.dispose();
- compositorRef.current = null;
- }
- const sizeChanged = vCanvas.width !== w || vCanvas.height !== h;
- if (sizeChanged || !compositorRef.current) {
- if (!compositorRef.current) {
- vCanvas.width = w;
- vCanvas.height = h;
- compositorRef.current = new ViewportCompositor(vCanvas);
- } else {
- compositorRef.current.resize(w, h);
- }
- const rp = renderParamsRef.current;
- compositorRef.current.render(
- rp.effectiveLayers,
- {
- pan: rp.pan,
- zoom: rp.zoom,
- rotation: rp.rotation,
- flipX: rp.flipX,
- flipY: rp.flipY,
- },
- rp.dimensions,
- tileGridRef.current,
- buildCompositorOptions(rp, dpr)
- );
- }
- }
- };
-
- const handleDprChange = () => {
- updateCanvasSizes();
- attachDprListener();
- };
-
- const attachDprListener = () => {
- if (dprMql) {
- dprMql.removeEventListener?.('change', handleDprChange);
- dprMql = null;
- }
- if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
- const curDpr = window.devicePixelRatio || 1;
- dprMql = window.matchMedia(`(resolution: ${curDpr}dppx)`);
- dprMql.addEventListener?.('change', handleDprChange);
- }
- };
-
- updateCanvasSizes();
- attachDprListener();
- window.addEventListener('resize', updateCanvasSizes);
- const ro = typeof ResizeObserver !== 'undefined' && viewportRef.current
- ? new ResizeObserver(updateCanvasSizes)
- : null;
- if (ro && viewportRef.current) {
- ro.observe(viewportRef.current);
- }
- return () => {
- window.removeEventListener('resize', updateCanvasSizes);
- dprMql?.removeEventListener?.('change', handleDprChange);
- ro?.disconnect();
- };
- }, [viewportRef, effectiveDraftCanvasRef, effectivePredictedCanvasRef, hasOpenDocument]);
-
- useEffect(() => {
- if (viewportRef.current) {
- onViewportReady?.(viewportRef.current);
- const raf = requestAnimationFrame(() => {
- if (viewportRef.current) {
- onViewportReady?.(viewportRef.current);
- }
- });
- return () => cancelAnimationFrame(raf);
- }
- }, [onViewportReady, viewportRef]);
-
- // Render scene using Unified GPU Viewport Compositor
- useEffect(() => {
- const vCanvas = viewportCanvasRef.current;
- if (!vCanvas) return;
- if (compositorRef.current && compositorRef.current.getCanvas() !== vCanvas) {
- compositorRef.current.dispose();
- compositorRef.current = null;
- }
- if (!compositorRef.current) {
- compositorRef.current = new ViewportCompositor(vCanvas);
- }
-
- const dpr = window.devicePixelRatio || 1;
- const rp = renderParamsRef.current;
- compositorRef.current.render(
- effectiveLayers,
- {
- pan: rp.pan,
- zoom: rp.zoom,
- rotation: rp.rotation,
- flipX: rp.flipX,
- flipY: rp.flipY,
- },
- dimensions,
- tileGrid,
- buildCompositorOptions(rp, dpr)
- );
- }, [effectiveLayers, layers, pan, zoom, rotation, flipX, flipY, dimensions, showCheckerboard, onionSkinFrames, softProofSettings, activeLayerId, brushSettings.opacity, colorMode, tileGrid]);
-
- // Event-Driven Compositor Invalidation via active document's SparseTileGrid subscription
- useEffect(() => {
- let rafId: number | null = null;
- const activeGrid = tileGrid;
- const renderCompositor = () => {
- if (compositorRef.current) {
- const dpr = window.devicePixelRatio || 1;
- const rp = renderParamsRef.current;
- compositorRef.current.render(
- rp.effectiveLayers,
- {
- pan: rp.pan,
- zoom: rp.zoom,
- rotation: rp.rotation,
- flipX: rp.flipX,
- flipY: rp.flipY,
- },
- rp.dimensions,
- activeGrid,
- buildCompositorOptions(rp, dpr)
- );
- }
- };
-
- const handleGridChange = (immediate?: boolean) => {
- if (immediate) {
- if (rafId !== null) {
- cancelAnimationFrame(rafId);
- rafId = null;
- }
- renderCompositor();
- return;
- }
- if (rafId !== null) return;
- rafId = requestAnimationFrame(() => {
- rafId = null;
- renderCompositor();
- });
- };
-
- const unsubscribe = activeGrid.subscribe(handleGridChange);
- return () => {
- unsubscribe();
- if (rafId !== null) cancelAnimationFrame(rafId);
- };
- }, [tileGrid]);
-
- useEffect(() => {
- return () => {
- if (compositorRef.current) {
- compositorRef.current.dispose();
- compositorRef.current = null;
- }
- };
- }, []);
-
- // Track held modifier key combinations globally according to Modifier Key Settings
- useEffect(() => {
- const syncHeldAction = (e: KeyboardEvent, spaceOverride?: boolean) => {
- const action = resolveHeldKeyModifierAction(
- {
- ctrl: e.ctrlKey || e.metaKey,
- shift: e.shiftKey,
- alt: e.altKey,
- space: spaceOverride !== undefined ? spaceOverride : isSpaceDown,
- },
- useUiStore.getState().appSettings.modifierKeys
- );
- setHeldModifierAction(action);
- };
-
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape' && quickPalettePos) {
- setQuickPalettePos(null);
- }
- syncHeldAction(e, e.code === 'Space' ? true : undefined);
- };
-
- const handleKeyUp = (e: KeyboardEvent) => {
- syncHeldAction(e, e.code === 'Space' ? false : undefined);
- };
-
- const handleBlur = () => {
- setHeldModifierAction('none');
- setIsResizingBrush(false);
- setQuickPalettePos(null);
- };
-
- window.addEventListener('keydown', handleKeyDown);
- window.addEventListener('keyup', handleKeyUp);
- window.addEventListener('blur', handleBlur);
- return () => {
- window.removeEventListener('keydown', handleKeyDown);
- window.removeEventListener('keyup', handleKeyUp);
- window.removeEventListener('blur', handleBlur);
- };
- }, [isSpaceDown, quickPalettePos]);
-
- // Handle active brush resizing window drag listeners
- useEffect(() => {
- if (!isResizingBrush) return;
-
- let rafId: number | null = null;
- let pendingSize = resizeStartSettingsRef.current.size;
- let pendingHardness = resizeStartSettingsRef.current.hardness;
-
- const commitResize = () => {
- rafId = null;
- if (tool === 'liquify' && onUpdateLiquifySettings) {
- onUpdateLiquifySettings({ size: Math.round(pendingSize) });
- } else {
- onUpdateBrushSettings({ size: pendingSize, hardness: pendingHardness });
- }
- };
-
- const handleWindowPointerMove = (e: PointerEvent) => {
- const dx = e.clientX - resizeOriginRef.current.clientX;
- const dy = resizeOriginRef.current.clientY - e.clientY;
-
- // Exponential + linear hybrid sensitivity for 0.5px..1000px precision (CSP-style)
- const baseSize = Math.max(0.5, resizeStartSettingsRef.current.size);
- const rawSize = baseSize * Math.exp(dx * 0.006) + dx * 0.15;
- const clampedSize = Math.max(0.5, Math.min(1000, rawSize));
- pendingSize = clampedSize < 10 ? Math.round(clampedSize * 10) / 10 : Math.round(clampedSize);
-
- pendingHardness = Math.max(
- 0.05,
- Math.min(
- 1.0,
- Math.round((resizeStartSettingsRef.current.hardness + dy * 0.004) * 100) / 100
- )
- );
-
- if (rafId === null) {
- rafId = requestAnimationFrame(commitResize);
- }
- };
-
- const handleWindowPointerUp = () => {
- if (rafId !== null) {
- cancelAnimationFrame(rafId);
- commitResize();
- }
- setIsResizingBrush(false);
- };
-
- window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
- window.addEventListener('pointerup', handleWindowPointerUp);
- window.addEventListener('pointercancel', handleWindowPointerUp);
-
- const prevCursor = document.body.style.cursor;
- const prevUserSelect = document.body.style.userSelect;
- document.body.style.cursor = 'ew-resize';
- document.body.style.userSelect = 'none';
-
- return () => {
- if (rafId !== null) cancelAnimationFrame(rafId);
- window.removeEventListener('pointermove', handleWindowPointerMove);
- window.removeEventListener('pointerup', handleWindowPointerUp);
- window.removeEventListener('pointercancel', handleWindowPointerUp);
- document.body.style.cursor = prevCursor;
- document.body.style.userSelect = prevUserSelect;
- };
- }, [isResizingBrush, onUpdateBrushSettings, onUpdateLiquifySettings, tool]);
-
- const releaseExternalFocus = () => {
- const active = document.activeElement as HTMLElement | null;
- if (!active || active === document.body) return;
- if (viewportRef.current?.contains(active)) return;
- const tag = active.tagName;
- if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || tag === 'BUTTON') {
- active.blur();
- }
- };
-
- // Start brush resizing drag
- const startBrushResize = (e: React.PointerEvent) => {
- e.preventDefault();
- e.stopPropagation();
- setIsResizingBrush(true);
- resizeOriginRef.current = { clientX: e.clientX, clientY: e.clientY };
- resizeStartSettingsRef.current = {
- size: tool === 'liquify' && liquifySettings ? liquifySettings.size : brushSettings.size,
- hardness: brushSettings.hardness ?? 1.0,
- };
- };
-
- // Start continuous eyedropper sampling for modifier buttons (e.g. Right Click / Barrel Button)
- const startModifierEyedropper = (e: React.PointerEvent) => {
- if (!onSampleColor || !viewportRef.current) return;
- e.preventDefault();
- e.stopPropagation();
-
- const sampleAtClient = (clientX: number, clientY: number) => {
- const vp = viewportRef.current;
- if (!vp) return;
- const rect = vp.getBoundingClientRect();
- const cam = navigation
- ? navigation.getCameraState()
- : { pan, zoom, rotation, flipX, flipY };
- const pt = screenToCanvas(
- clientX,
- clientY,
- rect,
- cam.pan,
- cam.zoom,
- cam.rotation,
- dimensions,
- cam.flipX,
- cam.flipY
- );
- onSampleColor(pt);
- };
-
- sampleAtClient(e.clientX, e.clientY);
-
- const handleMove = (ev: PointerEvent) => {
- sampleAtClient(ev.clientX, ev.clientY);
- };
- const handleUp = () => {
- window.removeEventListener('pointermove', handleMove);
- window.removeEventListener('pointerup', handleUp);
- window.removeEventListener('pointercancel', handleUp);
- };
- window.addEventListener('pointermove', handleMove, { passive: true });
- window.addEventListener('pointerup', handleUp);
- window.addEventListener('pointercancel', handleUp);
- };
-
- // Open floating Quick Palette near cursor when mapped to 'quick-palette'
- const openQuickPaletteAt = (e: React.PointerEvent) => {
- e.preventDefault();
- e.stopPropagation();
- const vp = viewportRef.current;
- if (!vp) return;
- const rect = vp.getBoundingClientRect();
- const x = Math.max(12, Math.min(rect.width - 210, e.clientX - rect.left));
- const y = Math.max(12, Math.min(rect.height - 150, e.clientY - rect.top));
- setQuickPalettePos({ x, y });
- };
-
- // Dispatch a resolved ModifierAction; returns true if the event was consumed
- const dispatchModifierAction = (
- action: ModifierAction,
- e: React.PointerEvent<HTMLElement>,
- allowDrawingPassThrough: boolean
- ): boolean => {
- switch (action) {
- case 'pan':
- onStartPan(e);
- return true;
- case 'rotate':
- onStartRotate(e);
- return true;
- case 'zoom-drag':
- if (onStartZoomDrag) {
- onStartZoomDrag(e);
- return true;
- }
- return false;
- case 'brush-size':
- startBrushResize(e);
- return true;
- case 'eyedropper':
- if (e.button !== 0 || !allowDrawingPassThrough) {
- startModifierEyedropper(e);
- return true;
- }
- // When button 0 + Alt is held, GlobalShortcutListener already switched tool to pipette,
- // or if not, sample directly via startModifierEyedropper
- if (tool !== 'pipette') {
- startModifierEyedropper(e);
- return true;
- }
- return false;
- case 'temp-eraser': {
- if (!allowDrawingPassThrough) return false;
- const cur = useToolStore.getState().tool;
- if (cur !== 'eraser') {
- tempEraserPrevToolRef.current = cur;
- toolStoreActions.selectTool('eraser');
- }
- return false; // let stroke begin on eraser
- }
- case 'undo':
- e.preventDefault();
- e.stopPropagation();
- onUndo?.();
- return true;
- case 'swap-colors':
- e.preventDefault();
- e.stopPropagation();
- onSwapColors?.();
- return true;
- case 'quick-palette':
- openQuickPaletteAt(e);
- return true;
- case 'straight-line':
- case 'none':
- default:
- return false;
- }
- };
-
- // Viewport background pointer down (clicking gray area to pan, rotate, zoom, resize, or quick palette)
- const handleViewportPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
- releaseExternalFocus();
- if (quickPalettePos) setQuickPalettePos(null);
-
- const modSettings = useUiStore.getState().appSettings.modifierKeys;
- const resolved = resolvePointerModifierAction(
- {
- button: e.button,
- pointerType: e.pointerType,
- ctrlKey: e.ctrlKey,
- metaKey: e.metaKey,
- shiftKey: e.shiftKey,
- altKey: e.altKey,
- isSpaceDown,
- },
- modSettings
- );
- if (resolved && dispatchModifierAction(resolved.action, e, false)) {
- return;
- }
- };
-
- // Canvas pointer down: resolve Modifier Key Settings first, otherwise dispatch drawing/tool stroke
- const handleCanvasPointerDown = (e: React.PointerEvent<HTMLElement>) => {
- releaseExternalFocus();
- if (quickPalettePos) setQuickPalettePos(null);
-
- const modSettings = useUiStore.getState().appSettings.modifierKeys;
- const resolved = resolvePointerModifierAction(
- {
- button: e.button,
- pointerType: e.pointerType,
- ctrlKey: e.ctrlKey,
- metaKey: e.metaKey,
- shiftKey: e.shiftKey,
- altKey: e.altKey,
- isSpaceDown,
- },
- modSettings
- );
-
- if (resolved) {
- if (dispatchModifierAction(resolved.action, e, true)) {
- return;
- }
- }
-
- if (e.button === 0) {
- e.preventDefault();
- } else {
- return;
- }
-
- const coalesced = extractCoalescedEvents(e);
- (e as any).coalescedEvents = coalesced;
- if (e.nativeEvent) {
- (e.nativeEvent as any).coalescedEvents = coalesced;
- }
- onPointerDown(e, coalesced);
- };
-
- const handleCanvasPointerMove = (e: React.PointerEvent<HTMLElement>) => {
- const coalesced = extractCoalescedEvents(e);
- const predicted = extractPredictedEvents(e);
- (e as any).coalescedEvents = coalesced;
- (e as any).predictedEvents = predicted;
- if (e.nativeEvent) {
- (e.nativeEvent as any).coalescedEvents = coalesced;
- (e.nativeEvent as any).predictedEvents = predicted;
- }
- onPointerMove(e, coalesced, predicted);
- };
-
- const handleCanvasPointerUp = (e: React.PointerEvent<HTMLElement>) => {
- onPointerUp(e);
- if (tempEraserPrevToolRef.current !== null) {
- const prev = tempEraserPrevToolRef.current;
- tempEraserPrevToolRef.current = null;
- toolStoreActions.selectTool(prev);
- }
- };
-
- const handleCanvasPointerCancel = (e: React.PointerEvent<HTMLElement>) => {
- handleCanvasPointerUp(e);
- };
+ brushOpacity: brushSettings.opacity,
+ colorMode,
+ tileGrid,
+ });
- const handleContextMenu = (e: React.MouseEvent<HTMLElement>) => {
- const modSettings = useUiStore.getState().appSettings.modifierKeys;
- if (modSettings.rightClick !== 'none' || modSettings.stylusButton1 !== 'none') {
- e.preventDefault();
- }
- };
+ const {
+ handleViewportPointerDown,
+ handleCanvasPointerDown,
+ handleCanvasPointerMove,
+ handleCanvasPointerUp,
+ handleCanvasPointerCancel,
+ handleContextMenu,
+ } = useCanvasPointerHandlers({
+ viewportRef,
+ dimensions,
+ brushSettings,
+ liquifySettings,
+ tool,
+ navigation,
+ pan,
+ zoom,
+ rotation,
+ flipX,
+ flipY,
+ isSpaceDown,
+ quickPalettePos,
+ setQuickPalettePos,
+ setIsResizingBrush,
+ resizeOriginRef,
+ resizeStartSettingsRef,
+ onStartPan,
+ onStartRotate,
+ onStartZoomDrag,
+ onSampleColor,
+ onUndo,
+ onSwapColors,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+ });
- // Determine cursor based on active mode
- const getCursorStyle = (isOverCanvas: boolean): React.CSSProperties => {
- if (isResizingBrush || heldModifierAction === 'brush-size') {
- return { cursor: 'ew-resize' };
- }
- if (isZoomDragging || heldModifierAction === 'zoom-drag') {
- return { cursor: 'zoom-in' };
- }
- if (isRotating || isRotateModifier || heldModifierAction === 'rotate') {
- return { cursor: ROTATE_CURSOR_CSS };
- }
- if (isPanning) {
- return { cursor: 'grabbing' };
- }
- if (isSpaceDown || heldModifierAction === 'pan') {
- return { cursor: 'grab' };
- }
- if (tool === 'pipette' || heldModifierAction === 'eyedropper') {
- return { cursor: PIPETTE_CURSOR_CSS };
- }
- if (tool === 'text') {
- return { cursor: 'text' };
- }
- if (tool === 'select-rect' || tool === 'select-lasso' || tool === 'select-wand' || tool === 'fill' || tool === 'frame' || tool === 'shape') {
- return { cursor: 'crosshair' };
- }
- if (tool === 'liquify') {
- return { cursor: isOverCanvas ? 'none' : 'default' };
- }
- if (tool === 'transform') {
- return { cursor: 'default' };
- }
- if (tool === 'brush' || tool === 'eraser' || tool === 'select-pen' || tool === 'select-eraser') {
- return { cursor: isOverCanvas ? 'none' : 'default' };
- }
- return { cursor: isOverCanvas ? 'crosshair' : 'default' };
+ const cursorStyleBase = {
+ isResizingBrush,
+ heldModifierAction,
+ isZoomDragging,
+ isRotating,
+ isRotateModifier,
+ isPanning,
+ isSpaceDown,
+ tool,
};
// Viewport bounds for positioning floating preview
@@ -1354,7 +244,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
className="flex-1 bg-[#161616] overflow-hidden relative select-none canvas-viewport"
style={{
touchAction: 'none',
- ...getCursorStyle(false),
+ ...getCursorStyle({ ...cursorStyleBase, isOverCanvas: false }),
}}
>
{/* Sleek Floating Pill Slider near Canvas Edge for Brush Size & Opacity */}
@@ -1382,315 +272,21 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
/>
{/* Artboard Container with 2D Affine Transformation (Pan, Zoom, Rotation, and Non-Destructive View Flip) */}
- <div
- ref={artboardRef}
- className="absolute origin-top-left select-none z-20"
- style={{
- width: dimensions.width,
- height: dimensions.height,
- transform: formatArtboardTransform(
- livePan,
- liveZoom,
- liveRotation,
- liveFlipX,
- liveFlipY,
- dimensions
- ),
- transformOrigin: '0 0',
- willChange: 'transform',
- backgroundColor: 'transparent',
- backgroundImage: 'none',
- }}
- >
- {/* Remote Peer Live Stroke Draft Overlay Canvases */}
- {peers.map((peer) => (
- <canvas
- key={`peer-canvas-${peer.id}`}
- ref={(el) => {
- if (remoteDraftCanvasesRef) {
- if (el) remoteDraftCanvasesRef.current.set(peer.id, el);
- else remoteDraftCanvasesRef.current.delete(peer.id);
- }
- }}
- width={dimensions.width}
- height={dimensions.height}
- className="absolute inset-0 block pointer-events-none z-15"
- style={{ imageRendering: zoom > 1 ? 'pixelated' : 'auto' }}
- />
- ))}
-
- {/* Remote Peer Ghost Cursors with Nametag Badges */}
- {peers.map((peer) => {
- if (peer.x === undefined || peer.y === undefined) return null;
- return (
- <div
- key={`peer-cursor-${peer.id}`}
- className="absolute pointer-events-none transition-transform duration-75 ease-out z-25 select-none -translate-x-1/2 -translate-y-1/2"
- style={{
- left: `${peer.x}px`,
- top: `${peer.y}px`,
- }}
- >
- {/* Colored Cursor Ring */}
- <div
- className="w-3.5 h-3.5 rounded-full border-2 border-white shadow-md animate-in fade-in"
- style={{ backgroundColor: peer.color }}
- />
- {/* Floating Nametag Pill */}
- <div
- className="absolute top-4 left-2 px-1.5 py-0.5 rounded text-[10px] font-semibold text-white shadow-lg whitespace-nowrap flex items-center space-x-1 pointer-events-none"
- style={{
- backgroundColor: peer.color,
- transform: `scale(${liveFlipX ? -1 : 1}, ${liveFlipY ? -1 : 1})`,
- }}
- >
- <span>{peer.name}</span>
- {peer.isDrawing && <span className="w-1.5 h-1.5 rounded-full bg-white animate-pulse" />}
- </div>
- </div>
- );
- })}
-
- {/* Canvas Radar Pings */}
- {activePings.map((ping) => (
- <div
- key={ping.id}
- className="absolute pointer-events-none z-30 -translate-x-1/2 -translate-y-1/2"
- style={{ left: `${ping.x}px`, top: `${ping.y}px` }}
- >
- <div
- className="w-12 h-12 rounded-full border-2 animate-ping"
- style={{ borderColor: ping.color }}
- />
- <div
- className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-3.5 h-3.5 rounded-full shadow-md"
- style={{ backgroundColor: ping.color }}
- />
- <div
- className="absolute top-5 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded text-[10px] font-bold text-white whitespace-nowrap shadow-md"
- style={{
- backgroundColor: ping.color,
- transform: `scale(${liveFlipX ? -1 : 1}, ${liveFlipY ? -1 : 1})`,
- }}
- >
- {ping.name}
- </div>
- </div>
- ))}
-
- {/* Selection Overlay */}
- {selection && (
- <SelectionOverlay
- selection={selection}
- dimensions={dimensions}
- zoom={liveZoom}
- flipX={liveFlipX}
- flipY={liveFlipY}
- onDeselect={onDeselect || (() => {})}
- onTransformSelection={onTransformSelection || (() => {})}
- onFillScreentone={onFillScreentone || (() => {})}
- onFillColor={onFillColor || (() => {})}
- onClearSelection={onClearSelection || (() => {})}
- onInvertSelection={onInvertSelection || (() => {})}
- onExpandSelection={onExpandSelection}
- onContractSelection={onContractSelection}
- onFeatherSelection={onFeatherSelection}
- />
- )}
-
- {/* Free Transform Overlay */}
- {transformSession?.active && (
- <TransformOverlay
- session={transformSession}
- zoom={liveZoom}
- rotation={liveRotation}
- flipX={liveFlipX}
- flipY={liveFlipY}
- onUpdateSession={onUpdateTransformSession || (() => {})}
- onApply={onApplyTransform || (() => {})}
- onCancel={onCancelTransform || (() => {})}
- />
- )}
-
- {/* Manga Text Editor Overlay */}
- {textSession && (
- <TextEditorOverlay
- x={textSession.x}
- y={textSession.y}
- settings={textSession.settings}
- zoom={liveZoom}
- rotation={liveRotation}
- flipX={liveFlipX}
- flipY={liveFlipY}
- onUpdateSettings={onUpdateTextSettings || (() => {})}
- onMove={onMoveTextSession || (() => {})}
- onConfirm={onConfirmText || (() => {})}
- onCancel={onCancelText || (() => {})}
- />
- )}
-
- {/* Parametric Speech Balloon Overlay */}
- {activeBalloon && (
- <SpeechBalloonOverlay
- balloon={activeBalloon}
- zoom={liveZoom}
- rotation={liveRotation}
- flipX={liveFlipX}
- flipY={liveFlipY}
- onUpdateBalloon={onUpdateBalloon || (() => {})}
- onConfirmBalloon={onConfirmBalloon || (() => {})}
- onDeleteBalloon={onDeleteBalloon || (() => {})}
- />
- )}
-
- {/* Frame Border Folder Create / Divide Live Preview */}
- {frameDragPreview && (
- <svg className="absolute inset-0 w-full h-full overflow-visible pointer-events-none z-35">
- {frameDragPreview.mode === 'create' ? (
- <rect
- x={Math.min(frameDragPreview.start.x, frameDragPreview.end.x)}
- y={Math.min(frameDragPreview.start.y, frameDragPreview.end.y)}
- width={Math.abs(frameDragPreview.end.x - frameDragPreview.start.x)}
- height={Math.abs(frameDragPreview.end.y - frameDragPreview.start.y)}
- fill="rgba(0, 188, 212, 0.08)"
- stroke="#00bcd4"
- strokeWidth={2 / liveZoom}
- strokeDasharray={`${6 / liveZoom},${4 / liveZoom}`}
- />
- ) : (
- <>
- <line
- x1={frameDragPreview.start.x}
- y1={frameDragPreview.start.y}
- x2={frameDragPreview.end.x}
- y2={frameDragPreview.end.y}
- stroke="#00e5ff"
- strokeWidth={2.5 / liveZoom}
- strokeDasharray={`${8 / liveZoom},${4 / liveZoom}`}
- />
- <circle
- cx={frameDragPreview.start.x}
- cy={frameDragPreview.start.y}
- r={4 / liveZoom}
- fill="#00e5ff"
- />
- <circle
- cx={frameDragPreview.end.x}
- cy={frameDragPreview.end.y}
- r={4 / liveZoom}
- fill="#00e5ff"
- />
- </>
- )}
- </svg>
- )}
-
- {/* Live Geometric Shape Placement Preview */}
- {shapeDragPreview && (() => {
- const { geom, mainPath, arrowHeadPath } = buildShapeSvgPaths(shapeDragPreview);
- const s = shapeDragPreview.settings;
- const open = isOpenShape(s.shape);
- const strokeColor = primaryColor || '#000000';
- const fillColor = resolveShapeFillColor(s, strokeColor, secondaryColor);
- const shouldFill = !open && (s.mode === 'fill' || s.mode === 'both');
- const shouldStroke = open || s.mode === 'stroke' || s.mode === 'both';
- const dashArray = s.dashed ? `${Math.max(1, s.dashLength)} ${Math.max(1, s.dashGap)}` : undefined;
- const invZoom = 1 / Math.max(0.05, liveZoom);
- const readoutText = open
- ? `${Math.round(geom.length)}px · ${Math.round(geom.angleDeg)}°`
- : `${Math.round(geom.width)} × ${Math.round(geom.height)}px`;
- return (
- <>
- <svg
- className="absolute inset-0 w-full h-full pointer-events-none z-30 overflow-visible"
- viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}
- >
- {mainPath && (
- <path
- d={mainPath}
- fill={shouldFill ? fillColor : 'none'}
- stroke={shouldStroke ? strokeColor : 'none'}
- strokeWidth={Math.max(1, s.strokeWidth)}
- strokeLinecap={s.lineCap}
- strokeLinejoin={s.lineJoin}
- strokeDasharray={dashArray}
- opacity={Math.max(0.05, Math.min(1, s.opacity))}
- />
- )}
- {arrowHeadPath && (
- <path
- d={arrowHeadPath}
- fill="none"
- stroke={strokeColor}
- strokeWidth={Math.max(1, s.strokeWidth)}
- strokeLinecap={s.lineCap}
- strokeLinejoin={s.lineJoin}
- opacity={Math.max(0.05, Math.min(1, s.opacity))}
- />
- )}
- {!open && geom.width > 1 && geom.height > 1 && (
- <rect
- x={geom.x}
- y={geom.y}
- width={geom.width}
- height={geom.height}
- fill="none"
- stroke="#e5e5e5"
- strokeOpacity={0.55}
- strokeWidth={1 * invZoom}
- strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}
- />
- )}
- </svg>
- <div
- className="absolute pointer-events-none z-30 px-1.5 py-0.5 rounded bg-[#161616]/90 border border-white/15 text-[#e5e5e5] font-mono text-[10px] whitespace-nowrap"
- style={{
- left: `${geom.x2}px`,
- top: `${geom.y2}px`,
- transform: `translate(${10 * invZoom}px, ${10 * invZoom}px) scale(${invZoom})`,
- transformOrigin: 'top left',
- }}
- >
- {readoutText}
- </div>
- </>
- );
- })()}
-
- {/* Local-Only 3D Viewport Ghost Layer (Strictly Client-Side Isolated State) */}
- {is3DLayerOpen && onClose3DLayer && onInsertRasterLayer && (
- <Local3DContainer
- dimensions={dimensions}
- zoom={zoom}
- pan={pan}
- rotation={rotation}
- isOpen={is3DLayerOpen}
- initialFile={initial3DFile}
- onClose={onClose3DLayer}
- onInsertRasterLayer={onInsertRasterLayer}
- onBakeSuccess={onBake3DSuccess}
- perspectiveRuler={perspectiveRuler}
- onUpdatePerspectiveRuler={onUpdatePerspectiveRuler}
- />
- )}
-
- {/* Top Transparent Interaction Surface capturing Stylus / Mouse Pointer Events */}
- <div
- ref={interactionRef}
- onPointerDown={handleCanvasPointerDown}
- onPointerMove={handleCanvasPointerMove}
- onPointerUp={handleCanvasPointerUp}
- onPointerCancel={handleCanvasPointerCancel}
- onLostPointerCapture={handleCanvasPointerCancel}
- onPointerEnter={onPointerEnter}
- onPointerLeave={onPointerLeave}
- onContextMenu={handleContextMenu}
- className="absolute inset-0 block touch-none z-20"
- style={{
- ...getCursorStyle(true),
- }}
- />
- </div>
+ <CanvasArtboardOverlays
+ canvasProps={props}
+ artboardRef={artboardRef}
+ livePan={livePan}
+ liveZoom={liveZoom}
+ liveRotation={liveRotation}
+ liveFlipX={liveFlipX}
+ liveFlipY={liveFlipY}
+ handleCanvasPointerDown={handleCanvasPointerDown}
+ handleCanvasPointerMove={handleCanvasPointerMove}
+ handleCanvasPointerUp={handleCanvasPointerUp}
+ handleCanvasPointerCancel={handleCanvasPointerCancel}
+ handleContextMenu={handleContextMenu}
+ canvasCursorStyle={getCursorStyle({ ...cursorStyleBase, isOverCanvas: true })}
+ />
{/* Offscreen Active Draft/Stroke Backing Canvas (composited in-stack inside ViewportCompositor at activeLayerId) */}
<canvas
@@ -1729,358 +325,30 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
</defs>
</svg>
- {/* Interactive Straight Ruler Overlay */}
- {straightRuler && straightRuler.enabled && onUpdateStraightRuler && (
- <StraightRulerOverlay
- ruler={straightRuler}
- onUpdateRuler={onUpdateStraightRuler}
- onCloseRuler={() => onUpdateStraightRuler({ ...straightRuler, enabled: false })}
- dimensions={dimensions}
- pan={livePan}
- zoom={liveZoom}
- rotation={liveRotation}
- flipX={liveFlipX}
- flipY={liveFlipY}
- navigation={navigation}
- viewportRef={viewportRef}
- />
- )}
-
- {/* Interactive Perspective Ruler Overlay Layer (Clip Studio Paint style) */}
- {perspectiveRuler && onUpdatePerspectiveRuler && (
- <PerspectiveRulerOverlay
- ruler={perspectiveRuler}
- onUpdateRuler={onUpdatePerspectiveRuler}
- onRemoveRuler={() => onUpdatePerspectiveRuler(null)}
- dimensions={dimensions}
- pan={livePan}
- zoom={liveZoom}
- rotation={liveRotation}
- flipX={liveFlipX}
- flipY={liveFlipY}
- navigation={navigation}
- viewportRef={viewportRef}
- activeLockedAxis={activeLockedAxis}
- isDrawing={isDrawing}
- />
- )}
-
- {/* Dynamic Dual-Tone Brush Silhouette Outline Cursor (CSP / Photoshop style) */}
- <div
- ref={cursorRingRef}
- className="pointer-events-none absolute top-0 left-0 z-30 select-none"
- style={{
- display: 'none',
- width: `${cursorWidth}px`,
- height: `${cursorHeight}px`,
- willChange: 'transform',
- transformOrigin: 'center center',
- }}
- >
- <svg
- viewBox={isCustomTip && tipOutline ? tipOutline.viewBox : '0 0 100 100'}
- className="w-full h-full overflow-visible pointer-events-none select-none"
- style={{ display: 'block' }}
- >
- {isCustomTip && tipOutline ? (
- <>
- <path
- d={tipOutline.path}
- fill="none"
- stroke="rgba(255, 255, 255, 0.85)"
- strokeWidth="2.5"
- strokeLinejoin="round"
- strokeLinecap="round"
- vectorEffect="non-scaling-stroke"
- />
- <path
- d={tipOutline.path}
- fill="none"
- stroke="rgba(0, 0, 0, 0.85)"
- strokeWidth="1"
- strokeLinejoin="round"
- strokeLinecap="round"
- vectorEffect="non-scaling-stroke"
- />
- </>
- ) : isSquare ? (
- <>
- <rect
- x="1"
- y="1"
- width="98"
- height="98"
- fill="none"
- stroke="rgba(255, 255, 255, 0.85)"
- strokeWidth="2.5"
- vectorEffect="non-scaling-stroke"
- />
- <rect
- x="1"
- y="1"
- width="98"
- height="98"
- fill="none"
- stroke="rgba(0, 0, 0, 0.85)"
- strokeWidth="1"
- vectorEffect="non-scaling-stroke"
- />
- </>
- ) : (
- <>
- <ellipse
- cx="50"
- cy="50"
- rx="49.5"
- ry="49.5"
- fill="none"
- stroke="rgba(255, 255, 255, 0.85)"
- strokeWidth="2.5"
- vectorEffect="non-scaling-stroke"
- />
- <ellipse
- cx="50"
- cy="50"
- rx="49.5"
- ry="49.5"
- fill="none"
- stroke="rgba(0, 0, 0, 0.85)"
- strokeWidth="1"
- vectorEffect="non-scaling-stroke"
- />
- </>
- )}
- </svg>
- </div>
-
- {/* Floating Visual Preview for On-Canvas Brush Resizing (Ctrl + Alt + Drag) */}
- {isResizingBrush && (
- <div
- className="pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 z-50 flex items-center justify-center"
- style={{
- left: `${resizePreviewX}px`,
- top: `${resizePreviewY}px`,
- width: `${cursorWidth}px`,
- height: `${cursorHeight}px`,
- transform: `translate(-50%, -50%) rotate(${totalAngleDeg}deg)`,
- transformOrigin: 'center center',
- }}
- >
- {isCustomTip && tipOutline ? (
- <svg
- viewBox={tipOutline.viewBox}
- className="w-full h-full overflow-visible pointer-events-none"
- style={{ display: 'block' }}
- >
- <path
- d={tipOutline.path}
- fill="rgba(239, 68, 68, 0.35)"
- stroke="rgba(255, 255, 255, 0.95)"
- strokeWidth="2.5"
- strokeLinejoin="round"
- vectorEffect="non-scaling-stroke"
- />
- <path
- d={tipOutline.path}
- fill="none"
- stroke="rgba(0, 0, 0, 0.9)"
- strokeWidth="1"
- strokeLinejoin="round"
- vectorEffect="non-scaling-stroke"
- />
- </svg>
- ) : (
- <>
- {/* Outer diameter & hardness preview circle */}
- <div
- className={`w-full h-full ${isSquare ? 'rounded-none' : 'rounded-full'} border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.8),0_4px_16px_rgba(0,0,0,0.5)] transition-[width,height] duration-75`}
- style={{
- background:
- (brushSettings.hardness ?? 1.0) < 0.98
- ? `radial-gradient(circle, rgba(239, 68, 68, 0.45) 0%, rgba(239, 68, 68, 0.45) ${Math.round(
- (brushSettings.hardness ?? 1.0) * 100
- )}%, rgba(239, 68, 68, 0.05) 100%)`
- : 'rgba(239, 68, 68, 0.38)',
- }}
- />
-
- {/* Inner hardness boundary indicator if soft brush */}
- {(brushSettings.hardness ?? 1.0) < 0.98 && (
- <div
- className={`absolute ${isSquare ? 'rounded-none' : 'rounded-full'} border border-dashed border-white/80 pointer-events-none`}
- style={{
- width: `${Math.max(2, cursorWidth * (brushSettings.hardness ?? 1.0))}px`,
- height: `${Math.max(2, cursorHeight * (brushSettings.hardness ?? 1.0))}px`,
- }}
- />
- )}
- </>
- )}
-
- {/* Floating HUD Tooltip Card */}
- <div
- className="absolute top-full mt-3 bg-[#202020] text-[#e5e5e5] px-3 py-1.5 rounded-md shadow-[0_8px_24px_rgba(0,0,0,0.65)] flex flex-col items-center pointer-events-none whitespace-nowrap min-w-36"
- style={{ zIndex: 60 }}
- >
- <div className="flex items-center gap-2 text-[11px] font-mono font-medium text-[#e5e5e5]">
- <span>Size {brushSettings.size}px</span>
- <span className="text-[#8a8a8a]">·</span>
- <span>Hard {Math.round((brushSettings.hardness ?? 1.0) * 100)}%</span>
- </div>
- </div>
- </div>
- )}
-
- {/* Floating Quick Palette Popover (triggered by modifier mapped to 'quick-palette') */}
- {quickPalettePos && (
- <div
- onPointerDown={(e) => e.stopPropagation()}
- onContextMenu={(e) => e.preventDefault()}
- className="absolute z-50 bg-[#202020] border border-white/10 rounded-md shadow-[0_12px_32px_rgba(0,0,0,0.75)] p-2.5 w-48 space-y-2 text-[11px] text-[#e5e5e5] select-none"
- style={{ left: `${quickPalettePos.x}px`, top: `${quickPalettePos.y}px` }}
- >
- <div className="flex items-center justify-between text-[10px] text-[#8a8a8a] uppercase tracking-wider">
- <span>Quick Palette</span>
- <button
- type="button"
- onClick={() => setQuickPalettePos(null)}
- className="hover:text-[#e5e5e5] cursor-pointer px-1"
- >
- ×
- </button>
- </div>
- <div className="grid grid-cols-6 gap-1">
- {useToolStore.getState().recentColors.slice(0, 12).map((hex) => (
- <button
- key={hex}
- type="button"
- onClick={() => {
- toolStoreActions.setPrimaryColor(hex);
- setQuickPalettePos(null);
- }}
- className="w-6 h-6 rounded border border-white/15 cursor-pointer"
- style={{ backgroundColor: hex }}
- title={hex}
- />
- ))}
- </div>
- <div className="space-y-1">
- <div className="flex items-center justify-between text-[10px] text-[#8a8a8a]">
- <span>Size</span>
- <span className="font-mono text-[#e5e5e5]">{brushSettings.size}px</span>
- </div>
- <input
- type="range"
- min="1"
- max="300"
- value={Math.round(brushSettings.size)}
- onChange={(e) => onUpdateBrushSettings({ size: Number(e.target.value) })}
- className="w-full"
- />
- </div>
- <div className="grid grid-cols-3 gap-1 pt-0.5">
- <button
- type="button"
- onClick={() => {
- onUndo?.();
- setQuickPalettePos(null);
- }}
- className="px-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] cursor-pointer"
- >
- Undo
- </button>
- <button
- type="button"
- onClick={() => {
- onRedo?.();
- setQuickPalettePos(null);
- }}
- className="px-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] cursor-pointer"
- >
- Redo
- </button>
- <button
- type="button"
- onClick={() => {
- onFlipHorizontal?.();
- setQuickPalettePos(null);
- }}
- className="px-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] cursor-pointer"
- >
- Flip H
- </button>
- </div>
- </div>
- )}
-
- {/* Floating Webtoon Mode Controls (only shown when Webtoon Mode is active) */}
- {isWebtoonMode && (
- <div className="absolute top-3 right-3 z-40 flex items-center gap-1.5 select-none">
- <button
- onClick={onToggleWebtoonMode}
- className="px-2.5 py-1 rounded-full text-[11px] font-medium flex items-center gap-1.5 bg-[#202020] hover:bg-[#2c2c2c] text-[#e5e5e5] shadow-lg transition-colors cursor-pointer"
- title="Exit Webtoon Studio Mode"
- >
- <Smartphone className="w-3.5 h-3.5 text-[var(--accent)]" />
- <span>Exit Webtoon</span>
- </button>
-
- {onOpenWebtoonExport && (
- <button
- onClick={onOpenWebtoonExport}
- className="px-2.5 py-1 rounded-full text-[11px] font-medium bg-[#202020] hover:bg-[#2c2c2c] text-[#e5e5e5] flex items-center gap-1.5 shadow-lg transition-colors cursor-pointer"
- title="Export Chapter Slices (.zip)"
- >
- <Archive className="w-3.5 h-3.5 text-[#8a8a8a]" />
- <span>Export Slices</span>
- </button>
- )}
- </div>
- )}
-
- {/* Subtle Zero-Height Canvas Coordinate / Pressure Readout (only shown if bottom StatusBar is hidden) */}
- {false && (showCursorCoordinates || showPressureInStatusBar) && (
- <div
- ref={pointerStatRef}
- className="pointer-events-none absolute bottom-2 right-3 z-30 text-[10px] font-mono text-[#8a8a8a]/70 select-none"
- />
- )}
-
- {/* Smartphone Viewport Simulator in Webtoon Mode */}
- {isWebtoonMode && (
- <SmartphoneViewportSimulator
- visible={true}
- onToggleVisible={onToggleWebtoonMode || (() => {})}
- />
- )}
-
- {/* 2D Frame-by-Frame Animation Timeline Scrubber Dock */}
- {animationTimeline && onUpdateAnimationTimeline && (
- <AnimationTimeline
- timeline={animationTimeline}
- onChangeTimeline={onUpdateAnimationTimeline}
- layers={layers}
- layerCanvasesMap={layerCanvasesRef?.current || new Map()}
- dimensions={dimensions}
- onAddCel={onAddAnimationCel || (() => {})}
- onDeleteCel={onDeleteAnimationCel || (() => {})}
- onSelectCelLayer={onSelectCelLayer}
- />
- )}
-
- {isExternalFileDropActive && (
- <div
- data-testid="canvas-file-drop-overlay"
- className="pointer-events-none absolute inset-2 z-50 rounded-md border-2 border-dashed border-[var(--accent)] bg-[var(--accent)]/8 flex items-center justify-center"
- >
- <div className="px-3.5 py-2 rounded-md bg-[#161616]/95 border border-[var(--accent)]/60 text-xs font-medium text-[#f5f5f5] shadow-xl">
- Drop image to import as layer
- </div>
- </div>
- )}
+ {/* Viewport-Space Overlays & HUD */}
+ <CanvasViewportHud
+ canvasProps={props}
+ cursorRingRef={cursorRingRef}
+ pointerStatRef={pointerStatRef}
+ livePan={livePan}
+ liveZoom={liveZoom}
+ liveRotation={liveRotation}
+ liveFlipX={liveFlipX}
+ liveFlipY={liveFlipY}
+ cursorWidth={cursorWidth}
+ cursorHeight={cursorHeight}
+ totalAngleDeg={totalAngleDeg}
+ isCustomTip={isCustomTip}
+ isSquare={isSquare}
+ tipOutline={tipOutline}
+ isResizingBrush={isResizingBrush}
+ resizePreviewX={resizePreviewX}
+ resizePreviewY={resizePreviewY}
+ quickPalettePos={quickPalettePos}
+ setQuickPalettePos={setQuickPalettePos}
+ />
</main>
);
});
CanvasArea.displayName = 'CanvasArea';
-
diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsx
index 2d13723..3db0963 100644
--- a/src/components/DocumentLifecycleManager.tsx
+++ b/src/components/DocumentLifecycleManager.tsx
@@ -23,6 +23,7 @@ import { importBrushFile, isSupportedBrushFileName } from '../utils/inkbBrushFor
import { documentStore } from '../utils/documentStore';
import { shortcutManager } from '../utils/shortcutManager';
import { recoveryService, CrashedSessionInfo } from '../services/recoveryService';
+import { multiplayerService } from '../services/multiplayerService';
import {
documentStoreActions,
toolStoreActions,
@@ -45,7 +46,6 @@ export interface UseDocumentLifecycleParams {
layers: LayerItem[];
activeLayer: LayerItem | undefined;
activeLayerId: string;
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
getEffectiveOpacity: (layer: LayerItem) => number;
isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
setActiveLayerId: (id: string) => void;
@@ -84,7 +84,6 @@ export function useDocumentLifecycle({
layers,
activeLayer,
activeLayerId,
- layerCanvasesRef,
getEffectiveOpacity,
isLayerEffectivelyVisible,
setActiveLayerId,
@@ -279,6 +278,9 @@ export function useDocumentLifecycle({
needsAdaptiveFitRef.current = true;
resetZoomAndCenter(newDims);
resetHistory();
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendCanvasResize(newDims, options);
+ }
showToast(`Canvas resized to ${newDims.width} × ${newDims.height} px`);
},
[resetHistory, resetZoomAndCenter, resizeCanvas, showToast]
@@ -370,7 +372,14 @@ export function useDocumentLifecycle({
isSaved: true,
}).catch(console.warn);
- showToast(`Opened ${file.name}`);
+ const openedExt = file.name.includes('.')
+ ? file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
+ : '';
+ showToast(
+ openedExt === '.sora'
+ ? `Migrated legacy ${file.name} (read-only) — save as .ink`
+ : `Opened ${file.name}`
+ );
} catch (err: unknown) {
console.error('Failed to open file:', err);
const errMsg = err instanceof Error ? err.message : String(err);
@@ -611,7 +620,6 @@ export function useDocumentLifecycle({
dimensions,
colorMode,
layers,
- layerCanvasesMap: layerCanvasesRef.current,
tileGrid: documentStore.getActiveTileGrid(),
getEffectiveOpacity,
isLayerEffectivelyVisible,
@@ -632,7 +640,6 @@ export function useDocumentLifecycle({
documentName,
getEffectiveOpacity,
isLayerEffectivelyVisible,
- layerCanvasesRef,
layers,
]
);
@@ -643,9 +650,14 @@ export function useDocumentLifecycle({
};
const docData = buildSaveData(onProgress);
- if (!savedFileInfo?.handle) {
+ const preferredExt =
+ savedFileInfo?.extension && savedFileInfo.extension.toLowerCase() !== '.sora'
+ ? savedFileInfo.extension
+ : '.ink';
+
+ if (!savedFileInfo?.handle || savedFileInfo.extension?.toLowerCase() === '.sora') {
try {
- const info = await promptSaveAs(docData, savedFileInfo?.extension || '.sora');
+ const info = await promptSaveAs(docData, preferredExt);
documentStoreActions.setSavedFileInfo(info);
documentStoreActions.setDocumentName(info.name);
documentStoreActions.setDocuments((prev) =>
@@ -695,7 +707,7 @@ export function useDocumentLifecycle({
} catch (err: unknown) {
console.warn('Direct handle save failed, prompting with Save As:', err);
try {
- const info = await promptSaveAs(docData, savedFileInfo.extension || '.sora');
+ const info = await promptSaveAs(docData, preferredExt);
documentStoreActions.setSavedFileInfo(info);
documentStoreActions.setDocumentName(info.name);
documentStoreActions.setDocuments((prev) =>
@@ -733,7 +745,10 @@ export function useDocumentLifecycle({
const docData = buildSaveData(onProgress);
try {
- const defaultExt = savedFileInfo?.extension || '.sora';
+ const defaultExt =
+ savedFileInfo?.extension && savedFileInfo.extension.toLowerCase() !== '.sora'
+ ? savedFileInfo.extension
+ : '.ink';
const info = await promptSaveAs(docData, defaultExt);
documentStoreActions.setSavedFileInfo(info);
documentStoreActions.setDocumentName(info.name);
@@ -853,7 +868,6 @@ export function useDocumentLifecycle({
export interface DocumentLifecycleManagerProps {
layers: LayerItem[];
activeLayerId: string;
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
needsAdaptiveFitRef: React.MutableRefObject<boolean>;
pendingFitDimsRef: React.MutableRefObject<CanvasDimensions | null>;
resetToNewCanvas: (
@@ -876,7 +890,6 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
({
layers,
activeLayerId,
- layerCanvasesRef,
needsAdaptiveFitRef,
pendingFitDimsRef,
resetToNewCanvas,
@@ -1035,7 +1048,7 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
}
}
);
- }, [activeDocumentId, layerCanvasesRef]);
+ }, [activeDocumentId]);
// 5. Keep active document tab's metadata in sync
useEffect(() => {
diff --git a/src/components/Header.tsx b/src/components/Header.tsx
index f9866cc..7c75700 100644
--- a/src/components/Header.tsx
+++ b/src/components/Header.tsx
@@ -50,6 +50,7 @@ export interface HeaderProps {
onRenameDocument?: (id: string, newName: string) => void;
commandHandlers?: WorkspaceCommandHandlers;
isCollabConnected?: boolean;
+ isCollabReconnecting?: boolean;
collabPeerCount?: number;
onOpenCollabModal?: () => void;
onOpenSettings?: () => void;
@@ -80,6 +81,7 @@ export const Header: React.FC<HeaderProps> = React.memo(({
hasOpenDocument = true,
commandHandlers,
isCollabConnected = false,
+ isCollabReconnecting = false,
collabPeerCount = 1,
onOpenCollabModal,
onOpenSettings,
@@ -281,15 +283,27 @@ export const Header: React.FC<HeaderProps> = React.memo(({
<button
type="button"
onClick={onOpenCollabModal}
- title={isCollabConnected ? `Collab (${collabPeerCount} online)` : 'Collaborative Session'}
+ title={
+ isCollabReconnecting
+ ? 'Collab: Reconnecting...'
+ : isCollabConnected
+ ? `Collab (${collabPeerCount} online)`
+ : 'Collaborative Session'
+ }
className={`h-6 px-1.5 rounded flex items-center gap-1 text-[11px] transition-colors cursor-pointer ${
- isCollabConnected
- ? 'bg-[#2c2c2c] text-[var(--accent)]'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ isCollabReconnecting
+ ? 'bg-amber-500/20 text-amber-300 animate-pulse'
+ : isCollabConnected
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
}`}
>
<Users className="w-3.5 h-3.5" />
- {isCollabConnected && <span className="font-mono text-[10px]">{collabPeerCount}</span>}
+ {isCollabReconnecting ? (
+ <span className="font-mono text-[10px]">...</span>
+ ) : (
+ isCollabConnected && <span className="font-mono text-[10px]">{collabPeerCount}</span>
+ )}
</button>
)}
diff --git a/src/components/HostModal.tsx b/src/components/HostModal.tsx
index 326c16a..54d746f 100644
--- a/src/components/HostModal.tsx
+++ b/src/components/HostModal.tsx
@@ -1,5 +1,10 @@
import React, { useState, useEffect, useRef } from 'react';
-import { SessionHostInfo, CollabPeer } from '../types/multiplayer';
+import {
+ SessionHostInfo,
+ CollabPeer,
+ CollabRole,
+ ConnectionStatus,
+} from '../types/multiplayer';
import {
Users,
Copy,
@@ -14,6 +19,9 @@ import {
Link2,
LogOut,
AlertTriangle,
+ Ban,
+ UserX,
+ RefreshCw,
} from 'lucide-react';
interface HostModalProps {
@@ -21,8 +29,12 @@ interface HostModalProps {
onClose: () => void;
isHost: boolean;
isConnected: boolean;
+ connectionStatus?: ConnectionStatus;
+ reconnectAttempt?: number;
+ myRole?: CollabRole;
hostInfo: SessionHostInfo | null;
peers: CollabPeer[];
+ bannedPeerIds?: string[];
myPeer: CollabPeer;
onUpdateMyName: (name: string) => void;
onStartHosting: (
@@ -35,6 +47,10 @@ interface HostModalProps {
onStopHosting: () => void;
onJoinByInviteUrl: (rawUrl: string, nickname?: string, persistName?: boolean) => Promise<boolean>;
onLeaveRoom: () => void;
+ onSetPeerRole?: (peerId: string | number, role: 'editor' | 'viewer') => void;
+ onKickPeer?: (peerId: string | number) => void;
+ onBanPeer?: (peerId: string | number) => void;
+ onUnbanPeer?: (peerId: string | number) => void;
showToast: (msg: string) => void;
}
@@ -48,14 +64,22 @@ export const HostModal: React.FC<HostModalProps> = ({
onClose,
isHost,
isConnected,
+ connectionStatus = isConnected ? 'connected' : 'disconnected',
+ reconnectAttempt = 0,
+ myRole = isHost ? 'host' : 'editor',
hostInfo,
peers,
+ bannedPeerIds = [],
myPeer,
onUpdateMyName,
onStartHosting,
onStopHosting,
onJoinByInviteUrl,
onLeaveRoom,
+ onSetPeerRole,
+ onKickPeer,
+ onBanPeer,
+ onUnbanPeer,
showToast,
}) => {
const [activeTab, setActiveTab] = useState<'host' | 'join'>('host');
@@ -175,11 +199,13 @@ export const HostModal: React.FC<HostModalProps> = ({
<div>
<h3 className="text-sm font-semibold text-white">Collaborative Drawing</h3>
<p className="text-[11px] text-[#888888]">
- {isConnected
- ? isHost
- ? 'Hosting active session'
- : 'Connected to remote canvas'
- : 'Host or join a live canvas session'}
+ {connectionStatus === 'reconnecting'
+ ? `Reconnecting (attempt ${reconnectAttempt || 1})...`
+ : isConnected
+ ? isHost
+ ? 'Hosting active session'
+ : `Connected as ${myRole === 'viewer' ? 'Viewer (Read-Only)' : 'Editor'}`
+ : 'Host or join a live canvas session'}
</p>
</div>
</div>
@@ -193,7 +219,39 @@ export const HostModal: React.FC<HostModalProps> = ({
{/* Content */}
<div className="p-5 space-y-4">
- {isConnected && isHost ? (
+ {connectionStatus === 'reconnecting' ? (
+ <div className="space-y-4">
+ <div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3.5 flex items-start space-x-3">
+ <RefreshCw className="w-5 h-5 text-amber-400 shrink-0 mt-0.5 animate-spin" />
+ <div className="flex-1 min-w-0">
+ <div className="text-xs font-semibold text-amber-300">
+ Reconnecting to Session...
+ </div>
+ <div className="text-[11px] text-[#aaaaaa] mt-0.5 truncate">
+ Room: <span className="text-white font-medium">{hostInfo?.roomName || 'Studio'}</span>{' '}
+ (attempt {reconnectAttempt || 1})
+ </div>
+ <div className="text-[10px] text-[#888888] mt-1">
+ Session state is preserved. Missed tiles and layer updates will catch up automatically.
+ </div>
+ </div>
+ </div>
+ <button
+ onClick={() => {
+ if (isHost) {
+ onStopHosting();
+ } else {
+ onLeaveRoom();
+ }
+ onClose();
+ }}
+ className="w-full flex items-center justify-center space-x-2 rounded border border-rose-500/30 bg-rose-500/10 hover:bg-rose-500/20 py-2 text-xs font-medium text-rose-400 transition-colors cursor-pointer"
+ >
+ <LogOut className="w-3.5 h-3.5" />
+ <span>{isHost ? 'Stop Session' : 'Cancel & Leave'}</span>
+ </button>
+ </div>
+ ) : isConnected && isHost ? (
// Active Host View
<div className="space-y-4">
{hostInfo?.isGlobal ? (
@@ -295,27 +353,95 @@ export const HostModal: React.FC<HostModalProps> = ({
</span>
</div>
- {peers.map((peer) => (
- <div
- key={peer.id}
- className="flex items-center justify-between px-3 py-2 text-xs"
- >
- <div className="flex items-center space-x-2">
- <div
- className="w-3 h-3 rounded-full shrink-0"
- style={{ backgroundColor: peer.color }}
- />
- <span className="text-[#dddddd]">{peer.name}</span>
+ {peers.map((peer) => {
+ const peerRole = peer.role === 'viewer' ? 'viewer' : 'editor';
+ return (
+ <div
+ key={peer.id}
+ className="flex items-center justify-between gap-2 px-3 py-2 text-xs"
+ >
+ <div className="flex items-center space-x-2 min-w-0">
+ <div
+ className="w-3 h-3 rounded-full shrink-0"
+ style={{ backgroundColor: peer.color }}
+ />
+ <span className="text-[#dddddd] truncate">{peer.name}</span>
+ </div>
+ <div className="flex items-center space-x-1.5 shrink-0">
+ {onSetPeerRole ? (
+ <select
+ aria-label={`Role for ${peer.name}`}
+ value={peerRole}
+ onChange={(e) =>
+ onSetPeerRole(
+ peer.id,
+ e.target.value === 'viewer' ? 'viewer' : 'editor'
+ )
+ }
+ className="rounded border border-[#3e3e3e] bg-[#252525] px-1.5 py-0.5 text-[10px] text-[#e0e0e0] focus:outline-hidden cursor-pointer"
+ >
+ <option value="editor">Editor</option>
+ <option value="viewer">Viewer</option>
+ </select>
+ ) : (
+ <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#2a2a2a] text-[#aaaaaa] capitalize">
+ {peerRole}
+ </span>
+ )}
+ {onKickPeer && (
+ <button
+ type="button"
+ onClick={() => onKickPeer(peer.id)}
+ title={`Kick ${peer.name}`}
+ className="p-1 rounded text-[#999999] hover:text-amber-300 hover:bg-amber-500/15 transition-colors cursor-pointer"
+ >
+ <UserX className="w-3.5 h-3.5" />
+ </button>
+ )}
+ {onBanPeer && (
+ <button
+ type="button"
+ onClick={() => onBanPeer(peer.id)}
+ title={`Ban ${peer.name}`}
+ className="p-1 rounded text-[#999999] hover:text-rose-400 hover:bg-rose-500/15 transition-colors cursor-pointer"
+ >
+ <Ban className="w-3.5 h-3.5" />
+ </button>
+ )}
+ </div>
</div>
- <span className="text-[10px] text-emerald-400 flex items-center space-x-1">
- <span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
- <span>Online</span>
- </span>
- </div>
- ))}
+ );
+ })}
</div>
</div>
+ {bannedPeerIds.length > 0 && (
+ <div>
+ <div className="text-[11px] font-medium text-[#aaaaaa] mb-1.5">
+ Banned Peers ({bannedPeerIds.length})
+ </div>
+ <div className="rounded border border-[#333333] bg-[#1a1a1a] max-h-24 overflow-y-auto divide-y divide-[#2a2a2a]">
+ {bannedPeerIds.map((pid) => (
+ <div
+ key={pid}
+ className="flex items-center justify-between px-3 py-1.5 text-[11px]"
+ >
+ <span className="font-mono text-[#aaaaaa] truncate">{pid}</span>
+ {onUnbanPeer && (
+ <button
+ type="button"
+ onClick={() => onUnbanPeer(pid)}
+ className="text-[10px] text-sky-400 hover:text-sky-300 underline ml-2 shrink-0 cursor-pointer"
+ >
+ Unban
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
{/* Stop Button */}
<div className="pt-2">
<button
@@ -364,7 +490,15 @@ export const HostModal: React.FC<HostModalProps> = ({
/>
<span className="font-medium text-white">{myPeer.name} (You)</span>
</div>
- <span className="text-[10px] text-emerald-400">Online</span>
+ <span
+ className={`text-[10px] font-mono px-1.5 py-0.5 rounded capitalize ${
+ myRole === 'viewer'
+ ? 'bg-slate-500/20 text-slate-300'
+ : 'bg-emerald-500/20 text-emerald-300'
+ }`}
+ >
+ {myRole}
+ </span>
</div>
{peers.map((peer) => (
<div
@@ -378,8 +512,8 @@ export const HostModal: React.FC<HostModalProps> = ({
/>
<span className="text-[#dddddd]">{peer.name}</span>
</div>
- <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#2a2a2a] text-[#aaaaaa]">
- {peer.isHost ? 'Host' : 'Peer'}
+ <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#2a2a2a] text-[#aaaaaa] capitalize">
+ {peer.isHost ? 'Host' : peer.role || 'Editor'}
</span>
</div>
))}
diff --git a/src/components/ModalHost.tsx b/src/components/ModalHost.tsx
index f645426..c8e70f8 100644
--- a/src/components/ModalHost.tsx
+++ b/src/components/ModalHost.tsx
@@ -7,7 +7,7 @@ import {
NewCanvasOptions,
} from '../types/editor';
import { AppSettings, ResizeCanvasOptions } from '../types/settings';
-import { CollabPeer, SessionHostInfo } from '../types/multiplayer';
+import { CollabPeer, CollabRole, ConnectionStatus, SessionHostInfo } from '../types/multiplayer';
import { ParsedInviteLink } from '../services/multiplayerService';
import { CrashedSessionInfo } from '../services/recoveryService';
import { TonalCorrectionType } from '../utils/tonalEngine';
@@ -39,7 +39,6 @@ export type InviteLinkPayload = ParsedInviteLink;
export interface ModalHostProps {
layers: LayerItem[];
activeLayer: LayerItem | undefined;
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
getEffectiveOpacity: (layer: LayerItem) => number;
isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
handleCreateNewCanvas: (options: NewCanvasOptions) => void;
@@ -69,8 +68,12 @@ export interface ModalHostProps {
setIsHostModalOpen: (open: boolean) => void;
isCollabHost: boolean;
isCollabConnected: boolean;
+ collabConnectionStatus?: ConnectionStatus;
+ collabReconnectAttempt?: number;
+ collabMyRole?: CollabRole;
collabHostInfo: SessionHostInfo | null;
collabPeers: CollabPeer[];
+ collabBannedPeerIds?: string[];
collabMyPeer: CollabPeer;
updateMyName: (name: string) => void;
handleStartHosting: (
@@ -83,6 +86,10 @@ export interface ModalHostProps {
stopHosting: () => void;
joinByInviteUrl: (rawUrl: string, nickname?: string, persistName?: boolean) => Promise<boolean>;
leaveRoom: () => void;
+ onSetPeerRole?: (peerId: string | number, role: 'editor' | 'viewer') => void;
+ onKickPeer?: (peerId: string | number) => void;
+ onBanPeer?: (peerId: string | number) => void;
+ onUnbanPeer?: (peerId: string | number) => void;
clipboardInvite: InviteLinkPayload | null;
setClipboardInvite: (invite: InviteLinkPayload | null) => void;
webLandingInvite: InviteLinkPayload | null;
@@ -105,7 +112,6 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
({
layers,
activeLayer,
- layerCanvasesRef,
getEffectiveOpacity,
isLayerEffectivelyVisible,
handleCreateNewCanvas,
@@ -124,14 +130,22 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
setIsHostModalOpen,
isCollabHost,
isCollabConnected,
+ collabConnectionStatus,
+ collabReconnectAttempt,
+ collabMyRole,
collabHostInfo,
collabPeers,
+ collabBannedPeerIds,
collabMyPeer,
updateMyName,
handleStartHosting,
stopHosting,
joinByInviteUrl,
leaveRoom,
+ onSetPeerRole,
+ onKickPeer,
+ onBanPeer,
+ onUnbanPeer,
clipboardInvite,
setClipboardInvite,
webLandingInvite,
@@ -170,14 +184,14 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
compositeCanvas(
dimensions,
layers,
- layerCanvasesRef.current,
+ undefined,
getEffectiveOpacity,
isLayerEffectivelyVisible,
false,
documentStore.getActiveTileGrid(),
{ colorMode }
),
- [dimensions, layers, layerCanvasesRef, getEffectiveOpacity, isLayerEffectivelyVisible, colorMode]
+ [dimensions, layers, getEffectiveOpacity, isLayerEffectivelyVisible, colorMode]
);
const createWebtoonRegionRenderer = useCallback(
@@ -185,13 +199,13 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
createDocumentRegionRenderer(
dimensions,
layers,
- layerCanvasesRef.current,
+ undefined,
getEffectiveOpacity,
isLayerEffectivelyVisible,
documentStore.getActiveTileGrid(),
{ colorMode }
),
- [dimensions, layers, layerCanvasesRef, getEffectiveOpacity, isLayerEffectivelyVisible, colorMode]
+ [dimensions, layers, getEffectiveOpacity, isLayerEffectivelyVisible, colorMode]
);
const activeDoc = documents.find((d) => d.id === activeDocumentId);
@@ -210,9 +224,10 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
isOpen={isNewCanvasModalOpen}
onClose={() => uiStoreActions.setNewCanvasModalOpen(false)}
onCreate={handleCreateNewCanvas}
- initialWidth={dimensions.width}
- initialHeight={dimensions.height}
- initialDpi={dimensions.dpi || 300}
+ initialWidth={activeDoc ? dimensions.width : (appSettings.defaultWidth || 1920)}
+ initialHeight={activeDoc ? dimensions.height : (appSettings.defaultHeight || 1080)}
+ initialDpi={activeDoc ? (dimensions.dpi || 300) : (appSettings.defaultDpi || 300)}
+ initialColorMode={activeDoc ? colorMode : (appSettings.defaultColorMode || 'color')}
initialName="Untitled*"
/>
@@ -240,7 +255,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
<TonalCorrectionModal
isOpen={tonalModalState.isOpen}
type={tonalModalState.type}
- beforeImageData={tonalModalState.beforeImageData}
+ histograms={tonalModalState.histograms}
selectionMask={tonalModalState.selectionMask}
onClose={handleTonalCancel}
onApply={handleTonalApply}
@@ -288,14 +303,22 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
onClose={() => setIsHostModalOpen(false)}
isHost={isCollabHost}
isConnected={isCollabConnected}
+ connectionStatus={collabConnectionStatus}
+ reconnectAttempt={collabReconnectAttempt}
+ myRole={collabMyRole}
hostInfo={collabHostInfo}
peers={collabPeers}
+ bannedPeerIds={collabBannedPeerIds}
myPeer={collabMyPeer}
onUpdateMyName={updateMyName}
onStartHosting={handleStartHosting}
onStopHosting={stopHosting}
onJoinByInviteUrl={joinByInviteUrl}
onLeaveRoom={leaveRoom}
+ onSetPeerRole={onSetPeerRole}
+ onKickPeer={onKickPeer}
+ onBanPeer={onBanPeer}
+ onUnbanPeer={onUnbanPeer}
showToast={showToast}
/>
diff --git a/src/components/NewCanvasModal.tsx b/src/components/NewCanvasModal.tsx
index 2e66bd5..bd8ac8a 100644
--- a/src/components/NewCanvasModal.tsx
+++ b/src/components/NewCanvasModal.tsx
@@ -1,20 +1,20 @@
-import React, { useState, useId, useMemo, useEffect } from 'react';
+import React, { useState, useId, useMemo, useEffect, useCallback, useRef } from 'react';
import {
X,
Lock,
Unlock,
- ArrowLeftRight,
- Palette,
- FileCheck,
- Printer,
+ FilePlus,
Paintbrush,
BookOpen,
Smartphone,
- Sliders,
+ Check,
+ AlertTriangle,
} from 'lucide-react';
import { CanvasColorMode, NewCanvasOptions } from '../types/editor';
export type ProjectCategory = 'illustration' | 'manga' | 'webtoon' | 'custom';
+type PresetTabCategory = Exclude<ProjectCategory, 'custom'>;
+type DimensionUnit = 'px' | 'cm' | 'mm' | 'in';
export interface PresetCanvas {
id: string;
@@ -33,85 +33,7 @@ export interface PresetCanvas {
}
export const CANVAS_PRESETS: PresetCanvas[] = [
- // --Shueisha Presets
- {
- id: 'shueisha-manga-a',
- name: 'Shueisha manga A (Shonen Jump)',
- category: 'manga',
- groupLabel: '--Shueisha--',
- width: 6071,
- height: 8598,
- ratioLabel: 'Shueisha B5 (1:1.42)',
- ratioX: 6071,
- ratioY: 8598,
- defaultMode: 'monochrome',
- defaultDpi: 600,
- defaultFrequency: 60,
- description: 'Weekly Shonen Jump manuscript submission standard (600 DPI monochrome, 60 LPI)',
- },
- {
- id: 'shueisha-manga-b',
- name: 'Shueisha manga B (Young Jump)',
- category: 'manga',
- groupLabel: '--Shueisha--',
- width: 6071,
- height: 8598,
- ratioLabel: 'Shueisha B5 (1:1.42)',
- ratioX: 6071,
- ratioY: 8598,
- defaultMode: 'monochrome',
- defaultDpi: 600,
- defaultFrequency: 60,
- description: 'Young Jump manuscript submission standard (600 DPI monochrome, 60 LPI)',
- },
-
- // Commercial Manga & Print
- {
- id: 'manga-b5-600',
- name: 'Manga B5 Commercial (600 DPI)',
- category: 'manga',
- groupLabel: 'Commercial Manga & Print',
- width: 4299,
- height: 6071,
- ratioLabel: 'B5 (~1:1.41)',
- ratioX: 1,
- ratioY: 1.412,
- defaultMode: 'monochrome',
- defaultDpi: 600,
- defaultFrequency: 60,
- description: 'Standard tankobon/commercial manga publishing (600 DPI)',
- },
- {
- id: 'manga-b5-300',
- name: 'Manga B5 Standard (300 DPI)',
- category: 'manga',
- groupLabel: 'Commercial Manga & Print',
- width: 2150,
- height: 3035,
- ratioLabel: 'B5 (~1:1.41)',
- ratioX: 1,
- ratioY: 1.412,
- defaultMode: 'monochrome',
- defaultDpi: 300,
- defaultFrequency: 60,
- description: 'Draft or web manga format at 300 DPI',
- },
- {
- id: 'a4-300',
- name: 'A4 Document / Print (300 DPI)',
- category: 'illustration',
- groupLabel: 'Commercial Manga & Print',
- width: 2480,
- height: 3508,
- ratioLabel: 'A4 (1:√2)',
- ratioX: 1,
- ratioY: 1.414,
- defaultMode: 'color',
- defaultDpi: 300,
- description: 'Standard international A4 print format (300 DPI)',
- },
-
- // Illustration & Screen
+ // Illustration & Print
{
id: 'fhd',
name: 'Full HD (1080p)',
@@ -140,9 +62,23 @@ export const CANVAS_PRESETS: PresetCanvas[] = [
defaultDpi: 150,
description: '3840 × 2160 high-resolution digital art canvas',
},
+ {
+ id: 'a4-300',
+ name: 'A4 Print (300 DPI)',
+ category: 'illustration',
+ groupLabel: 'Commercial Manga & Print',
+ width: 2480,
+ height: 3508,
+ ratioLabel: 'A4',
+ ratioX: 2480,
+ ratioY: 3508,
+ defaultMode: 'color',
+ defaultDpi: 300,
+ description: 'Standard international A4 print format (300 DPI)',
+ },
{
id: 'square',
- name: 'Square Post / Icon',
+ name: 'Square (1:1)',
category: 'illustration',
groupLabel: 'Illustration & Screen',
width: 1080,
@@ -170,7 +106,7 @@ export const CANVAS_PRESETS: PresetCanvas[] = [
},
{
id: 'cinema',
- name: 'Cinematic Ultrawide (21:9)',
+ name: 'Ultrawide (21:9)',
category: 'illustration',
groupLabel: 'Illustration & Screen',
width: 2560,
@@ -183,24 +119,86 @@ export const CANVAS_PRESETS: PresetCanvas[] = [
description: '21:9 ultrawide panoramic canvas',
},
+ // Manga & Print
+ {
+ id: 'shueisha-manga-a',
+ name: 'Shueisha A (Shonen Jump)',
+ category: 'manga',
+ groupLabel: '--Shueisha--',
+ width: 6071,
+ height: 8598,
+ ratioLabel: 'B5',
+ ratioX: 6071,
+ ratioY: 8598,
+ defaultMode: 'monochrome',
+ defaultDpi: 600,
+ defaultFrequency: 60,
+ description: 'Weekly Shonen Jump manuscript standard (600 DPI monochrome, 60 LPI)',
+ },
+ {
+ id: 'shueisha-manga-b',
+ name: 'Shueisha B (Young Jump)',
+ category: 'manga',
+ groupLabel: '--Shueisha--',
+ width: 6071,
+ height: 8598,
+ ratioLabel: 'B5',
+ ratioX: 6071,
+ ratioY: 8598,
+ defaultMode: 'monochrome',
+ defaultDpi: 600,
+ defaultFrequency: 60,
+ description: 'Young Jump manuscript standard (600 DPI monochrome, 60 LPI)',
+ },
+ {
+ id: 'manga-b5-600',
+ name: 'Manga B5 Commercial',
+ category: 'manga',
+ groupLabel: 'Commercial Manga & Print',
+ width: 4299,
+ height: 6071,
+ ratioLabel: 'B5',
+ ratioX: 4299,
+ ratioY: 6071,
+ defaultMode: 'monochrome',
+ defaultDpi: 600,
+ defaultFrequency: 60,
+ description: 'Standard commercial manga publishing (600 DPI)',
+ },
+ {
+ id: 'manga-b5-300',
+ name: 'Manga B5 Draft',
+ category: 'manga',
+ groupLabel: 'Commercial Manga & Print',
+ width: 2150,
+ height: 3035,
+ ratioLabel: 'B5',
+ ratioX: 2150,
+ ratioY: 3035,
+ defaultMode: 'monochrome',
+ defaultDpi: 300,
+ defaultFrequency: 60,
+ description: 'Draft or web manga format at 300 DPI',
+ },
+
// Webtoon & Mobile
{
id: 'webtoon',
- name: 'Webtoon Vertical Episode',
+ name: 'Webtoon Episode',
category: 'webtoon',
groupLabel: 'Webtoon & Mobile',
width: 800,
height: 1280,
- ratioLabel: '10:16',
- ratioX: 10,
- ratioY: 16,
+ ratioLabel: '5:8',
+ ratioX: 5,
+ ratioY: 8,
defaultMode: 'color',
defaultDpi: 150,
description: 'Standard 800px width vertical webtoon canvas strip',
},
{
id: 'story',
- name: 'Mobile Story / Reel (9:16)',
+ name: 'Mobile Story (9:16)',
category: 'webtoon',
groupLabel: 'Webtoon & Mobile',
width: 1080,
@@ -239,19 +237,119 @@ export const DPI_PRESETS = [
{ dpi: 1200, label: '1200', desc: 'Hi-Res' },
];
+const QUICK_DPI_VALUES = [72, 150, 300, 600] as const;
+
export const COMMON_FREQUENCIES = [28, 42.5, 50, 60, 70, 85];
-const BG_PRESETS = [
- { label: 'White', value: '#ffffff', color: '#ffffff' },
- { label: 'Warm Paper', value: '#fcf8f2', color: '#fcf8f2' },
- { label: 'Dark Slate', value: '#1e1e1e', color: '#1e1e1e' },
- { label: 'Black', value: '#000000', color: '#000000' },
+const UNITS: DimensionUnit[] = ['px', 'cm', 'mm', 'in'];
+
+const BG_SWATCHES: Array<{ id: string; label: string; value: string; color?: string }> = [
+ { id: 'transparent', label: 'None', value: 'transparent' },
+ { id: 'white', label: 'White', value: '#ffffff', color: '#ffffff' },
+ { id: 'warm', label: 'Warm', value: '#fcf8f2', color: '#fcf8f2' },
+ { id: 'slate', label: 'Dark', value: '#1e1e1e', color: '#1e1e1e' },
+ { id: 'black', label: 'Black', value: '#000000', color: '#000000' },
];
+const CATEGORY_TABS: Array<{ id: PresetTabCategory; label: string; icon: React.ReactNode }> = [
+ { id: 'illustration', label: 'Illustration', icon: <Paintbrush className="w-3 h-3" /> },
+ { id: 'manga', label: 'Manga', icon: <BookOpen className="w-3 h-3" /> },
+ { id: 'webtoon', label: 'Webtoon', icon: <Smartphone className="w-3 h-3" /> },
+];
+
+const MIN_PX = 1;
+const MAX_PX = 16384;
+const MIN_DPI = 1;
+const MAX_DPI = 4800;
+const LARGE_CANVAS_MP = 64;
+
+function clampPx(val: number): number {
+ if (!Number.isFinite(val)) return MIN_PX;
+ return Math.max(MIN_PX, Math.min(MAX_PX, Math.round(val)));
+}
+
+function clampDpi(val: number): number {
+ if (!Number.isFinite(val)) return 300;
+ return Math.max(MIN_DPI, Math.min(MAX_DPI, Math.round(val)));
+}
+
+function clampFrequency(val: number): number {
+ if (!Number.isFinite(val)) return 60;
+ return Math.max(20, Math.min(85, val));
+}
+
function gcd(a: number, b: number): number {
- a = Math.round(Math.abs(a));
- b = Math.round(Math.abs(b));
- return b ? gcd(b, a % b) : a;
+ let x = Math.round(Math.abs(a));
+ let y = Math.round(Math.abs(b));
+ while (y !== 0) {
+ const t = y;
+ y = x % y;
+ x = t;
+ }
+ return x || 1;
+}
+
+function pxToUnit(px: number, unit: DimensionUnit, dpi: number): number {
+ const safeDpi = Math.max(1, dpi);
+ switch (unit) {
+ case 'px':
+ return Math.round(px);
+ case 'in':
+ return px / safeDpi;
+ case 'cm':
+ return (px / safeDpi) * 2.54;
+ case 'mm':
+ return (px / safeDpi) * 25.4;
+ }
+}
+
+function unitToPx(value: number, unit: DimensionUnit, dpi: number): number {
+ const safeDpi = Math.max(1, dpi);
+ switch (unit) {
+ case 'px':
+ return clampPx(value);
+ case 'in':
+ return clampPx(value * safeDpi);
+ case 'cm':
+ return clampPx((value / 2.54) * safeDpi);
+ case 'mm':
+ return clampPx((value / 25.4) * safeDpi);
+ }
+}
+
+function formatUnitValue(px: number, unit: DimensionUnit, dpi: number): string {
+ const val = pxToUnit(px, unit, dpi);
+ if (unit === 'px') return String(Math.round(val));
+ const decimals = unit === 'mm' ? 1 : 2;
+ return String(Number(val.toFixed(decimals)));
+}
+
+function normalizeHex(raw: string): string | null {
+ const trimmed = raw.trim();
+ const shortMatch = /^#([0-9a-fA-F]{3})$/.exec(trimmed);
+ if (shortMatch) {
+ const [r, g, b] = shortMatch[1].split('');
+ return `#${r}${r}${g}${g}${b}${b}`.toLowerCase();
+ }
+ if (/^#[0-9a-fA-F]{6}$/.test(trimmed)) {
+ return trimmed.toLowerCase();
+ }
+ return null;
+}
+
+function isDarkHex(hex: string): boolean {
+ const norm = normalizeHex(hex);
+ if (!norm) return false;
+ const r = parseInt(norm.slice(1, 3), 16);
+ const g = parseInt(norm.slice(3, 5), 16);
+ const b = parseInt(norm.slice(5, 7), 16);
+ return 0.299 * r + 0.587 * g + 0.114 * b < 110;
+}
+
+function findMatchingPreset(w: number, h: number): PresetCanvas | undefined {
+ return CANVAS_PRESETS.find(
+ (p) => p.category !== 'custom' && p.width === w && p.height === h
+ );
}
interface NewCanvasModalProps {
@@ -261,6 +359,7 @@ interface NewCanvasModalProps {
initialWidth?: number;
initialHeight?: number;
initialDpi?: number;
+ initialColorMode?: CanvasColorMode;
initialName?: string;
}
@@ -271,148 +370,241 @@ export const NewCanvasModal: React.FC<NewCanvasModalProps> = ({
initialWidth = 1920,
initialHeight = 1080,
initialDpi = 300,
+ initialColorMode = 'color',
initialName = 'Untitled*',
}) => {
- const presetSelectId = useId();
+ const titleId = useId();
+ const nameInputId = useId();
const widthInputId = useId();
const heightInputId = useId();
const dpiInputId = useId();
const freqInputId = useId();
- // State
- const [activeCategory, setActiveCategory] = useState<ProjectCategory>('illustration');
- const [selectedPresetId, setSelectedPresetId] = useState<string>('fhd');
- const [documentName, setDocumentName] = useState<string>(initialName);
- const [width, setWidth] = useState<number>(initialWidth);
- const [height, setHeight] = useState<number>(initialHeight);
- const [dpi, setDpi] = useState<number>(initialDpi);
- const [lockRatio, setLockRatio] = useState<boolean>(true);
- const [ratioX, setRatioX] = useState<number>(16);
- const [ratioY, setRatioY] = useState<number>(9);
- const [colorMode, setColorMode] = useState<CanvasColorMode>('color');
+ const [activeTab, setActiveTab] = useState<PresetTabCategory>('illustration');
+ const [selectedPresetId, setSelectedPresetId] = useState<string>('custom');
+ const [documentName, setDocumentName] = useState<string>('Untitled');
+ const [unit, setUnit] = useState<DimensionUnit>('px');
+
+ const [width, setWidth] = useState<number>(() => clampPx(initialWidth));
+ const [height, setHeight] = useState<number>(() => clampPx(initialHeight));
+ const [dpi, setDpi] = useState<number>(() => clampDpi(initialDpi));
+
+ // String-backed drafts prevent aggressive clamping mid-keystroke
+ const [widthDraft, setWidthDraft] = useState<string>(() => String(clampPx(initialWidth)));
+ const [heightDraft, setHeightDraft] = useState<string>(() => String(clampPx(initialHeight)));
+ const [dpiDraft, setDpiDraft] = useState<string>(() => String(clampDpi(initialDpi)));
+
+ const [lockRatio, setLockRatio] = useState<boolean>(false);
+ const [ratioX, setRatioX] = useState<number>(() => clampPx(initialWidth));
+ const [ratioY, setRatioY] = useState<number>(() => clampPx(initialHeight));
+
+ const [colorMode, setColorMode] = useState<CanvasColorMode>(initialColorMode);
const [defaultFrequency, setDefaultFrequency] = useState<number>(60);
- const [enablePaperColor, setEnablePaperColor] = useState<boolean>(true);
const [backgroundColor, setBackgroundColor] = useState<string>('#ffffff');
const [customHex, setCustomHex] = useState<string>('#ffffff');
- // Reset when opened
+ const wasOpenRef = useRef(false);
+
+ // Sync state strictly on open transition
useEffect(() => {
- if (isOpen) {
- setDocumentName(initialName);
+ if (isOpen && !wasOpenRef.current) {
+ const safeW = clampPx(initialWidth);
+ const safeH = clampPx(initialHeight);
+ const safeDpi = clampDpi(initialDpi);
+ const matched = findMatchingPreset(safeW, safeH);
+
+ setDocumentName((initialName || 'Untitled').replace(/\*+$/, '').trim() || 'Untitled');
+ setWidth(safeW);
+ setHeight(safeH);
+ setDpi(safeDpi);
+ setUnit('px');
+ setWidthDraft(String(safeW));
+ setHeightDraft(String(safeH));
+ setDpiDraft(String(safeDpi));
+ setRatioX(matched ? matched.ratioX : safeW);
+ setRatioY(matched ? matched.ratioY : safeH);
+ setColorMode(initialColorMode);
+ setSelectedPresetId(matched ? matched.id : 'custom');
+ if (matched && matched.category !== 'custom') {
+ setActiveTab(matched.category);
+ }
}
- }, [isOpen, initialName]);
+ wasOpenRef.current = isOpen;
+ }, [isOpen, initialWidth, initialHeight, initialDpi, initialColorMode, initialName]);
+
+ const syncDimensionDrafts = useCallback(
+ (nextW: number, nextH: number, nextUnit: DimensionUnit, nextDpi: number) => {
+ setWidthDraft(formatUnitValue(nextW, nextUnit, nextDpi));
+ setHeightDraft(formatUnitValue(nextH, nextUnit, nextDpi));
+ },
+ []
+ );
+
+ const visiblePresets = useMemo(
+ () => CANVAS_PRESETS.filter((p) => p.category === activeTab),
+ [activeTab]
+ );
- // Aspect ratio display string
const simplifiedRatio = useMemo(() => {
if (width <= 0 || height <= 0) return '1:1';
- const divisor = gcd(width, height);
- const simpleX = width / divisor;
- const simpleY = height / divisor;
- if (simpleX < 50 && simpleY < 50) {
- return `${simpleX}:${simpleY}`;
- }
- const dec = (width / height).toFixed(2);
- return `${dec}:1`;
+ const d = gcd(width, height);
+ const sx = width / d;
+ const sy = height / d;
+ if (sx <= 32 && sy <= 32) return `${sx}:${sy}`;
+ return `${(width / height).toFixed(2)}:1`;
}, [width, height]);
- // Physical Print Dimensions calculated from current width, height, and DPI
- const printDimensions = useMemo(() => {
+ const printCm = useMemo(() => {
const safeDpi = Math.max(1, dpi);
return {
- cmW: ((width / safeDpi) * 2.54).toFixed(1),
- cmH: ((height / safeDpi) * 2.54).toFixed(1),
- inW: (width / safeDpi).toFixed(2),
- inH: (height / safeDpi).toFixed(2),
+ w: ((width / safeDpi) * 2.54).toFixed(1),
+ h: ((height / safeDpi) * 2.54).toFixed(1),
};
}, [width, height, dpi]);
- const megapixels = useMemo(() => {
- return ((width * height) / 1000000).toFixed(1);
- }, [width, height]);
+ const megapixelsNum = useMemo(() => (width * height) / 1_000_000, [width, height]);
+ const megapixels = useMemo(() => megapixelsNum.toFixed(1), [megapixelsNum]);
+
+ const applyPreset = useCallback(
+ (preset: PresetCanvas) => {
+ setSelectedPresetId(preset.id);
+ setWidth(preset.width);
+ setHeight(preset.height);
+ setDpi(preset.defaultDpi);
+ setRatioX(preset.ratioX);
+ setRatioY(preset.ratioY);
+ setColorMode(preset.defaultMode);
+ if (preset.defaultFrequency) {
+ setDefaultFrequency(preset.defaultFrequency);
+ }
+ setDpiDraft(String(preset.defaultDpi));
+ syncDimensionDrafts(preset.width, preset.height, unit, preset.defaultDpi);
+ },
+ [syncDimensionDrafts, unit]
+ );
- const orientation = useMemo(() => {
- if (width > height) return 'Landscape';
- if (height > width) return 'Portrait';
- return 'Square';
- }, [width, height]);
+ const handleUnitChange = (nextUnit: DimensionUnit) => {
+ setUnit(nextUnit);
+ syncDimensionDrafts(width, height, nextUnit, dpi);
+ };
- // Category switch (Use of Work tab selection in CSP)
- const handleSelectCategory = (cat: ProjectCategory) => {
- setActiveCategory(cat);
- if (cat === 'manga') {
- applyPreset('shueisha-manga-a');
- } else if (cat === 'webtoon') {
- applyPreset('webtoon');
- } else if (cat === 'illustration') {
- applyPreset('fhd');
+ const handleWidthInputChange = (raw: string) => {
+ setWidthDraft(raw);
+ const parsed = Number(raw);
+ if (!raw.trim() || !Number.isFinite(parsed) || parsed <= 0) return;
+
+ const nextW = unitToPx(parsed, unit, dpi);
+ let nextH = height;
+ if (lockRatio && ratioX > 0 && ratioY > 0) {
+ nextH = clampPx((nextW * ratioY) / ratioX);
+ setHeight(nextH);
+ setHeightDraft(formatUnitValue(nextH, unit, dpi));
} else {
- setSelectedPresetId('custom');
+ setRatioX(nextW);
+ setRatioY(nextH);
}
+ setWidth(nextW);
+ const matched = findMatchingPreset(nextW, nextH);
+ setSelectedPresetId(matched ? matched.id : 'custom');
};
- // Preset Selection helper
- const applyPreset = (presetId: string) => {
- setSelectedPresetId(presetId);
- const preset = CANVAS_PRESETS.find((p) => p.id === presetId);
- if (!preset) return;
-
- setActiveCategory(preset.category);
- setWidth(preset.width);
- setHeight(preset.height);
- setRatioX(preset.ratioX);
- setRatioY(preset.ratioY);
- setDpi(preset.defaultDpi);
- setColorMode(preset.defaultMode);
- if (preset.defaultFrequency) {
- setDefaultFrequency(preset.defaultFrequency);
+ const handleHeightInputChange = (raw: string) => {
+ setHeightDraft(raw);
+ const parsed = Number(raw);
+ if (!raw.trim() || !Number.isFinite(parsed) || parsed <= 0) return;
+
+ const nextH = unitToPx(parsed, unit, dpi);
+ let nextW = width;
+ if (lockRatio && ratioX > 0 && ratioY > 0) {
+ nextW = clampPx((nextH * ratioX) / ratioY);
+ setWidth(nextW);
+ setWidthDraft(formatUnitValue(nextW, unit, dpi));
+ } else {
+ setRatioX(nextW);
+ setRatioY(nextH);
}
+ setHeight(nextH);
+ const matched = findMatchingPreset(nextW, nextH);
+ setSelectedPresetId(matched ? matched.id : 'custom');
};
- const handleSelectPreset = (presetId: string) => {
- applyPreset(presetId);
+ const handleDimensionBlur = () => {
+ syncDimensionDrafts(width, height, unit, dpi);
};
- // Dimension changes
- const handleWidthChange = (val: number) => {
- const newW = Math.max(1, Math.min(16384, Math.round(val)));
- setWidth(newW);
- if (lockRatio && ratioX > 0 && ratioY > 0) {
- const newH = Math.max(1, Math.round((newW * ratioY) / ratioX));
- setHeight(newH);
- }
- setSelectedPresetId('custom');
- setActiveCategory('custom');
+ const handleToggleLockRatio = () => {
+ setLockRatio((prev) => {
+ if (!prev) {
+ setRatioX(width);
+ setRatioY(height);
+ }
+ return !prev;
+ });
};
- const handleHeightChange = (val: number) => {
- const newH = Math.max(1, Math.min(16384, Math.round(val)));
- setHeight(newH);
- if (lockRatio && ratioX > 0 && ratioY > 0) {
- const newW = Math.max(1, Math.round((newH * ratioX) / ratioY));
- setWidth(newW);
+ const handleSetOrientation = (target: 'portrait' | 'landscape') => {
+ if (width === height) return;
+ const isCurrentlyLandscape = width > height;
+ if ((target === 'landscape' && isCurrentlyLandscape) || (target === 'portrait' && !isCurrentlyLandscape)) {
+ return;
}
- setSelectedPresetId('custom');
- setActiveCategory('custom');
- };
-
- // Swap Width and Height
- const handleSwapDimensions = () => {
- const prevW = width;
- const prevH = height;
- setWidth(prevH);
- setHeight(prevW);
+ const nextW = height;
+ const nextH = width;
+ setWidth(nextW);
+ setHeight(nextH);
setRatioX(ratioY);
setRatioY(ratioX);
- setSelectedPresetId('custom');
+ syncDimensionDrafts(nextW, nextH, unit, dpi);
+ const matched = findMatchingPreset(nextW, nextH);
+ setSelectedPresetId(matched ? matched.id : 'custom');
+ };
+
+ const applyDpiChange = useCallback(
+ (nextDpiRaw: number) => {
+ const nextDpi = clampDpi(nextDpiRaw);
+ if (unit !== 'px') {
+ // Preserve physical print size when editing in cm/mm/in
+ const physW = pxToUnit(width, unit, dpi);
+ const physH = pxToUnit(height, unit, dpi);
+ const nextW = unitToPx(physW, unit, nextDpi);
+ const nextH = unitToPx(physH, unit, nextDpi);
+ setWidth(nextW);
+ setHeight(nextH);
+ setRatioX(nextW);
+ setRatioY(nextH);
+ syncDimensionDrafts(nextW, nextH, unit, nextDpi);
+ const matched = findMatchingPreset(nextW, nextH);
+ setSelectedPresetId(matched ? matched.id : 'custom');
+ }
+ setDpi(nextDpi);
+ setDpiDraft(String(nextDpi));
+ },
+ [dpi, height, syncDimensionDrafts, unit, width]
+ );
+
+ const handleDpiInputChange = (raw: string) => {
+ setDpiDraft(raw);
+ const parsed = Number(raw);
+ if (!raw.trim() || !Number.isFinite(parsed) || parsed < 1) return;
+ applyDpiChange(parsed);
};
- // Resolution DPI change
- const handleDpiSelect = (val: number) => {
- setDpi(val);
+ const handleDpiBlur = () => {
+ setDpiDraft(String(dpi));
};
- // Submit
- const handleCreate = () => {
+ const handleSelectColorMode = (mode: CanvasColorMode) => {
+ setColorMode(mode);
+ if (mode === 'monochrome' && dpi < 600) {
+ applyDpiChange(600);
+ }
+ };
+
+ const handleCreate = useCallback(() => {
+ const safeW = clampPx(width);
+ const safeH = clampPx(height);
+ const safeDpi = clampDpi(dpi);
+ const safeFreq = clampFrequency(defaultFrequency);
let finalName = documentName.trim() || 'Untitled';
if (!/\.[a-zA-Z0-9]+$/.test(finalName) && !finalName.endsWith('*')) {
finalName = `${finalName}*`;
@@ -420,353 +612,455 @@ export const NewCanvasModal: React.FC<NewCanvasModalProps> = ({
onCreate({
name: finalName,
- width,
- height,
- dpi: Math.max(1, Math.round(dpi)),
+ width: safeW,
+ height: safeH,
+ dpi: safeDpi,
aspectRatioPreset: selectedPresetId,
aspectRatioX: ratioX,
aspectRatioY: ratioY,
lockAspectRatio: lockRatio,
- backgroundColor: enablePaperColor ? backgroundColor : 'transparent',
+ backgroundColor,
colorMode,
- defaultFrequency,
+ defaultFrequency: safeFreq,
});
onClose();
- };
+ }, [
+ backgroundColor,
+ colorMode,
+ defaultFrequency,
+ documentName,
+ dpi,
+ height,
+ lockRatio,
+ onClose,
+ onCreate,
+ ratioX,
+ ratioY,
+ selectedPresetId,
+ width,
+ ]);
+
+ // Global Escape / Enter shortcuts while open
+ useEffect(() => {
+ if (!isOpen) return;
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ onClose();
+ return;
+ }
+ if (e.key === 'Enter') {
+ const target = e.target as HTMLElement | null;
+ if (target instanceof HTMLButtonElement && !e.ctrlKey && !e.metaKey) {
+ return;
+ }
+ e.preventDefault();
+ handleCreate();
+ }
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [isOpen, onClose, handleCreate]);
if (!isOpen) return null;
- const isMangaMode = colorMode === 'monochrome' || activeCategory === 'manga';
+ const isTransparent = backgroundColor === 'transparent';
+ const isCustomBg =
+ !isTransparent &&
+ !BG_SWATCHES.some((s) => s.value.toLowerCase() === backgroundColor.toLowerCase());
+ const isLargeCanvas = megapixelsNum > LARGE_CANVAS_MP;
+ const isLandscape = width > height;
+ const isPortrait = height > width;
return (
<div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-xs p-4 select-none animate-in fade-in duration-100"
- onKeyDown={(e) => {
- if (e.key === 'Escape') onClose();
- if (e.key === 'Enter' && (e.ctrlKey || e.metaKey || e.target instanceof HTMLInputElement)) {
- handleCreate();
- }
- }}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={titleId}
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-4 select-none"
+ onClick={onClose}
>
- <div className="bg-[#242426] border border-[#3c3c40] rounded-lg shadow-2xl w-full max-w-4xl flex flex-col overflow-hidden text-xs text-[#d0d0d0]">
- {/* Header Bar */}
- <div className="flex items-center justify-between px-5 py-3 bg-[#2a2a2d] border-b border-[#38383a]">
- <h2 className="text-sm font-semibold text-white tracking-wide">New Canvas</h2>
+ <div
+ onClick={(e) => e.stopPropagation()}
+ className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] border border-[#2c2c2c] w-full max-w-[780px] max-h-[88vh] flex flex-col overflow-hidden text-xs text-[#e5e5e5]"
+ >
+ {/* Header */}
+ <div className="h-10 px-4 flex items-center justify-between bg-[#161616] border-b border-[#2c2c2c] shrink-0">
+ <div className="flex items-center gap-2">
+ <FilePlus className="w-3.5 h-3.5 text-[var(--accent)]" />
+ <h2 id={titleId} className="text-xs font-medium text-[#e5e5e5]">
+ New Canvas
+ </h2>
+ </div>
<button
+ type="button"
onClick={onClose}
- className="p-1 rounded hover:bg-[#38383a] text-[#888888] hover:text-white transition-colors"
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
title="Close (Esc)"
+ aria-label="Close new canvas dialog"
>
- <X className="w-4 h-4" />
+ <X className="w-3.5 h-3.5" />
</button>
</div>
- {/* CSP Style Project Type Bar (Use of Work) */}
- <div className="px-5 py-2.5 bg-[#202022] border-b border-[#323235] flex items-center justify-between gap-2 overflow-x-auto">
- <span className="text-[11px] font-semibold text-[#888888] uppercase tracking-wider shrink-0 mr-1">
- Project Type:
- </span>
- <div className="flex items-center gap-1.5 flex-1 max-w-xl">
- <button
- type="button"
- onClick={() => handleSelectCategory('illustration')}
- className={`flex-1 flex items-center justify-center space-x-1.5 py-1.5 px-3 rounded text-xs transition-colors border ${
- activeCategory === 'illustration'
- ? 'bg-[#007acc] border-[#007acc] text-white font-medium shadow-xs'
- : 'bg-[#29292c] border-[#38383c] text-[#b0b0b0] hover:bg-[#323236] hover:text-white'
- }`}
- >
- <Paintbrush className="w-3.5 h-3.5" />
- <span>Illustration</span>
- </button>
+ {/* Body: 2-Pane Split */}
+ <div className="flex flex-col md:flex-row flex-1 min-h-0 overflow-hidden gap-px bg-[#161616]">
+ {/* Left Pane: Presets & Live Ratio Preview */}
+ <div className="md:w-[272px] bg-[#202020] flex flex-col shrink-0 min-h-0">
+ {/* Category Tabs */}
+ <div className="p-2 pb-1.5 shrink-0">
+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {CATEGORY_TABS.map((tab) => {
+ const active = activeTab === tab.id;
+ return (
+ <button
+ key={tab.id}
+ type="button"
+ onClick={() => setActiveTab(tab.id)}
+ className={`flex items-center justify-center gap-1 py-1.5 px-1.5 rounded text-[11px] transition-colors cursor-pointer ${
+ active
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ <span className={active ? 'text-[var(--accent)]' : ''}>{tab.icon}</span>
+ <span className="truncate">{tab.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
- <button
- type="button"
- onClick={() => handleSelectCategory('manga')}
- className={`flex-1 flex items-center justify-center space-x-1.5 py-1.5 px-3 rounded text-xs transition-colors border ${
- activeCategory === 'manga'
- ? 'bg-[#007acc] border-[#007acc] text-white font-medium shadow-xs'
- : 'bg-[#29292c] border-[#38383c] text-[#b0b0b0] hover:bg-[#323236] hover:text-white'
- }`}
- >
- <BookOpen className="w-3.5 h-3.5" />
- <span>Comic / Manga</span>
- </button>
+ {/* Preset List */}
+ <div className="flex-1 overflow-y-auto px-2 py-1 space-y-1 max-h-[180px] md:max-h-none">
+ {visiblePresets.map((preset) => {
+ const selected = selectedPresetId === preset.id;
+ return (
+ <button
+ key={preset.id}
+ type="button"
+ onClick={() => applyPreset(preset)}
+ className={`w-full text-left px-2.5 py-2 rounded transition-colors cursor-pointer flex items-center justify-between gap-2 ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'bg-[#161616]/70 text-[#b5b5b5] hover:bg-[#2c2c2c]/60 hover:text-[#e5e5e5]'
+ }`}
+ >
+ <div className="min-w-0">
+ <div className="flex items-center gap-1.5">
+ <span className="text-xs font-medium truncate">{preset.name}</span>
+ {preset.defaultMode === 'monochrome' && (
+ <span className="text-[9px] font-mono px-1 py-0.25 rounded bg-[#161616] text-[#8a8a8a] shrink-0">
+ MONO
+ </span>
+ )}
+ </div>
+ <div className="text-[10px] font-mono text-[#8a8a8a] mt-0.5">
+ {preset.width} × {preset.height} · {preset.defaultDpi} DPI
+ </div>
+ </div>
+ {selected && <Check className="w-3.5 h-3.5 text-[var(--accent)] shrink-0" />}
+ </button>
+ );
+ })}
+ </div>
- <button
- type="button"
- onClick={() => handleSelectCategory('webtoon')}
- className={`flex-1 flex items-center justify-center space-x-1.5 py-1.5 px-3 rounded text-xs transition-colors border ${
- activeCategory === 'webtoon'
- ? 'bg-[#007acc] border-[#007acc] text-white font-medium shadow-xs'
- : 'bg-[#29292c] border-[#38383c] text-[#b0b0b0] hover:bg-[#323236] hover:text-white'
- }`}
- >
- <Smartphone className="w-3.5 h-3.5" />
- <span>Webtoon</span>
- </button>
+ {/* Compact Proportional Preview */}
+ <div className="p-3 bg-[#1a1a1a] border-t border-[#2c2c2c] shrink-0 space-y-2">
+ <div
+ className="w-full h-24 rounded flex items-center justify-center p-2.5 overflow-hidden"
+ style={{
+ backgroundImage:
+ 'conic-gradient(#1f1f1f 90deg, #161616 90deg 180deg, #1f1f1f 180deg 270deg, #161616 270deg)',
+ backgroundSize: '12px 12px',
+ }}
+ >
+ <div
+ className="max-w-full max-h-full transition-all duration-150 rounded-[2px] shadow-md relative border border-black/60 flex items-center justify-center overflow-hidden"
+ style={{
+ aspectRatio: `${Math.max(1, width)} / ${Math.max(1, height)}`,
+ width: width >= height ? '88%' : 'auto',
+ height: height > width ? '94%' : 'auto',
+ backgroundColor: isTransparent ? undefined : backgroundColor,
+ backgroundImage: isTransparent
+ ? 'conic-gradient(#7a7a7a 90deg, #525252 90deg 180deg, #7a7a7a 180deg 270deg, #525252 270deg)'
+ : undefined,
+ backgroundSize: '8px 8px',
+ }}
+ >
+ {colorMode === 'monochrome' && (
+ <div className="absolute inset-1.5 border border-dashed border-[#8a8a8a]/50 pointer-events-none" />
+ )}
+ <span
+ className={`text-[9px] font-mono px-1.5 py-0.5 rounded font-medium z-10 ${
+ !isTransparent && isDarkHex(backgroundColor)
+ ? 'bg-white/15 text-[#e5e5e5]'
+ : 'bg-black/60 text-white'
+ }`}
+ >
+ {simplifiedRatio}
+ </span>
+ </div>
+ </div>
- <button
- type="button"
- onClick={() => handleSelectCategory('custom')}
- className={`flex-1 flex items-center justify-center space-x-1.5 py-1.5 px-3 rounded text-xs transition-colors border ${
- activeCategory === 'custom'
- ? 'bg-[#007acc] border-[#007acc] text-white font-medium shadow-xs'
- : 'bg-[#29292c] border-[#38383c] text-[#b0b0b0] hover:bg-[#323236] hover:text-white'
- }`}
- >
- <Sliders className="w-3.5 h-3.5" />
- <span>Custom</span>
- </button>
+ <div className="flex items-center justify-between text-[10px] font-mono text-[#8a8a8a]">
+ <span className="text-[#e5e5e5]">
+ {width} × {height} px
+ </span>
+ <span>
+ {printCm.w} × {printCm.h} cm · {megapixels} MP
+ </span>
+ </div>
+ </div>
</div>
- </div>
- {/* Modal Main Content */}
- <div className="grid grid-cols-1 lg:grid-cols-12 gap-5 p-5 max-h-[76vh] overflow-y-auto">
- {/* Left Settings Column (7 cols) */}
- <div className="lg:col-span-7 space-y-3.5">
- {/* Document Name & Preset Group */}
- <div className="bg-[#1b1b1d] border border-[#323235] rounded-md p-3 space-y-3">
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <div className="space-y-1">
- <label className="text-[11px] font-semibold text-[#999999] uppercase tracking-wider block">
- File Name
+ {/* Right Pane: Configuration Form */}
+ <div className="flex-1 bg-[#202020] p-4 overflow-y-auto space-y-4 min-h-0">
+ {/* Document Name */}
+ <section className="space-y-1.5">
+ <label htmlFor={nameInputId} className="text-[11px] font-medium text-[#8a8a8a] block">
+ Document Name
+ </label>
+ <input
+ id={nameInputId}
+ type="text"
+ value={documentName}
+ onChange={(e) => setDocumentName(e.target.value)}
+ placeholder="Untitled"
+ className="w-full px-2.5 py-1.5 text-xs placeholder-[#8a8a8a]/50"
+ />
+ </section>
+
+ {/* Dimensions + Unit + Orientation */}
+ <section className="space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] font-medium text-[#8a8a8a]">Dimensions</span>
+ <div className="inline-flex bg-[#161616] p-0.5 rounded gap-0.5">
+ {UNITS.map((u) => (
+ <button
+ key={u}
+ type="button"
+ onClick={() => handleUnitChange(u)}
+ className={`px-2 py-0.5 rounded text-[10px] font-mono transition-colors cursor-pointer ${
+ unit === u
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {u}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex items-end gap-1.5">
+ <div className="flex-1 space-y-1">
+ <label htmlFor={widthInputId} className="text-[10px] text-[#8a8a8a] block">
+ Width ({unit})
</label>
<input
- type="text"
- value={documentName}
- onChange={(e) => setDocumentName(e.target.value)}
- placeholder="Untitled*"
- className="w-full bg-[#242427] border border-[#3c3c40] rounded px-3 py-1.5 text-xs text-white focus:outline-hidden focus:border-[#007acc]"
+ id={widthInputId}
+ type="number"
+ min={unit === 'px' ? MIN_PX : 0.1}
+ max={unit === 'px' ? MAX_PX : undefined}
+ step={unit === 'px' ? 1 : 0.1}
+ value={widthDraft}
+ onChange={(e) => handleWidthInputChange(e.target.value)}
+ onBlur={handleDimensionBlur}
+ className="w-full px-2.5 py-1.5 font-mono text-xs"
/>
</div>
- <div className="space-y-1">
- <label htmlFor={presetSelectId} className="text-[11px] font-semibold text-[#999999] uppercase tracking-wider block">
- Preset
+ <button
+ type="button"
+ onClick={handleToggleLockRatio}
+ aria-pressed={lockRatio}
+ title={lockRatio ? 'Aspect ratio locked' : 'Lock aspect ratio'}
+ className={`h-[30px] w-[30px] shrink-0 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ lockRatio
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {lockRatio ? <Lock className="w-3.5 h-3.5" /> : <Unlock className="w-3.5 h-3.5" />}
+ </button>
+
+ <div className="flex-1 space-y-1">
+ <label htmlFor={heightInputId} className="text-[10px] text-[#8a8a8a] block">
+ Height ({unit})
</label>
- <select
- id={presetSelectId}
- value={selectedPresetId}
- onChange={(e) => handleSelectPreset(e.target.value)}
- className="w-full bg-[#242427] border border-[#3c3c40] rounded px-3 py-1.5 text-xs text-white focus:outline-hidden focus:border-[#007acc]"
- >
- <optgroup label="--Shueisha--">
- <option value="shueisha-manga-a">Shueisha manga A (Shonen Jump)</option>
- <option value="shueisha-manga-b">Shueisha manga B (Young Jump)</option>
- </optgroup>
- <optgroup label="Commercial Manga & Print">
- <option value="manga-b5-600">Manga B5 Commercial (600 DPI)</option>
- <option value="manga-b5-300">Manga B5 Standard (300 DPI)</option>
- <option value="a4-300">A4 Document (300 DPI)</option>
- </optgroup>
- <optgroup label="Illustration & Screen">
- <option value="fhd">Full HD (1080p)</option>
- <option value="4k">4K Ultra HD</option>
- <option value="square">Square Post / Icon</option>
- <option value="photo-3-2">Classic Photo (3:2)</option>
- <option value="cinema">Cinematic Ultrawide (21:9)</option>
- </optgroup>
- <optgroup label="Webtoon & Mobile">
- <option value="webtoon">Webtoon Vertical Episode</option>
- <option value="story">Mobile Story / Reel (9:16)</option>
- </optgroup>
- <optgroup label="Custom">
- <option value="custom">Custom Size</option>
- </optgroup>
- </select>
+ <input
+ id={heightInputId}
+ type="number"
+ min={unit === 'px' ? MIN_PX : 0.1}
+ max={unit === 'px' ? MAX_PX : undefined}
+ step={unit === 'px' ? 1 : 0.1}
+ value={heightDraft}
+ onChange={(e) => handleHeightInputChange(e.target.value)}
+ onBlur={handleDimensionBlur}
+ className="w-full px-2.5 py-1.5 font-mono text-xs"
+ />
</div>
- </div>
- </div>
- {/* Canvas Dimensions & Resolution */}
- <div className="bg-[#1b1b1d] border border-[#323235] rounded-md p-3 space-y-3">
- <div className="flex items-center justify-between">
- <span className="text-[11px] font-semibold text-[#999999] uppercase tracking-wider">
- Canvas Size & Resolution
- </span>
- <div className="flex items-center space-x-1.5">
+ {/* Orientation Switch */}
+ <div className="h-[30px] shrink-0 bg-[#161616] p-0.5 rounded inline-flex items-center gap-0.5">
<button
type="button"
- onClick={() => setLockRatio(!lockRatio)}
- className={`flex items-center space-x-1 px-2 py-0.5 rounded text-[11px] transition-colors border ${
- lockRatio
- ? 'bg-[#007acc]/20 border-[#007acc]/50 text-[#38bdf8]'
- : 'bg-[#28282b] border-[#38383a] text-[#888888] hover:text-[#cccccc]'
+ onClick={() => handleSetOrientation('portrait')}
+ disabled={width === height}
+ title="Portrait orientation"
+ aria-label="Portrait orientation"
+ aria-pressed={isPortrait}
+ className={`h-full px-2 rounded flex items-center justify-center transition-colors ${
+ width === height
+ ? 'opacity-35 cursor-default text-[#8a8a8a]'
+ : isPortrait
+ ? 'bg-[#2c2c2c] text-[var(--accent)] cursor-pointer'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer'
}`}
- title={lockRatio ? 'Ratio locked: editing width preserves aspect' : 'Ratio unlocked'}
>
- {lockRatio ? <Lock className="w-3 h-3" /> : <Unlock className="w-3 h-3" />}
- <span>{lockRatio ? 'Locked' : 'Free'}</span>
+ <span className="w-2.5 h-3.5 rounded-[1px] border border-current block" />
</button>
<button
type="button"
- onClick={handleSwapDimensions}
- className="p-1 rounded bg-[#28282b] hover:bg-[#343438] border border-[#38383a] text-[#aaaaaa] hover:text-white transition-colors"
- title="Swap Width and Height (Landscape ⇄ Portrait)"
+ onClick={() => handleSetOrientation('landscape')}
+ disabled={width === height}
+ title="Landscape orientation"
+ aria-label="Landscape orientation"
+ aria-pressed={isLandscape}
+ className={`h-full px-2 rounded flex items-center justify-center transition-colors ${
+ width === height
+ ? 'opacity-35 cursor-default text-[#8a8a8a]'
+ : isLandscape
+ ? 'bg-[#2c2c2c] text-[var(--accent)] cursor-pointer'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer'
+ }`}
>
- <ArrowLeftRight className="w-3.5 h-3.5" />
+ <span className="w-3.5 h-2.5 rounded-[1px] border border-current block" />
</button>
</div>
</div>
- {/* Dimensions Input Row */}
- <div className="grid grid-cols-2 gap-3">
- <div className="space-y-1">
- <div className="flex items-center justify-between">
- <label htmlFor={widthInputId} className="text-[11px] text-[#888888]">Width (px)</label>
- <span className="text-[10px] text-[#666666] font-mono">{printDimensions.cmW} cm</span>
- </div>
- <input
- id={widthInputId}
- type="number"
- min="64"
- max="16384"
- value={width}
- onChange={(e) => handleWidthChange(Number(e.target.value))}
- className="w-full bg-[#242427] border border-[#3c3c40] rounded px-3 py-1.5 font-mono text-xs text-white focus:outline-hidden focus:border-[#007acc]"
- />
+ {isLargeCanvas && (
+ <div className="flex items-center gap-1.5 text-[11px] text-amber-400 pt-0.5">
+ <AlertTriangle className="w-3 h-3 shrink-0" />
+ <span>Large canvas ({megapixels} MP) — may increase memory usage.</span>
</div>
+ )}
+ </section>
- <div className="space-y-1">
- <div className="flex items-center justify-between">
- <label htmlFor={heightInputId} className="text-[11px] text-[#888888]">Height (px)</label>
- <span className="text-[10px] text-[#666666] font-mono">{printDimensions.cmH} cm</span>
- </div>
- <input
- id={heightInputId}
- type="number"
- min="64"
- max="16384"
- value={height}
- onChange={(e) => handleHeightChange(Number(e.target.value))}
- className="w-full bg-[#242427] border border-[#3c3c40] rounded px-3 py-1.5 font-mono text-xs text-white focus:outline-hidden focus:border-[#007acc]"
- />
- </div>
+ {/* Resolution (DPI) */}
+ <section className="space-y-1.5">
+ <div className="flex items-center justify-between">
+ <label htmlFor={dpiInputId} className="text-[11px] font-medium text-[#8a8a8a]">
+ Resolution (DPI)
+ </label>
+ <span className="text-[10px] font-mono text-[#8a8a8a]">
+ {dpi <= 96 ? 'Screen' : dpi < 300 ? 'Draft' : dpi < 600 ? 'Print' : 'Manga / Hi-Res'}
+ </span>
</div>
- {/* Resolution Dropdown & Print dimensions */}
- <div className="pt-2 border-t border-[#2a2a2d] flex items-center justify-between gap-3">
- <div className="flex items-center space-x-2 flex-1">
- <Printer className="w-3.5 h-3.5 text-[#38bdf8] shrink-0" />
- <label htmlFor={dpiInputId} className="text-[11px] text-[#888888] whitespace-nowrap">
- Resolution:
- </label>
- <select
- id={dpiInputId}
- value={DPI_PRESETS.some((p) => p.dpi === dpi) ? dpi : 'custom'}
- onChange={(e) => {
- if (e.target.value !== 'custom') {
- handleDpiSelect(Number(e.target.value));
- }
- }}
- className="bg-[#242427] border border-[#3c3c40] rounded px-2.5 py-1 text-xs text-white focus:outline-hidden focus:border-[#007acc]"
- >
- {DPI_PRESETS.map((p) => (
- <option key={p.dpi} value={p.dpi}>
- {p.dpi} DPI ({p.desc})
- </option>
- ))}
- {!DPI_PRESETS.some((p) => p.dpi === dpi) && (
- <option value="custom">{dpi} DPI (Custom)</option>
- )}
- </select>
-
+ <div className="flex items-center gap-1.5">
+ <div className="grid grid-cols-4 gap-1.5 flex-1">
+ {QUICK_DPI_VALUES.map((val) => {
+ const selected = dpi === val;
+ return (
+ <button
+ key={val}
+ type="button"
+ onClick={() => applyDpiChange(val)}
+ className={`py-1.5 rounded font-mono text-xs transition-colors cursor-pointer ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {val}
+ </button>
+ );
+ })}
+ </div>
+ <div className="relative w-20 shrink-0">
<input
+ id={dpiInputId}
type="number"
- min="1"
- max="4800"
- value={dpi}
- onChange={(e) => setDpi(Math.max(1, Math.min(4800, Number(e.target.value) || 1)))}
- className="w-16 bg-[#242427] border border-[#3c3c40] rounded px-2 py-1 text-center font-mono text-xs text-white focus:outline-hidden focus:border-[#007acc]"
- title="Enter custom DPI"
+ min={MIN_DPI}
+ max={MAX_DPI}
+ value={dpiDraft}
+ onChange={(e) => handleDpiInputChange(e.target.value)}
+ onBlur={handleDpiBlur}
+ aria-label="Custom DPI"
+ className="w-full px-2 py-1.5 font-mono text-xs text-center"
/>
- <span className="text-[11px] text-[#666666]">DPI</span>
- </div>
-
- <div className="text-[11px] text-[#888888] font-mono shrink-0">
- <span>{printDimensions.cmW} × {printDimensions.cmH} cm</span>
- <span className="text-[#555555]"> ({printDimensions.inW} × {printDimensions.inH} in)</span>
</div>
</div>
- </div>
-
- {/* Basic Expression Color (CSP Style) */}
- <div className="bg-[#1b1b1d] border border-[#323235] rounded-md p-3 space-y-2.5">
- <div className="flex items-center justify-between">
- <span className="text-[11px] font-semibold text-[#999999] uppercase tracking-wider">
- Basic Expression Color
- </span>
- <span className="text-[11px] font-medium text-[#38bdf8] capitalize">
- {colorMode === 'monochrome' ? 'Monochrome (Manga)' : colorMode === 'grayscale' ? 'Grayscale' : 'Color (RGB)'}
- </span>
+ </section>
+
+ {/* Color Mode */}
+ <section className="space-y-2">
+ <span className="text-[11px] font-medium text-[#8a8a8a] block">Color Mode</span>
+
+ <div className="grid grid-cols-3 gap-1.5">
+ {(
+ [
+ {
+ id: 'color' as CanvasColorMode,
+ label: 'Color',
+ swatch: 'bg-gradient-to-tr from-rose-500 via-emerald-400 to-sky-500',
+ },
+ {
+ id: 'grayscale' as CanvasColorMode,
+ label: 'Grayscale',
+ swatch: 'bg-gradient-to-r from-[#111] via-[#888] to-[#eee]',
+ },
+ {
+ id: 'monochrome' as CanvasColorMode,
+ label: 'Monochrome',
+ swatch: 'bg-gradient-to-r from-black from-50% to-white to-50%',
+ },
+ ] as const
+ ).map((item) => {
+ const selected = colorMode === item.id;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => handleSelectColorMode(item.id)}
+ className={`flex items-center justify-center gap-2 py-1.5 px-2.5 rounded text-xs transition-colors cursor-pointer ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ <span
+ className={`w-2.5 h-2.5 rounded-full shrink-0 border border-white/15 ${item.swatch}`}
+ />
+ <span>{item.label}</span>
+ </button>
+ );
+ })}
</div>
- <div className="grid grid-cols-3 gap-2">
- <button
- type="button"
- onClick={() => setColorMode('color')}
- className={`flex items-center justify-center space-x-2 py-2 px-2.5 rounded border transition-colors ${
- colorMode === 'color'
- ? 'bg-[#007acc]/20 border-[#007acc] text-white ring-1 ring-[#007acc]'
- : 'bg-[#242427] border-[#38383c] text-[#a0a0a0] hover:bg-[#2c2c30] hover:text-white'
- }`}
- >
- <span className="w-3 h-3 rounded-full bg-gradient-to-tr from-rose-500 via-emerald-400 to-sky-500 shrink-0" />
- <span className="font-medium text-xs">Color</span>
- </button>
-
- <button
- type="button"
- onClick={() => setColorMode('grayscale')}
- className={`flex items-center justify-center space-x-2 py-2 px-2.5 rounded border transition-colors ${
- colorMode === 'grayscale'
- ? 'bg-[#007acc]/20 border-[#007acc] text-white ring-1 ring-[#007acc]'
- : 'bg-[#242427] border-[#38383c] text-[#a0a0a0] hover:bg-[#2c2c30] hover:text-white'
- }`}
- >
- <span className="w-3 h-3 rounded-full bg-gradient-to-r from-black via-gray-400 to-white shrink-0" />
- <span className="font-medium text-xs">Gray</span>
- </button>
-
- <button
- type="button"
- onClick={() => {
- setColorMode('monochrome');
- if (dpi < 600) setDpi(600);
- }}
- className={`flex items-center justify-center space-x-2 py-2 px-2.5 rounded border transition-colors ${
- colorMode === 'monochrome'
- ? 'bg-[#007acc]/20 border-[#007acc] text-white ring-1 ring-[#007acc]'
- : 'bg-[#242427] border-[#38383c] text-[#a0a0a0] hover:bg-[#2c2c30] hover:text-white'
- }`}
- >
- <span className="w-3 h-3 rounded-full border border-white/40 bg-black flex items-center justify-center text-[7px] text-white font-bold shrink-0">
- B
- </span>
- <span className="font-medium text-xs">Monochrome</span>
- </button>
- </div>
-
- {/* Default Frequency (screentones) - Clip Studio Paint Manga Tone Line Count */}
- {isMangaMode && (
- <div className="pt-2.5 mt-2 border-t border-[#2a2a2d] space-y-2 animate-in fade-in duration-150">
+ {colorMode === 'monochrome' && (
+ <div className="bg-[#161616] rounded p-2.5 space-y-2">
<div className="flex items-center justify-between">
- <span className="text-[11px] font-semibold text-[#aaaaaa]">
- Default Frequency (screentones): <strong className="text-amber-300 font-mono">{defaultFrequency} LPI</strong>
+ <label htmlFor={freqInputId} className="text-[11px] text-[#8a8a8a]">
+ Screentone Frequency
+ </label>
+ <span className="text-[11px] font-mono text-[#e5e5e5]">
+ {defaultFrequency} LPI
</span>
- <span className="text-[10px] text-[#777777] font-mono">20 to 85 LPI</span>
</div>
- <div className="flex items-center space-x-3">
+ <div className="flex items-center gap-2.5">
<input
type="range"
min="20"
max="85"
step="0.5"
value={defaultFrequency}
- onChange={(e) => setDefaultFrequency(Number(e.target.value))}
- className="flex-1 cursor-pointer h-1.5 accent-[#007acc]"
+ onChange={(e) => setDefaultFrequency(clampFrequency(Number(e.target.value)))}
+ className="flex-1"
/>
<input
id={freqInputId}
@@ -775,235 +1069,151 @@ export const NewCanvasModal: React.FC<NewCanvasModalProps> = ({
max="85"
step="0.5"
value={defaultFrequency}
- onChange={(e) => setDefaultFrequency(Math.max(20, Math.min(85, Number(e.target.value) || 60)))}
- className="w-14 bg-[#242427] border border-[#3c3c40] rounded px-2 py-0.5 text-center font-mono text-xs text-white focus:outline-hidden focus:border-[#007acc]"
+ onChange={(e) =>
+ setDefaultFrequency(clampFrequency(Number(e.target.value) || 60))
+ }
+ className="w-14 px-1.5 py-1 text-center font-mono text-[11px]"
/>
</div>
- {/* Quick frequency presets */}
- <div className="flex items-center gap-1.5 pt-0.5">
- <span className="text-[10px] text-[#777777] mr-1">Common:</span>
- {COMMON_FREQUENCIES.map((f) => (
- <button
- key={f}
- type="button"
- onClick={() => setDefaultFrequency(f)}
- className={`px-2 py-0.5 rounded text-[10px] font-mono border transition-colors ${
- defaultFrequency === f
- ? 'bg-amber-400/20 border-amber-400/60 text-amber-300 font-bold'
- : 'bg-[#242427] border-[#38383c] text-[#999999] hover:bg-[#303034] hover:text-white'
- }`}
- >
- {f}L
- </button>
- ))}
+ <div className="flex items-center gap-1 flex-wrap">
+ {COMMON_FREQUENCIES.map((f) => {
+ const active = defaultFrequency === f;
+ return (
+ <button
+ key={f}
+ type="button"
+ onClick={() => setDefaultFrequency(f)}
+ className={`px-2 py-0.5 rounded text-[10px] font-mono transition-colors cursor-pointer ${
+ active
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'bg-[#202020] text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {f}L
+ </button>
+ );
+ })}
</div>
</div>
)}
- </div>
+ </section>
- {/* Paper Color (Background) */}
- <div className="bg-[#1b1b1d] border border-[#323235] rounded-md p-3 space-y-2.5">
+ {/* Paper Background */}
+ <section className="space-y-1.5">
<div className="flex items-center justify-between">
- <label className="flex items-center space-x-2 cursor-pointer">
- <input
- type="checkbox"
- checked={enablePaperColor}
- onChange={(e) => setEnablePaperColor(e.target.checked)}
- className="w-3.5 h-3.5 rounded accent-[#007acc] cursor-pointer"
- />
- <span className="text-[11px] font-semibold text-[#999999] uppercase tracking-wider">
- Paper Color
- </span>
- </label>
- <span className="text-[11px] text-[#777777]">
- {enablePaperColor ? backgroundColor.toUpperCase() : 'Transparent'}
+ <span className="text-[11px] font-medium text-[#8a8a8a]">Background</span>
+ <span className="text-[10px] font-mono text-[#8a8a8a]">
+ {isTransparent ? 'Transparent' : backgroundColor.toUpperCase()}
</span>
</div>
- {enablePaperColor && (
- <div className="flex items-center flex-wrap gap-2 pt-1">
- {BG_PRESETS.map((bg) => {
- const isSelected = backgroundColor.toLowerCase() === bg.value.toLowerCase();
- return (
- <button
- key={bg.label}
- type="button"
- onClick={() => {
- setBackgroundColor(bg.value);
- setCustomHex(bg.value);
- }}
- className={`flex items-center space-x-1.5 px-2.5 py-1 rounded text-xs border transition-colors ${
- isSelected
- ? 'border-[#007acc] bg-[#007acc]/15 text-white ring-1 ring-[#007acc]'
- : 'border-[#38383c] bg-[#242427] text-[#cccccc] hover:bg-[#2c2c30]'
- }`}
- >
+ <div className="flex items-center gap-1.5 flex-wrap">
+ {BG_SWATCHES.map((swatch) => {
+ const selected =
+ backgroundColor.toLowerCase() === swatch.value.toLowerCase();
+ return (
+ <button
+ key={swatch.id}
+ type="button"
+ onClick={() => {
+ setBackgroundColor(swatch.value);
+ if (swatch.color) setCustomHex(swatch.color);
+ }}
+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded text-[11px] transition-colors cursor-pointer ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {swatch.color ? (
<span
- className="w-3 h-3 rounded-full border border-black/40 shrink-0"
- style={{ backgroundColor: bg.color }}
+ className="w-2.5 h-2.5 rounded-full border border-white/20 shrink-0"
+ style={{ backgroundColor: swatch.color }}
/>
- <span>{bg.label}</span>
- </button>
- );
- })}
-
- {/* Custom Color Input */}
- <div className="flex items-center space-x-1.5 bg-[#242427] border border-[#38383c] rounded px-2 py-0.5 ml-auto">
- <Palette className="w-3.5 h-3.5 text-[#888888]" />
- <input
- type="color"
- value={customHex.startsWith('#') ? customHex : '#ffffff'}
- onChange={(e) => {
- setCustomHex(e.target.value);
- setBackgroundColor(e.target.value);
- }}
- className="w-4 h-4 cursor-pointer bg-transparent border-none rounded"
- title="Pick custom color"
- />
- <input
- type="text"
- value={customHex}
- onChange={(e) => {
- setCustomHex(e.target.value);
- if (e.target.value.startsWith('#') && e.target.value.length >= 4) {
- setBackgroundColor(e.target.value);
- }
- }}
- className="w-16 bg-transparent font-mono text-[11px] text-white focus:outline-hidden"
- />
- </div>
- </div>
- )}
- </div>
- </div>
-
- {/* Right Column: Live Proportional Manuscript Preview (5 cols) */}
- <div className="lg:col-span-5 flex flex-col space-y-3">
- <span className="text-[11px] font-semibold text-[#888888] uppercase tracking-wider">
- Canvas Ratio Preview
- </span>
+ ) : (
+ <span
+ className="w-2.5 h-2.5 rounded-full border border-white/20 shrink-0"
+ style={{
+ backgroundImage:
+ 'conic-gradient(#888 90deg, #444 90deg 180deg, #888 180deg 270deg, #444 270deg)',
+ backgroundSize: '6px 6px',
+ }}
+ />
+ )}
+ <span>{swatch.label}</span>
+ </button>
+ );
+ })}
- <div className="flex-1 bg-[#18181a] border border-[#323235] rounded-md p-4 flex flex-col items-center justify-between min-h-[300px] relative overflow-hidden">
- {/* Proportional Page Preview Area */}
- <div
- className="w-full h-48 rounded-sm flex items-center justify-center relative p-3 overflow-hidden shadow-inner"
- style={{
- backgroundImage: `conic-gradient(#202022 90deg, #161618 90deg 180deg, #202022 180deg 270deg, #161618 270deg)`,
- backgroundSize: '16px 16px',
- }}
- >
- {/* Dynamically Scaled Page Representation */}
<div
- className="max-w-full max-h-full transition-all duration-200 rounded-[2px] shadow-xl relative border border-black/70 flex items-center justify-center overflow-hidden"
- style={{
- aspectRatio: `${Math.max(1, width)} / ${Math.max(1, height)}`,
- width: width >= height ? '90%' : 'auto',
- height: height > width ? '95%' : 'auto',
- backgroundColor: enablePaperColor ? backgroundColor : undefined,
- backgroundImage:
- !enablePaperColor
- ? 'conic-gradient(#888 90deg, #555 90deg 180deg, #888 180deg 270deg, #555 270deg)'
- : undefined,
- backgroundSize: '10px 10px',
- }}
+ className={`flex items-center gap-1.5 rounded px-2 py-1 ml-auto ${
+ isCustomBg ? 'bg-[#2c2c2c]' : 'bg-[#161616]'
+ }`}
>
- {/* Subtle Manga Margin / Safe Bleed Line Guides (CSP Manuscript Overlay) */}
- {isMangaMode && (
- <div className="absolute inset-2 border border-sky-400/30 border-dashed pointer-events-none flex items-center justify-center">
- <div className="absolute inset-2 border border-sky-400/20 pointer-events-none" />
- </div>
- )}
-
- {/* Ratio badge inside page preview */}
- <span
- className={`text-[9px] font-mono px-1.5 py-0.5 rounded shadow-sm font-semibold select-none z-10 ${
- enablePaperColor && (backgroundColor === '#000000' || backgroundColor === '#1e1e1e')
- ? 'bg-white/20 text-white'
- : 'bg-black/60 text-white'
- }`}
- >
- {simplifiedRatio}
- </span>
- </div>
- </div>
-
- {/* Informative Specs Card */}
- <div className="w-full mt-3 bg-[#1f1f22] border border-[#2b2b2e] rounded p-3 space-y-1.5 text-[11px]">
- <div className="flex items-center justify-between text-[#aaaaaa]">
- <span>Resolution:</span>
- <span className="font-mono text-white font-medium">
- {width} × {height} px
- </span>
- </div>
-
- <div className="flex items-center justify-between text-[#aaaaaa]">
- <span>Aspect Ratio:</span>
- <span className="font-mono text-[#38bdf8] font-medium">
- {simplifiedRatio} ({(width / height).toFixed(2)}:1)
- </span>
- </div>
-
- <div className="flex items-center justify-between text-[#aaaaaa]">
- <span>Print Size:</span>
- <span className="font-mono text-[#e0e0e0]">
- {printDimensions.cmW} × {printDimensions.cmH} cm
- </span>
- </div>
-
- <div className="flex items-center justify-between text-[#aaaaaa]">
- <span>Density:</span>
- <span className="font-mono text-[#38bdf8] font-medium">
- {dpi} DPI ({megapixels} MP)
- </span>
- </div>
-
- <div className="flex items-center justify-between text-[#aaaaaa]">
- <span>Orientation:</span>
- <span className="text-[#e0e0e0] font-medium">
- {orientation}
- </span>
- </div>
-
- <div className="flex items-center justify-between text-[#aaaaaa] pt-1.5 border-t border-[#2d2d30]">
- <span>Expression Color:</span>
- <span
- className={`font-semibold capitalize ${
- colorMode === 'monochrome'
- ? 'text-amber-400'
- : colorMode === 'grayscale'
- ? 'text-slate-300'
- : 'text-emerald-400'
- }`}
- >
- {colorMode === 'monochrome' ? `Monochrome (${defaultFrequency}L tone)` : colorMode}
- </span>
+ <input
+ type="color"
+ value={normalizeHex(customHex) ?? '#ffffff'}
+ onChange={(e) => {
+ const hex = e.target.value.toLowerCase();
+ setCustomHex(hex);
+ setBackgroundColor(hex);
+ }}
+ className="w-4 h-4 cursor-pointer bg-transparent border-0 p-0 rounded shrink-0"
+ title="Pick custom background color"
+ aria-label="Custom background color picker"
+ />
+ <input
+ type="text"
+ value={customHex}
+ maxLength={7}
+ onChange={(e) => {
+ const val = e.target.value;
+ setCustomHex(val);
+ const norm = normalizeHex(val);
+ if (norm) setBackgroundColor(norm);
+ }}
+ onBlur={() => {
+ const norm = normalizeHex(customHex);
+ if (!norm && !isTransparent) {
+ setCustomHex(backgroundColor);
+ }
+ }}
+ aria-label="Custom background hex color"
+ className="w-[58px] font-mono text-[11px] px-1 py-0.5"
+ />
</div>
</div>
- </div>
+ </section>
</div>
</div>
- {/* Modal Footer Actions */}
- <div className="flex items-center justify-between px-5 py-3 bg-[#2a2a2d] border-t border-[#38383a]">
- <div className="text-[11px] text-[#777777] hidden sm:block">
- Press <kbd className="px-1.5 py-0.5 rounded bg-[#1c1c1e] border border-[#3e3e42] text-[#aaaaaa]">Enter</kbd> to Create
- </div>
+ {/* Footer */}
+ <div className="h-12 px-4 flex items-center justify-between bg-[#161616] border-t border-[#2c2c2c] shrink-0">
+ <span className="text-[11px] text-[#8a8a8a] hidden sm:inline">
+ <kbd className="px-1.5 py-0.5 rounded bg-[#202020] text-[#b5b5b5] font-mono text-[10px]">
+ Enter
+ </kbd>{' '}
+ to create
+ </span>
- <div className="flex items-center space-x-2.5 ml-auto">
+ <div className="flex items-center gap-2 ml-auto">
<button
type="button"
onClick={onClose}
- className="px-4 py-1.5 rounded bg-[#333336] hover:bg-[#3d3d42] text-[#cccccc] hover:text-white border border-[#444448] transition-colors"
+ className="px-3.5 py-1.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5] text-xs font-medium transition-colors cursor-pointer"
>
Cancel
</button>
<button
type="button"
onClick={handleCreate}
- className="flex items-center space-x-1.5 px-5 py-1.5 rounded bg-[#007acc] hover:bg-[#008be5] active:bg-[#006bb3] text-white font-medium shadow-sm transition-colors"
+ className="px-4 py-1.5 rounded text-xs font-medium transition-opacity hover:opacity-90 cursor-pointer flex items-center gap-1.5"
+ style={{
+ backgroundColor: 'var(--accent)',
+ color: 'var(--accent-contrast)',
+ }}
>
- <FileCheck className="w-4 h-4" />
<span>Create Canvas</span>
</button>
</div>
diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsx
index c7bdb2b..9dd71d9 100644
--- a/src/components/RightSidebar.tsx
+++ b/src/components/RightSidebar.tsx
@@ -21,6 +21,7 @@ import {
Frame,
Type,
MessageSquare,
+ Shield,
} from 'lucide-react';
import {
HistoryItemMeta,
@@ -129,6 +130,8 @@ export interface RightSidebarProps {
onSetOpacity: (id: string, opacity: number) => void;
onSetBlendMode: (id: string, blendMode: BlendMode) => void;
onToggleLock: (id: string) => void;
+ onToggleOwnerLock?: (id: string) => void;
+ isCollabActive?: boolean;
onToggleAlphaLock?: (id: string) => void;
onToggleClipping?: (id: string) => void;
onToggleCollapse: (id: string) => void;
@@ -229,6 +232,8 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
onSetOpacity,
onSetBlendMode,
onToggleLock,
+ onToggleOwnerLock,
+ isCollabActive = false,
onToggleAlphaLock,
onToggleClipping,
onToggleCollapse,
@@ -770,6 +775,24 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
<Unlock className="w-3 h-3" />
)}
</button>
+ {isCollabActive && onToggleOwnerLock && activeLayer.id !== 'layer-bg' && (
+ <button
+ type="button"
+ onClick={() => onToggleOwnerLock(activeLayer.id)}
+ title={
+ activeLayer.reservedByPeerId
+ ? `Owner-Locked by ${activeLayer.reservedByPeerName || 'Owner'} (click to unlock)`
+ : 'Lock Layer to Owner (prevents edits by other peers)'
+ }
+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ activeLayer.reservedByPeerId
+ ? 'bg-amber-500/20 text-amber-300'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ <Shield className="w-3 h-3" />
+ </button>
+ )}
</div>
<div className="flex items-center gap-0.5">
@@ -1127,6 +1150,14 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
{layer.toneEnabled && <span>{layer.toneFrequency ?? 60}L</span>}
{hasStyles && <span>fx</span>}
{layer.opacity < 0.99 && <span>{Math.round(layer.opacity * 100)}%</span>}
+ {layer.reservedByPeerId && (
+ <span
+ title={`Locked by ${layer.reservedByPeerName || 'owner'}`}
+ className="text-amber-400 flex items-center"
+ >
+ <Shield className="w-2.5 h-2.5" />
+ </span>
+ )}
{layer.locked && <Lock className="w-2.5 h-2.5" />}
</div>
</div>
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index af8055a..e5f45dd 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -31,6 +31,8 @@ import {
MouseWheelAction,
ModernAccentColor,
MODERN_ACCENTS,
+ NICKNAME_CUSTOMIZED_STORAGE_KEY,
+ NICKNAME_STORAGE_KEY,
ShortcutCategory,
resolveModernAccentColor,
} from '../types/settings';
@@ -498,8 +500,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onChange={(e) => {
const val = e.target.value;
handleChange('userName', val);
- safeLocalStorageSetItem('sora_paint_nickname', val, 'artist name');
- safeLocalStorageSetItem('ink_nickname_customized', val.trim() ? '1' : '0', 'artist name flag');
+ safeLocalStorageSetItem(NICKNAME_STORAGE_KEY, val, 'artist name');
+ safeLocalStorageSetItem(NICKNAME_CUSTOMIZED_STORAGE_KEY, val.trim() ? '1' : '0', 'artist name flag');
}}
placeholder="Artist"
className="w-full bg-[#161616] px-3 py-1.5 rounded text-xs text-[#e5e5e5] placeholder-[#8a8a8a]/50"
diff --git a/src/components/TonalCorrectionModal.tsx b/src/components/TonalCorrectionModal.tsx
index 7bf1184..b349c1a 100644
--- a/src/components/TonalCorrectionModal.tsx
+++ b/src/components/TonalCorrectionModal.tsx
@@ -7,13 +7,15 @@ import {
HueSaturationParams,
PosterizationParams,
LevelCorrectionParams,
+ TileHistogramMap,
computeHistogram,
} from '../utils/tonalEngine';
interface TonalCorrectionModalProps {
isOpen: boolean;
type: TonalCorrectionType;
- beforeImageData: ImageData | null;
+ histograms?: TileHistogramMap | null;
+ beforeImageData?: ImageData | null;
selectionMask: Uint8Array | null;
onClose: () => void;
onApply: (type: TonalCorrectionType, params: any) => void;
@@ -51,6 +53,7 @@ const DEFAULT_LEVEL_CORRECTION: LevelCorrectionParams = {
export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({
isOpen,
type,
+ histograms,
beforeImageData,
selectionMask,
onClose,
@@ -78,16 +81,18 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({
const histogramCanvasRef = useRef<HTMLCanvasElement | null>(null);
- // Compute histograms for level correction
+ // Use precomputed tile histograms (zero full-doc ImageData allocation) or fallback to ImageData
const histogramMap = useMemo(() => {
- if (!beforeImageData || type !== 'level-correction') return null;
+ if (type !== 'level-correction') return null;
+ if (histograms) return histograms;
+ if (!beforeImageData) return null;
return {
rgb: computeHistogram(beforeImageData, 'rgb', selectionMask),
r: computeHistogram(beforeImageData, 'r', selectionMask),
g: computeHistogram(beforeImageData, 'g', selectionMask),
b: computeHistogram(beforeImageData, 'b', selectionMask),
};
- }, [beforeImageData, type, selectionMask]);
+ }, [histograms, beforeImageData, type, selectionMask]);
// Reset state when opening
useEffect(() => {
diff --git a/src/components/ToolPropertyInspector.tsx b/src/components/ToolPropertyInspector.tsx
index effaa75..6945143 100644
--- a/src/components/ToolPropertyInspector.tsx
+++ b/src/components/ToolPropertyInspector.tsx
@@ -35,7 +35,7 @@ import {
DEFAULT_BRUSH_PRESET_ID,
} from '../utils/brushPresetManager';
import { renderBrushStrokePreview } from '../utils/brushPreview';
-import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/CspBrushEngine';
+import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/BrushEngine';
import { useToolStore, toolStoreActions, useUiStore, uiStoreActions } from '../stores';
interface CompactSliderProps {
diff --git a/src/components/WebLandingModal.tsx b/src/components/WebLandingModal.tsx
index 1a1d5d4..cc3d09c 100644
--- a/src/components/WebLandingModal.tsx
+++ b/src/components/WebLandingModal.tsx
@@ -1,7 +1,8 @@
-import React, { useState } from 'react';
+import React, { useEffect, useState } from 'react';
import { Users, Globe, Monitor, ArrowRight, User, X } from 'lucide-react';
import { isTauriEnvironment } from '../hooks/useMultiplayer';
-import { ParsedInviteLink } from '../services/multiplayerService';
+import { DEEP_LINK_SCHEME, ParsedInviteLink } from '../services/multiplayerService';
+import { NICKNAME_CUSTOMIZED_STORAGE_KEY, NICKNAME_STORAGE_KEY } from '../types/settings';
import { safeLocalStorageSetItem } from '../utils/safeStorage';
interface WebLandingModalProps {
@@ -26,36 +27,53 @@ export const WebLandingModal: React.FC<WebLandingModalProps> = ({
const [userName, setUserName] = useState(() => {
if (typeof window === 'undefined') return '';
try {
- const customized = localStorage.getItem('ink_nickname_customized') === '1';
- const saved = (localStorage.getItem('sora_paint_nickname') || '').trim();
+ const customized = localStorage.getItem(NICKNAME_CUSTOMIZED_STORAGE_KEY) === '1';
+ const saved = (localStorage.getItem(NICKNAME_STORAGE_KEY) || '').trim();
return customized && saved && saved !== 'Guest' ? saved : '';
} catch {
return '';
}
});
const isTauri = isTauriEnvironment();
+ const isVisible = Boolean(invite) && !isTauri;
+
+ useEffect(() => {
+ if (!isVisible) return;
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ onDismiss();
+ }
+ };
+ window.addEventListener('keydown', handleKeyDown);
+ return () => window.removeEventListener('keydown', handleKeyDown);
+ }, [isVisible, onDismiss]);
// If running inside desktop Tauri app, don't show the web browser welcome banner
if (!invite || isTauri) return null;
+ const trimmedName = userName.trim();
+ const hostDisplay = `${invite.host}${
+ invite.port && invite.port !== 443 && invite.port !== 80 ? `:${invite.port}` : ''
+ }`;
+
const handleOpenInApp = () => {
const tokenPart = invite.token ? `&token=${encodeURIComponent(invite.token)}` : '';
const protoPart = invite.isSecure ? '&protocol=https' : '';
- const deepLink = `forsora://join?host=${encodeURIComponent(invite.host)}&port=${invite.port}&room=${encodeURIComponent(invite.roomName)}${tokenPart}${protoPart}`;
+ const deepLink = `${DEEP_LINK_SCHEME}//join?host=${encodeURIComponent(invite.host)}&port=${invite.port}&room=${encodeURIComponent(invite.roomName)}${tokenPart}${protoPart}`;
window.location.href = deepLink;
};
const handleJoinWithNickname = (e?: React.FormEvent) => {
e?.preventDefault();
- const trimmed = userName.trim();
- if (!trimmed) {
+ if (!trimmedName) {
handlePlayAsGuest();
return;
}
- safeLocalStorageSetItem('sora_paint_nickname', trimmed, 'artist name');
- safeLocalStorageSetItem('ink_nickname_customized', '1', 'artist name flag');
+ safeLocalStorageSetItem(NICKNAME_STORAGE_KEY, trimmedName, 'artist name');
+ safeLocalStorageSetItem(NICKNAME_CUSTOMIZED_STORAGE_KEY, '1', 'artist name flag');
onJoinInBrowser(
- trimmed,
+ trimmedName,
invite.host,
invite.port,
invite.roomName,
@@ -78,97 +96,128 @@ export const WebLandingModal: React.FC<WebLandingModalProps> = ({
};
return (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none">
- <div className="relative w-full max-w-md rounded-[2px] border border-[#242426] bg-[#444447] p-5 shadow-[0_8px_24px_rgba(0,0,0,0.8)] text-[#d6d6da]">
- <button
- onClick={onDismiss}
- className="absolute top-3 right-3 rounded-[2px] p-1 text-[#99999e] hover:bg-[#525255] hover:text-white transition-colors cursor-pointer"
- >
- <X className="w-4 h-4" />
- </button>
-
- {/* Header Icon */}
- <div className="flex items-center space-x-2.5 mb-4">
- <div className="flex items-center justify-center w-8 h-8 rounded-[2px] bg-[#363639] border border-[#242426] shadow-xs">
- <Users className="w-4 h-4 text-[#93c5fd]" />
- </div>
- <div>
- <h2 className="text-sm font-semibold text-[#f0f0f4]">Ink Studio Collab</h2>
- <p className="text-[11px] text-[#8c8c92]">Real-time canvas session</p>
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="web-landing-modal-title"
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-4 select-none"
+ onClick={onDismiss}
+ >
+ <div
+ onClick={(e) => e.stopPropagation()}
+ className="w-full max-w-md rounded-lg border border-[#2c2c2c] bg-[#202020] shadow-[0_24px_64px_rgba(0,0,0,0.8)] flex flex-col overflow-hidden text-xs text-[#e5e5e5]"
+ >
+ {/* Header */}
+ <div className="h-10 px-4 flex items-center justify-between bg-[#161616] border-b border-[#2c2c2c] shrink-0">
+ <div className="flex items-center gap-2 min-w-0">
+ <Users className="w-3.5 h-3.5 text-[var(--accent)] shrink-0" />
+ <h2 id="web-landing-modal-title" className="text-xs font-medium text-[#e5e5e5] truncate">
+ Ink Studio Collab
+ </h2>
</div>
+ <button
+ type="button"
+ onClick={onDismiss}
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer shrink-0"
+ title="Close (Esc)"
+ aria-label="Close connection dialog"
+ >
+ <X className="w-3.5 h-3.5" />
+ </button>
</div>
- {/* Room Info Card */}
- <div className="rounded-[2px] border border-[#242426] bg-[#2b2b2e] p-3 mb-4 space-y-1 shadow-[inset_1px_1px_2px_rgba(0,0,0,0.5)]">
- <div className="text-[11px] font-medium text-[#99999e]">Connecting to canvas:</div>
- <div className="text-xs font-semibold text-[#f0f0f4]">"{invite.roomName}"</div>
- <div className="text-[10px] text-[#808085] font-mono">
- Host: {invite.host}
- {invite.port && invite.port !== 443 && invite.port !== 80 ? `:${invite.port}` : ''}
+ {/* Body */}
+ <div className="p-5 space-y-4">
+ {/* Room Info Card */}
+ <div className="rounded border border-[#2c2c2c] bg-[#161616] p-3.5 space-y-1">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">
+ Connecting to Canvas
+ </span>
+ {invite.isSecure && (
+ <span className="font-mono text-[10px] px-1.5 py-0.5 rounded bg-[#202020] border border-[#2c2c2c] text-[#a0a0a0]">
+ HTTPS · WSS
+ </span>
+ )}
+ </div>
+ <div className="text-sm font-semibold text-[#e5e5e5] truncate" title={invite.roomName}>
+ {invite.roomName}
+ </div>
+ <div
+ className="text-[11px] text-[#8a8a8a] font-mono truncate select-text"
+ title={hostDisplay}
+ >
+ Host: {hostDisplay}
+ </div>
</div>
- </div>
- <form onSubmit={handleJoinWithNickname} className="space-y-4">
- {/* Name input */}
- <div className="space-y-1">
- <label className="block text-xs font-medium text-[#cccccc]">
- Choose a Nickname (optional):
- </label>
- <input
- type="text"
- autoFocus
- maxLength={40}
- value={userName}
- onChange={(e) => setUserName(e.target.value)}
- placeholder="Enter nickname..."
- className="w-full rounded-[2px] border border-[#1e1e20] bg-[#2b2b2e] px-2.5 py-1.5 text-xs text-[#f0f0f4] placeholder-[#707075] outline-none focus:border-[#4a8fc7] shadow-[inset_1px_1px_2px_rgba(0,0,0,0.5)]"
- />
- </div>
+ <form onSubmit={handleJoinWithNickname} className="space-y-4">
+ {/* Name input */}
+ <div className="space-y-1.5">
+ <label
+ htmlFor="web-landing-nickname"
+ className="flex items-center justify-between text-[11px] font-medium text-[#e5e5e5]"
+ >
+ <span>Choose a Nickname</span>
+ <span className="font-normal text-[#8a8a8a]">Optional</span>
+ </label>
+ <input
+ id="web-landing-nickname"
+ type="text"
+ autoFocus
+ maxLength={40}
+ value={userName}
+ onChange={(e) => setUserName(e.target.value)}
+ placeholder="Enter nickname..."
+ className="w-full rounded bg-[#161616] px-3 py-2 text-xs text-[#e5e5e5] placeholder-[#8a8a8a]/50"
+ />
+ </div>
- {/* Action Buttons */}
- <div className="space-y-2">
- <button
- type="submit"
- className="w-full flex items-center justify-between rounded-[2px] border border-[#242426] bg-gradient-to-b from-[#56565a] to-[#424245] hover:from-[#626266] hover:to-[#4b4b4e] px-3.5 py-2 text-xs font-medium text-[#f0f0f4] transition-colors shadow-[inset_0_1px_0_rgba(255,255,255,0.18),0_1px_1px_rgba(0,0,0,0.3)] cursor-pointer"
- >
- <div className="flex items-center space-x-2">
- <Globe className="w-3.5 h-3.5 text-[#93c5fd]" />
- <span>
- {userName.trim()
- ? `Join as "${userName.trim()}"`
- : 'Join in Browser'}
+ {/* Action Buttons */}
+ <div className="space-y-2">
+ <button
+ type="submit"
+ className="w-full flex items-center justify-between gap-2 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 px-3.5 py-2 text-xs font-medium transition-opacity cursor-pointer"
+ >
+ <span className="flex items-center gap-2 min-w-0">
+ <Globe className="w-3.5 h-3.5 shrink-0" />
+ <span className="truncate">
+ {trimmedName ? `Join as "${trimmedName}"` : 'Join in Browser'}
+ </span>
</span>
- </div>
- <ArrowRight className="w-3.5 h-3.5" />
- </button>
+ <ArrowRight className="w-3.5 h-3.5 shrink-0" />
+ </button>
- <button
- type="button"
- onClick={handlePlayAsGuest}
- className="w-full flex items-center justify-between rounded-[2px] border border-[#242426] bg-[#363639] hover:bg-[#404044] px-3.5 py-2 text-xs font-medium text-[#d6d6da] transition-colors cursor-pointer"
- >
- <div className="flex items-center space-x-2">
- <User className="w-3.5 h-3.5 text-[#aaaaaa]" />
- <span>Play as Guest</span>
- </div>
- <ArrowRight className="w-3.5 h-3.5 opacity-70" />
- </button>
+ <button
+ type="button"
+ onClick={handlePlayAsGuest}
+ className="w-full flex items-center justify-between gap-2 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-[#2c2c2c] px-3.5 py-2 text-xs font-medium text-[#e5e5e5] transition-colors cursor-pointer"
+ >
+ <span className="flex items-center gap-2">
+ <User className="w-3.5 h-3.5 text-[#8a8a8a]" />
+ <span>Play as Guest</span>
+ </span>
+ <ArrowRight className="w-3.5 h-3.5 text-[#8a8a8a]" />
+ </button>
- <button
- type="button"
- onClick={handleOpenInApp}
- className="w-full flex items-center justify-between rounded-[2px] border border-[#242426] bg-gradient-to-b from-[#48484c] to-[#38383b] hover:from-[#525256] hover:to-[#404043] px-3.5 py-2 text-xs font-medium text-[#d0d0d5] transition-colors shadow-[inset_0_1px_0_rgba(255,255,255,0.12)] cursor-pointer"
- >
- <div className="flex items-center space-x-2">
- <Monitor className="w-3.5 h-3.5 text-emerald-400" />
- <span>Launch Desktop Client (.exe)</span>
- </div>
- </button>
- </div>
- </form>
+ <button
+ type="button"
+ onClick={handleOpenInApp}
+ className="w-full flex items-center justify-between gap-2 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-[#2c2c2c] px-3.5 py-2 text-xs font-medium text-[#d4d4d4] hover:text-[#e5e5e5] transition-colors cursor-pointer"
+ >
+ <span className="flex items-center gap-2">
+ <Monitor className="w-3.5 h-3.5 text-[var(--accent)]" />
+ <span>Launch Desktop Client (.exe)</span>
+ </span>
+ <ArrowRight className="w-3.5 h-3.5 text-[#8a8a8a]" />
+ </button>
+ </div>
+ </form>
+ </div>
- <div className="mt-3.5 text-center">
- <span className="text-[10px] text-[#808085]">
+ {/* Footer */}
+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] text-center">
+ <span className="text-[10px] text-[#737373]">
Supports graphic tablets, stylus pressure, and real-time synchronization.
</span>
</div>
diff --git a/src/components/canvasArea/CanvasArtboardOverlays.tsx b/src/components/canvasArea/CanvasArtboardOverlays.tsx
new file mode 100644
index 0000000..15c1096
--- /dev/null
+++ b/src/components/canvasArea/CanvasArtboardOverlays.tsx
@@ -0,0 +1,399 @@
+import React from 'react';
+import { buildShapeSvgPaths, isOpenShape, resolveShapeFillColor } from '../../utils/shapeEngine';
+import { SelectionOverlay } from '../SelectionOverlay';
+import { TransformOverlay } from '../TransformOverlay';
+import { TextEditorOverlay } from '../TextEditorOverlay';
+import { SpeechBalloonOverlay } from '../SpeechBalloonOverlay';
+import { Local3DContainer } from '../Local3DContainer';
+import { CanvasAreaProps, formatArtboardTransform } from './types';
+
+export interface CanvasArtboardOverlaysProps {
+ canvasProps: CanvasAreaProps;
+ artboardRef: React.RefObject<HTMLDivElement | null>;
+ livePan: { x: number; y: number };
+ liveZoom: number;
+ liveRotation: number;
+ liveFlipX: boolean;
+ liveFlipY: boolean;
+ handleCanvasPointerDown: (e: React.PointerEvent<HTMLElement>) => void;
+ handleCanvasPointerMove: (e: React.PointerEvent<HTMLElement>) => void;
+ handleCanvasPointerUp: (e: React.PointerEvent<HTMLElement>) => void;
+ handleCanvasPointerCancel: (e: React.PointerEvent<HTMLElement>) => void;
+ handleContextMenu: (e: React.MouseEvent<HTMLElement>) => void;
+ canvasCursorStyle: React.CSSProperties;
+}
+
+export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({
+ canvasProps,
+ artboardRef,
+ livePan,
+ liveZoom,
+ liveRotation,
+ liveFlipX,
+ liveFlipY,
+ handleCanvasPointerDown,
+ handleCanvasPointerMove,
+ handleCanvasPointerUp,
+ handleCanvasPointerCancel,
+ handleContextMenu,
+ canvasCursorStyle,
+}) => {
+ const {
+ interactionRef,
+ dimensions,
+ zoom,
+ pan,
+ rotation,
+ peers = [],
+ activePings = [],
+ remoteDraftCanvasesRef,
+ selection = null,
+ onDeselect,
+ onTransformSelection,
+ onFillScreentone,
+ onFillColor,
+ onClearSelection,
+ onInvertSelection,
+ onExpandSelection,
+ onContractSelection,
+ onFeatherSelection,
+ transformSession = null,
+ onUpdateTransformSession,
+ onApplyTransform,
+ onCancelTransform,
+ textSession = null,
+ onUpdateTextSettings,
+ onMoveTextSession,
+ onConfirmText,
+ onCancelText,
+ activeBalloon = null,
+ onUpdateBalloon,
+ onConfirmBalloon,
+ onDeleteBalloon,
+ frameDragPreview = null,
+ shapeDragPreview = null,
+ primaryColor = '#000000',
+ secondaryColor = '#ffffff',
+ is3DLayerOpen = false,
+ initial3DFile = null,
+ onClose3DLayer,
+ onInsertRasterLayer,
+ onBake3DSuccess,
+ perspectiveRuler = null,
+ onUpdatePerspectiveRuler,
+ onPointerEnter,
+ onPointerLeave,
+ } = canvasProps;
+
+ return (
+ <div
+ ref={artboardRef}
+ className="absolute origin-top-left select-none z-20"
+ style={{
+ width: dimensions.width,
+ height: dimensions.height,
+ transform: formatArtboardTransform(
+ livePan,
+ liveZoom,
+ liveRotation,
+ liveFlipX,
+ liveFlipY,
+ dimensions
+ ),
+ transformOrigin: '0 0',
+ willChange: 'transform',
+ backgroundColor: 'transparent',
+ backgroundImage: 'none',
+ }}
+ >
+ {/* Remote Peer Live Stroke Draft Overlay Canvases */}
+ {peers.map((peer) => (
+ <canvas
+ key={`peer-canvas-${peer.id}`}
+ ref={(el) => {
+ if (remoteDraftCanvasesRef) {
+ if (el) remoteDraftCanvasesRef.current.set(peer.id, el);
+ else remoteDraftCanvasesRef.current.delete(peer.id);
+ }
+ }}
+ width={dimensions.width}
+ height={dimensions.height}
+ className="absolute inset-0 block pointer-events-none z-15"
+ style={{ imageRendering: zoom > 1 ? 'pixelated' : 'auto' }}
+ />
+ ))}
+
+ {/* Remote Peer Ghost Cursors with Nametag Badges */}
+ {peers.map((peer) => {
+ if (peer.x === undefined || peer.y === undefined) return null;
+ return (
+ <div
+ key={`peer-cursor-${peer.id}`}
+ className="absolute pointer-events-none transition-transform duration-75 ease-out z-25 select-none -translate-x-1/2 -translate-y-1/2"
+ style={{
+ left: `${peer.x}px`,
+ top: `${peer.y}px`,
+ }}
+ >
+ {/* Colored Cursor Ring */}
+ <div
+ className="w-3.5 h-3.5 rounded-full border-2 border-white shadow-md animate-in fade-in"
+ style={{ backgroundColor: peer.color }}
+ />
+ {/* Floating Nametag Pill */}
+ <div
+ className="absolute top-4 left-2 px-1.5 py-0.5 rounded text-[10px] font-semibold text-white shadow-lg whitespace-nowrap flex items-center space-x-1 pointer-events-none"
+ style={{
+ backgroundColor: peer.color,
+ transform: `scale(${liveFlipX ? -1 : 1}, ${liveFlipY ? -1 : 1})`,
+ }}
+ >
+ <span>{peer.name}</span>
+ {peer.isDrawing && <span className="w-1.5 h-1.5 rounded-full bg-white animate-pulse" />}
+ </div>
+ </div>
+ );
+ })}
+
+ {/* Canvas Radar Pings */}
+ {activePings.map((ping) => (
+ <div
+ key={ping.id}
+ className="absolute pointer-events-none z-30 -translate-x-1/2 -translate-y-1/2"
+ style={{ left: `${ping.x}px`, top: `${ping.y}px` }}
+ >
+ <div
+ className="w-12 h-12 rounded-full border-2 animate-ping"
+ style={{ borderColor: ping.color }}
+ />
+ <div
+ className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-3.5 h-3.5 rounded-full shadow-md"
+ style={{ backgroundColor: ping.color }}
+ />
+ <div
+ className="absolute top-5 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded text-[10px] font-bold text-white whitespace-nowrap shadow-md"
+ style={{
+ backgroundColor: ping.color,
+ transform: `scale(${liveFlipX ? -1 : 1}, ${liveFlipY ? -1 : 1})`,
+ }}
+ >
+ {ping.name}
+ </div>
+ </div>
+ ))}
+
+ {/* Selection Overlay */}
+ {selection && (
+ <SelectionOverlay
+ selection={selection}
+ dimensions={dimensions}
+ zoom={liveZoom}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
+ onDeselect={onDeselect || (() => {})}
+ onTransformSelection={onTransformSelection || (() => {})}
+ onFillScreentone={onFillScreentone || (() => {})}
+ onFillColor={onFillColor || (() => {})}
+ onClearSelection={onClearSelection || (() => {})}
+ onInvertSelection={onInvertSelection || (() => {})}
+ onExpandSelection={onExpandSelection}
+ onContractSelection={onContractSelection}
+ onFeatherSelection={onFeatherSelection}
+ />
+ )}
+
+ {/* Free Transform Overlay */}
+ {transformSession?.active && (
+ <TransformOverlay
+ session={transformSession}
+ zoom={liveZoom}
+ rotation={liveRotation}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
+ onUpdateSession={onUpdateTransformSession || (() => {})}
+ onApply={onApplyTransform || (() => {})}
+ onCancel={onCancelTransform || (() => {})}
+ />
+ )}
+
+ {/* Manga Text Editor Overlay */}
+ {textSession && (
+ <TextEditorOverlay
+ x={textSession.x}
+ y={textSession.y}
+ settings={textSession.settings}
+ zoom={liveZoom}
+ rotation={liveRotation}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
+ onUpdateSettings={onUpdateTextSettings || (() => {})}
+ onMove={onMoveTextSession || (() => {})}
+ onConfirm={onConfirmText || (() => {})}
+ onCancel={onCancelText || (() => {})}
+ />
+ )}
+
+ {/* Parametric Speech Balloon Overlay */}
+ {activeBalloon && (
+ <SpeechBalloonOverlay
+ balloon={activeBalloon}
+ zoom={liveZoom}
+ rotation={liveRotation}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
+ onUpdateBalloon={onUpdateBalloon || (() => {})}
+ onConfirmBalloon={onConfirmBalloon || (() => {})}
+ onDeleteBalloon={onDeleteBalloon || (() => {})}
+ />
+ )}
+
+ {/* Frame Border Folder Create / Divide Live Preview */}
+ {frameDragPreview && (
+ <svg className="absolute inset-0 w-full h-full overflow-visible pointer-events-none z-35">
+ {frameDragPreview.mode === 'create' ? (
+ <rect
+ x={Math.min(frameDragPreview.start.x, frameDragPreview.end.x)}
+ y={Math.min(frameDragPreview.start.y, frameDragPreview.end.y)}
+ width={Math.abs(frameDragPreview.end.x - frameDragPreview.start.x)}
+ height={Math.abs(frameDragPreview.end.y - frameDragPreview.start.y)}
+ fill="rgba(0, 188, 212, 0.08)"
+ stroke="#00bcd4"
+ strokeWidth={2 / liveZoom}
+ strokeDasharray={`${6 / liveZoom},${4 / liveZoom}`}
+ />
+ ) : (
+ <>
+ <line
+ x1={frameDragPreview.start.x}
+ y1={frameDragPreview.start.y}
+ x2={frameDragPreview.end.x}
+ y2={frameDragPreview.end.y}
+ stroke="#00e5ff"
+ strokeWidth={2.5 / liveZoom}
+ strokeDasharray={`${8 / liveZoom},${4 / liveZoom}`}
+ />
+ <circle
+ cx={frameDragPreview.start.x}
+ cy={frameDragPreview.start.y}
+ r={4 / liveZoom}
+ fill="#00e5ff"
+ />
+ <circle
+ cx={frameDragPreview.end.x}
+ cy={frameDragPreview.end.y}
+ r={4 / liveZoom}
+ fill="#00e5ff"
+ />
+ </>
+ )}
+ </svg>
+ )}
+
+ {/* Live Geometric Shape Placement Preview */}
+ {shapeDragPreview && (() => {
+ const { geom, mainPath, arrowHeadPath } = buildShapeSvgPaths(shapeDragPreview);
+ const s = shapeDragPreview.settings;
+ const open = isOpenShape(s.shape);
+ const strokeColor = primaryColor || '#000000';
+ const fillColor = resolveShapeFillColor(s, strokeColor, secondaryColor);
+ const shouldFill = !open && (s.mode === 'fill' || s.mode === 'both');
+ const shouldStroke = open || s.mode === 'stroke' || s.mode === 'both';
+ const dashArray = s.dashed ? `${Math.max(1, s.dashLength)} ${Math.max(1, s.dashGap)}` : undefined;
+ const invZoom = 1 / Math.max(0.05, liveZoom);
+ const readoutText = open
+ ? `${Math.round(geom.length)}px · ${Math.round(geom.angleDeg)}°`
+ : `${Math.round(geom.width)} × ${Math.round(geom.height)}px`;
+ return (
+ <>
+ <svg
+ className="absolute inset-0 w-full h-full pointer-events-none z-30 overflow-visible"
+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}
+ >
+ {mainPath && (
+ <path
+ d={mainPath}
+ fill={shouldFill ? fillColor : 'none'}
+ stroke={shouldStroke ? strokeColor : 'none'}
+ strokeWidth={Math.max(1, s.strokeWidth)}
+ strokeLinecap={s.lineCap}
+ strokeLinejoin={s.lineJoin}
+ strokeDasharray={dashArray}
+ opacity={Math.max(0.05, Math.min(1, s.opacity))}
+ />
+ )}
+ {arrowHeadPath && (
+ <path
+ d={arrowHeadPath}
+ fill="none"
+ stroke={strokeColor}
+ strokeWidth={Math.max(1, s.strokeWidth)}
+ strokeLinecap={s.lineCap}
+ strokeLinejoin={s.lineJoin}
+ opacity={Math.max(0.05, Math.min(1, s.opacity))}
+ />
+ )}
+ {!open && geom.width > 1 && geom.height > 1 && (
+ <rect
+ x={geom.x}
+ y={geom.y}
+ width={geom.width}
+ height={geom.height}
+ fill="none"
+ stroke="#e5e5e5"
+ strokeOpacity={0.55}
+ strokeWidth={1 * invZoom}
+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}
+ />
+ )}
+ </svg>
+ <div
+ className="absolute pointer-events-none z-30 px-1.5 py-0.5 rounded bg-[#161616]/90 border border-white/15 text-[#e5e5e5] font-mono text-[10px] whitespace-nowrap"
+ style={{
+ left: `${geom.x2}px`,
+ top: `${geom.y2}px`,
+ transform: `translate(${10 * invZoom}px, ${10 * invZoom}px) scale(${invZoom})`,
+ transformOrigin: 'top left',
+ }}
+ >
+ {readoutText}
+ </div>
+ </>
+ );
+ })()}
+
+ {/* Local-Only 3D Viewport Ghost Layer (Strictly Client-Side Isolated State) */}
+ {is3DLayerOpen && onClose3DLayer && onInsertRasterLayer && (
+ <Local3DContainer
+ dimensions={dimensions}
+ zoom={zoom}
+ pan={pan}
+ rotation={rotation}
+ isOpen={is3DLayerOpen}
+ initialFile={initial3DFile}
+ onClose={onClose3DLayer}
+ onInsertRasterLayer={onInsertRasterLayer}
+ onBakeSuccess={onBake3DSuccess}
+ perspectiveRuler={perspectiveRuler}
+ onUpdatePerspectiveRuler={onUpdatePerspectiveRuler}
+ />
+ )}
+
+ {/* Top Transparent Interaction Surface capturing Stylus / Mouse Pointer Events */}
+ <div
+ ref={interactionRef}
+ onPointerDown={handleCanvasPointerDown}
+ onPointerMove={handleCanvasPointerMove}
+ onPointerUp={handleCanvasPointerUp}
+ onPointerCancel={handleCanvasPointerCancel}
+ onLostPointerCapture={handleCanvasPointerCancel}
+ onPointerEnter={onPointerEnter}
+ onPointerLeave={onPointerLeave}
+ onContextMenu={handleContextMenu}
+ className="absolute inset-0 block touch-none z-20"
+ style={{
+ ...canvasCursorStyle,
+ }}
+ />
+ </div>
+ );
+};
diff --git a/src/components/canvasArea/CanvasViewportHud.tsx b/src/components/canvasArea/CanvasViewportHud.tsx
new file mode 100644
index 0000000..d93f12b
--- /dev/null
+++ b/src/components/canvasArea/CanvasViewportHud.tsx
@@ -0,0 +1,437 @@
+import React from 'react';
+import { Smartphone, Archive } from 'lucide-react';
+import { TipOutline } from '../../utils/brushOutline';
+import { toolStoreActions, useToolStore } from '../../stores';
+import { StraightRulerOverlay } from '../StraightRulerOverlay';
+import { PerspectiveRulerOverlay } from '../PerspectiveRulerOverlay';
+import { SmartphoneViewportSimulator } from '../SmartphoneViewportSimulator';
+import { AnimationTimeline } from '../AnimationTimeline';
+import { CanvasAreaProps } from './types';
+
+export interface CanvasViewportHudProps {
+ canvasProps: CanvasAreaProps;
+ cursorRingRef: React.RefObject<HTMLDivElement | null>;
+ pointerStatRef: React.RefObject<HTMLDivElement | null>;
+ livePan: { x: number; y: number };
+ liveZoom: number;
+ liveRotation: number;
+ liveFlipX: boolean;
+ liveFlipY: boolean;
+ cursorWidth: number;
+ cursorHeight: number;
+ totalAngleDeg: number;
+ isCustomTip: boolean;
+ isSquare: boolean;
+ tipOutline: TipOutline | null;
+ isResizingBrush: boolean;
+ resizePreviewX: number;
+ resizePreviewY: number;
+ quickPalettePos: { x: number; y: number } | null;
+ setQuickPalettePos: React.Dispatch<React.SetStateAction<{ x: number; y: number } | null>>;
+}
+
+export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({
+ canvasProps,
+ cursorRingRef,
+ pointerStatRef,
+ livePan,
+ liveZoom,
+ liveRotation,
+ liveFlipX,
+ liveFlipY,
+ cursorWidth,
+ cursorHeight,
+ totalAngleDeg,
+ isCustomTip,
+ isSquare,
+ tipOutline,
+ isResizingBrush,
+ resizePreviewX,
+ resizePreviewY,
+ quickPalettePos,
+ setQuickPalettePos,
+}) => {
+ const {
+ viewportRef,
+ dimensions,
+ navigation,
+ straightRuler = null,
+ onUpdateStraightRuler,
+ perspectiveRuler = null,
+ onUpdatePerspectiveRuler,
+ activeLockedAxis = null,
+ isDrawing = false,
+ brushSettings,
+ onUpdateBrushSettings,
+ onUndo,
+ onRedo,
+ onFlipHorizontal,
+ isWebtoonMode = false,
+ onToggleWebtoonMode,
+ onOpenWebtoonExport,
+ showCursorCoordinates = false,
+ showPressureInStatusBar = false,
+ animationTimeline = null,
+ onUpdateAnimationTimeline,
+ layers,
+ tileGrid,
+ onAddAnimationCel,
+ onDeleteAnimationCel,
+ onSelectCelLayer,
+ isExternalFileDropActive = false,
+ } = canvasProps;
+
+ return (
+ <>
+ {/* Interactive Straight Ruler Overlay */}
+ {straightRuler && straightRuler.enabled && onUpdateStraightRuler && (
+ <StraightRulerOverlay
+ ruler={straightRuler}
+ onUpdateRuler={onUpdateStraightRuler}
+ onCloseRuler={() => onUpdateStraightRuler({ ...straightRuler, enabled: false })}
+ dimensions={dimensions}
+ pan={livePan}
+ zoom={liveZoom}
+ rotation={liveRotation}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
+ navigation={navigation}
+ viewportRef={viewportRef}
+ />
+ )}
+
+ {/* Interactive Perspective Ruler Overlay Layer (Clip Studio Paint style) */}
+ {perspectiveRuler && onUpdatePerspectiveRuler && (
+ <PerspectiveRulerOverlay
+ ruler={perspectiveRuler}
+ onUpdateRuler={onUpdatePerspectiveRuler}
+ onRemoveRuler={() => onUpdatePerspectiveRuler(null)}
+ dimensions={dimensions}
+ pan={livePan}
+ zoom={liveZoom}
+ rotation={liveRotation}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
+ navigation={navigation}
+ viewportRef={viewportRef}
+ activeLockedAxis={activeLockedAxis}
+ isDrawing={isDrawing}
+ />
+ )}
+
+ {/* Dynamic Dual-Tone Brush Silhouette Outline Cursor (CSP / Photoshop style) */}
+ <div
+ ref={cursorRingRef}
+ className="pointer-events-none absolute top-0 left-0 z-30 select-none"
+ style={{
+ display: 'none',
+ width: `${cursorWidth}px`,
+ height: `${cursorHeight}px`,
+ willChange: 'transform',
+ transformOrigin: 'center center',
+ }}
+ >
+ <svg
+ viewBox={isCustomTip && tipOutline ? tipOutline.viewBox : '0 0 100 100'}
+ className="w-full h-full overflow-visible pointer-events-none select-none"
+ style={{ display: 'block' }}
+ >
+ {isCustomTip && tipOutline ? (
+ <>
+ <path
+ d={tipOutline.path}
+ fill="none"
+ stroke="rgba(255, 255, 255, 0.85)"
+ strokeWidth="2.5"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ <path
+ d={tipOutline.path}
+ fill="none"
+ stroke="rgba(0, 0, 0, 0.85)"
+ strokeWidth="1"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ </>
+ ) : isSquare ? (
+ <>
+ <rect
+ x="1"
+ y="1"
+ width="98"
+ height="98"
+ fill="none"
+ stroke="rgba(255, 255, 255, 0.85)"
+ strokeWidth="2.5"
+ vectorEffect="non-scaling-stroke"
+ />
+ <rect
+ x="1"
+ y="1"
+ width="98"
+ height="98"
+ fill="none"
+ stroke="rgba(0, 0, 0, 0.85)"
+ strokeWidth="1"
+ vectorEffect="non-scaling-stroke"
+ />
+ </>
+ ) : (
+ <>
+ <ellipse
+ cx="50"
+ cy="50"
+ rx="49.5"
+ ry="49.5"
+ fill="none"
+ stroke="rgba(255, 255, 255, 0.85)"
+ strokeWidth="2.5"
+ vectorEffect="non-scaling-stroke"
+ />
+ <ellipse
+ cx="50"
+ cy="50"
+ rx="49.5"
+ ry="49.5"
+ fill="none"
+ stroke="rgba(0, 0, 0, 0.85)"
+ strokeWidth="1"
+ vectorEffect="non-scaling-stroke"
+ />
+ </>
+ )}
+ </svg>
+ </div>
+
+ {/* Floating Visual Preview for On-Canvas Brush Resizing (Ctrl + Alt + Drag) */}
+ {isResizingBrush && (
+ <div
+ className="pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 z-50 flex items-center justify-center"
+ style={{
+ left: `${resizePreviewX}px`,
+ top: `${resizePreviewY}px`,
+ width: `${cursorWidth}px`,
+ height: `${cursorHeight}px`,
+ transform: `translate(-50%, -50%) rotate(${totalAngleDeg}deg)`,
+ transformOrigin: 'center center',
+ }}
+ >
+ {isCustomTip && tipOutline ? (
+ <svg
+ viewBox={tipOutline.viewBox}
+ className="w-full h-full overflow-visible pointer-events-none"
+ style={{ display: 'block' }}
+ >
+ <path
+ d={tipOutline.path}
+ fill="rgba(239, 68, 68, 0.35)"
+ stroke="rgba(255, 255, 255, 0.95)"
+ strokeWidth="2.5"
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ <path
+ d={tipOutline.path}
+ fill="none"
+ stroke="rgba(0, 0, 0, 0.9)"
+ strokeWidth="1"
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ </svg>
+ ) : (
+ <>
+ {/* Outer diameter & hardness preview circle */}
+ <div
+ className={`w-full h-full ${isSquare ? 'rounded-none' : 'rounded-full'} border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.8),0_4px_16px_rgba(0,0,0,0.5)] transition-[width,height] duration-75`}
+ style={{
+ background:
+ (brushSettings.hardness ?? 1.0) < 0.98
+ ? `radial-gradient(circle, rgba(239, 68, 68, 0.45) 0%, rgba(239, 68, 68, 0.45) ${Math.round(
+ (brushSettings.hardness ?? 1.0) * 100
+ )}%, rgba(239, 68, 68, 0.05) 100%)`
+ : 'rgba(239, 68, 68, 0.38)',
+ }}
+ />
+
+ {/* Inner hardness boundary indicator if soft brush */}
+ {(brushSettings.hardness ?? 1.0) < 0.98 && (
+ <div
+ className={`absolute ${isSquare ? 'rounded-none' : 'rounded-full'} border border-dashed border-white/80 pointer-events-none`}
+ style={{
+ width: `${Math.max(2, cursorWidth * (brushSettings.hardness ?? 1.0))}px`,
+ height: `${Math.max(2, cursorHeight * (brushSettings.hardness ?? 1.0))}px`,
+ }}
+ />
+ )}
+ </>
+ )}
+
+ {/* Floating HUD Tooltip Card */}
+ <div
+ className="absolute top-full mt-3 bg-[#202020] text-[#e5e5e5] px-3 py-1.5 rounded-md shadow-[0_8px_24px_rgba(0,0,0,0.65)] flex flex-col items-center pointer-events-none whitespace-nowrap min-w-36"
+ style={{ zIndex: 60 }}
+ >
+ <div className="flex items-center gap-2 text-[11px] font-mono font-medium text-[#e5e5e5]">
+ <span>Size {brushSettings.size}px</span>
+ <span className="text-[#8a8a8a]">·</span>
+ <span>Hard {Math.round((brushSettings.hardness ?? 1.0) * 100)}%</span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Floating Quick Palette Popover (triggered by modifier mapped to 'quick-palette') */}
+ {quickPalettePos && (
+ <div
+ onPointerDown={(e) => e.stopPropagation()}
+ onContextMenu={(e) => e.preventDefault()}
+ className="absolute z-50 bg-[#202020] border border-white/10 rounded-md shadow-[0_12px_32px_rgba(0,0,0,0.75)] p-2.5 w-48 space-y-2 text-[11px] text-[#e5e5e5] select-none"
+ style={{ left: `${quickPalettePos.x}px`, top: `${quickPalettePos.y}px` }}
+ >
+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a] uppercase tracking-wider">
+ <span>Quick Palette</span>
+ <button
+ type="button"
+ onClick={() => setQuickPalettePos(null)}
+ className="hover:text-[#e5e5e5] cursor-pointer px-1"
+ >
+ ×
+ </button>
+ </div>
+ <div className="grid grid-cols-6 gap-1">
+ {useToolStore.getState().recentColors.slice(0, 12).map((hex) => (
+ <button
+ key={hex}
+ type="button"
+ onClick={() => {
+ toolStoreActions.setPrimaryColor(hex);
+ setQuickPalettePos(null);
+ }}
+ className="w-6 h-6 rounded border border-white/15 cursor-pointer"
+ style={{ backgroundColor: hex }}
+ title={hex}
+ />
+ ))}
+ </div>
+ <div className="space-y-1">
+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a]">
+ <span>Size</span>
+ <span className="font-mono text-[#e5e5e5]">{brushSettings.size}px</span>
+ </div>
+ <input
+ type="range"
+ min="1"
+ max="300"
+ value={Math.round(brushSettings.size)}
+ onChange={(e) => onUpdateBrushSettings({ size: Number(e.target.value) })}
+ className="w-full"
+ />
+ </div>
+ <div className="grid grid-cols-3 gap-1 pt-0.5">
+ <button
+ type="button"
+ onClick={() => {
+ onUndo?.();
+ setQuickPalettePos(null);
+ }}
+ className="px-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Undo
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ onRedo?.();
+ setQuickPalettePos(null);
+ }}
+ className="px-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Redo
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ onFlipHorizontal?.();
+ setQuickPalettePos(null);
+ }}
+ className="px-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Flip H
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Floating Webtoon Mode Controls (only shown when Webtoon Mode is active) */}
+ {isWebtoonMode && (
+ <div className="absolute top-3 right-3 z-40 flex items-center gap-1.5 select-none">
+ <button
+ onClick={onToggleWebtoonMode}
+ className="px-2.5 py-1 rounded-full text-[11px] font-medium flex items-center gap-1.5 bg-[#202020] hover:bg-[#2c2c2c] text-[#e5e5e5] shadow-lg transition-colors cursor-pointer"
+ title="Exit Webtoon Studio Mode"
+ >
+ <Smartphone className="w-3.5 h-3.5 text-[var(--accent)]" />
+ <span>Exit Webtoon</span>
+ </button>
+
+ {onOpenWebtoonExport && (
+ <button
+ onClick={onOpenWebtoonExport}
+ className="px-2.5 py-1 rounded-full text-[11px] font-medium bg-[#202020] hover:bg-[#2c2c2c] text-[#e5e5e5] flex items-center gap-1.5 shadow-lg transition-colors cursor-pointer"
+ title="Export Chapter Slices (.zip)"
+ >
+ <Archive className="w-3.5 h-3.5 text-[#8a8a8a]" />
+ <span>Export Slices</span>
+ </button>
+ )}
+ </div>
+ )}
+
+ {/* Subtle Zero-Height Canvas Coordinate / Pressure Readout (only shown if bottom StatusBar is hidden) */}
+ {false && (showCursorCoordinates || showPressureInStatusBar) && (
+ <div
+ ref={pointerStatRef}
+ className="pointer-events-none absolute bottom-2 right-3 z-30 text-[10px] font-mono text-[#8a8a8a]/70 select-none"
+ />
+ )}
+
+ {/* Smartphone Viewport Simulator in Webtoon Mode */}
+ {isWebtoonMode && (
+ <SmartphoneViewportSimulator
+ visible={true}
+ onToggleVisible={onToggleWebtoonMode || (() => {})}
+ />
+ )}
+
+ {/* 2D Frame-by-Frame Animation Timeline Scrubber Dock */}
+ {animationTimeline && onUpdateAnimationTimeline && (
+ <AnimationTimeline
+ timeline={animationTimeline}
+ onChangeTimeline={onUpdateAnimationTimeline}
+ layers={layers}
+ tileGrid={tileGrid}
+ dimensions={dimensions}
+ onAddCel={onAddAnimationCel || (() => {})}
+ onDeleteCel={onDeleteAnimationCel || (() => {})}
+ onSelectCelLayer={onSelectCelLayer}
+ />
+ )}
+
+ {isExternalFileDropActive && (
+ <div
+ data-testid="canvas-file-drop-overlay"
+ className="pointer-events-none absolute inset-2 z-50 rounded-md border-2 border-dashed border-[var(--accent)] bg-[var(--accent)]/8 flex items-center justify-center"
+ >
+ <div className="px-3.5 py-2 rounded-md bg-[#161616]/95 border border-[var(--accent)]/60 text-xs font-medium text-[#f5f5f5] shadow-xl">
+ Drop image to import as layer
+ </div>
+ </div>
+ )}
+ </>
+ );
+};
diff --git a/src/components/canvasArea/types.ts b/src/components/canvasArea/types.ts
new file mode 100644
index 0000000..79140f5
--- /dev/null
+++ b/src/components/canvasArea/types.ts
@@ -0,0 +1,263 @@
+import React from 'react';
+import {
+ CanvasDimensions,
+ BrushSettings,
+ LayerItem,
+ CanvasSelection,
+ TransformSession,
+ TextSettings,
+ ToolType,
+ LiquifySettings,
+ SpeechBalloon,
+ SoftProofSettings,
+ CanvasColorMode,
+ ShapeDragPreview,
+ AnimationTimeline as AnimationTimelineType,
+} from '../../types/editor';
+import { ROTATE_CURSOR_CSS, CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
+import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../types/perspective';
+import { SparseTileGrid } from '../../utils/tileEngine';
+import { ModifierAction } from '../../types/settings';
+
+export const PIPETTE_CURSOR_CSS = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cg stroke='%23000000' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3Cg stroke='%23ffffff' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3C/svg%3E") 2 22, crosshair`;
+
+export interface CanvasAreaProps {
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ dimensions: CanvasDimensions;
+ brushSettings: BrushSettings;
+ onUpdateBrushSettings: (newSettings: Partial<BrushSettings>) => void;
+ zoom: number;
+ pan: { x: number; y: number };
+ rotation: number;
+ flipX?: boolean;
+ flipY?: boolean;
+ navigation?: CanvasNavigationHandle;
+ isSpaceDown: boolean;
+ isShiftDown: boolean;
+ isRotateModifier: boolean;
+ isPanning: boolean;
+ isRotating: boolean;
+ isZoomDragging?: boolean;
+ onStartPan: (e: React.PointerEvent) => void;
+ onStartRotate: (e: React.PointerEvent) => void;
+ onStartZoomDrag?: (e: React.PointerEvent) => void;
+ onSampleColor?: (pt: { x: number; y: number }) => void;
+ onUndo?: () => void;
+ onRedo?: () => void;
+ onFlipHorizontal?: () => void;
+ isHovering: boolean;
+ cursorPos: { x: number; y: number } | null;
+ onPointerDown: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[]) => void;
+ onPointerMove: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[], predicted?: PointerEvent[]) => void;
+ onPointerUp: (e: React.PointerEvent<HTMLElement>) => void;
+ predictedCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ onPointerEnter: () => void;
+ onPointerLeave: () => void;
+ layers: LayerItem[];
+ getEffectiveOpacity: (layer: LayerItem) => number;
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
+ interactionRef: React.RefObject<HTMLDivElement | null>;
+ showCheckerboard?: boolean;
+ hasOpenDocument?: boolean;
+ draftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ strokeCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ peers?: import('../../types/multiplayer').CollabPeer[];
+ activePings?: Array<{ id: string; x: number; y: number; color: string; name: string }>;
+ remoteDraftCanvasesRef?: React.MutableRefObject<Map<string | number, HTMLCanvasElement>>;
+ tool?: ToolType;
+ selection?: CanvasSelection | null;
+ onDeselect?: () => void;
+ onTransformSelection?: () => void;
+ onFillScreentone?: () => void;
+ onFillColor?: () => void;
+ onClearSelection?: () => void;
+ onInvertSelection?: () => void;
+ onExpandSelection?: (pixels: number) => void;
+ onContractSelection?: (pixels: number) => void;
+ onFeatherSelection?: (radius: number) => void;
+ transformSession?: TransformSession | null;
+ onUpdateTransformSession?: (updater: (prev: TransformSession) => TransformSession) => void;
+ onApplyTransform?: () => void;
+ onCancelTransform?: () => void;
+ textSession?: { x: number; y: number; settings: TextSettings } | null;
+ onUpdateTextSettings?: (updater: (prev: TextSettings) => TextSettings) => void;
+ onMoveTextSession?: (x: number, y: number) => void;
+ onConfirmText?: () => void;
+ onCancelText?: () => void;
+ perspectiveRuler?: PerspectiveRuler | null;
+ onUpdatePerspectiveRuler?: (ruler: PerspectiveRuler | null) => void;
+ straightRuler?: StraightRuler | null;
+ onUpdateStraightRuler?: (ruler: StraightRuler | null) => void;
+ activeLockedAxis?: ConstraintAxis | null;
+ isDrawing?: boolean;
+ is3DLayerOpen?: boolean;
+ initial3DFile?: File | null;
+ onClose3DLayer?: () => void;
+ onInsertRasterLayer?: (layer: LayerItem, canvas: HTMLCanvasElement) => void;
+ onBake3DSuccess?: (layer: LayerItem) => void;
+ liquifySettings?: LiquifySettings;
+ onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;
+ primaryColor?: string;
+ onSwapColors?: () => void;
+ showCursorCoordinates?: boolean;
+ showPressureInStatusBar?: boolean;
+ isWebtoonMode?: boolean;
+ onToggleWebtoonMode?: () => void;
+ onOpenWebtoonExport?: () => void;
+ activeBalloon?: SpeechBalloon | null;
+ onUpdateBalloon?: (updater: (prev: SpeechBalloon) => SpeechBalloon) => void;
+ onConfirmBalloon?: () => void;
+ onDeleteBalloon?: () => void;
+ frameDragPreview?: { mode: 'create' | 'divide'; start: { x: number; y: number }; end: { x: number; y: number } } | null;
+ shapeDragPreview?: ShapeDragPreview | null;
+ secondaryColor?: string;
+ animationTimeline?: AnimationTimelineType | null;
+ onUpdateAnimationTimeline?: (timeline: AnimationTimelineType) => void;
+ onAddAnimationCel?: (frameIndex: number) => void;
+ onDeleteAnimationCel?: (frameIndex: number) => void;
+ onSelectCelLayer?: (layerId: string) => void;
+ softProofSettings?: SoftProofSettings;
+ onViewportReady?: (viewport: HTMLDivElement) => void;
+ activeLayerId?: string;
+ colorMode?: CanvasColorMode;
+ tileGrid?: SparseTileGrid;
+ isExternalFileDropActive?: boolean;
+}
+
+export interface CursorConfig {
+ activeToolSize: number;
+ tipAspect: number;
+ thicknessRatio: number;
+ thicknessVertical: boolean;
+ tipAngleDeg: number;
+ rotation: number;
+ flipX: boolean;
+ flipY: boolean;
+}
+
+export interface CursorStyleParams {
+ isOverCanvas: boolean;
+ isResizingBrush: boolean;
+ heldModifierAction: ModifierAction;
+ isZoomDragging: boolean;
+ isRotating: boolean;
+ isRotateModifier: boolean;
+ isPanning: boolean;
+ isSpaceDown: boolean;
+ tool: ToolType;
+}
+
+export function extractCoalescedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {
+ const native = e.nativeEvent;
+ if (!native) return [];
+ // Per W3C Pointer Events spec, pointerdown represents a single contact event;
+ // some Windows/WebView2 stylus drivers emit stale or DPI-offset coalesced packets on pointerdown.
+ if (native.type === 'pointerdown') {
+ return [native];
+ }
+ if (typeof native.getCoalescedEvents === 'function') {
+ try {
+ const coalesced = native.getCoalescedEvents();
+ if (coalesced && coalesced.length > 0) {
+ const last = coalesced[coalesced.length - 1];
+ // Guard against Chromium/WebView2 Windows Ink DPI coordinate-space mismatch where
+ // getCoalescedEvents() diverges from the dispatching PointerEvent's clientX/clientY.
+ if (
+ last &&
+ Number.isFinite(last.clientX) &&
+ Number.isFinite(last.clientY) &&
+ Math.hypot(last.clientX - native.clientX, last.clientY - native.clientY) <= 1.5
+ ) {
+ return coalesced as unknown as PointerEvent[];
+ }
+ }
+ } catch {}
+ }
+ return [native];
+}
+
+export function extractPredictedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {
+ const native = e.nativeEvent;
+ if (native && typeof native.getPredictedEvents === 'function') {
+ try {
+ const predicted = native.getPredictedEvents();
+ if (predicted && predicted.length > 0) {
+ return predicted as unknown as PointerEvent[];
+ }
+ } catch {}
+ }
+ return [];
+}
+
+export function formatArtboardTransform(
+ pan: { x: number; y: number },
+ zoom: number,
+ rotation: number,
+ flipX: boolean,
+ flipY: boolean,
+ dimensions: CanvasDimensions
+): string {
+ const sx = (flipX ? -1 : 1) * zoom;
+ const sy = (flipY ? -1 : 1) * zoom;
+ return `translate3d(${pan.x}px, ${pan.y}px, 0) rotate(${rotation}deg) scale(${sx}, ${sy}) translate3d(${-dimensions.width / 2}px, ${-dimensions.height / 2}px, 0)`;
+}
+
+export function formatCursorRingTransform(
+ x: number,
+ y: number,
+ rotation: number,
+ flipX: boolean,
+ flipY: boolean,
+ tipAngleDeg: number
+): string {
+ const fx = flipX ? -1 : 1;
+ const fy = flipY ? -1 : 1;
+ return `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%) rotate(${rotation}deg) scale(${fx}, ${fy}) rotate(${tipAngleDeg}deg)`;
+}
+
+export function getCursorStyle({
+ isOverCanvas,
+ isResizingBrush,
+ heldModifierAction,
+ isZoomDragging,
+ isRotating,
+ isRotateModifier,
+ isPanning,
+ isSpaceDown,
+ tool,
+}: CursorStyleParams): React.CSSProperties {
+ if (isResizingBrush || heldModifierAction === 'brush-size') {
+ return { cursor: 'ew-resize' };
+ }
+ if (isZoomDragging || heldModifierAction === 'zoom-drag') {
+ return { cursor: 'zoom-in' };
+ }
+ if (isRotating || isRotateModifier || heldModifierAction === 'rotate') {
+ return { cursor: ROTATE_CURSOR_CSS };
+ }
+ if (isPanning) {
+ return { cursor: 'grabbing' };
+ }
+ if (isSpaceDown || heldModifierAction === 'pan') {
+ return { cursor: 'grab' };
+ }
+ if (tool === 'pipette' || heldModifierAction === 'eyedropper') {
+ return { cursor: PIPETTE_CURSOR_CSS };
+ }
+ if (tool === 'text') {
+ return { cursor: 'text' };
+ }
+ if (tool === 'select-rect' || tool === 'select-lasso' || tool === 'select-wand' || tool === 'fill' || tool === 'frame' || tool === 'shape') {
+ return { cursor: 'crosshair' };
+ }
+ if (tool === 'liquify') {
+ return { cursor: isOverCanvas ? 'none' : 'default' };
+ }
+ if (tool === 'transform') {
+ return { cursor: 'default' };
+ }
+ if (tool === 'brush' || tool === 'eraser' || tool === 'select-pen' || tool === 'select-eraser') {
+ return { cursor: isOverCanvas ? 'none' : 'default' };
+ }
+ return { cursor: isOverCanvas ? 'crosshair' : 'default' };
+}
diff --git a/src/components/canvasArea/useCanvasEffects.ts b/src/components/canvasArea/useCanvasEffects.ts
new file mode 100644
index 0000000..b27256b
--- /dev/null
+++ b/src/components/canvasArea/useCanvasEffects.ts
@@ -0,0 +1,413 @@
+import React, { useEffect, useRef, useState } from 'react';
+import { BrushSettings, LiquifySettings, ToolType } from '../../types/editor';
+import { ModifierAction } from '../../types/settings';
+import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../../utils/brushOutline';
+import { preloadTipImage } from '../../utils/brushStorage';
+import { resolveHeldKeyModifierAction } from '../../utils/shortcutManager';
+import { useUiStore } from '../../stores';
+import { CursorConfig, formatCursorRingTransform } from './types';
+
+export interface UseCanvasEffectsParams {
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ brushSettings: BrushSettings;
+ onUpdateBrushSettings: (newSettings: Partial<BrushSettings>) => void;
+ liquifySettings?: LiquifySettings;
+ onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;
+ tool: ToolType;
+ liveZoom: number;
+ liveRotation: number;
+ liveFlipX: boolean;
+ liveFlipY: boolean;
+ isSpaceDown: boolean;
+ isPanning: boolean;
+ isRotating: boolean;
+ isZoomDragging: boolean;
+ isRotateModifier: boolean;
+ hasOpenDocument: boolean;
+ showCursorCoordinates: boolean;
+ showPressureInStatusBar: boolean;
+ heldModifierAction: ModifierAction;
+ setHeldModifierAction: React.Dispatch<React.SetStateAction<ModifierAction>>;
+ isResizingBrush: boolean;
+ setIsResizingBrush: React.Dispatch<React.SetStateAction<boolean>>;
+ quickPalettePos: { x: number; y: number } | null;
+ setQuickPalettePos: React.Dispatch<React.SetStateAction<{ x: number; y: number } | null>>;
+ resizeOriginRef: React.MutableRefObject<{ clientX: number; clientY: number }>;
+ resizeStartSettingsRef: React.MutableRefObject<{ size: number; hardness: number }>;
+}
+
+export function useCanvasEffects({
+ viewportRef,
+ brushSettings,
+ onUpdateBrushSettings,
+ liquifySettings,
+ onUpdateLiquifySettings,
+ tool,
+ liveZoom,
+ liveRotation,
+ liveFlipX,
+ liveFlipY,
+ isSpaceDown,
+ isPanning,
+ isRotating,
+ isZoomDragging,
+ isRotateModifier,
+ hasOpenDocument,
+ showCursorCoordinates,
+ showPressureInStatusBar,
+ heldModifierAction,
+ setHeldModifierAction,
+ isResizingBrush,
+ setIsResizingBrush,
+ quickPalettePos,
+ setQuickPalettePos,
+ resizeOriginRef,
+ resizeStartSettingsRef,
+}: UseCanvasEffectsParams) {
+ // Resolve tip image and extract vector outline silhouette
+ const activeTipImage = resolveBrushTipImage(brushSettings);
+ const [tipOutline, setTipOutline] = useState<TipOutline | null>(() => {
+ return activeTipImage ? getBrushTipOutline(activeTipImage) : null;
+ });
+
+ useEffect(() => {
+ let isCancelled = false;
+
+ if (activeTipImage) {
+ if (activeTipImage.complete && activeTipImage.naturalWidth > 0) {
+ setTipOutline(getBrushTipOutline(activeTipImage));
+ } else {
+ const handleLoad = () => {
+ if (!isCancelled) {
+ setTipOutline(getBrushTipOutline(activeTipImage));
+ }
+ };
+ activeTipImage.addEventListener('load', handleLoad, { once: true });
+ }
+ return () => {
+ isCancelled = true;
+ };
+ }
+
+ if (brushSettings.customTipDataUrl) {
+ preloadTipImage(brushSettings.customTipDataUrl)
+ .then((img) => {
+ if (!isCancelled) {
+ setTipOutline(getBrushTipOutline(img));
+ }
+ })
+ .catch(() => {
+ if (!isCancelled) {
+ setTipOutline(null);
+ }
+ });
+ return () => {
+ isCancelled = true;
+ };
+ }
+
+ setTipOutline(null);
+ }, [activeTipImage, brushSettings.customTipDataUrl, brushSettings.preset]);
+
+ const isCustomTip = Boolean(tipOutline && (tool === 'brush' || tool === 'eraser'));
+ const isSquare = brushSettings.preset === 'square-digital' && !tipOutline;
+ const tipAspect = isCustomTip && tipOutline ? tipOutline.height / tipOutline.width : 1.0;
+
+ const activeToolSize = tool === 'liquify' && liquifySettings ? liquifySettings.size : brushSettings.size;
+ const cursorBaseWidth = Math.max(4, activeToolSize * liveZoom);
+ const thicknessRatio = tool === 'brush' ? (brushSettings.thickness ?? 1.0) : 1.0;
+ const thicknessVertical = Boolean(brushSettings.thicknessVertical && tool === 'brush');
+ const tipAngleDeg = tool === 'brush' ? (brushSettings.customTipAngle ?? 0) : 0;
+
+ const cursorWidth = thicknessVertical
+ ? Math.max(2, cursorBaseWidth * thicknessRatio)
+ : cursorBaseWidth;
+ const cursorHeight = thicknessVertical
+ ? Math.max(2, cursorBaseWidth * tipAspect)
+ : Math.max(2, cursorBaseWidth * tipAspect * thicknessRatio);
+
+ // Brush tip rotation: tip angle relative to canvas + viewport canvas rotation
+ const totalAngleDeg = tipAngleDeg + liveRotation;
+ const cursorConfigRef = useRef<CursorConfig>({
+ activeToolSize,
+ tipAspect,
+ thicknessRatio,
+ thicknessVertical,
+ tipAngleDeg,
+ rotation: liveRotation,
+ flipX: liveFlipX,
+ flipY: liveFlipY,
+ });
+ cursorConfigRef.current = {
+ activeToolSize,
+ tipAspect,
+ thicknessRatio,
+ thicknessVertical,
+ tipAngleDeg,
+ rotation: liveRotation,
+ flipX: liveFlipX,
+ flipY: liveFlipY,
+ };
+ const lastPointerPosRef = useRef<{ x: number; y: number } | null>(null);
+
+ // Zero-latency direct DOM cursor preview element & pointer stat readout
+ const cursorRingRef = useRef<HTMLDivElement | null>(null);
+ const pointerStatRef = useRef<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ if (!showCursorCoordinates && !showPressureInStatusBar) return;
+ let rafId = 0;
+ const handlePointerStat = (e: Event) => {
+ const detail = (e as CustomEvent).detail;
+ cancelAnimationFrame(rafId);
+ rafId = requestAnimationFrame(() => {
+ const el = pointerStatRef.current;
+ if (!el || !detail) return;
+ const parts: string[] = [];
+ if (showCursorCoordinates && detail.x !== null && detail.x !== undefined) {
+ parts.push(`${detail.x}, ${detail.y}`);
+ }
+ if (showPressureInStatusBar && detail.pressure > 0) {
+ parts.push(`${Math.round(detail.pressure * 100)}%`);
+ }
+ el.textContent = parts.join(' · ');
+ });
+ };
+ window.addEventListener('canvas-pointer-stat', handlePointerStat);
+ return () => {
+ window.removeEventListener('canvas-pointer-stat', handlePointerStat);
+ cancelAnimationFrame(rafId);
+ };
+ }, [showCursorCoordinates, showPressureInStatusBar]);
+
+ // Update cursor rotation/flip in-place when viewport rotates/flips or brush tip angle changes while hovering
+ useEffect(() => {
+ const ring = cursorRingRef.current;
+ const pos = lastPointerPosRef.current;
+ if (ring && pos && ring.style.display !== 'none') {
+ const cfg = cursorConfigRef.current;
+ ring.style.transform = formatCursorRingTransform(
+ pos.x,
+ pos.y,
+ cfg.rotation,
+ cfg.flipX,
+ cfg.flipY,
+ cfg.tipAngleDeg
+ );
+ }
+ }, [tipAngleDeg, liveRotation, liveFlipX, liveFlipY]);
+
+ useEffect(() => {
+ const viewport = viewportRef.current;
+ if (!viewport) return;
+
+ let cachedRect: DOMRect | null = viewport.getBoundingClientRect();
+ const updateRect = () => {
+ if (viewport) cachedRect = viewport.getBoundingClientRect();
+ };
+
+ window.addEventListener('resize', updateRect);
+ window.addEventListener('scroll', updateRect, true);
+ const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updateRect) : null;
+ ro?.observe(viewport);
+
+ const updateCursorRingPos = (e: PointerEvent, forceRefreshRect: boolean = false) => {
+ const ring = cursorRingRef.current;
+ if (!ring) return;
+
+ if (
+ isSpaceDown ||
+ isPanning ||
+ isRotating ||
+ isZoomDragging ||
+ isRotateModifier ||
+ isResizingBrush ||
+ heldModifierAction === 'brush-size' ||
+ heldModifierAction === 'pan' ||
+ heldModifierAction === 'rotate' ||
+ heldModifierAction === 'zoom-drag' ||
+ (tool !== 'brush' && tool !== 'eraser' && tool !== 'liquify' && tool !== 'select-pen' && tool !== 'select-eraser')
+ ) {
+ ring.style.display = 'none';
+ return;
+ }
+
+ if (forceRefreshRect || !cachedRect) updateRect();
+ if (!cachedRect) return;
+
+ const x = e.clientX - cachedRect.left;
+ const y = e.clientY - cachedRect.top;
+
+ if (x < 0 || x > cachedRect.width || y < 0 || y > cachedRect.height) {
+ ring.style.display = 'none';
+ return;
+ }
+
+ lastPointerPosRef.current = { x, y };
+ const cfg = cursorConfigRef.current;
+ ring.style.transform = formatCursorRingTransform(
+ x,
+ y,
+ cfg.rotation,
+ cfg.flipX,
+ cfg.flipY,
+ cfg.tipAngleDeg
+ );
+ if (ring.style.display !== 'block') {
+ ring.style.display = 'block';
+ }
+ };
+
+ const handleWindowPointerMove = (e: PointerEvent) => {
+ updateCursorRingPos(e, false);
+ };
+
+ const handleViewportPointerEnterOrDown = (e: PointerEvent) => {
+ updateCursorRingPos(e, true);
+ };
+
+ const handlePointerLeave = () => {
+ lastPointerPosRef.current = null;
+ if (cursorRingRef.current) {
+ cursorRingRef.current.style.display = 'none';
+ }
+ };
+
+ viewport.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
+ viewport.addEventListener('pointerdown', handleViewportPointerEnterOrDown, { passive: true });
+ viewport.addEventListener('pointerenter', handleViewportPointerEnterOrDown, { passive: true });
+ viewport.addEventListener('pointerleave', handlePointerLeave, { passive: true });
+
+ return () => {
+ window.removeEventListener('resize', updateRect);
+ window.removeEventListener('scroll', updateRect, true);
+ ro?.disconnect();
+ viewport.removeEventListener('pointermove', handleWindowPointerMove);
+ viewport.removeEventListener('pointerdown', handleViewportPointerEnterOrDown);
+ viewport.removeEventListener('pointerenter', handleViewportPointerEnterOrDown);
+ viewport.removeEventListener('pointerleave', handlePointerLeave);
+ };
+ }, [isSpaceDown, isPanning, isRotating, isZoomDragging, isRotateModifier, isResizingBrush, heldModifierAction, viewportRef, tool, hasOpenDocument]);
+
+ // Track held modifier key combinations globally according to Modifier Key Settings
+ useEffect(() => {
+ const syncHeldAction = (e: KeyboardEvent, spaceOverride?: boolean) => {
+ const action = resolveHeldKeyModifierAction(
+ {
+ ctrl: e.ctrlKey || e.metaKey,
+ shift: e.shiftKey,
+ alt: e.altKey,
+ space: spaceOverride !== undefined ? spaceOverride : isSpaceDown,
+ },
+ useUiStore.getState().appSettings.modifierKeys
+ );
+ setHeldModifierAction(action);
+ };
+
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape' && quickPalettePos) {
+ setQuickPalettePos(null);
+ }
+ syncHeldAction(e, e.code === 'Space' ? true : undefined);
+ };
+
+ const handleKeyUp = (e: KeyboardEvent) => {
+ syncHeldAction(e, e.code === 'Space' ? false : undefined);
+ };
+
+ const handleBlur = () => {
+ setHeldModifierAction('none');
+ setIsResizingBrush(false);
+ setQuickPalettePos(null);
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+ window.addEventListener('keyup', handleKeyUp);
+ window.addEventListener('blur', handleBlur);
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown);
+ window.removeEventListener('keyup', handleKeyUp);
+ window.removeEventListener('blur', handleBlur);
+ };
+ }, [isSpaceDown, quickPalettePos]);
+
+ // Handle active brush resizing window drag listeners
+ useEffect(() => {
+ if (!isResizingBrush) return;
+
+ let rafId: number | null = null;
+ let pendingSize = resizeStartSettingsRef.current.size;
+ let pendingHardness = resizeStartSettingsRef.current.hardness;
+
+ const commitResize = () => {
+ rafId = null;
+ if (tool === 'liquify' && onUpdateLiquifySettings) {
+ onUpdateLiquifySettings({ size: Math.round(pendingSize) });
+ } else {
+ onUpdateBrushSettings({ size: pendingSize, hardness: pendingHardness });
+ }
+ };
+
+ const handleWindowPointerMove = (e: PointerEvent) => {
+ const dx = e.clientX - resizeOriginRef.current.clientX;
+ const dy = resizeOriginRef.current.clientY - e.clientY;
+
+ // Exponential + linear hybrid sensitivity for 0.5px..1000px precision (CSP-style)
+ const baseSize = Math.max(0.5, resizeStartSettingsRef.current.size);
+ const rawSize = baseSize * Math.exp(dx * 0.006) + dx * 0.15;
+ const clampedSize = Math.max(0.5, Math.min(1000, rawSize));
+ pendingSize = clampedSize < 10 ? Math.round(clampedSize * 10) / 10 : Math.round(clampedSize);
+
+ pendingHardness = Math.max(
+ 0.05,
+ Math.min(
+ 1.0,
+ Math.round((resizeStartSettingsRef.current.hardness + dy * 0.004) * 100) / 100
+ )
+ );
+
+ if (rafId === null) {
+ rafId = requestAnimationFrame(commitResize);
+ }
+ };
+
+ const handleWindowPointerUp = () => {
+ if (rafId !== null) {
+ cancelAnimationFrame(rafId);
+ commitResize();
+ }
+ setIsResizingBrush(false);
+ };
+
+ window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
+ window.addEventListener('pointerup', handleWindowPointerUp);
+ window.addEventListener('pointercancel', handleWindowPointerUp);
+
+ const prevCursor = document.body.style.cursor;
+ const prevUserSelect = document.body.style.userSelect;
+ document.body.style.cursor = 'ew-resize';
+ document.body.style.userSelect = 'none';
+
+ return () => {
+ if (rafId !== null) cancelAnimationFrame(rafId);
+ window.removeEventListener('pointermove', handleWindowPointerMove);
+ window.removeEventListener('pointerup', handleWindowPointerUp);
+ window.removeEventListener('pointercancel', handleWindowPointerUp);
+ document.body.style.cursor = prevCursor;
+ document.body.style.userSelect = prevUserSelect;
+ };
+ }, [isResizingBrush, onUpdateBrushSettings, onUpdateLiquifySettings, tool]);
+
+ return {
+ tipOutline,
+ isCustomTip,
+ isSquare,
+ cursorWidth,
+ cursorHeight,
+ totalAngleDeg,
+ cursorConfigRef,
+ lastPointerPosRef,
+ cursorRingRef,
+ pointerStatRef,
+ };
+}
diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.ts
new file mode 100644
index 0000000..3d00e58
--- /dev/null
+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts
@@ -0,0 +1,345 @@
+import React, { useRef } from 'react';
+import {
+ BrushSettings,
+ CanvasDimensions,
+ LiquifySettings,
+ ToolType,
+} from '../../types/editor';
+import { ModifierAction } from '../../types/settings';
+import { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
+import { screenToCanvas } from '../../utils/canvasUtils';
+import { resolvePointerModifierAction } from '../../utils/shortcutManager';
+import { isNativePenStreamActive } from '../../utils/nativeTabletInput';
+import { toolStoreActions, useToolStore, useUiStore } from '../../stores';
+import { extractCoalescedEvents, extractPredictedEvents } from './types';
+
+export interface UseCanvasPointerHandlersParams {
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ dimensions: CanvasDimensions;
+ brushSettings: BrushSettings;
+ liquifySettings?: LiquifySettings;
+ tool: ToolType;
+ navigation?: CanvasNavigationHandle;
+ pan: { x: number; y: number };
+ zoom: number;
+ rotation: number;
+ flipX: boolean;
+ flipY: boolean;
+ isSpaceDown: boolean;
+ quickPalettePos: { x: number; y: number } | null;
+ setQuickPalettePos: React.Dispatch<React.SetStateAction<{ x: number; y: number } | null>>;
+ setIsResizingBrush: React.Dispatch<React.SetStateAction<boolean>>;
+ resizeOriginRef: React.MutableRefObject<{ clientX: number; clientY: number }>;
+ resizeStartSettingsRef: React.MutableRefObject<{ size: number; hardness: number }>;
+ onStartPan: (e: React.PointerEvent) => void;
+ onStartRotate: (e: React.PointerEvent) => void;
+ onStartZoomDrag?: (e: React.PointerEvent) => void;
+ onSampleColor?: (pt: { x: number; y: number }) => void;
+ onUndo?: () => void;
+ onSwapColors?: () => void;
+ onPointerDown: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[]) => void;
+ onPointerMove: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[], predicted?: PointerEvent[]) => void;
+ onPointerUp: (e: React.PointerEvent<HTMLElement>) => void;
+}
+
+export function useCanvasPointerHandlers({
+ viewportRef,
+ dimensions,
+ brushSettings,
+ liquifySettings,
+ tool,
+ navigation,
+ pan,
+ zoom,
+ rotation,
+ flipX,
+ flipY,
+ isSpaceDown,
+ quickPalettePos,
+ setQuickPalettePos,
+ setIsResizingBrush,
+ resizeOriginRef,
+ resizeStartSettingsRef,
+ onStartPan,
+ onStartRotate,
+ onStartZoomDrag,
+ onSampleColor,
+ onUndo,
+ onSwapColors,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+}: UseCanvasPointerHandlersParams) {
+ const tempEraserPrevToolRef = useRef<ToolType | null>(null);
+
+ const releaseExternalFocus = () => {
+ const active = document.activeElement as HTMLElement | null;
+ if (!active || active === document.body) return;
+ if (viewportRef.current?.contains(active)) return;
+ const tag = active.tagName;
+ if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || tag === 'BUTTON') {
+ active.blur();
+ }
+ };
+
+ // Start brush resizing drag
+ const startBrushResize = (e: React.PointerEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsResizingBrush(true);
+ resizeOriginRef.current = { clientX: e.clientX, clientY: e.clientY };
+ resizeStartSettingsRef.current = {
+ size: tool === 'liquify' && liquifySettings ? liquifySettings.size : brushSettings.size,
+ hardness: brushSettings.hardness ?? 1.0,
+ };
+ };
+
+ // Start continuous eyedropper sampling for modifier buttons (e.g. Right Click / Barrel Button)
+ const startModifierEyedropper = (e: React.PointerEvent) => {
+ if (!onSampleColor || !viewportRef.current) return;
+ e.preventDefault();
+ e.stopPropagation();
+
+ const sampleAtClient = (clientX: number, clientY: number) => {
+ const vp = viewportRef.current;
+ if (!vp) return;
+ const rect = vp.getBoundingClientRect();
+ const cam = navigation
+ ? navigation.getCameraState()
+ : { pan, zoom, rotation, flipX, flipY };
+ const pt = screenToCanvas(
+ clientX,
+ clientY,
+ rect,
+ cam.pan,
+ cam.zoom,
+ cam.rotation,
+ dimensions,
+ cam.flipX,
+ cam.flipY
+ );
+ onSampleColor(pt);
+ };
+
+ sampleAtClient(e.clientX, e.clientY);
+
+ const handleMove = (ev: PointerEvent) => {
+ sampleAtClient(ev.clientX, ev.clientY);
+ };
+ const handleUp = () => {
+ window.removeEventListener('pointermove', handleMove);
+ window.removeEventListener('pointerup', handleUp);
+ window.removeEventListener('pointercancel', handleUp);
+ };
+ window.addEventListener('pointermove', handleMove, { passive: true });
+ window.addEventListener('pointerup', handleUp);
+ window.addEventListener('pointercancel', handleUp);
+ };
+
+ // Open floating Quick Palette near cursor when mapped to 'quick-palette'
+ const openQuickPaletteAt = (e: React.PointerEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const vp = viewportRef.current;
+ if (!vp) return;
+ const rect = vp.getBoundingClientRect();
+ const x = Math.max(12, Math.min(rect.width - 210, e.clientX - rect.left));
+ const y = Math.max(12, Math.min(rect.height - 150, e.clientY - rect.top));
+ setQuickPalettePos({ x, y });
+ };
+
+ // Dispatch a resolved ModifierAction; returns true if the event was consumed
+ const dispatchModifierAction = (
+ action: ModifierAction,
+ e: React.PointerEvent<HTMLElement>,
+ allowDrawingPassThrough: boolean
+ ): boolean => {
+ switch (action) {
+ case 'pan':
+ onStartPan(e);
+ return true;
+ case 'rotate':
+ onStartRotate(e);
+ return true;
+ case 'zoom-drag':
+ if (onStartZoomDrag) {
+ onStartZoomDrag(e);
+ return true;
+ }
+ return false;
+ case 'brush-size':
+ startBrushResize(e);
+ return true;
+ case 'eyedropper':
+ if (e.button !== 0 || !allowDrawingPassThrough) {
+ startModifierEyedropper(e);
+ return true;
+ }
+ // When button 0 + Alt is held, GlobalShortcutListener already switched tool to pipette,
+ // or if not, sample directly via startModifierEyedropper
+ if (tool !== 'pipette') {
+ startModifierEyedropper(e);
+ return true;
+ }
+ return false;
+ case 'temp-eraser': {
+ if (!allowDrawingPassThrough) return false;
+ const cur = useToolStore.getState().tool;
+ if (cur !== 'eraser') {
+ tempEraserPrevToolRef.current = cur;
+ toolStoreActions.selectTool('eraser');
+ }
+ return false; // let stroke begin on eraser
+ }
+ case 'undo':
+ e.preventDefault();
+ e.stopPropagation();
+ onUndo?.();
+ return true;
+ case 'swap-colors':
+ e.preventDefault();
+ e.stopPropagation();
+ onSwapColors?.();
+ return true;
+ case 'quick-palette':
+ openQuickPaletteAt(e);
+ return true;
+ case 'straight-line':
+ case 'none':
+ default:
+ return false;
+ }
+ };
+
+ // Viewport background pointer down (clicking gray area to pan, rotate, zoom, resize, or quick palette)
+ const handleViewportPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
+ releaseExternalFocus();
+ if (quickPalettePos) setQuickPalettePos(null);
+
+ const modSettings = useUiStore.getState().appSettings.modifierKeys;
+ const resolved = resolvePointerModifierAction(
+ {
+ button: e.button,
+ pointerType: e.pointerType,
+ ctrlKey: e.ctrlKey,
+ metaKey: e.metaKey,
+ shiftKey: e.shiftKey,
+ altKey: e.altKey,
+ isSpaceDown,
+ },
+ modSettings
+ );
+ if (resolved && dispatchModifierAction(resolved.action, e, false)) {
+ return;
+ }
+ };
+
+ // Canvas pointer down: resolve Modifier Key Settings first, otherwise dispatch drawing/tool stroke
+ const handleCanvasPointerDown = (e: React.PointerEvent<HTMLElement>) => {
+ releaseExternalFocus();
+ if (quickPalettePos) setQuickPalettePos(null);
+
+ const modSettings = useUiStore.getState().appSettings.modifierKeys;
+ const resolved = resolvePointerModifierAction(
+ {
+ button: e.button,
+ pointerType: e.pointerType,
+ ctrlKey: e.ctrlKey,
+ metaKey: e.metaKey,
+ shiftKey: e.shiftKey,
+ altKey: e.altKey,
+ isSpaceDown,
+ },
+ modSettings
+ );
+
+ if (resolved) {
+ if (dispatchModifierAction(resolved.action, e, true)) {
+ return;
+ }
+ }
+
+ if (e.button === 0) {
+ e.preventDefault();
+ } else {
+ return;
+ }
+
+ // Native WinTab / Windows Ink channel owns pen brush/eraser strokes; skip duplicate DOM PointerEvent.
+ if (
+ e.pointerType === 'pen' &&
+ isNativePenStreamActive() &&
+ (tool === 'brush' || tool === 'eraser')
+ ) {
+ return;
+ }
+
+ const coalesced = extractCoalescedEvents(e);
+ (e as any).coalescedEvents = coalesced;
+ if (e.nativeEvent) {
+ (e.nativeEvent as any).coalescedEvents = coalesced;
+ }
+ onPointerDown(e, coalesced);
+ };
+
+ const handleCanvasPointerMove = (e: React.PointerEvent<HTMLElement>) => {
+ if (
+ e.pointerType === 'pen' &&
+ isNativePenStreamActive() &&
+ (tool === 'brush' || tool === 'eraser')
+ ) {
+ return;
+ }
+ const coalesced = extractCoalescedEvents(e);
+ const predicted = extractPredictedEvents(e);
+ (e as any).coalescedEvents = coalesced;
+ (e as any).predictedEvents = predicted;
+ if (e.nativeEvent) {
+ (e.nativeEvent as any).coalescedEvents = coalesced;
+ (e.nativeEvent as any).predictedEvents = predicted;
+ }
+ onPointerMove(e, coalesced, predicted);
+ };
+
+ const handleCanvasPointerUp = (e: React.PointerEvent<HTMLElement>) => {
+ if (
+ !(
+ e.pointerType === 'pen' &&
+ isNativePenStreamActive() &&
+ (tool === 'brush' || tool === 'eraser')
+ )
+ ) {
+ onPointerUp(e);
+ }
+ if (tempEraserPrevToolRef.current !== null) {
+ const prev = tempEraserPrevToolRef.current;
+ tempEraserPrevToolRef.current = null;
+ toolStoreActions.selectTool(prev);
+ }
+ };
+
+ const handleCanvasPointerCancel = (e: React.PointerEvent<HTMLElement>) => {
+ handleCanvasPointerUp(e);
+ };
+
+ const handleContextMenu = (e: React.MouseEvent<HTMLElement>) => {
+ const modSettings = useUiStore.getState().appSettings.modifierKeys;
+ if (modSettings.rightClick !== 'none' || modSettings.stylusButton1 !== 'none') {
+ e.preventDefault();
+ }
+ };
+
+ return {
+ releaseExternalFocus,
+ startBrushResize,
+ startModifierEyedropper,
+ openQuickPaletteAt,
+ dispatchModifierAction,
+ handleViewportPointerDown,
+ handleCanvasPointerDown,
+ handleCanvasPointerMove,
+ handleCanvasPointerUp,
+ handleCanvasPointerCancel,
+ handleContextMenu,
+ };
+}
diff --git a/src/components/canvasArea/useCompositorViewport.ts b/src/components/canvasArea/useCompositorViewport.ts
new file mode 100644
index 0000000..65e96bd
--- /dev/null
+++ b/src/components/canvasArea/useCompositorViewport.ts
@@ -0,0 +1,451 @@
+import React, { useEffect, useMemo, useRef } from 'react';
+import {
+ AnimationTimeline as AnimationTimelineType,
+ CanvasColorMode,
+ CanvasDimensions,
+ LayerItem,
+ SoftProofSettings,
+} from '../../types/editor';
+import { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
+import { ViewportCompositor } from '../../utils/compositor';
+import { SparseTileGrid } from '../../utils/tileEngine';
+import { getOnionSkinFrames } from '../../utils/animationEngine';
+import {
+ CursorConfig,
+ formatArtboardTransform,
+ formatCursorRingTransform,
+} from './types';
+
+export interface UseCompositorViewportParams {
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ onViewportReady?: (viewport: HTMLDivElement) => void;
+ artboardRef: React.RefObject<HTMLDivElement | null>;
+ cursorRingRef: React.RefObject<HTMLDivElement | null>;
+ cursorConfigRef: React.MutableRefObject<CursorConfig>;
+ lastPointerPosRef: React.MutableRefObject<{ x: number; y: number } | null>;
+ effectiveDraftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ effectivePredictedCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ navigation?: CanvasNavigationHandle;
+ layers: LayerItem[];
+ animationTimeline: AnimationTimelineType | null;
+ pan: { x: number; y: number };
+ zoom: number;
+ rotation: number;
+ flipX: boolean;
+ flipY: boolean;
+ livePan: { x: number; y: number };
+ liveZoom: number;
+ liveRotation: number;
+ liveFlipX: boolean;
+ liveFlipY: boolean;
+ dimensions: CanvasDimensions;
+ showCheckerboard: boolean;
+ hasOpenDocument: boolean;
+ softProofSettings?: SoftProofSettings;
+ activeLayerId?: string;
+ brushOpacity?: number;
+ colorMode: CanvasColorMode;
+ tileGrid: SparseTileGrid;
+}
+
+export function useCompositorViewport({
+ viewportRef,
+ onViewportReady,
+ artboardRef,
+ cursorRingRef,
+ cursorConfigRef,
+ lastPointerPosRef,
+ effectiveDraftCanvasRef,
+ effectivePredictedCanvasRef,
+ navigation,
+ layers,
+ animationTimeline,
+ pan,
+ zoom,
+ rotation,
+ flipX,
+ flipY,
+ livePan,
+ liveZoom,
+ liveRotation,
+ liveFlipX,
+ liveFlipY,
+ dimensions,
+ showCheckerboard,
+ hasOpenDocument,
+ softProofSettings,
+ activeLayerId,
+ brushOpacity,
+ colorMode,
+ tileGrid,
+}: UseCompositorViewportParams) {
+ const tileGridRef = useRef<SparseTileGrid>(tileGrid);
+ tileGridRef.current = tileGrid;
+
+ // Compute colored onion skin frames and active cel isolation for animation
+ const onionSkinFrames = useMemo(() => {
+ if (!animationTimeline || !animationTimeline.onionSkin?.enabled) return [];
+ return getOnionSkinFrames(animationTimeline);
+ }, [animationTimeline]);
+
+ const effectiveLayers = useMemo(() => {
+ if (!animationTimeline) return layers;
+ const currentCelId = animationTimeline.cels[animationTimeline.currentFrame];
+ const allCelIds = new Set(Object.values(animationTimeline.cels));
+ return layers.map((layer) => {
+ if (allCelIds.has(layer.id)) {
+ return {
+ ...layer,
+ visible: layer.id === currentCelId && layer.visible,
+ };
+ }
+ return layer;
+ });
+ }, [layers, animationTimeline]);
+
+ // Unified GPU Viewport Compositor
+ const viewportCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const compositorRef = useRef<ViewportCompositor | null>(null);
+ const viewportCssSizeRef = useRef<{ width: number; height: number } | null>(null);
+ const renderParamsRef = useRef({
+ effectiveLayers,
+ pan: livePan,
+ zoom: liveZoom,
+ rotation: liveRotation,
+ flipX: liveFlipX,
+ flipY: liveFlipY,
+ dimensions,
+ showCheckerboard,
+ onionSkinFrames,
+ softProofSettings,
+ activeLayerId,
+ brushOpacity: brushOpacity ?? 1.0,
+ effectiveDraftCanvasRef,
+ });
+ renderParamsRef.current = {
+ effectiveLayers,
+ pan: livePan,
+ zoom: liveZoom,
+ rotation: liveRotation,
+ flipX: liveFlipX,
+ flipY: liveFlipY,
+ dimensions,
+ showCheckerboard,
+ onionSkinFrames,
+ softProofSettings,
+ activeLayerId,
+ brushOpacity: brushOpacity ?? 1.0,
+ effectiveDraftCanvasRef,
+ };
+
+ const buildCompositorOptions = (rp: typeof renderParamsRef.current, dpr: number) => {
+ const vCanvas = viewportCanvasRef.current;
+ const cssSize = viewportCssSizeRef.current;
+ if (vCanvas && compositorRef.current && cssSize && cssSize.width > 0 && cssSize.height > 0) {
+ const expectedW = Math.max(1, Math.round(cssSize.width * dpr));
+ const expectedH = Math.max(1, Math.round(cssSize.height * dpr));
+ if (vCanvas.width !== expectedW || vCanvas.height !== expectedH) {
+ compositorRef.current.resize(expectedW, expectedH);
+ const predCanvas = rp.effectiveDraftCanvasRef ? effectivePredictedCanvasRef?.current : null;
+ if (predCanvas && (predCanvas.width !== expectedW || predCanvas.height !== expectedH)) {
+ predCanvas.width = expectedW;
+ predCanvas.height = expectedH;
+ }
+ }
+ }
+ const draftCanvas = rp.effectiveDraftCanvasRef?.current ?? null;
+ const draftVersion = draftCanvas ? ((draftCanvas as any).__draftVersion ?? 0) : 0;
+ const draftSpace = ((draftCanvas as any)?.__draftSpace as 'document' | 'viewport' | undefined) ?? 'viewport';
+ const draftDocRect = (draftCanvas as any)?.__draftDocRect ?? null;
+ const draftMonochrome = Boolean((draftCanvas as any)?.__draftMonochrome);
+ return {
+ dimensions: rp.dimensions,
+ showCheckerboard: rp.showCheckerboard,
+ devicePixelRatio: dpr,
+ onionSkinFrames: rp.onionSkinFrames,
+ softProof: rp.softProofSettings,
+ activeLayerId: rp.activeLayerId ?? null,
+ activeDraftLayerId: rp.activeLayerId ?? null,
+ activeDraftCanvas: draftCanvas,
+ activeDraftDirtyRect: draftSpace === 'document' ? draftDocRect : null,
+ activeDraftVersion: draftVersion,
+ activeDraftSpace: draftSpace,
+ activeDraftOpacity: rp.brushOpacity,
+ activeDraftMonochrome: draftMonochrome,
+ };
+ };
+
+ // Direct zero-React-rerender camera subscription for smooth 60-240Hz pan, zoom, rotation, and view flip
+ useEffect(() => {
+ if (!navigation) return;
+ return navigation.subscribeCamera((cam) => {
+ const rp = renderParamsRef.current;
+ rp.pan = cam.pan;
+ rp.zoom = cam.zoom;
+ rp.rotation = cam.rotation;
+ rp.flipX = cam.flipX;
+ rp.flipY = cam.flipY;
+
+ const cfg = cursorConfigRef.current;
+ cfg.rotation = cam.rotation;
+ cfg.flipX = cam.flipX;
+ cfg.flipY = cam.flipY;
+
+ const artboard = artboardRef.current;
+ if (artboard) {
+ artboard.style.transform = formatArtboardTransform(
+ cam.pan,
+ cam.zoom,
+ cam.rotation,
+ cam.flipX,
+ cam.flipY,
+ rp.dimensions
+ );
+ }
+
+ const ring = cursorRingRef.current;
+ if (ring) {
+ const baseW = Math.max(4, cfg.activeToolSize * cam.zoom);
+ const cW = cfg.thicknessVertical
+ ? Math.max(2, baseW * cfg.thicknessRatio)
+ : baseW;
+ const cH = cfg.thicknessVertical
+ ? Math.max(2, baseW * cfg.tipAspect)
+ : Math.max(2, baseW * cfg.tipAspect * cfg.thicknessRatio);
+ ring.style.width = `${cW}px`;
+ ring.style.height = `${cH}px`;
+ const pos = lastPointerPosRef.current;
+ if (pos && ring.style.display !== 'none') {
+ ring.style.transform = formatCursorRingTransform(
+ pos.x,
+ pos.y,
+ cam.rotation,
+ cam.flipX,
+ cam.flipY,
+ cfg.tipAngleDeg
+ );
+ }
+ }
+
+ if (viewportCanvasRef.current && !compositorRef.current) {
+ compositorRef.current = new ViewportCompositor(viewportCanvasRef.current);
+ }
+ if (compositorRef.current) {
+ const dpr = window.devicePixelRatio || 1;
+ compositorRef.current.render(
+ rp.effectiveLayers,
+ {
+ pan: cam.pan,
+ zoom: cam.zoom,
+ rotation: cam.rotation,
+ flipX: cam.flipX,
+ flipY: cam.flipY,
+ },
+ rp.dimensions,
+ tileGridRef.current,
+ buildCompositorOptions(rp, dpr)
+ );
+ }
+ });
+ }, [navigation]);
+
+ // Synchronize viewport and draft overlay canvas resolution with the screen viewport
+ useEffect(() => {
+ let dprMql: MediaQueryList | null = null;
+
+ const updateCanvasSizes = () => {
+ const viewport = viewportRef.current;
+ if (!viewport) return;
+ const rect = viewport.getBoundingClientRect();
+ if (rect.width > 0 && rect.height > 0) {
+ viewportCssSizeRef.current = { width: rect.width, height: rect.height };
+ }
+ const dpr = window.devicePixelRatio || 1;
+ const w = Math.max(1, Math.round(rect.width * dpr));
+ const h = Math.max(1, Math.round(rect.height * dpr));
+
+ const draftCanvas = effectiveDraftCanvasRef?.current;
+ if (
+ draftCanvas &&
+ (draftCanvas as any).__draftSpace !== 'document' &&
+ (draftCanvas.width !== w || draftCanvas.height !== h)
+ ) {
+ draftCanvas.width = w;
+ draftCanvas.height = h;
+ (draftCanvas as any).__draftHasContent = false;
+ (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
+ }
+
+ const predCanvas = effectivePredictedCanvasRef?.current;
+ if (predCanvas && (predCanvas.width !== w || predCanvas.height !== h)) {
+ predCanvas.width = w;
+ predCanvas.height = h;
+ }
+
+ const vCanvas = viewportCanvasRef.current;
+ if (vCanvas) {
+ if (compositorRef.current && compositorRef.current.getCanvas() !== vCanvas) {
+ compositorRef.current.dispose();
+ compositorRef.current = null;
+ }
+ const sizeChanged = vCanvas.width !== w || vCanvas.height !== h;
+ if (sizeChanged || !compositorRef.current) {
+ if (!compositorRef.current) {
+ vCanvas.width = w;
+ vCanvas.height = h;
+ compositorRef.current = new ViewportCompositor(vCanvas);
+ } else {
+ compositorRef.current.resize(w, h);
+ }
+ const rp = renderParamsRef.current;
+ compositorRef.current.render(
+ rp.effectiveLayers,
+ {
+ pan: rp.pan,
+ zoom: rp.zoom,
+ rotation: rp.rotation,
+ flipX: rp.flipX,
+ flipY: rp.flipY,
+ },
+ rp.dimensions,
+ tileGridRef.current,
+ buildCompositorOptions(rp, dpr)
+ );
+ }
+ }
+ };
+
+ const handleDprChange = () => {
+ updateCanvasSizes();
+ attachDprListener();
+ };
+
+ const attachDprListener = () => {
+ if (dprMql) {
+ dprMql.removeEventListener?.('change', handleDprChange);
+ dprMql = null;
+ }
+ if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
+ const curDpr = window.devicePixelRatio || 1;
+ dprMql = window.matchMedia(`(resolution: ${curDpr}dppx)`);
+ dprMql.addEventListener?.('change', handleDprChange);
+ }
+ };
+
+ updateCanvasSizes();
+ attachDprListener();
+ window.addEventListener('resize', updateCanvasSizes);
+ const ro = typeof ResizeObserver !== 'undefined' && viewportRef.current
+ ? new ResizeObserver(updateCanvasSizes)
+ : null;
+ if (ro && viewportRef.current) {
+ ro.observe(viewportRef.current);
+ }
+ return () => {
+ window.removeEventListener('resize', updateCanvasSizes);
+ dprMql?.removeEventListener?.('change', handleDprChange);
+ ro?.disconnect();
+ };
+ }, [viewportRef, effectiveDraftCanvasRef, effectivePredictedCanvasRef, hasOpenDocument]);
+
+ useEffect(() => {
+ if (viewportRef.current) {
+ onViewportReady?.(viewportRef.current);
+ const raf = requestAnimationFrame(() => {
+ if (viewportRef.current) {
+ onViewportReady?.(viewportRef.current);
+ }
+ });
+ return () => cancelAnimationFrame(raf);
+ }
+ }, [onViewportReady, viewportRef]);
+
+ // Render scene using Unified GPU Viewport Compositor
+ useEffect(() => {
+ const vCanvas = viewportCanvasRef.current;
+ if (!vCanvas) return;
+ if (compositorRef.current && compositorRef.current.getCanvas() !== vCanvas) {
+ compositorRef.current.dispose();
+ compositorRef.current = null;
+ }
+ if (!compositorRef.current) {
+ compositorRef.current = new ViewportCompositor(vCanvas);
+ }
+
+ const dpr = window.devicePixelRatio || 1;
+ const rp = renderParamsRef.current;
+ compositorRef.current.render(
+ effectiveLayers,
+ {
+ pan: rp.pan,
+ zoom: rp.zoom,
+ rotation: rp.rotation,
+ flipX: rp.flipX,
+ flipY: rp.flipY,
+ },
+ dimensions,
+ tileGrid,
+ buildCompositorOptions(rp, dpr)
+ );
+ }, [effectiveLayers, layers, pan, zoom, rotation, flipX, flipY, dimensions, showCheckerboard, onionSkinFrames, softProofSettings, activeLayerId, brushOpacity, colorMode, tileGrid]);
+
+ // Event-Driven Compositor Invalidation via active document's SparseTileGrid subscription
+ useEffect(() => {
+ let rafId: number | null = null;
+ const activeGrid = tileGrid;
+ const renderCompositor = () => {
+ if (compositorRef.current) {
+ const dpr = window.devicePixelRatio || 1;
+ const rp = renderParamsRef.current;
+ compositorRef.current.render(
+ rp.effectiveLayers,
+ {
+ pan: rp.pan,
+ zoom: rp.zoom,
+ rotation: rp.rotation,
+ flipX: rp.flipX,
+ flipY: rp.flipY,
+ },
+ rp.dimensions,
+ activeGrid,
+ buildCompositorOptions(rp, dpr)
+ );
+ }
+ };
+
+ const handleGridChange = (immediate?: boolean) => {
+ if (immediate) {
+ if (rafId !== null) {
+ cancelAnimationFrame(rafId);
+ rafId = null;
+ }
+ renderCompositor();
+ return;
+ }
+ if (rafId !== null) return;
+ rafId = requestAnimationFrame(() => {
+ rafId = null;
+ renderCompositor();
+ });
+ };
+
+ const unsubscribe = activeGrid.subscribe(handleGridChange);
+ return () => {
+ unsubscribe();
+ if (rafId !== null) cancelAnimationFrame(rafId);
+ };
+ }, [tileGrid]);
+
+ useEffect(() => {
+ return () => {
+ if (compositorRef.current) {
+ compositorRef.current.dispose();
+ compositorRef.current = null;
+ }
+ };
+ }, []);
+
+ return {
+ viewportCanvasRef,
+ };
+}
diff --git a/src/engine/BrushEngine.ts b/src/engine/BrushEngine.ts
new file mode 100644
index 0000000..5afd505
--- /dev/null
+++ b/src/engine/BrushEngine.ts
@@ -0,0 +1,2437 @@
+/**
+ * BrushEngine.ts
+ * Unified Brush & Stroke Engine (CSP Mathematics + Paper Grain + WebGL Dispatch + Single CPU Fallback).
+ *
+ * Consolidates all brush rendering (textured tips, analytical radial tips, pencil presets,
+ * color mixing, spray, multi-sensor dynamics, post-correction, and watercolor edge) into one
+ * deterministic pipeline: WebGL instanced GPU path first, with a single Canvas2D CPU fallback.
+ */
+
+import {
+ Point,
+ BrushSettings,
+ BrushDynamics,
+ ToolType,
+ CanvasColorMode,
+ CspSensorConfig,
+ CspPaperTextureMode,
+ CspTipFlipMode,
+ CspAngleDynamicsMode,
+ CspBlendTipsMode,
+ CspSpraySettings,
+ CspTaperSettings,
+ CspSubTip,
+} from '../types/editor';
+import { enforceColorMode } from '../utils/colorUtils';
+import {
+ PaintReservoir,
+ LayerPixelSampler,
+ sampleCanvasColor,
+ parseColorToRgb,
+ rgbToHex,
+} from '../utils/colorMixingEngine';
+import { GpuDab, WebGlBrushEngine } from './WebGlBrushEngine';
+
+// ============================================================================
+// 1. Types & Unified Brush Render Options
+// ============================================================================
+
+export interface BrushRenderOptions {
+ size?: number;
+ minSizeFactor?: number;
+ opacity?: number;
+ flow?: number;
+ brushDensity?: number;
+ adjustDensityByGap?: boolean;
+ blendTipsMode?: CspBlendTipsMode;
+ spacing?: number;
+ thickness?: number;
+ thicknessVertical?: boolean;
+ flipH?: CspTipFlipMode;
+ flipV?: CspTipFlipMode;
+ angle?: number; // degrees
+ angleDynamics?: CspAngleDynamicsMode;
+ rotationRandomScale?: number;
+ hardness?: number;
+ antiAlias?: number;
+ tipImage?: HTMLImageElement;
+ isColorTip?: boolean;
+ pressureCurve?: [number, number][];
+ velocityCurve?: [number, number][];
+ usePressure?: boolean;
+ useTilt?: boolean;
+ tiltScale?: number;
+ useVelocity?: boolean;
+ sizeSensor?: CspSensorConfig;
+ opacitySensor?: CspSensorConfig;
+ densitySensor?: CspSensorConfig;
+ subTips?: CspSubTip[];
+ subTipOrder?: 'random' | 'sequential' | 'direction' | 'reverse';
+ subTipImages?: HTMLImageElement[];
+ spray?: CspSpraySettings;
+ taper?: CspTaperSettings;
+ colorMixing?: boolean;
+ perceptualMixing?: boolean;
+ amountOfPaint?: number;
+ densityOfPaint?: number;
+ colorStretch?: number;
+ mixingMode?: 'blend' | 'running_color' | 'smear';
+ wetEdge?: number;
+ wetEdgeRadius?: number;
+ wetEdgeAlphaPower?: number;
+ wetEdgeValuePower?: number;
+ grain?: number;
+ textureDensity?: number;
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureBrightness?: number;
+ paperTextureContrast?: number;
+ paperTextureInverted?: boolean;
+ paperTextureImage?: HTMLImageElement;
+ paperTextureScale?: number;
+ paperTextureRotate?: number;
+ dualBrush?: boolean;
+ dualTipImage?: HTMLImageElement;
+ dualBrushCompositeMode?: string;
+ useGpu?: boolean;
+ underlyingCanvas?: HTMLCanvasElement;
+ sampler?: LayerPixelSampler;
+ reservoir?: PaintReservoir;
+ isEraser?: boolean;
+ isBgEraser?: boolean;
+ alphaLocked?: boolean;
+ isTransparentInk?: boolean;
+ strokeIndex?: number;
+ totalLength?: number;
+ currentStrokeDist?: number;
+ dynamics?: BrushDynamics;
+ secondaryColor?: string;
+}
+
+export interface EvaluatedBezierSample {
+ x: number;
+ y: number;
+ width: number;
+ pressure: number;
+ dx: number;
+ dy: number;
+ speed: number;
+ tiltX: number;
+ tiltY: number;
+ twist: number;
+}
+
+export interface ArcLengthTable {
+ totalLength: number;
+ distances: number[];
+}
+
+// ============================================================================
+// 2. Legacy Pencil Preset Mapping (No Separate Pencil Engine)
+// ============================================================================
+
+export type LegacyPencilGrade = 'pencil-f' | 'pencil-hb' | 'pencil-2b' | 'pencil-4b';
+
+export const LEGACY_PENCIL_PRESETS: Record<LegacyPencilGrade, Partial<BrushSettings>> = {
+ 'pencil-f': {
+ size: 2.5,
+ minSizeFactor: 0.35,
+ hardness: 0.85,
+ flow: 0.55,
+ spacing: 0.08,
+ grain: 0.55,
+ textureDensity: 0.55,
+ useTilt: true,
+ tiltScale: 1.15,
+ paperTextureMode: 'compare',
+ opacitySensor: { usePressure: true, pressureMin: 0.25 },
+ },
+ 'pencil-hb': {
+ size: 3.2,
+ minSizeFactor: 0.25,
+ hardness: 0.75,
+ flow: 0.65,
+ spacing: 0.07,
+ grain: 0.65,
+ textureDensity: 0.65,
+ useTilt: true,
+ tiltScale: 1.25,
+ paperTextureMode: 'compare',
+ opacitySensor: { usePressure: true, pressureMin: 0.2 },
+ },
+ 'pencil-2b': {
+ size: 4.5,
+ minSizeFactor: 0.2,
+ hardness: 0.65,
+ flow: 0.74,
+ spacing: 0.06,
+ grain: 0.75,
+ textureDensity: 0.75,
+ useTilt: true,
+ tiltScale: 1.4,
+ paperTextureMode: 'compare',
+ opacitySensor: { usePressure: true, pressureMin: 0.18 },
+ },
+ 'pencil-4b': {
+ size: 6.5,
+ minSizeFactor: 0.15,
+ hardness: 0.5,
+ flow: 0.88,
+ spacing: 0.05,
+ grain: 0.85,
+ textureDensity: 0.85,
+ useTilt: true,
+ tiltScale: 1.6,
+ paperTextureMode: 'compare',
+ opacitySensor: { usePressure: true, pressureMin: 0.15 },
+ },
+};
+
+export function getLegacyPencilPresetDefaults(preset?: string): Partial<BrushSettings> | null {
+ if (!preset) return null;
+ return (LEGACY_PENCIL_PRESETS as Record<string, Partial<BrushSettings>>)[preset] ?? null;
+}
+
+/**
+ * Resolves legacy pencil-* presets into standard grain + tilt brush settings.
+ * Returns the original object untouched for all modern presets.
+ */
+export function resolveBrushPresetSettings(bs: BrushSettings): BrushSettings {
+ if (bs.customTipImage || !bs.preset) return bs;
+ const legacy = getLegacyPencilPresetDefaults(bs.preset);
+ if (!legacy) return bs;
+ return {
+ ...legacy,
+ ...bs,
+ grain: bs.grain ?? legacy.grain,
+ textureDensity: bs.textureDensity ?? bs.grain ?? legacy.textureDensity,
+ useTilt: bs.useTilt ?? true,
+ tiltScale: bs.tiltScale ?? legacy.tiltScale,
+ paperTextureMode: bs.paperTextureMode ?? legacy.paperTextureMode,
+ opacitySensor: bs.opacitySensor ?? legacy.opacitySensor,
+ };
+}
+
+// ============================================================================
+// 3. Seamless 512x512 Procedural Cold-Press Paper Grain
+// ============================================================================
+
+export const GRAIN_SIZE = 512;
+const GRAIN_MASK = GRAIN_SIZE - 1;
+export const paperGrainTable = new Uint8Array(GRAIN_SIZE * GRAIN_SIZE);
+
+function sfc32(a: number, b: number, c: number, d: number) {
+ return function () {
+ a |= 0;
+ b |= 0;
+ c |= 0;
+ d |= 0;
+ const t = (((a + b) | 0) + d) | 0;
+ d = (d + 1) | 0;
+ a = b ^ (b >>> 9);
+ b = (c + (c << 3)) | 0;
+ c = (c << 21) | (c >>> 11);
+ c = (c + t) | 0;
+ return (t >>> 0) / 4294967296;
+ };
+}
+
+(function initPaperGrain() {
+ const rand = sfc32(0x9e3779b9, 0x243f6a88, 0xb7e15162, 0x8aed2a6b);
+ const makeGrid = (res: number) => {
+ const g = new Float32Array(res * res);
+ for (let i = 0; i < g.length; i++) g[i] = rand();
+ return g;
+ };
+ const samplePeriodic = (grid: Float32Array, res: number, fx: number, fy: number): number => {
+ const mask = res - 1;
+ const x0 = Math.floor(fx);
+ const y0 = Math.floor(fy);
+ const tx = fx - x0;
+ const ty = fy - y0;
+ const sx = tx * tx * (3 - 2 * tx);
+ const sy = ty * ty * (3 - 2 * ty);
+ const ix0 = x0 & mask;
+ const iy0 = y0 & mask;
+ const ix1 = (ix0 + 1) & mask;
+ const iy1 = (iy0 + 1) & mask;
+ const v00 = grid[iy0 * res + ix0];
+ const v10 = grid[iy0 * res + ix1];
+ const v01 = grid[iy1 * res + ix0];
+ const v11 = grid[iy1 * res + ix1];
+ const top = v00 + (v10 - v00) * sx;
+ const bot = v01 + (v11 - v01) * sx;
+ return top + (bot - top) * sy;
+ };
+
+ const gCoarse = makeGrid(64);
+ const gMedium = makeGrid(128);
+ const gFine = makeGrid(256);
+ const gMicro = makeGrid(512);
+
+ for (let y = 0; y < GRAIN_SIZE; y++) {
+ const row = y * GRAIN_SIZE;
+ for (let x = 0; x < GRAIN_SIZE; x++) {
+ const warpX = x + Math.sin(y * 0.09817477) * 1.4;
+ const warpY = y + Math.cos(x * 0.09817477) * 1.4;
+ const nCoarse = samplePeriodic(gCoarse, 64, x * 0.125, y * 0.125);
+ const nMedium = samplePeriodic(gMedium, 128, warpX * 0.25, warpY * 0.25);
+ const nFine = samplePeriodic(gFine, 256, warpX * 0.5, warpY * 0.5);
+ const nMicro = gMicro[row + x];
+ const combined = nCoarse * 0.28 + nMedium * 0.36 + nFine * 0.24 + nMicro * 0.12;
+ const stretched = Math.max(0, Math.min(1, (combined - 0.18) / 0.64));
+ const curved = Math.pow(stretched, 1.18);
+ paperGrainTable[row + x] = Math.min(255, Math.max(0, Math.round(curved * 255)));
+ }
+ }
+
+ WebGlBrushEngine.setBuiltinPaperGrain(paperGrainTable, GRAIN_SIZE);
+})();
+
+export function getPaperGrain(x: number, y: number): number {
+ const fx = Math.floor(x);
+ const fy = Math.floor(y);
+ const tx = x - fx;
+ const ty = y - fy;
+
+ const x0 = (fx & GRAIN_MASK) >>> 0;
+ const y0 = (fy & GRAIN_MASK) >>> 0;
+ const x1 = ((fx + 1) & GRAIN_MASK) >>> 0;
+ const y1 = ((fy + 1) & GRAIN_MASK) >>> 0;
+
+ const v00 = paperGrainTable[y0 * GRAIN_SIZE + x0];
+ const v10 = paperGrainTable[y0 * GRAIN_SIZE + x1];
+ const v01 = paperGrainTable[y1 * GRAIN_SIZE + x0];
+ const v11 = paperGrainTable[y1 * GRAIN_SIZE + x1];
+
+ const top = v00 + (v10 - v00) * tx;
+ const bottom = v01 + (v11 - v01) * tx;
+ return Math.round(top + (bottom - top) * ty);
+}
+
+// ============================================================================
+// 4. CSP Mathematics, PCHIP LUTs, Sensors, Post-Correction & Watercolor Edge
+// ============================================================================
+
+const LUT_SIZE = 256;
+const LUT_MAX_IDX = LUT_SIZE - 1;
+const curveWeakCache = new WeakMap<readonly [number, number][], Float32Array>();
+const curveStringCache = new Map<string, Float32Array>();
+const MAX_STRING_CURVE_CACHE = 128;
+
+export function getCompiledCurveLut(curve?: readonly [number, number][]): Float32Array | null {
+ if (!curve || curve.length === 0) return null;
+
+ const weakHit = curveWeakCache.get(curve);
+ if (weakHit) return weakHit;
+
+ let key = '';
+ for (let i = 0; i < curve.length; i++) {
+ key += `${curve[i][0].toFixed(4)},${curve[i][1].toFixed(4)};`;
+ }
+ const strHit = curveStringCache.get(key);
+ if (strHit) {
+ curveWeakCache.set(curve, strHit);
+ return strHit;
+ }
+
+ const lut = new Float32Array(LUT_SIZE);
+ const pts = curve.slice().sort((a, b) => a[0] - b[0]);
+ const dedup: [number, number][] = [pts[0]];
+ for (let i = 1; i < pts.length; i++) {
+ if (pts[i][0] - dedup[dedup.length - 1][0] > 1e-5) {
+ dedup.push(pts[i]);
+ }
+ }
+
+ const n = dedup.length;
+ if (n === 1) {
+ lut.fill(Math.max(0, Math.min(1, dedup[0][1])));
+ } else if (n === 2) {
+ const [x0, y0] = dedup[0];
+ const [x1, y1] = dedup[1];
+ const span = Math.max(1e-5, x1 - x0);
+ for (let s = 0; s < LUT_SIZE; s++) {
+ const x = s / LUT_MAX_IDX;
+ if (x <= x0) lut[s] = Math.max(0, Math.min(1, y0));
+ else if (x >= x1) lut[s] = Math.max(0, Math.min(1, y1));
+ else {
+ const t = (x - x0) / span;
+ lut[s] = Math.max(0, Math.min(1, y0 + t * (y1 - y0)));
+ }
+ }
+ } else {
+ const deltas = new Float64Array(n - 1);
+ const m = new Float64Array(n);
+ for (let k = 0; k < n - 1; k++) {
+ deltas[k] = (dedup[k + 1][1] - dedup[k][1]) / Math.max(1e-5, dedup[k + 1][0] - dedup[k][0]);
+ }
+ m[0] = deltas[0];
+ for (let k = 1; k < n - 1; k++) {
+ m[k] = deltas[k - 1] * deltas[k] <= 0 ? 0 : (deltas[k - 1] + deltas[k]) * 0.5;
+ }
+ m[n - 1] = deltas[n - 2];
+
+ for (let k = 0; k < n - 1; k++) {
+ const dk = deltas[k];
+ if (Math.abs(dk) < 1e-6) {
+ m[k] = 0;
+ m[k + 1] = 0;
+ } else {
+ const alpha = m[k] / dk;
+ const beta = m[k + 1] / dk;
+ const sumSq = alpha * alpha + beta * beta;
+ if (sumSq > 9) {
+ const tau = 3 / Math.sqrt(sumSq);
+ m[k] = tau * alpha * dk;
+ m[k + 1] = tau * beta * dk;
+ }
+ }
+ }
+
+ let segIdx = 0;
+ for (let s = 0; s < LUT_SIZE; s++) {
+ const x = s / LUT_MAX_IDX;
+ if (x <= dedup[0][0]) {
+ lut[s] = Math.max(0, Math.min(1, dedup[0][1]));
+ continue;
+ }
+ if (x >= dedup[n - 1][0]) {
+ lut[s] = Math.max(0, Math.min(1, dedup[n - 1][1]));
+ continue;
+ }
+ while (segIdx < n - 2 && x > dedup[segIdx + 1][0]) segIdx++;
+ const [x0, y0] = dedup[segIdx];
+ const [x1, y1] = dedup[segIdx + 1];
+ const h = Math.max(1e-5, x1 - x0);
+ const t = (x - x0) / h;
+ const t2 = t * t;
+ const t3 = t2 * t;
+ const y =
+ (2 * t3 - 3 * t2 + 1) * y0 +
+ (t3 - 2 * t2 + t) * h * m[segIdx] +
+ (-2 * t3 + 3 * t2) * y1 +
+ (t3 - t2) * h * m[segIdx + 1];
+ lut[s] = Math.max(0, Math.min(1, y));
+ }
+ }
+
+ if (curveStringCache.size >= MAX_STRING_CURVE_CACHE) {
+ const oldest = curveStringCache.keys().next().value;
+ if (oldest !== undefined) curveStringCache.delete(oldest);
+ }
+ curveStringCache.set(key, lut);
+ curveWeakCache.set(curve, lut);
+ return lut;
+}
+
+export function evaluateFastSpline(x: number, curve?: readonly [number, number][]): number {
+ const clamped = x <= 0 ? 0 : x >= 1 ? 1 : x;
+ if (!curve || curve.length === 0) return clamped;
+ const lut = getCompiledCurveLut(curve);
+ if (!lut) return clamped;
+
+ const pos = clamped * LUT_MAX_IDX;
+ const idx = pos | 0;
+ if (idx >= LUT_MAX_IDX) return lut[LUT_MAX_IDX];
+ const frac = pos - idx;
+ return lut[idx] + (lut[idx + 1] - lut[idx]) * frac;
+}
+
+export function dabHashFloat(x: number, y: number, dabIndex: number, salt: number): number {
+ const ix = (x * 100) | 0;
+ const iy = (y * 100) | 0;
+ let h =
+ (Math.imul(ix, 73856093) ^
+ Math.imul(iy, 19349663) ^
+ Math.imul(dabIndex + 1, 83492791) ^
+ Math.imul(salt + 1, 0x9e3779b9)) |
+ 0;
+ h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
+ h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
+}
+
+export function evaluateCspSensor(
+ sensor: CspSensorConfig | undefined,
+ pressure: number,
+ tiltMagnitude: number,
+ speedPxPerMs: number,
+ randomVal: number
+): number {
+ if (!sensor) return 1.0;
+
+ let factor = 1.0;
+ if (sensor.usePressure) {
+ const pMin = Math.max(0, Math.min(1, sensor.pressureMin ?? 0));
+ const curvedP = sensor.pressureCurve
+ ? evaluateFastSpline(pressure, sensor.pressureCurve)
+ : Math.max(0, Math.min(1, pressure));
+ factor *= pMin + (1.0 - pMin) * curvedP;
+ }
+ if (sensor.useTilt) {
+ const tMin = Math.max(0, Math.min(1, sensor.tiltMin ?? 0));
+ factor *= tMin + (1.0 - tMin) * Math.max(0, Math.min(1, tiltMagnitude));
+ }
+ if (sensor.useVelocity) {
+ const vMin = Math.max(0, Math.min(1, sensor.velocityMin ?? 0));
+ const vNorm = Math.max(0, Math.min(1, speedPxPerMs / 3.5));
+ const vVal = sensor.invertVelocity !== false ? 1.0 - vNorm : vNorm;
+ factor *= vMin + (1.0 - vMin) * vVal;
+ }
+ if (sensor.useRandom) {
+ const rMin = Math.max(0, Math.min(1, sensor.randomMin ?? 0));
+ factor *= rMin + (1.0 - rMin) * Math.max(0, Math.min(1, randomVal));
+ }
+ return Math.max(0, Math.min(1, factor));
+}
+
+export function computeEllipticalStepDistance(
+ width: number,
+ height: number,
+ dabAngleRad: number,
+ tangentDx: number,
+ tangentDy: number,
+ spacingRatio: number,
+ minStepPx: number = 0.12
+): number {
+ const ratio = Math.max(0.01, Math.min(2.0, spacingRatio));
+ const w = Math.max(0.1, width);
+ const h = Math.max(0.1, height);
+
+ if (Math.abs(w - h) < 1e-2) {
+ return Math.max(minStepPx, w * ratio);
+ }
+
+ const tLen = Math.hypot(tangentDx, tangentDy);
+ if (tLen < 1e-4) {
+ return Math.max(minStepPx, Math.min(w, h) * ratio);
+ }
+
+ const ux = tangentDx / tLen;
+ const uy = tangentDy / tLen;
+ const cosA = Math.cos(dabAngleRad);
+ const sinA = Math.sin(dabAngleRad);
+ const localX = ux * cosA + uy * sinA;
+ const localY = -ux * sinA + uy * cosA;
+
+ const denom = Math.hypot(localX / w, localY / h);
+ const effectiveDiameter = denom > 1e-5 ? 1.0 / denom : Math.min(w, h);
+ return Math.max(minStepPx, effectiveDiameter * ratio);
+}
+
+export function computeGapAdjustedAlpha(
+ baseAlpha: number,
+ spacingRatio: number,
+ adjustByGap: boolean = false,
+ referenceSpacing: number = 0.08
+): number {
+ const a = Math.max(0, Math.min(1, baseAlpha));
+ if (!adjustByGap || a >= 0.998 || a <= 0.001) return a;
+ const ratio = Math.max(0.12, Math.min(4.0, spacingRatio / Math.max(0.01, referenceSpacing)));
+ return Math.max(0.002, Math.min(1.0, 1.0 - Math.pow(1.0 - a, ratio)));
+}
+
+export function computeSubpixelDabDimensions(
+ width: number,
+ height: number,
+ alpha: number,
+ minRenderDim: number = 0.75
+): { renderW: number; renderH: number; effAlpha: number } {
+ const renderW = Math.max(minRenderDim, width);
+ const renderH = Math.max(minRenderDim, height);
+ if (width >= minRenderDim && height >= minRenderDim) {
+ return { renderW, renderH, effAlpha: alpha };
+ }
+ const scaleW = width < minRenderDim ? Math.max(0.04, width / renderW) : 1.0;
+ const scaleH = height < minRenderDim ? Math.max(0.04, height / renderH) : 1.0;
+ return {
+ renderW,
+ renderH,
+ effAlpha: Math.max(0.003, Math.min(1.0, alpha * scaleW * scaleH)),
+ };
+}
+
+export function getCspAntiAliasFeather(antiAlias: number = 2): number {
+ switch (antiAlias) {
+ case 0:
+ return 0.0;
+ case 1:
+ return 0.65;
+ case 3:
+ return 1.95;
+ case 2:
+ default:
+ return 1.15;
+ }
+}
+
+export function resolveTipFlipSigns(
+ flipH: CspTipFlipMode | undefined,
+ flipV: CspTipFlipMode | undefined,
+ dabSeq: number,
+ x: number,
+ y: number
+): { signX: number; signY: number } {
+ let signX = 1;
+ let signY = 1;
+ if (flipH === 'alternate') signX = (dabSeq & 1) === 0 ? 1 : -1;
+ else if (flipH === 'random') signX = dabHashFloat(x, y, dabSeq, 71) < 0.5 ? 1 : -1;
+ if (flipV === 'alternate') signY = (dabSeq & 1) === 0 ? 1 : -1;
+ else if (flipV === 'random') signY = dabHashFloat(x, y, dabSeq, 73) < 0.5 ? 1 : -1;
+ return { signX, signY };
+}
+
+export function applyCspPaperTextureAlpha(
+ tipAlpha: number,
+ grainNorm: number,
+ textureDensity: number,
+ pressure: number,
+ mode: CspPaperTextureMode = 'subtract',
+ brightness: number = 0,
+ contrast: number = 0,
+ inverted: boolean = false
+): number {
+ if (textureDensity <= 0.001 || tipAlpha <= 0.001) return tipAlpha;
+
+ let g = inverted ? 1.0 - grainNorm : grainNorm;
+ if (brightness !== 0) g += brightness / 100.0;
+ if (contrast !== 0) {
+ const cFactor = Math.pow((contrast + 100.0) / 100.0, 2);
+ g = (g - 0.5) * cFactor + 0.5;
+ }
+ g = Math.max(0, Math.min(1, g));
+
+ const p = Math.max(0, Math.min(1, pressure));
+ const heavyExcess = Math.max(0, (p - 0.52) / 0.48);
+ const penetration = Math.min(0.92, p * 0.28 + heavyExcess * heavyExcess * 0.64);
+ const effDensity = textureDensity * (1.0 - penetration * 0.85);
+
+ switch (mode) {
+ case 'multiply':
+ return Math.max(0, Math.min(1, tipAlpha * (1.0 - effDensity * (1.0 - g))));
+ case 'subtract': {
+ const sub = (1.0 - g) * effDensity;
+ return Math.max(0, Math.min(1, tipAlpha - sub * (1.0 - penetration * 0.5)));
+ }
+ case 'compare': {
+ const contactHeight = g * (0.22 + 0.78 * tipAlpha);
+ const cutoff = effDensity * 0.68;
+ const edgeLow = cutoff - 0.05;
+ const edgeHigh = cutoff + 0.16;
+ const t = Math.max(0, Math.min(1, (contactHeight - edgeLow) / Math.max(0.01, edgeHigh - edgeLow)));
+ return Math.max(0, Math.min(1, tipAlpha * t * t * (3.0 - 2.0 * t)));
+ }
+ case 'overlay': {
+ const ov = tipAlpha < 0.5 ? 2.0 * tipAlpha * g : 1.0 - 2.0 * (1.0 - tipAlpha) * (1.0 - g);
+ return Math.max(0, Math.min(1, tipAlpha + (ov - tipAlpha) * effDensity));
+ }
+ case 'outline': {
+ const edgeFactor = 4.0 * tipAlpha * (1.0 - tipAlpha);
+ return Math.max(0, Math.min(1, tipAlpha * (1.0 - effDensity * (1.0 - g) * (0.35 + 0.65 * edgeFactor))));
+ }
+ default:
+ return tipAlpha;
+ }
+}
+
+export function applyCspPostCorrection(
+ points: Point[],
+ level: number = 0,
+ preserveSharpCorners: boolean = true
+): Point[] {
+ const passes = Math.max(0, Math.min(5, Math.round(level)));
+ if (passes <= 0 || points.length < 4) return points;
+
+ const current = points.map((p) => ({ ...p }));
+ const next = points.map((p) => ({ ...p }));
+
+ for (let pass = 0; pass < passes; pass++) {
+ const n = current.length;
+ next[0] = { ...current[0] };
+ next[n - 1] = { ...current[n - 1] };
+
+ for (let i = 1; i < n - 1; i++) {
+ const cur = current[i];
+ if (preserveSharpCorners && cur.isCorner) {
+ next[i] = { ...cur };
+ continue;
+ }
+ const prev = current[i - 1];
+ const nxt = current[i + 1];
+
+ if (preserveSharpCorners) {
+ const ax = cur.x - prev.x;
+ const ay = cur.y - prev.y;
+ const bx = nxt.x - cur.x;
+ const by = nxt.y - cur.y;
+ const la = Math.hypot(ax, ay);
+ const lb = Math.hypot(bx, by);
+ if (la > 1.5 && lb > 1.5 && (ax * bx + ay * by) / (la * lb) < 0.35) {
+ next[i] = { ...cur };
+ continue;
+ }
+ }
+
+ next[i] = {
+ ...cur,
+ x: prev.x * 0.25 + cur.x * 0.5 + nxt.x * 0.25,
+ y: prev.y * 0.25 + cur.y * 0.5 + nxt.y * 0.25,
+ width: prev.width * 0.2 + cur.width * 0.6 + nxt.width * 0.2,
+ pressure: prev.pressure * 0.2 + cur.pressure * 0.6 + nxt.pressure * 0.2,
+ };
+ }
+
+ for (let i = 0; i < n; i++) current[i] = next[i];
+ }
+
+ return current;
+}
+
+export function applyCspWatercolorEdge(
+ strokeImageData: { data: Uint8ClampedArray; width: number; height: number },
+ wetEdge: number,
+ radiusPx: number = 2.5,
+ alphaPower: number = 0.65,
+ valuePower: number = 0.55
+): void {
+ if (wetEdge <= 0.01) return;
+ const { data, width, height } = strokeImageData;
+ if (width < 3 || height < 3) return;
+
+ const strength = Math.max(0, Math.min(1, wetEdge));
+ const r = Math.max(1, Math.min(8, Math.round(radiusPx)));
+ const totalPixels = width * height;
+
+ const alphaOrig = new Float32Array(totalPixels);
+ const alphaTemp = new Float32Array(totalPixels);
+ for (let i = 0; i < totalPixels; i++) {
+ alphaOrig[i] = data[i * 4 + 3] / 255.0;
+ }
+
+ const invKernel = 1.0 / (2 * r + 1);
+ for (let y = 0; y < height; y++) {
+ const row = y * width;
+ let sum = alphaOrig[row] * (r + 1);
+ for (let k = 1; k <= r; k++) sum += alphaOrig[row + Math.min(width - 1, k)];
+ for (let x = 0; x < width; x++) {
+ alphaTemp[row + x] = sum * invKernel;
+ sum += alphaOrig[row + Math.min(width - 1, x + r + 1)] - alphaOrig[row + Math.max(0, x - r)];
+ }
+ }
+
+ const aBoost = strength * (0.45 + alphaPower * 1.15);
+ const vDarken = strength * (0.25 + valuePower * 0.55);
+
+ for (let x = 0; x < width; x++) {
+ let sum = alphaTemp[x] * (r + 1);
+ for (let k = 1; k <= r; k++) sum += alphaTemp[Math.min(height - 1, k) * width + x];
+ for (let y = 0; y < height; y++) {
+ const idx = y * width + x;
+ const blurredA = sum * invKernel;
+ const origA = alphaOrig[idx];
+
+ if (origA > 0.015) {
+ const rim = Math.max(0, origA - blurredA) * 2.4;
+ if (rim > 0.01) {
+ const p = idx * 4;
+ const darkScale = Math.max(0.18, 1.0 - rim * vDarken);
+ data[p] = Math.round(data[p] * darkScale);
+ data[p + 1] = Math.round(data[p + 1] * darkScale);
+ data[p + 2] = Math.round(data[p + 2] * darkScale);
+ data[p + 3] = Math.round(Math.min(1.0, origA * (1.0 + rim * aBoost)) * 255);
+ }
+ }
+
+ sum += alphaTemp[Math.min(height - 1, y + r + 1) * width + x] - alphaTemp[Math.max(0, y - r) * width + x];
+ }
+ }
+}
+
+export const CSP_PRESSURE_CURVE_PRESETS: Record<string, { label: string; points: [number, number][] }> = {
+ linear: { label: 'Linear', points: [[0, 0], [1, 1]] },
+ 'g-pen': { label: 'G-Pen S-Curve', points: [[0, 0], [0.2, 0.08], [0.55, 0.52], [0.82, 0.88], [1, 1]] },
+ soft: { label: 'Soft Touch', points: [[0, 0], [0.25, 0.48], [0.65, 0.84], [1, 1]] },
+ firm: { label: 'Firm Nib', points: [[0, 0], [0.35, 0.12], [0.7, 0.48], [1, 1]] },
+ chisel: { label: 'Steep Threshold', points: [[0, 0], [0.15, 0.03], [0.45, 0.72], [1, 1]] },
+};
+
+// ============================================================================
+// 5. Color Dynamics (HSV Jitter)
+// ============================================================================
+
+export function rgbToHsv(r: number, g: number, b: number): [number, number, number] {
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ const d = max - min;
+ let h = 0;
+ const s = max === 0 ? 0 : d / max;
+ const v = max;
+
+ if (max !== min) {
+ if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
+ else if (max === g) h = (b - r) / d + 2;
+ else h = (r - g) / d + 4;
+ h *= 60;
+ }
+ return [h, s, v];
+}
+
+export function hsvToRgb(h: number, s: number, v: number): [number, number, number] {
+ const c = v * s;
+ const hp = (((h % 360) + 360) % 360) / 60;
+ const x = c * (1 - Math.abs((hp % 2) - 1));
+ let r1 = 0;
+ let g1 = 0;
+ let b1 = 0;
+
+ if (hp >= 0 && hp < 1) { r1 = c; g1 = x; }
+ else if (hp < 2) { r1 = x; g1 = c; }
+ else if (hp < 3) { g1 = c; b1 = x; }
+ else if (hp < 4) { g1 = x; b1 = c; }
+ else if (hp < 5) { r1 = x; b1 = c; }
+ else if (hp < 6) { r1 = c; b1 = x; }
+
+ const m = v - c;
+ return [
+ Math.max(0, Math.min(1, r1 + m)),
+ Math.max(0, Math.min(1, g1 + m)),
+ Math.max(0, Math.min(1, b1 + m)),
+ ];
+}
+
+export function applyColorDynamics(
+ primaryRgb: { r: number; g: number; b: number },
+ secondaryRgb: { r: number; g: number; b: number },
+ dynamics?: BrushDynamics,
+ rng: () => number = Math.random
+): { r: number; g: number; b: number; hex: string } {
+ if (!dynamics || !dynamics.colorJitterEnabled) {
+ return {
+ r: primaryRgb.r,
+ g: primaryRgb.g,
+ b: primaryRgb.b,
+ hex: rgbToHex(Math.round(primaryRgb.r * 255), Math.round(primaryRgb.g * 255), Math.round(primaryRgb.b * 255)),
+ };
+ }
+
+ let r = primaryRgb.r;
+ let g = primaryRgb.g;
+ let b = primaryRgb.b;
+
+ if (dynamics.foregroundBackgroundJitter > 0) {
+ const mix = rng() * dynamics.foregroundBackgroundJitter;
+ r += (secondaryRgb.r - r) * mix;
+ g += (secondaryRgb.g - g) * mix;
+ b += (secondaryRgb.b - b) * mix;
+ }
+
+ if (dynamics.hueJitter > 0 || dynamics.saturationJitter > 0 || dynamics.brightnessJitter > 0) {
+ let [h, s, v] = rgbToHsv(r, g, b);
+ if (dynamics.hueJitter > 0) h = (h + (rng() - 0.5) * dynamics.hueJitter * 360 + 360) % 360;
+ if (dynamics.saturationJitter > 0) s = Math.max(0, Math.min(1, s * (1.0 + (rng() * 2 - 1) * dynamics.saturationJitter)));
+ if (dynamics.brightnessJitter > 0) v = Math.max(0, Math.min(1, v * (1.0 + (rng() * 2 - 1) * dynamics.brightnessJitter)));
+ [r, g, b] = hsvToRgb(h, s, v);
+ }
+
+ r = Math.max(0, Math.min(1, r));
+ g = Math.max(0, Math.min(1, g));
+ b = Math.max(0, Math.min(1, b));
+ return { r, g, b, hex: rgbToHex(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)) };
+}
+
+// ============================================================================
+// 6. Cubic Bézier & Centripetal Catmull-Rom Spline Math
+// ============================================================================
+
+const sharedBezierSample: EvaluatedBezierSample = {
+ x: 0,
+ y: 0,
+ width: 0,
+ pressure: 0,
+ dx: 0,
+ dy: 0,
+ speed: 0,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+};
+
+function evalCubicBezierInto(
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ t: number,
+ out: EvaluatedBezierSample
+): EvaluatedBezierSample {
+ const invT = 1.0 - t;
+ const invT2 = invT * invT;
+ const invT3 = invT2 * invT;
+ const t2 = t * t;
+ const t3 = t2 * t;
+ const b = 3.0 * invT2 * t;
+ const c = 3.0 * invT * t2;
+
+ out.x = invT3 * p0.x + b * c1.x + c * c2.x + t3 * p3.x;
+ out.y = invT3 * p0.y + b * c1.y + c * c2.y + t3 * p3.y;
+ out.width = invT3 * p0.width + b * c1.width + c * c2.width + t3 * p3.width;
+ out.pressure = invT3 * p0.pressure + b * c1.pressure + c * c2.pressure + t3 * p3.pressure;
+ out.tiltX = invT * (p0.tiltX ?? 0) + t * (p3.tiltX ?? 0);
+ out.tiltY = invT * (p0.tiltY ?? 0) + t * (p3.tiltY ?? 0);
+ out.twist = invT * (p0.twist ?? 0) + t * (p3.twist ?? 0);
+
+ const dx = 3.0 * invT2 * (c1.x - p0.x) + 6.0 * invT * t * (c2.x - c1.x) + 3.0 * t2 * (p3.x - c2.x);
+ const dy = 3.0 * invT2 * (c1.y - p0.y) + 6.0 * invT * t * (c2.y - c1.y) + 3.0 * t2 * (p3.y - c2.y);
+ out.dx = dx;
+ out.dy = dy;
+ out.speed = Math.hypot(dx, dy);
+ return out;
+}
+
+export function evalCubicBezier(p0: Point, c1: Point, c2: Point, p3: Point, t: number): EvaluatedBezierSample {
+ return evalCubicBezierInto(p0, c1, c2, p3, t, {
+ x: 0, y: 0, width: 0, pressure: 0, dx: 0, dy: 0, speed: 0, tiltX: 0, tiltY: 0, twist: 0,
+ });
+}
+
+const _fastArcDistances = new Float64Array(65);
+
+function buildFastArcLengthScratch(p0: Point, c1: Point, c2: Point, p3: Point): { totalLength: number; steps: number } {
+ const polyLen =
+ Math.hypot(c1.x - p0.x, c1.y - p0.y) +
+ Math.hypot(c2.x - c1.x, c2.y - c1.y) +
+ Math.hypot(p3.x - c2.x, p3.y - c2.y);
+ const steps = Math.max(24, Math.min(64, Math.ceil(polyLen * 0.5)));
+ _fastArcDistances[0] = 0;
+ let total = 0;
+ let prevX = p0.x;
+ let prevY = p0.y;
+
+ for (let i = 1; i <= steps; i++) {
+ const t = i / steps;
+ const invT = 1.0 - t;
+ const invT2 = invT * invT;
+ const invT3 = invT2 * invT;
+ const t2 = t * t;
+ const t3 = t2 * t;
+
+ const x = invT3 * p0.x + 3.0 * invT2 * t * c1.x + 3.0 * invT * t2 * c2.x + t3 * p3.x;
+ const y = invT3 * p0.y + 3.0 * invT2 * t * c1.y + 3.0 * invT * t2 * c2.y + t3 * p3.y;
+
+ total += Math.hypot(x - prevX, y - prevY);
+ _fastArcDistances[i] = total;
+ prevX = x;
+ prevY = y;
+ }
+
+ return { totalLength: total, steps };
+}
+
+function sampleFastArcLengthInto(
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ targetDist: number,
+ totalLength: number,
+ steps: number,
+ out: EvaluatedBezierSample
+): EvaluatedBezierSample {
+ if (totalLength <= 0.0001 || targetDist <= 0) return evalCubicBezierInto(p0, c1, c2, p3, 0, out);
+ if (targetDist >= totalLength) return evalCubicBezierInto(p0, c1, c2, p3, 1.0, out);
+
+ let low = 0;
+ let high = steps - 1;
+ while (low < high) {
+ const mid = (low + high + 1) >>> 1;
+ if (_fastArcDistances[mid] <= targetDist) low = mid;
+ else high = mid - 1;
+ }
+ const d0 = _fastArcDistances[low];
+ const d1 = _fastArcDistances[low + 1];
+ const frac = d1 > d0 ? (targetDist - d0) / (d1 - d0) : 0;
+ return evalCubicBezierInto(p0, c1, c2, p3, Math.max(0, Math.min(1.0, (low + frac) / steps)), out);
+}
+
+export function buildCubicArcLengthTable(p0: Point, c1: Point, c2: Point, p3: Point): ArcLengthTable {
+ const { totalLength, steps } = buildFastArcLengthScratch(p0, c1, c2, p3);
+ const distances: number[] = new Array(steps + 1);
+ for (let i = 0; i <= steps; i++) distances[i] = _fastArcDistances[i];
+ return { totalLength, distances };
+}
+
+export function getCubicPointAtArcLength(
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ targetDist: number,
+ table: ArcLengthTable
+): EvaluatedBezierSample {
+ const { totalLength, distances } = table;
+ if (totalLength <= 0.0001 || targetDist <= 0) return evalCubicBezier(p0, c1, c2, p3, 0);
+ if (targetDist >= totalLength) return evalCubicBezier(p0, c1, c2, p3, 1.0);
+
+ const steps = distances.length - 1;
+ let low = 0;
+ let high = steps - 1;
+ while (low < high) {
+ const mid = (low + high + 1) >>> 1;
+ if (distances[mid] <= targetDist) low = mid;
+ else high = mid - 1;
+ }
+ const d0 = distances[low];
+ const d1 = distances[low + 1];
+ const frac = d1 > d0 ? (targetDist - d0) / (d1 - d0) : 0;
+ return evalCubicBezier(p0, c1, c2, p3, Math.max(0, Math.min(1.0, (low + frac) / steps)));
+}
+
+export function centripetalCatmullRomToBezier(
+ p0: Point,
+ p1: Point,
+ p2: Point,
+ p3: Point
+): { c1: Point; c2: Point } {
+ const effP0 = p1.isCorner ? p1 : p0;
+ const effP3 = p2.isCorner ? p2 : p3;
+
+ const d01 = Math.hypot(p1.x - effP0.x, p1.y - effP0.y);
+ const d12 = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const d23 = Math.hypot(effP3.x - p2.x, effP3.y - p2.y);
+
+ const dt0 = Math.max(1e-4, Math.sqrt(d01));
+ const dt1 = Math.max(1e-4, Math.sqrt(d12));
+ const dt2 = Math.max(1e-4, Math.sqrt(d23));
+
+ const t1x = (p2.x - p1.x) / dt1 - (p1.x - effP0.x) / dt0 + (p2.x - effP0.x) / (dt0 + dt1);
+ const t1y = (p2.y - p1.y) / dt1 - (p1.y - effP0.y) / dt0 + (p2.y - effP0.y) / (dt0 + dt1);
+ const t2x = (effP3.x - p2.x) / dt2 - (p2.x - p1.x) / dt1 + (effP3.x - p1.x) / (dt1 + dt2);
+ const t2y = (effP3.y - p2.y) / dt2 - (p2.y - p1.y) / dt1 + (effP3.y - p1.y) / (dt1 + dt2);
+
+ let dx1 = (t1x * dt1) / 3;
+ let dy1 = (t1y * dt1) / 3;
+ let dx2 = (t2x * dt1) / 3;
+ let dy2 = (t2y * dt1) / 3;
+
+ if (d12 > 0.001) {
+ const maxHandle = d12 * 0.48;
+ const len1 = Math.hypot(dx1, dy1);
+ if (len1 > maxHandle) {
+ const s = maxHandle / len1;
+ dx1 *= s;
+ dy1 *= s;
+ }
+ const len2 = Math.hypot(dx2, dy2);
+ if (len2 > maxHandle) {
+ const s = maxHandle / len2;
+ dx2 *= s;
+ dy2 *= s;
+ }
+ }
+
+ const minP = Math.min(p1.pressure, p2.pressure);
+ const maxP = Math.max(p1.pressure, p2.pressure);
+ const minW = Math.min(p1.width, p2.width);
+ const maxW = Math.max(p1.width, p2.width);
+
+ return {
+ c1: {
+ x: p1.x + dx1,
+ y: p1.y + dy1,
+ pressure: Math.max(minP, Math.min(maxP, p1.pressure + (p2.pressure - effP0.pressure) / 6)),
+ width: Math.max(minW, Math.min(maxW, p1.width + (p2.width - effP0.width) / 6)),
+ },
+ c2: {
+ x: p2.x - dx2,
+ y: p2.y - dy2,
+ pressure: Math.max(minP, Math.min(maxP, p2.pressure - (effP3.pressure - p1.pressure) / 6)),
+ width: Math.max(minW, Math.min(maxW, p2.width - (effP3.width - p1.width) / 6)),
+ },
+ };
+}
+
+// ============================================================================
+// 7. Single General CPU Canvas2D Fallback (Tip Cache, Paper Mask, Stamper)
+// ============================================================================
+
+const MAX_CACHE_ENTRIES = 160;
+const MAX_RADIAL_MASKS = 96;
+const tintedMasterCache = new Map<string, HTMLCanvasElement>();
+const radialMaskCache = new Map<string, HTMLCanvasElement>();
+const canvasPool: HTMLCanvasElement[] = [];
+const sourceIdMap = new WeakMap<object, number>();
+let nextSourceId = 1;
+
+function getUniqueSourceKey(source: CanvasImageSource, fallbackPrefix: string): string {
+ if (typeof source === 'object' && source !== null) {
+ let id = sourceIdMap.get(source);
+ if (!id) {
+ id = nextSourceId++;
+ sourceIdMap.set(source, id);
+ }
+ return `${fallbackPrefix}_${id}`;
+ }
+ return fallbackPrefix;
+}
+
+function getPooledCanvas(w: number, h: number): HTMLCanvasElement {
+ const targetW = Math.max(1, w);
+ const targetH = Math.max(1, h);
+ for (let i = 0; i < canvasPool.length; i++) {
+ const c = canvasPool[i];
+ if (c.width === targetW && c.height === targetH) {
+ canvasPool.splice(i, 1);
+ return c;
+ }
+ }
+ const canvas = document.createElement('canvas');
+ canvas.width = targetW;
+ canvas.height = targetH;
+ return canvas;
+}
+
+function evictOrAllocateMasterCanvas(w: number, h: number): HTMLCanvasElement {
+ const targetW = Math.max(1, w);
+ const targetH = Math.max(1, h);
+ if (tintedMasterCache.size >= MAX_CACHE_ENTRIES) {
+ const oldestKey = tintedMasterCache.keys().next().value;
+ if (oldestKey) {
+ const canvas = tintedMasterCache.get(oldestKey)!;
+ tintedMasterCache.delete(oldestKey);
+ if (canvas.width !== targetW || canvas.height !== targetH) {
+ canvas.width = targetW;
+ canvas.height = targetH;
+ }
+ return canvas;
+ }
+ }
+ return getPooledCanvas(targetW, targetH);
+}
+
+export function getTintedMasterCanvas(
+ source: CanvasImageSource,
+ sourceKey: string,
+ color: string,
+ w: number,
+ h: number,
+ isColorTip: boolean = false
+): HTMLCanvasElement {
+ if (isColorTip) {
+ const key = `color_${sourceKey}_${w}x${h}`;
+ const cached = tintedMasterCache.get(key);
+ if (cached) return cached;
+ const canvas = evictOrAllocateMasterCanvas(w, h);
+ const ctx = canvas.getContext('2d');
+ if (ctx) {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
+ }
+ tintedMasterCache.set(key, canvas);
+ return canvas;
+ }
+
+ const rgb = parseColorToRgb(color);
+ const quantizedHex = rgbToHex(rgb.r & ~1, rgb.g & ~1, rgb.b & ~1);
+ const key = `${sourceKey}_${quantizedHex}_${w}x${h}`;
+ const cached = tintedMasterCache.get(key);
+ if (cached) return cached;
+
+ const canvas = evictOrAllocateMasterCanvas(w, h);
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return canvas;
+
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
+ ctx.globalCompositeOperation = 'source-in';
+ ctx.fillStyle = quantizedHex;
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+ tintedMasterCache.set(key, canvas);
+ return canvas;
+}
+
+export function getTintedTipMaster(
+ tipImage: HTMLImageElement,
+ color: string,
+ isColorTip: boolean = false
+): HTMLCanvasElement {
+ const w = tipImage.naturalWidth || tipImage.width || 64;
+ const h = tipImage.naturalHeight || tipImage.height || 64;
+ return getTintedMasterCanvas(tipImage, getUniqueSourceKey(tipImage, 'tip'), color, w, h, isColorTip);
+}
+
+export function getRadialDabMaster(
+ hardness: number,
+ color: string,
+ isEraser: boolean = false,
+ targetSize?: number,
+ antiAlias: number = 2
+): HTMLCanvasElement {
+ const clampedH = Math.max(0, Math.min(1.0, hardness));
+ const qH = Math.round(clampedH * 20) / 20;
+ const aaLevel = Math.max(0, Math.min(3, Math.round(antiAlias)));
+
+ let size = 128;
+ let qDiameter = 124;
+ if (targetSize !== undefined && targetSize > 0) {
+ if (targetSize <= 8) {
+ size = 24;
+ qDiameter = Math.max(1, Math.round(targetSize));
+ } else if (targetSize <= 24) {
+ size = 48;
+ qDiameter = Math.max(4, Math.round(targetSize / 2) * 2);
+ } else if (targetSize <= 64) {
+ size = 64;
+ qDiameter = Math.max(16, Math.round(targetSize / 4) * 4);
+ }
+ }
+
+ const aaKeySuffix = aaLevel === 2 ? '' : `_aa${aaLevel}`;
+ const maskKey =
+ targetSize === undefined ? `${qH}_128${aaKeySuffix}` : `${qH}_${size}_${qDiameter}${aaKeySuffix}`;
+ let maskCanvas = radialMaskCache.get(maskKey);
+ if (!maskCanvas) {
+ if (radialMaskCache.size >= MAX_RADIAL_MASKS) {
+ const oldest = radialMaskCache.keys().next().value;
+ if (oldest !== undefined) radialMaskCache.delete(oldest);
+ }
+ maskCanvas = document.createElement('canvas');
+ maskCanvas.width = size;
+ maskCanvas.height = size;
+ const ctx = maskCanvas.getContext('2d');
+ if (ctx) {
+ const imgData = ctx.createImageData(size, size);
+ const data = imgData.data;
+ const cx = size / 2;
+ const cy = size / 2;
+ const radius = size / 2 - 1;
+ const aaScale = aaLevel === 0 ? 0 : aaLevel === 1 ? 0.6 : aaLevel === 3 ? 1.65 : 1.0;
+ const baseAaTexels =
+ qH >= 0.98
+ ? 1.15
+ : targetSize === undefined
+ ? 1.0
+ : Math.max(0.85, Math.min(2.4, (radius / Math.max(1.5, qDiameter * 0.5)) * 0.85));
+ const aaTexels = baseAaTexels * aaScale;
+ const rCore = Math.min(radius - Math.max(0, aaTexels), radius * qH);
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - cy + 0.5;
+ const rowOffset = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - cx + 0.5;
+ const dist = Math.hypot(dx, dy);
+ let alpha = 0;
+ if (aaLevel === 0) {
+ alpha = dist <= radius ? 1.0 : 0.0;
+ } else if (qH >= 0.98) {
+ const u = Math.max(0, Math.min(1.0, (radius - dist) / Math.max(0.25, aaTexels) + 0.5));
+ alpha = u * u * (3.0 - 2.0 * u);
+ } else if (dist <= rCore) {
+ alpha = 1.0;
+ } else if (dist < radius) {
+ const t = (dist - rCore) / Math.max(1e-4, radius - rCore);
+ alpha = qH <= 0.05 ? 0.5 * (1.0 + Math.cos(t * Math.PI)) : 1.0 - (3.0 * t * t - 2.0 * t * t * t);
+ }
+
+ if (alpha > 0.002) {
+ const idx = rowOffset + x * 4;
+ data[idx] = 255;
+ data[idx + 1] = 255;
+ data[idx + 2] = 255;
+ data[idx + 3] = Math.round(alpha * 255);
+ }
+ }
+ }
+ ctx.putImageData(imgData, 0, 0);
+ }
+ radialMaskCache.set(maskKey, maskCanvas);
+ }
+
+ return getTintedMasterCanvas(maskCanvas, `radial_${maskKey}`, isEraser ? '#000000' : color, size, size);
+}
+
+export function drawSingleStamp(
+ ctx: CanvasRenderingContext2D,
+ stampSource: CanvasImageSource,
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ angleRad: number,
+ alpha: number,
+ isEraser: boolean = false,
+ isBgEraser: boolean = false,
+ alphaLocked: boolean = false,
+ isTransparentInk: boolean = false,
+ flipX: number = 1,
+ flipY: number = 1,
+ antiAlias: number = 2,
+ _blendTipsMode?: CspBlendTipsMode
+): void {
+ if (width < 0.08 || height < 0.08 || alpha <= 0.002) return;
+
+ const minRenderDim = antiAlias === 0 ? 1.0 : 0.75;
+ const sub = computeSubpixelDabDimensions(width, height, alpha, minRenderDim);
+ const renderW = sub.renderW;
+ const renderH = sub.renderH;
+ const effAlpha = antiAlias === 0 ? (sub.effAlpha >= 0.45 ? 1.0 : 0) : sub.effAlpha;
+ if (effAlpha <= 0.002) return;
+
+ const targetOp: GlobalCompositeOperation = isBgEraser
+ ? 'source-over'
+ : isTransparentInk || isEraser
+ ? 'destination-out'
+ : alphaLocked
+ ? 'source-atop'
+ : 'source-over';
+
+ const prevSmooth = ctx.imageSmoothingEnabled;
+ if (antiAlias === 0 && prevSmooth !== false) ctx.imageSmoothingEnabled = false;
+
+ if (Math.abs(angleRad) < 0.001 && flipX >= 0 && flipY >= 0) {
+ const prevAlpha = ctx.globalAlpha;
+ const prevOp = ctx.globalCompositeOperation;
+ ctx.globalCompositeOperation = targetOp;
+ ctx.globalAlpha = effAlpha;
+ const drawX = antiAlias === 0 ? Math.round(x - renderW / 2) : x - renderW / 2;
+ const drawY = antiAlias === 0 ? Math.round(y - renderH / 2) : y - renderH / 2;
+ ctx.drawImage(stampSource, drawX, drawY, renderW, renderH);
+ ctx.globalAlpha = prevAlpha;
+ ctx.globalCompositeOperation = prevOp;
+ if (antiAlias === 0 && prevSmooth !== false) ctx.imageSmoothingEnabled = prevSmooth;
+ return;
+ }
+
+ ctx.save();
+ ctx.globalCompositeOperation = targetOp;
+ ctx.globalAlpha = effAlpha;
+ ctx.translate(x, y);
+ if (Math.abs(angleRad) >= 0.001) ctx.rotate(angleRad);
+ if ((flipX < 0 || flipY < 0) && typeof ctx.scale === 'function') {
+ ctx.scale(flipX < 0 ? -1 : 1, flipY < 0 ? -1 : 1);
+ }
+ ctx.drawImage(stampSource, -renderW / 2, -renderH / 2, renderW, renderH);
+ ctx.restore();
+ if (antiAlias === 0 && prevSmooth !== false) ctx.imageSmoothingEnabled = prevSmooth;
+}
+
+function selectTipImage(
+ tipImages: HTMLImageElement[] | undefined,
+ fallbackTip: HTMLImageElement,
+ order: 'random' | 'sequential' | 'direction' | 'reverse' = 'sequential',
+ dabIndex: number = 0,
+ tangentAngle: number = 0,
+ x: number = 0,
+ y: number = 0
+): HTMLImageElement {
+ if (!tipImages || tipImages.length <= 1) {
+ return tipImages && tipImages.length === 1 ? tipImages[0] : fallbackTip;
+ }
+ const count = tipImages.length;
+ if (order === 'random') return tipImages[Math.floor(dabHashFloat(x, y, dabIndex, 97) * count) % count];
+ if (order === 'reverse') return tipImages[(count - 1 - (dabIndex % count)) % count];
+ if (order === 'direction') {
+ const normAngle = ((tangentAngle % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
+ return tipImages[Math.floor((normAngle / (2 * Math.PI)) * count) % count];
+ }
+ return tipImages[dabIndex % count];
+}
+
+let _invertedGrainCanvas: HTMLCanvasElement | null = null;
+let _grainScratchCanvas: HTMLCanvasElement | null = null;
+let _grainScratchCtx: CanvasRenderingContext2D | null = null;
+let _grainPattern: CanvasPattern | null = null;
+const _customGrainCanvasCache = new WeakMap<
+ HTMLImageElement,
+ { canvas: HTMLCanvasElement; pattern: CanvasPattern | null }
+>();
+
+function getInvertedGrainPattern(
+ scratchCtx: CanvasRenderingContext2D,
+ paperTextureImage?: HTMLImageElement
+): CanvasPattern | null {
+ if (typeof scratchCtx.createPattern !== 'function') return null;
+
+ if (
+ paperTextureImage &&
+ paperTextureImage.complete !== false &&
+ (paperTextureImage.naturalWidth || paperTextureImage.width) > 0
+ ) {
+ const cached = _customGrainCanvasCache.get(paperTextureImage);
+ if (cached) return cached.pattern;
+ const w = paperTextureImage.naturalWidth || paperTextureImage.width;
+ const h = paperTextureImage.naturalHeight || paperTextureImage.height;
+ const c = document.createElement('canvas');
+ c.width = w;
+ c.height = h;
+ const gCtx = c.getContext('2d', { willReadFrequently: true });
+ if (gCtx && typeof gCtx.getImageData === 'function') {
+ gCtx.drawImage(paperTextureImage, 0, 0, w, h);
+ const img = gCtx.getImageData(0, 0, w, h);
+ const d = img.data;
+ for (let i = 0; i < d.length; i += 4) {
+ const lum = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
+ d[i] = 255;
+ d[i + 1] = 255;
+ d[i + 2] = 255;
+ d[i + 3] = 255 - Math.round(lum);
+ }
+ gCtx.putImageData(img, 0, 0);
+ const pat = scratchCtx.createPattern(c, 'repeat');
+ _customGrainCanvasCache.set(paperTextureImage, { canvas: c, pattern: pat });
+ return pat;
+ }
+ }
+
+ if (!_invertedGrainCanvas) {
+ const c = document.createElement('canvas');
+ c.width = GRAIN_SIZE;
+ c.height = GRAIN_SIZE;
+ const gCtx = c.getContext('2d');
+ if (!gCtx) return null;
+ const img = gCtx.createImageData(GRAIN_SIZE, GRAIN_SIZE);
+ const d = img.data;
+ for (let i = 0; i < paperGrainTable.length; i++) {
+ const p = i * 4;
+ d[p] = 255;
+ d[p + 1] = 255;
+ d[p + 2] = 255;
+ d[p + 3] = 255 - paperGrainTable[i];
+ }
+ gCtx.putImageData(img, 0, 0);
+ _invertedGrainCanvas = c;
+ _grainPattern = scratchCtx.createPattern(c, 'repeat');
+ }
+ return _grainPattern;
+}
+
+function applyCpuPerPixelPaperGrain(
+ master: CanvasImageSource,
+ worldX: number,
+ worldY: number,
+ renderW: number,
+ renderH: number,
+ grainAmount: number,
+ pressure: number,
+ paperScale: number = 1.0,
+ paperTextureImage?: HTMLImageElement
+): HTMLCanvasElement | null {
+ if (typeof document === 'undefined' || grainAmount <= 0.005) return null;
+ if (!_grainScratchCanvas) {
+ _grainScratchCanvas = document.createElement('canvas');
+ _grainScratchCanvas.width = 128;
+ _grainScratchCanvas.height = 128;
+ _grainScratchCtx = _grainScratchCanvas.getContext('2d');
+ }
+ const sCtx = _grainScratchCtx;
+ if (!sCtx || typeof sCtx.createPattern !== 'function') return null;
+
+ const pat = getInvertedGrainPattern(sCtx, paperTextureImage);
+ if (!pat) return null;
+
+ const bufSize = 128;
+ const p = Math.max(0, Math.min(1, pressure));
+ const heavyExcess = Math.max(0, (p - 0.52) / 0.48);
+ const penetration = Math.min(0.92, p * 0.28 + heavyExcess * heavyExcess * 0.64);
+ const effDensity = Math.max(0, Math.min(0.98, grainAmount * (1.0 - penetration * 0.85)));
+ if (effDensity <= 0.005) return null;
+
+ sCtx.save();
+ sCtx.globalCompositeOperation = 'source-over';
+ sCtx.globalAlpha = 1.0;
+ sCtx.clearRect(0, 0, bufSize, bufSize);
+ sCtx.drawImage(master, 0, 0, bufSize, bufSize);
+
+ const scale = Math.max(0.1, paperScale);
+ const sx = (bufSize / Math.max(1, renderW)) * scale;
+ const sy = (bufSize / Math.max(1, renderH)) * scale;
+ const offX = -((worldX - renderW * 0.5) / scale);
+ const offY = -((worldY - renderH * 0.5) / scale);
+
+ sCtx.globalCompositeOperation = 'destination-out';
+ sCtx.globalAlpha = effDensity;
+ sCtx.fillStyle = pat;
+ sCtx.scale(sx, sy);
+ sCtx.translate(offX, offY);
+ sCtx.fillRect(-offX, -offY, bufSize / sx, bufSize / sy);
+ sCtx.restore();
+
+ return _grainScratchCanvas;
+}
+
+// ============================================================================
+// 8. Unified WebGL Dispatch
+// ============================================================================
+
+export function canUseWebGlForBrush(options?: BrushRenderOptions): boolean {
+ if (!options) return WebGlBrushEngine.getInstance().isAvailable();
+ if (options.useGpu === false) return false;
+ if (options.colorMixing) return false;
+ if ((options.antiAlias ?? 2) === 0) return false;
+ if (options.tipImage && options.subTipImages && options.subTipImages.length > 1) return false;
+ return WebGlBrushEngine.getInstance().isAvailable();
+}
+
+export function flushGpuDabs(
+ ctx: CanvasRenderingContext2D,
+ dabs: GpuDab[],
+ color: string,
+ options: BrushRenderOptions
+): boolean {
+ if (dabs.length === 0) return true;
+ const gpu = WebGlBrushEngine.getInstance();
+ if (!gpu.isAvailable()) return false;
+
+ const isEraser = Boolean(options.isEraser);
+ const isBgEraser = Boolean(options.isBgEraser);
+ const tool: ToolType = isEraser || isBgEraser ? 'eraser' : 'brush';
+ const settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean } = {
+ size: options.size ?? 10,
+ minSizeFactor: options.minSizeFactor ?? 0,
+ color,
+ opacity: options.opacity ?? 1.0,
+ flow: options.flow ?? 1.0,
+ spacing: options.spacing ?? 0.08,
+ usePressure: options.usePressure !== false,
+ smoothing: false,
+ stabilization: 0,
+ hardness: options.hardness ?? 1.0,
+ antiAlias: options.antiAlias ?? 2,
+ wetEdge: options.wetEdge ?? 0,
+ grain: options.grain ?? options.textureDensity ?? 0,
+ textureDensity: options.textureDensity,
+ paperTextureMode: options.paperTextureMode,
+ paperTextureBrightness: options.paperTextureBrightness,
+ paperTextureContrast: options.paperTextureContrast,
+ paperTextureInverted: options.paperTextureInverted,
+ paperTextureImage: options.paperTextureImage,
+ paperTextureScale: options.paperTextureScale,
+ paperTextureRotate: options.paperTextureRotate,
+ customTipImage: options.tipImage,
+ isColorTip: options.isColorTip,
+ subTips: options.subTips,
+ dualBrush: options.dualBrush,
+ dualTipImage: options.dualTipImage,
+ dualBrushCompositeMode: options.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode'],
+ colorMixing: false,
+ isTransparentInk: Boolean(options.isTransparentInk),
+ alphaLocked: Boolean(options.alphaLocked),
+ isBgEraser,
+ };
+
+ const docW = options.underlyingCanvas?.width || ctx.canvas?.width || 1024;
+ const docH = options.underlyingCanvas?.height || ctx.canvas?.height || 1024;
+ return gpu.renderDabsToContext(ctx, dabs, settings, tool, docW, docH, options.underlyingCanvas);
+}
+
+// ============================================================================
+// 9. Unified Dab & Stroke Renderer (Textured, Radial & Pencil Presets)
+// ============================================================================
+
+function sampleScalarPaperGrainNorm(x: number, y: number, width: number, scale: number): number {
+ const invScale = 1.0 / Math.max(0.1, scale);
+ const sx = x * invScale;
+ const sy = y * invScale;
+ if (width > 3.0) {
+ const off = width * 0.25 * invScale;
+ const avg =
+ (getPaperGrain(sx, sy) * 2 +
+ getPaperGrain(sx - off, sy - off) +
+ getPaperGrain(sx + off, sy - off) +
+ getPaperGrain(sx - off, sy + off) +
+ getPaperGrain(sx + off, sy + off)) /
+ 6;
+ return avg / 255.0;
+ }
+ return getPaperGrain(sx, sy) / 255.0;
+}
+
+function resolveCpuMaster(
+ activeTip: HTMLImageElement | undefined,
+ color: string,
+ hardness: number,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ isColorTip: boolean,
+ targetWidth: number,
+ aaMode: number
+): HTMLCanvasElement {
+ if (activeTip) {
+ return getTintedTipMaster(activeTip, color, isColorTip);
+ }
+ return getRadialDabMaster(hardness, color, isEraser && !isBgEraser, targetWidth, aaMode);
+}
+
+function sampleAndMixColor(
+ ctx: CanvasRenderingContext2D,
+ x: number,
+ y: number,
+ radius: number,
+ pressure: number,
+ flow: number,
+ stepDist: number,
+ options: BrushRenderOptions
+): { colorHex: string; alpha: number; r: number; g: number; b: number } {
+ const reservoir = options.reservoir!;
+ let sampled = { r: 255, g: 255, b: 255, a: 0 };
+ if (options.sampler) {
+ sampled = options.sampler.sampleColor(x, y, radius);
+ } else {
+ const sampleCanvas = options.underlyingCanvas || ctx.canvas;
+ const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;
+ if (sampleCtx) {
+ sampled = sampleCanvasColor(sampleCtx, x, y, radius);
+ }
+ }
+
+ const mixed = reservoir.mixWithCanvas(
+ sampled,
+ options.amountOfPaint ?? 0.65,
+ options.densityOfPaint ?? 0.9,
+ options.colorStretch ?? 0.75,
+ options.mixingMode ?? 'blend',
+ pressure,
+ flow,
+ stepDist,
+ options.perceptualMixing !== false
+ );
+
+ if (options.sampler && mixed.alpha > 0.002) {
+ options.sampler.depositDab(x, y, radius, mixed.r, mixed.g, mixed.b, mixed.alpha);
+ }
+ return mixed;
+}
+
+/**
+ * Renders a single brush dot (pointerdown / single tap) via GPU batching or single CPU fallback.
+ */
+export function drawBrushDot(
+ ctx: CanvasRenderingContext2D,
+ point: Point,
+ color: string,
+ options: BrushRenderOptions = {},
+ batchGpuDabs?: GpuDab[]
+): void {
+ const isEraser = Boolean(options.isEraser);
+ const isBgEraser = Boolean(options.isBgEraser);
+ const hardness = options.hardness ?? 1.0;
+ const thickness = options.thickness ?? 1.0;
+ const isVert = Boolean(options.thicknessVertical);
+ const aaMode = options.antiAlias ?? 2;
+ const spacing = options.spacing ?? 0.08;
+ const useTilt = Boolean(options.useTilt || options.angleDynamics === 'tilt');
+ const grainAmount = options.grain ?? options.textureDensity ?? 0;
+
+ let effectiveColor = isBgEraser ? '#ffffff' : color;
+ const rawDensity = options.brushDensity ?? options.flow ?? (options.tipImage ? 0.85 : 1.0);
+ let effectiveFlow = computeGapAdjustedAlpha(rawDensity, spacing, options.adjustDensityByGap);
+
+ const rawPressure = point.pressure ?? 1.0;
+ const effPressure = options.pressureCurve ? evaluateFastSpline(rawPressure, options.pressureCurve) : rawPressure;
+ const minFactor = options.minSizeFactor ?? 0.2;
+ let effWidth =
+ point.width > 0
+ ? Math.max(0.4, point.width)
+ : Math.max(0.5, (options.size ?? 10) * (minFactor + (1.0 - minFactor) * effPressure));
+
+ const tiltX = useTilt ? point.tiltX ?? 0 : 0;
+ const tiltY = useTilt ? point.tiltY ?? 0 : 0;
+ const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
+ const tiltSpread = tiltMagnitude * (options.tiltScale ?? 1.0);
+ const grainPressure =
+ useTilt && tiltMagnitude > 0.01 ? effPressure * (1.0 - tiltMagnitude * 0.55) : effPressure;
+
+ if (options.sizeSensor) {
+ effWidth = Math.max(
+ 0.15,
+ effWidth * evaluateCspSensor(options.sizeSensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 50))
+ );
+ }
+ if (options.opacitySensor) {
+ effectiveFlow *= evaluateCspSensor(options.opacitySensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 51));
+ }
+ if (options.densitySensor) {
+ effectiveFlow *= evaluateCspSensor(options.densitySensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 52));
+ }
+ if (useTilt && tiltMagnitude > 0.03 && (options.tipImage || grainAmount > 0.005)) {
+ effectiveFlow *= 1.0 - tiltMagnitude * 0.28;
+ }
+
+ const isColorMixing = Boolean(options.colorMixing) && !isEraser && !isBgEraser;
+ if (isColorMixing) {
+ if (!options.reservoir) options.reservoir = new PaintReservoir(effectiveColor);
+ const mixed = sampleAndMixColor(ctx, point.x, point.y, Math.max(1, effWidth * 0.5), effPressure, effectiveFlow, 0, options);
+ effectiveColor = mixed.colorHex;
+ effectiveFlow = mixed.alpha;
+ }
+ if (effectiveFlow <= 0.002) return;
+
+ const gpuDabs = batchGpuDabs || null;
+ const activeTip = options.tipImage
+ ? selectTipImage(options.subTipImages, options.tipImage, options.subTipOrder, 0, 0, point.x, point.y)
+ : undefined;
+ const isColorTip = Boolean(options.isColorTip || (options.subTips && options.subTips[0]?.isColor));
+ const aspect = activeTip
+ ? (activeTip.naturalHeight || activeTip.height || 1) / (activeTip.naturalWidth || activeTip.width || 1)
+ : 1.0;
+
+ let angleRad = ((options.angle ?? 0) * Math.PI) / 180;
+ if (useTilt && tiltMagnitude > 0.05) {
+ angleRad = Math.atan2(tiltY, tiltX) + angleRad;
+ }
+ if (point.twist && (options.angleDynamics === 'twist' || useTilt)) {
+ angleRad += (point.twist * Math.PI) / 180;
+ }
+
+ const hasPerPixelCpuGrain = !gpuDabs && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
+ if (!gpuDabs && grainAmount > 0.005 && !hasPerPixelCpuGrain) {
+ const gNorm = sampleScalarPaperGrainNorm(point.x, point.y, effWidth, options.paperTextureScale ?? 1.0);
+ const scalarMode = options.paperTextureMode === 'compare' ? 'subtract' : (options.paperTextureMode ?? 'subtract');
+ effectiveFlow *= applyCspPaperTextureAlpha(
+ 1.0,
+ gNorm,
+ grainAmount,
+ grainPressure,
+ scalarMode,
+ options.paperTextureBrightness ?? 0,
+ options.paperTextureContrast ?? 0,
+ Boolean(options.paperTextureInverted)
+ );
+ }
+ if (effectiveFlow <= 0.002) return;
+
+ const baseMaster = gpuDabs
+ ? null
+ : resolveCpuMaster(activeTip, effectiveColor, hardness, isEraser, isBgEraser, isColorTip, effWidth, aaMode);
+
+ const dynamics = options.dynamics;
+ const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
+ const sizeJitter = Math.max(0, Math.min(1, dynamics?.sizeJitter ?? 0));
+ const angleJitter = Math.max(0, Math.min(1, dynamics?.angleJitter ?? 0));
+ const roundnessJitter = Math.max(0, Math.min(1, dynamics?.roundnessJitter ?? 0));
+ const scatter = Math.max(0, Math.min(5, dynamics?.scatter ?? 0));
+ const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
+ const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
+ const primRgb = colorJitterEnabled || gpuDabs ? parseColorToRgb(effectiveColor) : null;
+ const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
+
+ for (let k = 0; k < dabCount; k++) {
+ let curDabW = effWidth;
+ if (sizeJitter > 0) curDabW *= Math.max(0.01, 1.0 - dabHashFloat(point.x, point.y, k, 1) * sizeJitter);
+ curDabW = Math.max(0.1, curDabW);
+
+ let curDabThickness = thickness;
+ if (roundnessJitter > 0) curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(point.x, point.y, k, 2) * roundnessJitter);
+
+ let curDabAngle = angleRad;
+ if (angleJitter > 0) curDabAngle += (dabHashFloat(point.x, point.y, k, 3) - 0.5) * Math.PI * 2 * angleJitter;
+
+ let curDabX = point.x;
+ let curDabY = point.y;
+ if (scatter > 0) {
+ const th = dabHashFloat(point.x, point.y, k, 4) * Math.PI * 2;
+ const sDist = dabHashFloat(point.x, point.y, k, 5) * effWidth * scatter;
+ curDabX += Math.cos(th) * sDist;
+ curDabY += Math.sin(th) * sDist;
+ }
+
+ let curDabAlpha = effectiveFlow;
+ if (flowJitter > 0) curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(point.x, point.y, k, 6) * flowJitter);
+
+ let curMaster: CanvasImageSource | null = baseMaster;
+ let dabR = primRgb ? primRgb.r / 255 : 0;
+ let dabG = primRgb ? primRgb.g / 255 : 0;
+ let dabB = primRgb ? primRgb.b / 255 : 0;
+ if (colorJitterEnabled && primRgb && secRgb && dynamics) {
+ let salt = 20;
+ const cd = applyColorDynamics(
+ { r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
+ { r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
+ dynamics,
+ () => dabHashFloat(point.x, point.y, k, salt++)
+ );
+ dabR = cd.r;
+ dabG = cd.g;
+ dabB = cd.b;
+ if (!gpuDabs) {
+ curMaster = resolveCpuMaster(activeTip, cd.hex, hardness, isEraser, isBgEraser, isColorTip, curDabW, aaMode);
+ }
+ }
+
+ let finalW = isVert ? curDabW * curDabThickness : curDabW;
+ let finalH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
+ if (useTilt && tiltMagnitude > 0.01) {
+ finalW *= 1.0 + tiltSpread * 1.85;
+ finalH *= Math.max(0.55, 1.0 / (1.0 + tiltMagnitude * 0.45));
+ }
+
+ const flips = resolveTipFlipSigns(options.flipH, options.flipV, k, curDabX, curDabY);
+
+ if (curMaster && hasPerPixelCpuGrain) {
+ const grained = applyCpuPerPixelPaperGrain(
+ curMaster,
+ curDabX,
+ curDabY,
+ finalW,
+ finalH,
+ grainAmount,
+ grainPressure,
+ options.paperTextureScale ?? 1.0,
+ options.paperTextureImage
+ );
+ if (grained) curMaster = grained;
+ }
+
+ if (options.spray?.enabled) {
+ const pCount = options.spray.density;
+ const pSize = Math.max(1, options.spray.size);
+ const radius = curDabW / 2;
+ for (let i = 0; i < pCount; i++) {
+ const u1 = dabHashFloat(curDabX, curDabY, k * 64 + i, 31);
+ const u2 = dabHashFloat(curDabX, curDabY, k * 64 + i, 32);
+ const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));
+ const th = Math.PI * 2 * dabHashFloat(curDabX, curDabY, k * 64 + i, 33);
+ const spX = curDabX + r * Math.cos(th);
+ const spY = curDabY + r * Math.sin(th);
+ const spW = isVert ? pSize * curDabThickness : pSize;
+ const spH = isVert ? pSize * aspect : pSize * aspect * curDabThickness;
+ if (gpuDabs) {
+ gpuDabs.push({
+ x: spX, y: spY, width: spW, height: spH, angle: curDabAngle,
+ r: dabR, g: dabG, b: dabB, alpha: curDabAlpha, pressure: grainPressure,
+ strokeDist: 0, flipX: flips.signX, flipY: flips.signY,
+ });
+ } else if (curMaster) {
+ drawSingleStamp(
+ ctx, curMaster, spX, spY, spW, spH, curDabAngle, curDabAlpha,
+ isEraser, isBgEraser, options.alphaLocked, options.isTransparentInk,
+ flips.signX, flips.signY, aaMode, options.blendTipsMode
+ );
+ }
+ }
+ } else if (gpuDabs) {
+ gpuDabs.push({
+ x: curDabX, y: curDabY, width: finalW, height: finalH, angle: curDabAngle,
+ r: dabR, g: dabG, b: dabB, alpha: curDabAlpha, pressure: grainPressure,
+ strokeDist: 0, flipX: flips.signX, flipY: flips.signY,
+ });
+ } else if (curMaster) {
+ drawSingleStamp(
+ ctx, curMaster, curDabX, curDabY, finalW, finalH, curDabAngle, curDabAlpha,
+ isEraser, isBgEraser, options.alphaLocked, options.isTransparentInk,
+ flips.signX, flips.signY, aaMode, options.blendTipsMode
+ );
+ }
+ }
+}
+
+/**
+ * Renders brush dabs along a cubic Bézier segment using zero-allocation arc-length stepping.
+ */
+export function drawBrushCubicBezierSegment(
+ ctx: CanvasRenderingContext2D,
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ color: string,
+ options: BrushRenderOptions = {},
+ remainderDist: number = 0,
+ dabCounter: { count: number } = { count: 0 },
+ batchGpuDabs?: GpuDab[]
+): number {
+ const { totalLength: totalCurveLength, steps: arcSteps } = buildFastArcLengthScratch(p0, c1, c2, p3);
+ if (totalCurveLength < 0.08) {
+ return Math.max(0, remainderDist - totalCurveLength);
+ }
+
+ const isEraser = Boolean(options.isEraser);
+ const isBgEraser = Boolean(options.isBgEraser);
+ const baseColor = isBgEraser ? '#ffffff' : color;
+ const hardness = options.hardness ?? 1.0;
+ const tipImage = options.tipImage;
+ const isColorMixing = Boolean(options.colorMixing) && !isEraser && !isBgEraser;
+
+ if (isColorMixing && !options.reservoir) {
+ options.reservoir = new PaintReservoir(baseColor);
+ }
+
+ const aspect = tipImage
+ ? (tipImage.naturalHeight || tipImage.height || 1) / (tipImage.naturalWidth || tipImage.width || 1)
+ : 1.0;
+ const baseAngleRad = ((options.angle ?? 0) * Math.PI) / 180;
+ const rawDensity = options.brushDensity ?? options.flow ?? (tipImage ? 0.85 : 1.0);
+ const spacingRatio = Math.max(0.015, Math.min(1.0, options.spacing ?? (tipImage ? 0.07 : 0.08)));
+ const baseFlow = computeGapAdjustedAlpha(rawDensity, spacingRatio, options.adjustDensityByGap);
+ const thickness = options.thickness ?? 1.0;
+ const isVert = Boolean(options.thicknessVertical);
+ const rotationRandomScale = options.rotationRandomScale ?? 0;
+ const useTilt = Boolean(options.useTilt || options.angleDynamics === 'tilt');
+ const aaMode = options.antiAlias ?? 2;
+ const grainAmount = options.grain ?? options.textureDensity ?? 0;
+ const isColorTip = Boolean(options.isColorTip || (options.subTips && options.subTips[0]?.isColor));
+
+ const gpuDabs = batchGpuDabs || null;
+ const avgSegWidth = Math.max(0.5, (p0.width + p3.width) * 0.5);
+ const hasMultiSubTips = Boolean(tipImage && options.subTipImages && options.subTipImages.length > 1);
+ const staticMaster =
+ isColorMixing || gpuDabs || hasMultiSubTips
+ ? null
+ : resolveCpuMaster(tipImage, baseColor, hardness, isEraser, isBgEraser, isColorTip, avgSegWidth, aaMode);
+
+ const dynamics = options.dynamics;
+ const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
+ const sizeJitter = Math.max(0, Math.min(1, dynamics?.sizeJitter ?? 0));
+ const angleJitter = Math.max(0, Math.min(1, dynamics?.angleJitter ?? 0));
+ const roundnessJitter = Math.max(0, Math.min(1, dynamics?.roundnessJitter ?? 0));
+ const scatter = Math.max(0, Math.min(5, dynamics?.scatter ?? 0));
+ const scatterBothAxes = Boolean(dynamics?.scatterBothAxes);
+ const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
+ const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
+ const baseRgb = colorJitterEnabled || gpuDabs ? parseColorToRgb(baseColor) : null;
+ const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
+ const minStepPx = tipImage ? 0.15 : 0.12;
+ const hasPerPixelCpuGrain = !gpuDabs && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
+
+ let smoothCos = Math.cos(baseAngleRad);
+ let smoothSin = Math.sin(baseAngleRad);
+ let currentDist = remainderDist > 0 ? remainderDist : 0;
+
+ while (currentDist <= totalCurveLength) {
+ const pt = sampleFastArcLengthInto(p0, c1, c2, p3, currentDist, totalCurveLength, arcSteps, sharedBezierSample);
+ const effPressure = Math.max(0, Math.min(1, pt.pressure));
+ const curvedPressure = options.pressureCurve ? evaluateFastSpline(effPressure, options.pressureCurve) : effPressure;
+ const minFactor = Math.max(0, Math.min(1.0, options.minSizeFactor ?? 0));
+
+ let curWidth =
+ pt.width > 0
+ ? pt.width
+ : options.usePressure !== false
+ ? (options.size ?? 10) * (minFactor + (1.0 - minFactor) * curvedPressure)
+ : options.size ?? 10;
+
+ const strokeDist = (options.currentStrokeDist ?? 0) + currentDist;
+
+ let taperAlphaScale = 1.0;
+ if (options.taper) {
+ const inSharp = 0.35 + (1.0 - (options.taper.startingSharpness ?? 0.5)) * 1.1;
+ const outSharp = 0.35 + (1.0 - (options.taper.endingSharpness ?? 0.5)) * 1.1;
+ const inLen = options.taper.inLength || (options.taper.inRatio ? options.taper.inRatio * 2.5 : 0);
+ if (options.taper.useIn && inLen > 0 && strokeDist < inLen) {
+ const inFactor = Math.pow(Math.max(0.01, Math.min(1.0, strokeDist / inLen)), inSharp);
+ if (options.taper.affectSize !== false) curWidth *= inFactor;
+ if (options.taper.affectDensity || options.taper.affectOpacity) taperAlphaScale *= inFactor;
+ }
+ if (options.totalLength && options.totalLength > 0) {
+ const distFromEnd = options.totalLength - strokeDist;
+ const outLen = options.taper.outLength || (options.taper.outRatio ? options.taper.outRatio * 3.0 : 0);
+ if (options.taper.useOut && outLen > 0 && distFromEnd < outLen) {
+ const outFactor = Math.pow(Math.max(0.01, Math.min(1.0, distFromEnd / outLen)), outSharp);
+ if (options.taper.affectSize !== false) curWidth *= outFactor;
+ if (options.taper.affectDensity || options.taper.affectOpacity) taperAlphaScale *= outFactor;
+ }
+ }
+ }
+
+ const dabSeq = dabCounter.count++;
+ const tiltX = useTilt ? pt.tiltX : 0;
+ const tiltY = useTilt ? pt.tiltY : 0;
+ const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
+ const tiltSpread = tiltMagnitude * (options.tiltScale ?? 1.0);
+ const grainPressure =
+ useTilt && tiltMagnitude > 0.01 ? effPressure * (1.0 - tiltMagnitude * 0.55) : effPressure;
+
+ if (options.sizeSensor) {
+ curWidth *= evaluateCspSensor(
+ options.sizeSensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 50)
+ );
+ }
+ curWidth = Math.max(0.1, curWidth);
+
+ let stampAngle = baseAngleRad;
+ const angleMode = options.angleDynamics;
+ if ((angleMode === 'direction' || angleMode === 'direction-random') && pt.speed > 0.05) {
+ const targetAngle = Math.atan2(pt.dy, pt.dx) + baseAngleRad;
+ smoothCos = smoothCos * 0.6 + Math.cos(targetAngle) * 0.4;
+ smoothSin = smoothSin * 0.6 + Math.sin(targetAngle) * 0.4;
+ stampAngle = Math.atan2(smoothSin, smoothCos);
+ }
+ if (angleMode === 'random' || angleMode === 'direction-random') {
+ const rScale = angleMode === 'random' ? 1.0 : rotationRandomScale || 0.35;
+ stampAngle += (dabHashFloat(pt.x, pt.y, dabSeq, 12) - 0.5) * Math.PI * 2 * rScale;
+ } else if (rotationRandomScale > 0) {
+ stampAngle += (dabHashFloat(pt.x, pt.y, dabSeq, 12) - 0.5) * Math.PI * 2 * rotationRandomScale;
+ }
+
+ if (useTilt && tiltMagnitude > 0.05) {
+ stampAngle = Math.atan2(tiltY, tiltX) + baseAngleRad;
+ }
+ if (pt.twist && (angleMode === 'twist' || useTilt)) {
+ stampAngle += (pt.twist * Math.PI) / 180;
+ }
+
+ let dabColor = baseColor;
+ let dabAlpha = baseFlow * taperAlphaScale;
+ let dabRgb = baseRgb;
+
+ if (options.opacitySensor) {
+ dabAlpha *= evaluateCspSensor(
+ options.opacitySensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 51)
+ );
+ }
+ if (options.densitySensor) {
+ dabAlpha *= evaluateCspSensor(
+ options.densitySensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 52)
+ );
+ }
+ if (useTilt && tiltMagnitude > 0.03 && (tipImage || grainAmount > 0.005)) {
+ dabAlpha *= 1.0 - tiltMagnitude * 0.28;
+ }
+
+ if (isColorMixing && options.reservoir) {
+ const prelimStep = Math.max(0.15, curWidth * spacingRatio);
+ const mixed = sampleAndMixColor(ctx, pt.x, pt.y, curWidth * 0.45, effPressure, dabAlpha, prelimStep, options);
+ dabColor = mixed.colorHex;
+ dabAlpha = mixed.alpha;
+ if (gpuDabs) {
+ dabRgb = { r: mixed.r, g: mixed.g, b: mixed.b };
+ }
+ }
+
+ if (!gpuDabs && grainAmount > 0.005 && !hasPerPixelCpuGrain) {
+ const gNorm = sampleScalarPaperGrainNorm(pt.x, pt.y, curWidth, options.paperTextureScale ?? 1.0);
+ const scalarMode = options.paperTextureMode === 'compare' ? 'subtract' : (options.paperTextureMode ?? 'subtract');
+ dabAlpha *= applyCspPaperTextureAlpha(
+ 1.0,
+ gNorm,
+ grainAmount,
+ grainPressure,
+ scalarMode,
+ options.paperTextureBrightness ?? 0,
+ options.paperTextureContrast ?? 0,
+ Boolean(options.paperTextureInverted)
+ );
+ }
+
+ const activeTip = tipImage
+ ? selectTipImage(options.subTipImages, tipImage, options.subTipOrder, dabSeq, stampAngle, pt.x, pt.y)
+ : undefined;
+ const baseMaster = gpuDabs
+ ? null
+ : staticMaster ?? resolveCpuMaster(activeTip, dabColor, hardness, isEraser, isBgEraser, isColorTip, curWidth, aaMode);
+
+ let tx = 1;
+ let ty = 0;
+ let nx = 0;
+ let ny = 1;
+ if (pt.speed > 0.001) {
+ tx = pt.dx / pt.speed;
+ ty = pt.dy / pt.speed;
+ nx = -ty;
+ ny = tx;
+ }
+
+ const primRgb = colorJitterEnabled && isColorMixing ? parseColorToRgb(dabColor) : dabRgb;
+ let stepRefW = isVert ? curWidth * thickness : curWidth;
+ let stepRefH = isVert ? curWidth * aspect : curWidth * aspect * thickness;
+
+ for (let k = 0; k < dabCount; k++) {
+ const seedIdx = dabSeq * 16 + k;
+ let curDabW = curWidth;
+ if (sizeJitter > 0) curDabW *= Math.max(0.01, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 1) * sizeJitter);
+ curDabW = Math.max(0.1, curDabW);
+
+ let curDabThickness = thickness;
+ if (roundnessJitter > 0) curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 2) * roundnessJitter);
+
+ let curDabAngle = stampAngle;
+ if (angleJitter > 0) curDabAngle += (dabHashFloat(pt.x, pt.y, seedIdx, 3) - 0.5) * Math.PI * 2 * angleJitter;
+
+ let curDabX = pt.x;
+ let curDabY = pt.y;
+ if (scatter > 0) {
+ const perpDist = (dabHashFloat(pt.x, pt.y, seedIdx, 4) * 2 - 1) * curWidth * scatter;
+ let sOffX = nx * perpDist;
+ let sOffY = ny * perpDist;
+ if (scatterBothAxes) {
+ const tangDist = (dabHashFloat(pt.x, pt.y, seedIdx, 5) * 2 - 1) * curWidth * scatter;
+ sOffX += tx * tangDist;
+ sOffY += ty * tangDist;
+ }
+ curDabX += sOffX;
+ curDabY += sOffY;
+ }
+
+ let curDabAlpha = dabAlpha;
+ if (flowJitter > 0) curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 6) * flowJitter);
+
+ let curMaster: CanvasImageSource | null = baseMaster;
+ let dabR = primRgb ? primRgb.r / 255 : 0;
+ let dabG = primRgb ? primRgb.g / 255 : 0;
+ let dabB = primRgb ? primRgb.b / 255 : 0;
+
+ if (colorJitterEnabled && primRgb && secRgb && dynamics) {
+ let salt = 20;
+ const cd = applyColorDynamics(
+ { r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
+ { r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
+ dynamics,
+ () => dabHashFloat(pt.x, pt.y, seedIdx, salt++)
+ );
+ dabR = cd.r;
+ dabG = cd.g;
+ dabB = cd.b;
+ if (!gpuDabs) {
+ curMaster = resolveCpuMaster(activeTip, cd.hex, hardness, isEraser, isBgEraser, isColorTip, curDabW, aaMode);
+ }
+ }
+
+ let finalW = isVert ? curDabW * curDabThickness : curDabW;
+ let finalH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
+ if (useTilt && tiltMagnitude > 0.01) {
+ finalW *= 1.0 + tiltSpread * 1.85;
+ finalH *= Math.max(0.55, 1.0 / (1.0 + tiltMagnitude * 0.45));
+ }
+ stepRefW = finalW;
+ stepRefH = finalH;
+
+ if (curDabAlpha <= 0.002) continue;
+
+ const flips = resolveTipFlipSigns(options.flipH, options.flipV, seedIdx, curDabX, curDabY);
+
+ if (curMaster && hasPerPixelCpuGrain) {
+ const grained = applyCpuPerPixelPaperGrain(
+ curMaster,
+ curDabX,
+ curDabY,
+ finalW,
+ finalH,
+ grainAmount,
+ grainPressure,
+ options.paperTextureScale ?? 1.0,
+ options.paperTextureImage
+ );
+ if (grained) curMaster = grained;
+ }
+
+ if (options.spray?.enabled) {
+ const pCount = options.spray.density;
+ const pSize = Math.max(1, options.spray.size);
+ const radius = curDabW / 2;
+ for (let sp = 0; sp < pCount; sp++) {
+ const u1 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 31);
+ const u2 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 32);
+ const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));
+ const th = Math.PI * 2 * dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 33);
+ const spX = curDabX + r * Math.cos(th);
+ const spY = curDabY + r * Math.sin(th);
+ const spW = isVert ? pSize * curDabThickness : pSize;
+ const spH = isVert ? pSize * aspect : pSize * aspect * curDabThickness;
+ if (gpuDabs) {
+ gpuDabs.push({
+ x: spX, y: spY, width: spW, height: spH, angle: curDabAngle,
+ r: dabR, g: dabG, b: dabB, alpha: curDabAlpha, pressure: grainPressure,
+ strokeDist, flipX: flips.signX, flipY: flips.signY,
+ });
+ } else if (curMaster) {
+ drawSingleStamp(
+ ctx, curMaster, spX, spY, spW, spH, curDabAngle, curDabAlpha,
+ isEraser, isBgEraser, options.alphaLocked, options.isTransparentInk,
+ flips.signX, flips.signY, aaMode, options.blendTipsMode
+ );
+ }
+ }
+ } else if (gpuDabs) {
+ gpuDabs.push({
+ x: curDabX, y: curDabY, width: finalW, height: finalH, angle: curDabAngle,
+ r: dabR, g: dabG, b: dabB, alpha: curDabAlpha, pressure: grainPressure,
+ strokeDist, flipX: flips.signX, flipY: flips.signY,
+ });
+ } else if (curMaster) {
+ drawSingleStamp(
+ ctx, curMaster, curDabX, curDabY, finalW, finalH, curDabAngle, curDabAlpha,
+ isEraser, isBgEraser, options.alphaLocked, options.isTransparentInk,
+ flips.signX, flips.signY, aaMode, options.blendTipsMode
+ );
+ }
+ }
+
+ currentDist += computeEllipticalStepDistance(
+ stepRefW,
+ stepRefH,
+ stampAngle,
+ pt.dx,
+ pt.dy,
+ spacingRatio,
+ minStepPx
+ );
+ }
+
+ return Math.max(0, currentDist - totalCurveLength);
+}
+
+/**
+ * Elevates a quadratic Bézier segment to cubic and renders via the unified engine.
+ */
+export function drawBrushQuadraticBezierSegment(
+ ctx: CanvasRenderingContext2D,
+ start: Point,
+ control: Point,
+ end: Point,
+ color: string,
+ options: BrushRenderOptions = {},
+ remainderDist: number = 0,
+ dabCounter: { count: number } = { count: 0 },
+ batchGpuDabs?: GpuDab[]
+): number {
+ const c1: Point = {
+ x: start.x + (2.0 / 3.0) * (control.x - start.x),
+ y: start.y + (2.0 / 3.0) * (control.y - start.y),
+ pressure: start.pressure + (2.0 / 3.0) * (control.pressure - start.pressure),
+ width: start.width + (2.0 / 3.0) * (control.width - start.width),
+ tiltX: start.tiltX !== undefined && control.tiltX !== undefined ? start.tiltX + (2.0 / 3.0) * (control.tiltX - start.tiltX) : start.tiltX,
+ tiltY: start.tiltY !== undefined && control.tiltY !== undefined ? start.tiltY + (2.0 / 3.0) * (control.tiltY - start.tiltY) : start.tiltY,
+ twist: start.twist !== undefined && control.twist !== undefined ? start.twist + (2.0 / 3.0) * (control.twist - start.twist) : start.twist,
+ };
+ const c2: Point = {
+ x: end.x + (2.0 / 3.0) * (control.x - end.x),
+ y: end.y + (2.0 / 3.0) * (control.y - end.y),
+ pressure: end.pressure + (2.0 / 3.0) * (control.pressure - end.pressure),
+ width: end.width + (2.0 / 3.0) * (control.width - end.width),
+ tiltX: end.tiltX !== undefined && control.tiltX !== undefined ? end.tiltX + (2.0 / 3.0) * (control.tiltX - end.tiltX) : end.tiltX,
+ tiltY: end.tiltY !== undefined && control.tiltY !== undefined ? end.tiltY + (2.0 / 3.0) * (control.tiltY - end.tiltY) : end.tiltY,
+ twist: end.twist !== undefined && control.twist !== undefined ? end.twist + (2.0 / 3.0) * (control.twist - end.twist) : end.twist,
+ };
+ return drawBrushCubicBezierSegment(ctx, start, c1, c2, end, color, options, remainderDist, dabCounter, batchGpuDabs);
+}
+
+/**
+ * Builds unified BrushRenderOptions from BrushSettings (with legacy pencil preset resolution).
+ */
+export function buildBrushRenderOptions(
+ rawSettings: BrushSettings,
+ overrides?: Partial<BrushRenderOptions>
+): BrushRenderOptions {
+ const bs = resolveBrushPresetSettings(rawSettings);
+ return {
+ size: bs.size,
+ minSizeFactor: bs.minSizeFactor,
+ opacity: bs.opacity,
+ flow: bs.flow ?? 1.0,
+ brushDensity: bs.brushDensity,
+ adjustDensityByGap: bs.adjustDensityByGap,
+ blendTipsMode: bs.blendTipsMode,
+ spacing: bs.spacing ?? 0.08,
+ thickness: bs.thickness,
+ thicknessVertical: bs.thicknessVertical,
+ flipH: bs.flipH,
+ flipV: bs.flipV,
+ tipImage: bs.customTipImage,
+ isColorTip: bs.isColorTip,
+ angle: bs.customTipAngle,
+ angleDynamics: bs.customTipAngleDynamics,
+ rotationRandomScale: bs.customTipRotationRandomScale,
+ hardness: bs.hardness ?? 1.0,
+ antiAlias: bs.antiAlias,
+ pressureCurve: bs.pressureCurve,
+ velocityCurve: bs.velocityCurve,
+ usePressure: bs.usePressure,
+ useVelocity: bs.useVelocity,
+ useTilt: Boolean(bs.useTilt),
+ tiltScale: bs.tiltScale,
+ sizeSensor: bs.sizeSensor,
+ opacitySensor: bs.opacitySensor,
+ densitySensor: bs.densitySensor,
+ subTips: bs.subTips,
+ subTipOrder: bs.subTipOrder,
+ subTipImages: bs.subTipImages,
+ spray: bs.spray,
+ taper: bs.taper,
+ colorMixing: bs.colorMixing,
+ perceptualMixing: bs.perceptualMixing,
+ amountOfPaint: bs.amountOfPaint,
+ densityOfPaint: bs.densityOfPaint,
+ colorStretch: bs.colorStretch,
+ mixingMode: bs.mixingMode,
+ wetEdge: bs.wetEdge,
+ wetEdgeRadius: bs.wetEdgeRadius,
+ wetEdgeAlphaPower: bs.wetEdgeAlphaPower,
+ wetEdgeValuePower: bs.wetEdgeValuePower,
+ grain: bs.grain ?? bs.textureDensity,
+ textureDensity: bs.textureDensity,
+ paperTextureMode: bs.paperTextureMode,
+ paperTextureBrightness: bs.paperTextureBrightness,
+ paperTextureContrast: bs.paperTextureContrast,
+ paperTextureInverted: bs.paperTextureInverted,
+ paperTextureImage: bs.paperTextureImage,
+ paperTextureScale: bs.paperTextureScale,
+ paperTextureRotate: bs.paperTextureRotate,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ useGpu: bs.useGpu !== false,
+ isTransparentInk: Boolean(bs.isTransparentInk),
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ ...overrides,
+ };
+}
+
+/**
+ * Renders an entire completed brush stroke through the single unified pipeline:
+ * WebGL instanced batch when available & eligible, single Canvas2D CPU fallback otherwise.
+ */
+export function renderCompleteStroke(
+ ctx: CanvasRenderingContext2D,
+ points: Point[],
+ brushSettings: BrushSettings,
+ tool: ToolType,
+ colorMode: CanvasColorMode = 'color',
+ isBgEraser: boolean = false,
+ underlyingCanvas?: HTMLCanvasElement,
+ alphaLocked: boolean = false,
+ explicitSampler?: LayerPixelSampler,
+ allowGpuForMonochrome: boolean = false
+): void {
+ if (!points || points.length === 0) return;
+
+ const resolvedSettings = resolveBrushPresetSettings(brushSettings);
+ const isMono = colorMode === 'monochrome';
+ const postCorrLevel = resolvedSettings.postCorrection ?? 0;
+ const postCorrectedPoints =
+ postCorrLevel > 0 && points.length >= 3
+ ? applyCspPostCorrection(points, postCorrLevel, resolvedSettings.sharpCorners !== false)
+ : points;
+
+ const hasTaper = Boolean(resolvedSettings.taper?.useOut || resolvedSettings.taper?.useIn);
+ const effectivePoints =
+ isMono && !hasTaper
+ ? postCorrectedPoints.map((p) => (p.width < 1.25 ? { ...p, width: 1.25 } : p))
+ : postCorrectedPoints;
+
+ const isEraser = tool === 'eraser';
+ const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(resolvedSettings.color, colorMode);
+ const strokeHardness = isMono ? 1.0 : resolvedSettings.hardness ?? 1.0;
+ const strokeFlow = isMono ? 1.0 : resolvedSettings.flow ?? 1.0;
+ const strokeSpacing = resolvedSettings.spacing ?? 0.08;
+ const effectiveAntiAlias = isMono
+ ? allowGpuForMonochrome && (resolvedSettings.antiAlias ?? 2) !== 0 && resolvedSettings.useGpu !== false
+ ? resolvedSettings.antiAlias ?? 2
+ : 0
+ : resolvedSettings.antiAlias;
+
+ const effectiveUnderlying = underlyingCanvas || ctx.canvas;
+ const options = buildBrushRenderOptions(resolvedSettings, {
+ hardness: strokeHardness,
+ flow: strokeFlow,
+ spacing: strokeSpacing,
+ antiAlias: effectiveAntiAlias,
+ underlyingCanvas: effectiveUnderlying,
+ sampler: resolvedSettings.colorMixing
+ ? explicitSampler || (effectiveUnderlying ? new LayerPixelSampler(effectiveUnderlying) : undefined)
+ : undefined,
+ reservoir: resolvedSettings.colorMixing && !isEraser && !isBgEraser ? new PaintReservoir(strokeColor) : undefined,
+ isEraser: isEraser && !isBgEraser,
+ isBgEraser,
+ alphaLocked,
+ isTransparentInk: Boolean(resolvedSettings.isTransparentInk),
+ });
+
+ let totalLen = 0;
+ for (let i = 1; i < effectivePoints.length; i++) {
+ totalLen += Math.hypot(effectivePoints[i].x - effectivePoints[i - 1].x, effectivePoints[i].y - effectivePoints[i - 1].y);
+ }
+ options.totalLength = totalLen;
+
+ const emitStroke = (batchGpuDabs: GpuDab[] | undefined) => {
+ options.currentStrokeDist = 0;
+ drawBrushDot(ctx, effectivePoints[0], strokeColor, options, batchGpuDabs);
+ if (effectivePoints.length === 1) return;
+
+ const dabCounter = { count: 0 };
+ const minInitDist = options.tipImage ? 0.15 : 0.12;
+ let accDist = Math.max(minInitDist, Math.max(0.2, effectivePoints[0].width) * strokeSpacing);
+
+ if (effectivePoints.length === 2) {
+ const p0 = effectivePoints[0];
+ const p1 = effectivePoints[1];
+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
+ drawBrushCubicBezierSegment(ctx, p0, c1, c2, p1, strokeColor, options, accDist, dabCounter, batchGpuDabs);
+ return;
+ }
+
+ const p0 = effectivePoints[0];
+ const p1 = effectivePoints[1];
+ const p2 = effectivePoints[2];
+ const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
+ accDist = drawBrushCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, strokeColor, options, accDist, dabCounter, batchGpuDabs);
+ options.currentStrokeDist = (options.currentStrokeDist ?? 0) + Math.hypot(p1.x - p0.x, p1.y - p0.y);
+
+ for (let i = 2; i < effectivePoints.length - 1; i++) {
+ const seg = centripetalCatmullRomToBezier(
+ effectivePoints[i - 2],
+ effectivePoints[i - 1],
+ effectivePoints[i],
+ effectivePoints[i + 1]
+ );
+ accDist = drawBrushCubicBezierSegment(
+ ctx,
+ effectivePoints[i - 1],
+ seg.c1,
+ seg.c2,
+ effectivePoints[i],
+ strokeColor,
+ options,
+ accDist,
+ dabCounter,
+ batchGpuDabs
+ );
+ options.currentStrokeDist =
+ (options.currentStrokeDist ?? 0) +
+ Math.hypot(effectivePoints[i].x - effectivePoints[i - 1].x, effectivePoints[i].y - effectivePoints[i - 1].y);
+ }
+
+ const n = effectivePoints.length;
+ const last = centripetalCatmullRomToBezier(effectivePoints[n - 3], effectivePoints[n - 2], effectivePoints[n - 1], effectivePoints[n - 1]);
+ drawBrushCubicBezierSegment(
+ ctx,
+ effectivePoints[n - 2],
+ last.c1,
+ last.c2,
+ effectivePoints[n - 1],
+ strokeColor,
+ options,
+ accDist,
+ dabCounter,
+ batchGpuDabs
+ );
+ };
+
+ if (canUseWebGlForBrush(options)) {
+ const batchGpuDabs: GpuDab[] = [];
+ emitStroke(batchGpuDabs);
+ if (flushGpuDabs(ctx, batchGpuDabs, strokeColor, options)) {
+ return;
+ }
+ }
+
+ // Single general CPU Canvas2D fallback (WebGL unavailable/lost, AA=0, CPU colorMixing, or multi-subTip)
+ emitStroke(undefined);
+}
diff --git a/src/engine/CspBrushEngine.ts b/src/engine/CspBrushEngine.ts
deleted file mode 100644
index f3e1678..0000000
--- a/src/engine/CspBrushEngine.ts
+++ /dev/null
@@ -1,613 +0,0 @@
-/**
- * CspBrushEngine.ts
- * Authentic Clip Studio Paint (CSP) Brush Mathematics & Zero-Allocation Dynamics Engine.
- *
- * Implements:
- * 1. O(1) Precompiled Monotone Cubic Hermite (PCHIP) Spline Curve LUTs (256-entry Float32Array, zero GC).
- * 2. Zero-Closure Deterministic Hash PRNG for live/bake-identical scatter, jitter, and multi-tip selection.
- * 3. Multi-Sensor CSP Effector Matrix (Pressure x Tilt x Velocity x Random with independent min-floors & curves).
- * 4. Ellipse-Aware Directional Spacing (eliminates Venetian-blind gaps on flat/calligraphic nibs).
- * 5. CSP "Adjust Brush Density by Gap" (gap-invariant Beer-Lambert optical transmittance).
- * 6. 4-Stage CSP Anti-Aliasing (None/Binary, Weak, Medium, Strong) + 2D Sub-Pixel Hairline Coverage.
- * 7. 5-Mode CSP Paper Texture Physics (Multiply, Subtract/Valley-Fill, Compare, Overlay, Outline).
- * 8. Corner-Preserving CSP Post-Correction (Levels 1-5) & Stroke-Silhouette Watercolor Edge Filter.
- */
-
-import {
- Point,
- CspSensorConfig,
- CspPaperTextureMode,
- CspTipFlipMode,
-} from '../types/editor';
-
-const LUT_SIZE = 256;
-const LUT_MAX_IDX = LUT_SIZE - 1;
-const curveWeakCache = new WeakMap<readonly [number, number][], Float32Array>();
-const curveStringCache = new Map<string, Float32Array>();
-const MAX_STRING_CURVE_CACHE = 128;
-
-/**
- * Compiles a CSP control-point array [[x0,y0], [x1,y1], ...] into a 256-sample Float32Array LUT
- * using Fritsch-Carlson Monotone Piecewise Cubic Hermite Interpolation (PCHIP).
- */
-export function getCompiledCurveLut(curve?: readonly [number, number][]): Float32Array | null {
- if (!curve || curve.length === 0) return null;
-
- const weakHit = curveWeakCache.get(curve);
- if (weakHit) return weakHit;
-
- let key = '';
- for (let i = 0; i < curve.length; i++) {
- key += `${curve[i][0].toFixed(4)},${curve[i][1].toFixed(4)};`;
- }
- const strHit = curveStringCache.get(key);
- if (strHit) {
- curveWeakCache.set(curve, strHit);
- return strHit;
- }
-
- const lut = new Float32Array(LUT_SIZE);
- const pts = curve.slice().sort((a, b) => a[0] - b[0]);
- const dedup: [number, number][] = [pts[0]];
- for (let i = 1; i < pts.length; i++) {
- if (pts[i][0] - dedup[dedup.length - 1][0] > 1e-5) {
- dedup.push(pts[i]);
- }
- }
-
- const n = dedup.length;
- if (n === 1) {
- const val = Math.max(0, Math.min(1, dedup[0][1]));
- lut.fill(val);
- } else if (n === 2) {
- const [x0, y0] = dedup[0];
- const [x1, y1] = dedup[1];
- const span = Math.max(1e-5, x1 - x0);
- for (let s = 0; s < LUT_SIZE; s++) {
- const x = s / LUT_MAX_IDX;
- if (x <= x0) lut[s] = Math.max(0, Math.min(1, y0));
- else if (x >= x1) lut[s] = Math.max(0, Math.min(1, y1));
- else {
- const t = (x - x0) / span;
- lut[s] = Math.max(0, Math.min(1, y0 + t * (y1 - y0)));
- }
- }
- } else {
- const deltas = new Float64Array(n - 1);
- const m = new Float64Array(n);
- for (let k = 0; k < n - 1; k++) {
- deltas[k] = (dedup[k + 1][1] - dedup[k][1]) / Math.max(1e-5, dedup[k + 1][0] - dedup[k][0]);
- }
- m[0] = deltas[0];
- for (let k = 1; k < n - 1; k++) {
- if (deltas[k - 1] * deltas[k] <= 0) {
- m[k] = 0;
- } else {
- m[k] = (deltas[k - 1] + deltas[k]) * 0.5;
- }
- }
- m[n - 1] = deltas[n - 2];
-
- for (let k = 0; k < n - 1; k++) {
- const dk = deltas[k];
- if (Math.abs(dk) < 1e-6) {
- m[k] = 0;
- m[k + 1] = 0;
- } else {
- const alpha = m[k] / dk;
- const beta = m[k + 1] / dk;
- const sumSq = alpha * alpha + beta * beta;
- if (sumSq > 9) {
- const tau = 3 / Math.sqrt(sumSq);
- m[k] = tau * alpha * dk;
- m[k + 1] = tau * beta * dk;
- }
- }
- }
-
- let segIdx = 0;
- for (let s = 0; s < LUT_SIZE; s++) {
- const x = s / LUT_MAX_IDX;
- if (x <= dedup[0][0]) {
- lut[s] = Math.max(0, Math.min(1, dedup[0][1]));
- continue;
- }
- if (x >= dedup[n - 1][0]) {
- lut[s] = Math.max(0, Math.min(1, dedup[n - 1][1]));
- continue;
- }
- while (segIdx < n - 2 && x > dedup[segIdx + 1][0]) {
- segIdx++;
- }
- const x0 = dedup[segIdx][0];
- const y0 = dedup[segIdx][1];
- const x1 = dedup[segIdx + 1][0];
- const y1 = dedup[segIdx + 1][1];
- const h = Math.max(1e-5, x1 - x0);
- const t = (x - x0) / h;
- const t2 = t * t;
- const t3 = t2 * t;
- const h00 = 2 * t3 - 3 * t2 + 1;
- const h10 = t3 - 2 * t2 + t;
- const h01 = -2 * t3 + 3 * t2;
- const h11 = t3 - t2;
- const y = h00 * y0 + h10 * h * m[segIdx] + h01 * y1 + h11 * h * m[segIdx + 1];
- lut[s] = Math.max(0, Math.min(1, y));
- }
- }
-
- if (curveStringCache.size >= MAX_STRING_CURVE_CACHE) {
- const oldest = curveStringCache.keys().next().value;
- if (oldest !== undefined) curveStringCache.delete(oldest);
- }
- curveStringCache.set(key, lut);
- curveWeakCache.set(curve, lut);
- return lut;
-}
-
-/**
- * Evaluates a CSP spline curve in O(1) time with zero allocations.
- */
-export function evaluateFastSpline(x: number, curve?: readonly [number, number][]): number {
- const clamped = x <= 0 ? 0 : x >= 1 ? 1 : x;
- if (!curve || curve.length === 0) return clamped;
- const lut = getCompiledCurveLut(curve);
- if (!lut) return clamped;
-
- const pos = clamped * LUT_MAX_IDX;
- const idx = pos | 0;
- if (idx >= LUT_MAX_IDX) return lut[LUT_MAX_IDX];
- const frac = pos - idx;
- return lut[idx] + (lut[idx + 1] - lut[idx]) * frac;
-}
-
-/**
- * Zero-closure deterministic 32-bit integer hash returning [0, 1).
- * Guarantees identical dab scatter/jitter/sub-tip order between live preview and stroke commit.
- */
-export function dabHashFloat(x: number, y: number, dabIndex: number, salt: number): number {
- const ix = (x * 100) | 0;
- const iy = (y * 100) | 0;
- let h = (Math.imul(ix, 73856093) ^ Math.imul(iy, 19349663) ^ Math.imul(dabIndex + 1, 83492791) ^ Math.imul(salt + 1, 0x9e3779b9)) | 0;
- h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
- h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
- return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
-}
-
-/**
- * Evaluates a CSP multi-sensor dynamic multiplier in [0, 1].
- * Follows Clip Studio Paint's exact multiplicative sensor law:
- * factor = pFactor * tFactor * vFactor * rFactor
- */
-export function evaluateCspSensor(
- sensor: CspSensorConfig | undefined,
- pressure: number,
- tiltMagnitude: number, // [0, 1] where 0 = upright, 1 = flat horizontal
- speedPxPerMs: number, // stylus speed in px/ms
- randomVal: number // deterministic [0, 1)
-): number {
- if (!sensor) return 1.0;
-
- let factor = 1.0;
-
- if (sensor.usePressure) {
- const pMin = Math.max(0, Math.min(1, sensor.pressureMin ?? 0));
- const curvedP = sensor.pressureCurve
- ? evaluateFastSpline(pressure, sensor.pressureCurve)
- : Math.max(0, Math.min(1, pressure));
- factor *= pMin + (1.0 - pMin) * curvedP;
- }
-
- if (sensor.useTilt) {
- const tMin = Math.max(0, Math.min(1, sensor.tiltMin ?? 0));
- const clampedTilt = Math.max(0, Math.min(1, tiltMagnitude));
- factor *= tMin + (1.0 - tMin) * clampedTilt;
- }
-
- if (sensor.useVelocity) {
- const vMin = Math.max(0, Math.min(1, sensor.velocityMin ?? 0));
- // Normalize speed: 3.5 px/ms (~3500 px/s) maps to full velocity 1.0
- const vNorm = Math.max(0, Math.min(1, speedPxPerMs / 3.5));
- const vVal = sensor.invertVelocity !== false ? 1.0 - vNorm : vNorm;
- factor *= vMin + (1.0 - vMin) * vVal;
- }
-
- if (sensor.useRandom) {
- const rMin = Math.max(0, Math.min(1, sensor.randomMin ?? 0));
- factor *= rMin + (1.0 - rMin) * Math.max(0, Math.min(1, randomVal));
- }
-
- return Math.max(0, Math.min(1, factor));
-}
-
-/**
- * Computes ellipse-aware step distance along the local stroke tangent.
- * Prevents discrete "Venetian blind" stamp gaps when drawing perpendicular to a flat/calligraphic brush's thin axis.
- */
-export function computeEllipticalStepDistance(
- width: number,
- height: number,
- dabAngleRad: number,
- tangentDx: number,
- tangentDy: number,
- spacingRatio: number,
- minStepPx: number = 0.12
-): number {
- const ratio = Math.max(0.01, Math.min(2.0, spacingRatio));
- const w = Math.max(0.1, width);
- const h = Math.max(0.1, height);
-
- // Fast isotropic path for round tips
- if (Math.abs(w - h) < 1e-2) {
- return Math.max(minStepPx, w * ratio);
- }
-
- const tLen = Math.hypot(tangentDx, tangentDy);
- if (tLen < 1e-4) {
- return Math.max(minStepPx, Math.min(w, h) * ratio);
- }
-
- // Project tangent unit vector into the rotated ellipse's local frame
- const ux = tangentDx / tLen;
- const uy = tangentDy / tLen;
- const cosA = Math.cos(dabAngleRad);
- const sinA = Math.sin(dabAngleRad);
- const localX = ux * cosA + uy * sinA;
- const localY = -ux * sinA + uy * cosA;
-
- // Support diameter of ellipse (w, h) along direction (localX, localY)
- const denom = Math.hypot(localX / w, localY / h);
- const effectiveDiameter = denom > 1e-5 ? 1.0 / denom : Math.min(w, h);
- return Math.max(minStepPx, effectiveDiameter * ratio);
-}
-
-/**
- * CSP "Adjust brush density by gap":
- * Compensates dab alpha using Beer-Lambert transmittance law so changing spacing
- * preserves perceived stroke optical density and prevents 8-bit Mach-band rings.
- */
-export function computeGapAdjustedAlpha(
- baseAlpha: number,
- spacingRatio: number,
- adjustByGap: boolean = false,
- referenceSpacing: number = 0.08
-): number {
- const a = Math.max(0, Math.min(1, baseAlpha));
- if (!adjustByGap || a >= 0.998 || a <= 0.001) return a;
- const ratio = Math.max(0.12, Math.min(4.0, spacingRatio / Math.max(0.01, referenceSpacing)));
- return Math.max(0.002, Math.min(1.0, 1.0 - Math.pow(1.0 - a, ratio)));
-}
-
-/**
- * Computes exact 2D sub-pixel area conservation for ultra-fine manga hairlines (< 1.0px).
- * Prevents sub-pixel widths/heights from bloating to 1.25px or flickering.
- */
-export function computeSubpixelDabDimensions(
- width: number,
- height: number,
- alpha: number,
- minRenderDim: number = 0.75
-): { renderW: number; renderH: number; effAlpha: number } {
- const renderW = Math.max(minRenderDim, width);
- const renderH = Math.max(minRenderDim, height);
- if (width >= minRenderDim && height >= minRenderDim) {
- return { renderW, renderH, effAlpha: alpha };
- }
- const scaleW = width < minRenderDim ? Math.max(0.04, width / renderW) : 1.0;
- const scaleH = height < minRenderDim ? Math.max(0.04, height / renderH) : 1.0;
- return {
- renderW,
- renderH,
- effAlpha: Math.max(0.003, Math.min(1.0, alpha * scaleW * scaleH)),
- };
-}
-
-/**
- * Maps CSP 4-level Anti-Aliasing setting (0: None, 1: Weak, 2: Medium, 3: Strong)
- * into feather width in pixels.
- */
-export function getCspAntiAliasFeather(antiAlias: number = 2): number {
- switch (antiAlias) {
- case 0:
- return 0.0; // Binary 1-bit crisp threshold
- case 1:
- return 0.65; // Weak (sharp manga pen)
- case 3:
- return 1.95; // Strong (silky illustration pen)
- case 2:
- default:
- return 1.15; // Medium (standard CSP G-Pen)
- }
-}
-
-/**
- * Resolves horizontal/vertical flip signs (+1 or -1) for a dab according to CSP Tip Flip mode.
- */
-export function resolveTipFlipSigns(
- flipH: CspTipFlipMode | undefined,
- flipV: CspTipFlipMode | undefined,
- dabSeq: number,
- x: number,
- y: number
-): { signX: number; signY: number } {
- let signX = 1;
- let signY = 1;
- if (flipH === 'alternate') {
- signX = (dabSeq & 1) === 0 ? 1 : -1;
- } else if (flipH === 'random') {
- signX = dabHashFloat(x, y, dabSeq, 71) < 0.5 ? 1 : -1;
- }
- if (flipV === 'alternate') {
- signY = (dabSeq & 1) === 0 ? 1 : -1;
- } else if (flipV === 'random') {
- signY = dabHashFloat(x, y, dabSeq, 73) < 0.5 ? 1 : -1;
- }
- return { signX, signY };
-}
-
-/**
- * Evaluates CSP 5-mode Paper Texture modulation on dab alpha:
- * - multiply: tipAlpha * grain
- * - subtract: max(0, tipAlpha - (1 - grain) * density) [CSP classic valley-fill with pressure!]
- * - compare: tipAlpha >= (1 - grain) ? tipAlpha : 0
- * - overlay: contrast-preserving texture tooth
- * - outline: accentuates texture contours along dab edges
- */
-export function applyCspPaperTextureAlpha(
- tipAlpha: number,
- grainNorm: number, // [0, 1] raw paper height
- textureDensity: number, // [0, 1]
- pressure: number, // [0, 1]
- mode: CspPaperTextureMode = 'subtract',
- brightness: number = 0, // [-100, 100]
- contrast: number = 0, // [-100, 100]
- inverted: boolean = false
-): number {
- if (textureDensity <= 0.001 || tipAlpha <= 0.001) return tipAlpha;
-
- let g = inverted ? 1.0 - grainNorm : grainNorm;
- if (brightness !== 0) {
- g += brightness / 100.0;
- }
- if (contrast !== 0) {
- const cFactor = Math.pow((contrast + 100.0) / 100.0, 2);
- g = (g - 0.5) * cFactor + 0.5;
- }
- g = Math.max(0, Math.min(1, g));
-
- // Nonlinear valley-clogging physics: light-to-medium pressure catches crisp paper peaks;
- // heavy pressure (> 0.55) compresses soft graphite/charcoal into valleys to clog the grain.
- const p = Math.max(0, Math.min(1, pressure));
- const heavyExcess = Math.max(0, (p - 0.52) / 0.48);
- const penetration = Math.min(0.92, p * 0.28 + heavyExcess * heavyExcess * 0.64);
- const effDensity = textureDensity * (1.0 - penetration * 0.85);
-
- switch (mode) {
- case 'multiply': {
- const m = 1.0 - effDensity * (1.0 - g);
- return Math.max(0, Math.min(1, tipAlpha * m));
- }
- case 'subtract': {
- const sub = (1.0 - g) * effDensity;
- return Math.max(0, Math.min(1, tipAlpha - sub * (1.0 - penetration * 0.5)));
- }
- case 'compare': {
- // Physical dry-media height-field tooth:
- // Pigment deposits only where paper fiber ridges reach the tip contact plane;
- // recessed valleys cut cleanly to 0.0 (preventing multi-dab overlap from filling valleys)
- // until heavy pressure compresses soft lead into the troughs.
- const contactHeight = g * (0.22 + 0.78 * tipAlpha);
- const cutoff = effDensity * 0.68;
- const edgeLow = cutoff - 0.05;
- const edgeHigh = cutoff + 0.16;
- const t = Math.max(0, Math.min(1, (contactHeight - edgeLow) / Math.max(0.01, edgeHigh - edgeLow)));
- const tooth = t * t * (3.0 - 2.0 * t);
- return Math.max(0, Math.min(1, tipAlpha * tooth));
- }
- case 'overlay': {
- const ov = tipAlpha < 0.5
- ? 2.0 * tipAlpha * g
- : 1.0 - 2.0 * (1.0 - tipAlpha) * (1.0 - g);
- return Math.max(0, Math.min(1, tipAlpha + (ov - tipAlpha) * effDensity));
- }
- case 'outline': {
- const edgeFactor = 4.0 * tipAlpha * (1.0 - tipAlpha);
- return Math.max(0, Math.min(1, tipAlpha * (1.0 - effDensity * (1.0 - g) * (0.35 + 0.65 * edgeFactor))));
- }
- default:
- return tipAlpha;
- }
-}
-
-/**
- * Applies Clip Studio Paint Post-Correction (levels 1..5) to a finished stroke's knot array,
- * smoothing micro-wobble while strictly preserving endpoints and sharp corner vertices (isCorner).
- */
-export function applyCspPostCorrection(
- points: Point[],
- level: number = 0,
- preserveSharpCorners: boolean = true
-): Point[] {
- const passes = Math.max(0, Math.min(5, Math.round(level)));
- if (passes <= 0 || points.length < 4) return points;
-
- let current = points.map((p) => ({ ...p }));
- const next = points.map((p) => ({ ...p }));
-
- for (let pass = 0; pass < passes; pass++) {
- const n = current.length;
- next[0] = { ...current[0] };
- next[n - 1] = { ...current[n - 1] };
-
- for (let i = 1; i < n - 1; i++) {
- const cur = current[i];
- if (preserveSharpCorners && cur.isCorner) {
- next[i] = { ...cur };
- continue;
- }
- const prev = current[i - 1];
- const nxt = current[i + 1];
-
- // Check local angle so deliberate acute corners (< 115 deg) aren't rounded off
- if (preserveSharpCorners) {
- const ax = cur.x - prev.x;
- const ay = cur.y - prev.y;
- const bx = nxt.x - cur.x;
- const by = nxt.y - cur.y;
- const la = Math.hypot(ax, ay);
- const lb = Math.hypot(bx, by);
- if (la > 1.5 && lb > 1.5) {
- const cos = (ax * bx + ay * by) / (la * lb);
- if (cos < 0.35) {
- next[i] = { ...cur };
- continue;
- }
- }
- }
-
- // [0.25, 0.50, 0.25] zero-phase Gaussian smoothing kernel
- next[i] = {
- ...cur,
- x: prev.x * 0.25 + cur.x * 0.5 + nxt.x * 0.25,
- y: prev.y * 0.25 + cur.y * 0.5 + nxt.y * 0.25,
- width: prev.width * 0.2 + cur.width * 0.6 + nxt.width * 0.2,
- pressure: prev.pressure * 0.2 + cur.pressure * 0.6 + nxt.pressure * 0.2,
- };
- }
-
- for (let i = 0; i < n; i++) {
- current[i] = next[i];
- }
- }
-
- return current;
-}
-
-/**
- * Applies authentic Clip Studio Paint Stroke-Perimeter Watercolor Edge ("Water Edge")
- * onto an isolated stroke ImageData buffer before compositing onto the canvas layer.
- * Produces capillary pigment accumulation & darkening ONLY at the outer silhouette of the entire stroke
- * (eliminating internal fish-scale dab rings!).
- */
-export function applyCspWatercolorEdge(
- strokeImageData: { data: Uint8ClampedArray; width: number; height: number },
- wetEdge: number,
- radiusPx: number = 2.5,
- alphaPower: number = 0.65,
- valuePower: number = 0.55
-): void {
- if (wetEdge <= 0.01) return;
- const { data, width, height } = strokeImageData;
- if (width < 3 || height < 3) return;
-
- const strength = Math.max(0, Math.min(1, wetEdge));
- const r = Math.max(1, Math.min(8, Math.round(radiusPx)));
- const totalPixels = width * height;
-
- // Separable box-blur of stroke alpha channel to detect silhouette boundary gradient
- const alphaOrig = new Float32Array(totalPixels);
- const alphaTemp = new Float32Array(totalPixels);
- for (let i = 0; i < totalPixels; i++) {
- alphaOrig[i] = data[i * 4 + 3] / 255.0;
- }
-
- // Horizontal pass
- const invKernel = 1.0 / (2 * r + 1);
- for (let y = 0; y < height; y++) {
- const row = y * width;
- let sum = alphaOrig[row] * (r + 1);
- for (let k = 1; k <= r; k++) {
- sum += alphaOrig[row + Math.min(width - 1, k)];
- }
- for (let x = 0; x < width; x++) {
- alphaTemp[row + x] = sum * invKernel;
- const leftIdx = Math.max(0, x - r);
- const rightIdx = Math.min(width - 1, x + r + 1);
- sum += alphaOrig[row + rightIdx] - alphaOrig[row + leftIdx];
- }
- }
-
- // Vertical pass + capillary rim modulation
- const aBoost = strength * (0.45 + alphaPower * 1.15);
- const vDarken = strength * (0.25 + valuePower * 0.55);
-
- for (let x = 0; x < width; x++) {
- let sum = alphaTemp[x] * (r + 1);
- for (let k = 1; k <= r; k++) {
- sum += alphaTemp[Math.min(height - 1, k) * width + x];
- }
- for (let y = 0; y < height; y++) {
- const idx = y * width + x;
- const blurredA = sum * invKernel;
- const origA = alphaOrig[idx];
-
- if (origA > 0.015) {
- // Rim is high where pixel is inside the stroke (origA > 0) but near transparent exterior (origA > blurredA)
- const rim = Math.max(0, origA - blurredA) * 2.4;
- if (rim > 0.01) {
- const p = idx * 4;
- const darkScale = Math.max(0.18, 1.0 - rim * vDarken);
- data[p] = Math.round(data[p] * darkScale);
- data[p + 1] = Math.round(data[p + 1] * darkScale);
- data[p + 2] = Math.round(data[p + 2] * darkScale);
- const nextA = Math.min(1.0, origA * (1.0 + rim * aBoost));
- data[p + 3] = Math.round(nextA * 255);
- }
- }
-
- const topIdx = Math.max(0, y - r);
- const botIdx = Math.min(height - 1, y + r + 1);
- sum += alphaTemp[botIdx * width + x] - alphaTemp[topIdx * width + x];
- }
- }
-}
-
-/**
- * Built-in CSP Pressure Curve Presets for quick 1-click studio switching.
- */
-export const CSP_PRESSURE_CURVE_PRESETS: Record<string, { label: string; points: [number, number][] }> = {
- linear: {
- label: 'Linear',
- points: [
- [0, 0],
- [1, 1],
- ],
- },
- 'g-pen': {
- label: 'G-Pen S-Curve',
- points: [
- [0, 0],
- [0.2, 0.08],
- [0.55, 0.52],
- [0.82, 0.88],
- [1, 1],
- ],
- },
- soft: {
- label: 'Soft Touch',
- points: [
- [0, 0],
- [0.25, 0.48],
- [0.65, 0.84],
- [1, 1],
- ],
- },
- firm: {
- label: 'Firm Nib',
- points: [
- [0, 0],
- [0.35, 0.12],
- [0.7, 0.48],
- [1, 1],
- ],
- },
- chisel: {
- label: 'Steep Threshold',
- points: [
- [0, 0],
- [0.15, 0.03],
- [0.45, 0.72],
- [1, 1],
- ],
- },
-};
diff --git a/src/engine/RemoteStrokeRenderer.ts b/src/engine/RemoteStrokeRenderer.ts
new file mode 100644
index 0000000..74f5499
--- /dev/null
+++ b/src/engine/RemoteStrokeRenderer.ts
@@ -0,0 +1,386 @@
+/**
+ * Deterministic remote stroke live-preview renderer.
+ * Routes remote STROKE_START / STROKE_CHUNK packets through the exact same
+ * StrokePipeline (Catmull-Rom + corner-snapping) and WebGL instanced brush engine
+ * used locally, with hash-synchronized brush tip and texture assets.
+ *
+ * Strictly for ephemeral live preview; authoritative raster state arrives via BINARY_TILE.
+ */
+
+import type {
+ BrushSettings,
+ CanvasColorMode,
+ LayerItem,
+ Point,
+ ToolType,
+} from '../types/editor';
+import type { BrushAssetRefs } from '../types/multiplayer';
+import { get2DContext } from '../utils/canvasUtils';
+import { enforceColorMode } from '../utils/colorUtils';
+import {
+ hydrateBrushSettingsFromHashes,
+ onBrushAssetReady,
+} from '../utils/brushAssetSync';
+import { StrokePipeline } from './StrokePipeline';
+import {
+ BrushRenderOptions,
+ buildBrushRenderOptions,
+ canUseWebGlForBrush,
+ drawBrushCubicBezierSegment,
+ drawBrushDot,
+ flushGpuDabs,
+} from './BrushEngine';
+import type { GpuDab } from './WebGlBrushEngine';
+import type { CubicBezierSegment } from './SplineGenerator';
+
+export interface RemoteStrokeSessionOptions {
+ strokeId: string;
+ peerId: string | number;
+ layerId: string;
+ tool: ToolType;
+ brushSettings: BrushSettings;
+ brushAssetRefs?: BrushAssetRefs;
+ startPoint: Point;
+ colorMode: CanvasColorMode;
+ targetLayer?: LayerItem;
+ onRequestAsset?: (hash: string) => void;
+}
+
+const MAX_PREVIEW_POINTS_BUFFER = 4096;
+
+export class RemoteStrokeSession {
+ public readonly strokeId: string;
+ public readonly peerId: string | number;
+ public readonly layerId: string;
+ public readonly tool: ToolType;
+
+ private readonly pipeline = new StrokePipeline();
+ private readonly rawBrushSettings: BrushSettings;
+ private readonly brushAssetRefs?: BrushAssetRefs;
+ private readonly colorMode: CanvasColorMode;
+ private readonly isMonochrome: boolean;
+ private readonly isEraser: boolean;
+ private readonly isBgEraser: boolean;
+
+ private brushSettings: BrushSettings;
+ private points: Point[];
+ private stampRemainderDist = 0;
+ private strokeTotalDistance = 0;
+ private dabCounter = { count: 0 };
+ private gpuBatch: GpuDab[] = [];
+ private assetUnsubscribers: Array<() => void> = [];
+ private disposed = false;
+
+ constructor(opts: RemoteStrokeSessionOptions) {
+ this.strokeId = opts.strokeId;
+ this.peerId = opts.peerId;
+ this.layerId = opts.layerId;
+ this.tool = opts.tool;
+ this.rawBrushSettings = opts.brushSettings;
+ this.brushAssetRefs = opts.brushAssetRefs;
+ this.colorMode = opts.colorMode;
+ this.isEraser = opts.tool === 'eraser';
+ this.isBgEraser =
+ this.isEraser &&
+ (opts.layerId === 'layer-bg' || opts.layerId.startsWith('layer-bg'));
+ this.isMonochrome =
+ !opts.layerId.startsWith('layer-bg') &&
+ (opts.colorMode === 'monochrome' ||
+ opts.targetLayer?.expressionColor === 'monochrome');
+
+ const { hydrated, missingHashes } = hydrateBrushSettingsFromHashes(
+ opts.brushSettings,
+ opts.brushAssetRefs
+ );
+ this.brushSettings = hydrated;
+ this.points = [opts.startPoint];
+
+ if (opts.onRequestAsset) {
+ for (const hash of missingHashes) {
+ opts.onRequestAsset(hash);
+ }
+ }
+ }
+
+ public getBrushSettings(): BrushSettings {
+ return this.brushSettings;
+ }
+
+ public getPoints(): readonly Point[] {
+ return this.points;
+ }
+
+ private resolvePreviewColor(): string {
+ if (this.isBgEraser) return '#ffffff';
+ if (this.isEraser || this.brushSettings.isTransparentInk) return '#ffffff';
+ return enforceColorMode(
+ this.brushSettings.color,
+ this.isMonochrome ? 'monochrome' : this.colorMode
+ );
+ }
+
+ private resolvePreviewOpacity(): number {
+ const baseOpacity = Math.max(0, Math.min(1, this.brushSettings.opacity ?? 1.0));
+ if ((this.isEraser && !this.isBgEraser) || this.brushSettings.isTransparentInk) {
+ return Math.min(0.45, baseOpacity * 0.45);
+ }
+ return baseOpacity;
+ }
+
+ private buildPreviewRenderOptions(): BrushRenderOptions {
+ const bs = this.brushSettings;
+ const strokeHardness = this.isMonochrome ? 1.0 : bs.hardness ?? 1.0;
+ const strokeFlow = this.isMonochrome ? 1.0 : bs.flow ?? 1.0;
+ const strokeSpacing = bs.spacing ?? 0.08;
+ const effectiveAA = this.isMonochrome
+ ? (bs.antiAlias ?? 2) !== 0 && bs.useGpu !== false
+ ? bs.antiAlias ?? 2
+ : 0
+ : bs.antiAlias;
+
+ const effectiveOpacitySensor =
+ bs.opacitySensor ??
+ (bs.usePressure && !this.isMonochrome && !this.isEraser && strokeFlow < 0.99
+ ? { usePressure: true, pressureMin: 0.2 }
+ : undefined);
+
+ return buildBrushRenderOptions(bs, {
+ opacity: 1.0, // Isolated pass; stroke opacity applied to peer draft canvas element
+ flow: strokeFlow,
+ spacing: strokeSpacing,
+ hardness: strokeHardness,
+ antiAlias: effectiveAA,
+ opacitySensor: effectiveOpacitySensor,
+ wetEdge: 0,
+ colorMixing: false,
+ isEraser: false,
+ isBgEraser: false,
+ alphaLocked: false,
+ isTransparentInk: false,
+ useGpu: bs.useGpu !== false,
+ currentStrokeDist: this.strokeTotalDistance,
+ });
+ }
+
+ private bindAssetWatchers(getDraftCanvas: () => HTMLCanvasElement | undefined): void {
+ this.clearAssetWatchers();
+ if (!this.brushAssetRefs) return;
+
+ const { missingHashes, pendingHashes } = hydrateBrushSettingsFromHashes(
+ this.rawBrushSettings,
+ this.brushAssetRefs
+ );
+ const watched = new Set<string>([...missingHashes, ...pendingHashes]);
+ for (const hash of watched) {
+ const unsub = onBrushAssetReady(hash, () => {
+ if (this.disposed) return;
+ const { hydrated } = hydrateBrushSettingsFromHashes(
+ this.rawBrushSettings,
+ this.brushAssetRefs
+ );
+ this.brushSettings = hydrated;
+ const canvas = getDraftCanvas();
+ if (canvas) {
+ this.replayPreview(canvas);
+ }
+ });
+ this.assetUnsubscribers.push(unsub);
+ }
+ }
+
+ private clearAssetWatchers(): void {
+ for (const unsub of this.assetUnsubscribers) {
+ unsub();
+ }
+ this.assetUnsubscribers.length = 0;
+ }
+
+ private resetPipelineState(startPoint: Point, strokeColor: string): void {
+ const bs = this.brushSettings;
+ this.pipeline.beginStroke({
+ stabilizerLevel: 0, // Incoming points are already stabilized by sender StrokePipeline
+ sharpCorners: bs.sharpCorners !== false,
+ brushSize: bs.size,
+ color: strokeColor,
+ });
+
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const padExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + 24);
+ this.pipeline.seedKnot(
+ startPoint.x,
+ startPoint.y,
+ startPoint.pressure,
+ startPoint.width,
+ startPoint.tiltX ?? 0,
+ startPoint.tiltY ?? 0,
+ startPoint.twist ?? 0,
+ startPoint.timestamp ?? 0,
+ padExtra
+ );
+
+ this.dabCounter.count = 0;
+ this.strokeTotalDistance = 0;
+ this.stampRemainderDist = bs.customTipImage
+ ? Math.max(0.15, startPoint.width * (bs.spacing ?? 0.07))
+ : Math.max(0.12, startPoint.width * (bs.spacing ?? 0.08));
+ }
+
+ public start(
+ draftCanvas: HTMLCanvasElement | undefined,
+ getDraftCanvas?: () => HTMLCanvasElement | undefined
+ ): void {
+ if (this.disposed) return;
+ if (getDraftCanvas) {
+ this.bindAssetWatchers(getDraftCanvas);
+ }
+
+ const startPoint = this.points[0];
+ const strokeColor = this.resolvePreviewColor();
+ this.resetPipelineState(startPoint, strokeColor);
+
+ if (!draftCanvas) return;
+ const ctx = get2DContext(draftCanvas);
+ if (!ctx) return;
+
+ ctx.resetTransform();
+ ctx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ draftCanvas.style.opacity = String(this.resolvePreviewOpacity());
+
+ const opts = this.buildPreviewRenderOptions();
+ const useGpu = canUseWebGlForBrush(opts);
+ this.gpuBatch.length = 0;
+
+ drawBrushDot(ctx, startPoint, strokeColor, opts, useGpu ? this.gpuBatch : undefined);
+
+ if (useGpu && this.gpuBatch.length > 0) {
+ if (!flushGpuDabs(ctx, this.gpuBatch, strokeColor, opts)) {
+ drawBrushDot(ctx, startPoint, strokeColor, opts);
+ }
+ this.gpuBatch.length = 0;
+ }
+ }
+
+ public appendChunk(
+ incomingPoints: Point[],
+ draftCanvas: HTMLCanvasElement | undefined
+ ): void {
+ if (this.disposed || incomingPoints.length === 0) return;
+
+ const ctx = draftCanvas ? get2DContext(draftCanvas) : null;
+ const strokeColor = this.resolvePreviewColor();
+ const opts = this.buildPreviewRenderOptions();
+ const useGpu = canUseWebGlForBrush(opts);
+ const bs = this.brushSettings;
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const padExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + 24);
+
+ this.gpuBatch.length = 0;
+ const emittedSegments: CubicBezierSegment[] = [];
+ const preRemainder = this.stampRemainderDist;
+ const preDabCount = this.dabCounter.count;
+
+ for (let i = 0; i < incomingPoints.length; i++) {
+ const pt = incomingPoints[i];
+ if (this.points.length > 0) {
+ const prev = this.points[this.points.length - 1];
+ this.strokeTotalDistance += Math.hypot(pt.x - prev.x, pt.y - prev.y);
+ }
+ if (this.points.length < MAX_PREVIEW_POINTS_BUFFER) {
+ this.points.push(pt);
+ }
+
+ opts.currentStrokeDist = this.strokeTotalDistance;
+
+ this.pipeline.pushStabilizedKnot(
+ pt.x,
+ pt.y,
+ pt.pressure,
+ pt.width,
+ pt.tiltX ?? 0,
+ pt.tiltY ?? 0,
+ pt.twist ?? 0,
+ pt.timestamp ?? 0,
+ Boolean(pt.isCorner),
+ padExtra,
+ (seg) => {
+ if (!ctx) return;
+ if (useGpu) {
+ emittedSegments.push({
+ p0: { ...seg.p0 },
+ c1: { ...seg.c1 },
+ c2: { ...seg.c2 },
+ p3: { ...seg.p3 },
+ });
+ }
+ this.stampRemainderDist = drawBrushCubicBezierSegment(
+ ctx,
+ seg.p0,
+ seg.c1,
+ seg.c2,
+ seg.p3,
+ strokeColor,
+ opts,
+ this.stampRemainderDist,
+ this.dabCounter,
+ useGpu ? this.gpuBatch : undefined
+ );
+ }
+ );
+ }
+
+ if (ctx && useGpu && this.gpuBatch.length > 0) {
+ if (!flushGpuDabs(ctx, this.gpuBatch, strokeColor, opts)) {
+ // Fallback replay of failed GPU batch preserving exact dab counter & remainder
+ this.stampRemainderDist = preRemainder;
+ this.dabCounter.count = preDabCount;
+ for (let i = 0; i < emittedSegments.length; i++) {
+ const seg = emittedSegments[i];
+ this.stampRemainderDist = drawBrushCubicBezierSegment(
+ ctx,
+ seg.p0,
+ seg.c1,
+ seg.c2,
+ seg.p3,
+ strokeColor,
+ opts,
+ this.stampRemainderDist,
+ this.dabCounter
+ );
+ }
+ }
+ this.gpuBatch.length = 0;
+ }
+ }
+
+ /**
+ * Re-renders buffered live preview points through StrokePipeline + WebGL after a hash-synced
+ * brush tip or texture asset finishes decoding mid-stroke.
+ */
+ public replayPreview(draftCanvas: HTMLCanvasElement): void {
+ if (this.disposed || this.points.length === 0) return;
+ const savedPoints = this.points.slice();
+ this.points = [savedPoints[0]];
+ this.start(draftCanvas);
+ if (savedPoints.length > 1) {
+ this.appendChunk(savedPoints.slice(1), draftCanvas);
+ }
+ }
+
+ public dispose(draftCanvas: HTMLCanvasElement | undefined): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.clearAssetWatchers();
+ this.pipeline.abortStroke();
+ this.gpuBatch.length = 0;
+ this.points.length = 0;
+
+ if (draftCanvas) {
+ const ctx = get2DContext(draftCanvas);
+ if (ctx) {
+ ctx.resetTransform();
+ ctx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ }
+ draftCanvas.style.opacity = '';
+ }
+ }
+}
diff --git a/src/engine/StrokePipeline.ts b/src/engine/StrokePipeline.ts
index e8f46cf..e45aa81 100644
--- a/src/engine/StrokePipeline.ts
+++ b/src/engine/StrokePipeline.ts
@@ -419,6 +419,52 @@ export class StrokePipeline {
this.expandDirtyRect(x, y, width + padExtra);
}
+ /**
+ * Advances the deterministic Catmull-Rom + corner-snapping spline window using an already-stabilized
+ * sample (e.g. remote STROKE_CHUNK preview points) without double-applying input stabilization.
+ */
+ public pushStabilizedKnot(
+ x: number,
+ y: number,
+ pressure: number,
+ width: number,
+ tiltX: number = 0,
+ tiltY: number = 0,
+ twist: number = 0,
+ timestamp: number = 0,
+ isCorner: boolean = false,
+ padExtra: number = 0,
+ onSegment?: (seg: CubicBezierSegment, isCorner: boolean) => void
+ ): void {
+ const dtMs = this.hasLastRaw ? Math.max(1, timestamp - this.lastRawTime) : 1;
+ const vx = this.hasLastRaw ? (x - this.lastRawX) / dtMs : 0;
+ const vy = this.hasLastRaw ? (y - this.lastRawY) / dtMs : 0;
+
+ this.lastRawX = x;
+ this.lastRawY = y;
+ this.lastRawTime = timestamp;
+ this.lastVx = vx;
+ this.lastVy = vy;
+ this.hasLastRaw = true;
+
+ this.expandDirtyRect(x, y, width + padExtra);
+ this.advanceSplineKnot(
+ x,
+ y,
+ pressure,
+ width,
+ tiltX,
+ tiltY,
+ twist,
+ timestamp,
+ vx,
+ vy,
+ isCorner,
+ padExtra,
+ onSegment
+ );
+ }
+
/**
* Zero-allocation write of a single raw pointer sample into the Float64Array ring buffer.
* If the buffer is full (2048 unread samples), advances tailIndex to drop the oldest unread sample safely.
diff --git a/src/utils/webglBrushEngine.ts b/src/engine/WebGlBrushEngine.ts
similarity index 75%
rename from src/utils/webglBrushEngine.ts
rename to src/engine/WebGlBrushEngine.ts
index dedb51b..2e22e21 100644
--- a/src/utils/webglBrushEngine.ts
+++ b/src/engine/WebGlBrushEngine.ts
@@ -1,11 +1,5 @@
import { Point, BrushSettings, ToolType } from '../types/editor';
-import { applyColorDynamics } from './stampEngine';
-import { paperGrainTable, GRAIN_SIZE } from './pencilEngine';
-import { computeSubpixelDabDimensions, dabHashFloat, resolveTipFlipSigns } from '../engine/CspBrushEngine';
-/**
- * Information about the host video card powering the WebGL brush engine.
- */
export interface GpuInfo {
isSupported: boolean;
renderer: string;
@@ -13,41 +7,34 @@ export interface GpuInfo {
glVersion: string;
}
-/**
- * GPU Dab instance for batch drawing.
- */
export interface GpuDab {
x: number;
y: number;
width: number;
height: number;
- angle: number; // in radians
+ angle: number;
r: number;
g: number;
b: number;
alpha: number;
pressure: number;
strokeDist: number;
- flipX?: number; // +1 or -1
- flipY?: number; // +1 or -1
+ flipX?: number;
+ flipY?: number;
}
-// -------------------------------------------------------------
-// Shaders for GPU Video Card Execution (Track B: Instanced CSP Dabs)
-// -------------------------------------------------------------
-
const VERTEX_SHADER_SRC = `
precision highp float;
-attribute vec2 a_quadVertex; // [-0.5, 0.5] quad
-attribute vec2 a_center; // dab center in canvas pixels
-attribute vec2 a_size; // width, height
-attribute float a_angle; // rotation in radians
-attribute vec4 a_color; // dab color rgba
-attribute float a_alpha; // dab stamp flow / alpha
-attribute float a_pressure; // stylus pressure
-attribute float a_strokeDist;// cumulative stroke distance
-attribute vec2 a_flip; // horizontal/vertical UV flip (+1 or -1)
+attribute vec2 a_quadVertex;
+attribute vec2 a_center;
+attribute vec2 a_size;
+attribute float a_angle;
+attribute vec4 a_color;
+attribute float a_alpha;
+attribute float a_pressure;
+attribute float a_strokeDist;
+attribute vec2 a_flip;
uniform vec2 u_canvasResolution;
uniform vec2 u_dirtyOffset;
@@ -64,14 +51,13 @@ varying vec2 v_size;
void main() {
vec2 flipSign = vec2(a_flip.x == 0.0 ? 1.0 : a_flip.x, a_flip.y == 0.0 ? 1.0 : a_flip.y);
v_uv = a_quadVertex * flipSign + 0.5;
- v_localPos = a_quadVertex * 2.0; // [-1.0, 1.0]
+ v_localPos = a_quadVertex * 2.0;
v_color = a_color;
v_alpha = a_alpha;
v_pressure = a_pressure;
v_strokeDist = a_strokeDist;
v_size = a_size;
- // Rotate quad vertex
float cosA = cos(a_angle);
float sinA = sin(a_angle);
vec2 scaled = a_quadVertex * a_size;
@@ -83,9 +69,8 @@ void main() {
vec2 worldPixelPos = a_center + rotated;
v_worldPos = worldPixelPos;
- // Convert local dirty-rect pixel coordinates [0, dirtyW] x [0, dirtyH] to WebGL clip space [-1, 1] x [1, -1]
vec2 clipPos = ((worldPixelPos - u_dirtyOffset) / u_canvasResolution) * 2.0 - 1.0;
- clipPos.y = -clipPos.y; // Invert Y for canvas coordinate system
+ clipPos.y = -clipPos.y;
gl_Position = vec4(clipPos, 0.0, 1.0);
}
@@ -109,24 +94,24 @@ uniform sampler2D u_tipTexture;
uniform bool u_hasDualTipTexture;
uniform sampler2D u_dualTipTexture;
-uniform int u_dualBlendMode; // 0: multiply, 1: subtract, 2: darken, 3: overlay, 4: screen
-
-uniform int u_antiAlias; // 0: None (binary), 1: Weak, 2: Medium, 3: Strong
-uniform float u_hardness; // 0.0 to 1.0
-uniform float u_wetEdge; // 0.0 to 1.0
-uniform float u_paperGrain; // 0.0 to 1.0 (CSP Paper Tooth density)
-uniform float u_grainScale; // scale of paper texture
-uniform float u_grainRotateRad; // rotation of paper texture
-uniform int u_paperMode; // 0: subtract, 1: multiply, 2: compare, 3: overlay, 4: outline
-uniform float u_paperBrightness; // [-1.0, 1.0]
-uniform float u_paperContrast; // [-1.0, 1.0]
+uniform int u_dualBlendMode;
+
+uniform int u_antiAlias;
+uniform float u_hardness;
+uniform float u_wetEdge;
+uniform float u_paperGrain;
+uniform float u_grainScale;
+uniform float u_grainRotateRad;
+uniform int u_paperMode;
+uniform float u_paperBrightness;
+uniform float u_paperContrast;
uniform bool u_paperInvert;
uniform bool u_hasPaperTex;
uniform sampler2D u_paperTexture;
uniform vec2 u_paperTexSize;
-uniform bool u_colorMixing; // CSP Color Mixing active
-uniform bool u_perceptualMixing; // OKLab + Kubelka-Munk spectral pigment mixing
+uniform bool u_colorMixing;
+uniform bool u_perceptualMixing;
uniform bool u_hasCanvasTexture;
uniform sampler2D u_canvasTexture;
uniform vec2 u_canvasResolution;
@@ -137,7 +122,6 @@ uniform float u_colorStretch;
uniform bool u_isEraser;
uniform bool u_isBgEraser;
-// Evaluates seamless paper grain from uploaded 512x512 cold-press texture or custom paper image
float samplePaperTooth(vec2 worldPos) {
float invScale = 1.0 / max(0.05, u_grainScale);
float c = cos(u_grainRotateRad);
@@ -148,7 +132,6 @@ float samplePaperTooth(vec2 worldPos) {
if (u_hasPaperTex) {
vec2 uv = fract(rotP / max(vec2(1.0), u_paperTexSize));
vec4 pSample = texture2D(u_paperTexture, uv);
- // Support both luminance (R=G=B) and alpha-encoded CSP paper textures
float lum = dot(pSample.rgb, vec3(0.299, 0.587, 0.114));
g = pSample.a < 0.98 ? (1.0 - pSample.a) : lum;
} else {
@@ -171,7 +154,6 @@ float samplePaperTooth(vec2 worldPos) {
return clamp(g, 0.0, 1.0);
}
-// Perceptual Kubelka-Munk + Spectral Yellow-Blue Pigment Mixing on GPU
vec3 mixPigmentsGpu(vec3 c1, vec3 c2, float w2) {
float w1 = 1.0 - w2;
vec3 l1 = pow(max(c1, vec3(0.0)), vec3(2.2));
@@ -200,7 +182,6 @@ void main() {
float dist = length(v_localPos);
vec3 rgb = v_color.rgb;
- // 1. Base tip profile, CSP 4-level Anti-Aliasing, and Color Tip support
float tipAlpha = 1.0;
if (u_hasTipTexture) {
vec4 tex = texture2D(u_tipTexture, v_uv);
@@ -216,7 +197,6 @@ void main() {
discard;
}
if (u_antiAlias == 0) {
- // Binary 1-bit manga pen (zero feather)
tipAlpha = dist <= 1.0 ? 1.0 : 0.0;
} else {
float aaPx = u_antiAlias == 1 ? 1.3 : (u_antiAlias == 3 ? 3.8 : 2.2);
@@ -224,7 +204,6 @@ void main() {
float aa = clamp(aaPx / minDim, 0.015, 0.92);
float clampedH = clamp(u_hardness, 0.0, 1.0);
if (clampedH <= 0.05) {
- // Silky Gaussian cosine falloff for soft airbrush
tipAlpha = 0.5 * (1.0 + cos(min(1.0, dist) * 3.14159265));
} else {
float edge = min(clampedH, 1.0 - aa);
@@ -233,7 +212,6 @@ void main() {
}
}
- // 1b. Dual-Brush Texture Modulation
if (u_hasDualTipTexture) {
vec4 dualTex = texture2D(u_dualTipTexture, v_uv);
float dualA = dualTex.a;
@@ -254,7 +232,6 @@ void main() {
discard;
}
- // 2. CSP 5-Mode Paper Grain / Canvas Tooth
if (u_paperGrain > 0.001) {
float g = samplePaperTooth(v_worldPos);
float p = clamp(v_pressure, 0.0, 1.0);
@@ -263,24 +240,19 @@ void main() {
float effDensity = u_paperGrain * (1.0 - penetration * 0.85);
if (u_paperMode == 1) {
- // Multiply
tipAlpha *= (1.0 - effDensity * (1.0 - g));
} else if (u_paperMode == 2) {
- // Compare: physical dry-media height-field tooth (true zero in recessed paper valleys)
float contactHeight = g * (0.22 + 0.78 * tipAlpha);
float cutoff = effDensity * 0.68;
float tooth = smoothstep(cutoff - 0.05, cutoff + 0.16, contactHeight);
tipAlpha *= tooth;
} else if (u_paperMode == 3) {
- // Overlay
float ov = tipAlpha < 0.5 ? (2.0 * tipAlpha * g) : (1.0 - 2.0 * (1.0 - tipAlpha) * (1.0 - g));
tipAlpha = mix(tipAlpha, ov, effDensity);
} else if (u_paperMode == 4) {
- // Outline
float edgeFactor = 4.0 * tipAlpha * (1.0 - tipAlpha);
tipAlpha *= (1.0 - effDensity * (1.0 - g) * (0.35 + 0.65 * edgeFactor));
} else {
- // Subtract (CSP default valley-fill physics)
float sub = (1.0 - g) * effDensity * (1.0 - penetration * 0.5);
tipAlpha = max(0.0, tipAlpha - sub);
}
@@ -290,7 +262,6 @@ void main() {
}
}
- // 3. Optional GPU Color Mixing fallback
if (u_colorMixing && u_hasCanvasTexture && !u_isEraser) {
vec2 docRes = max(vec2(1.0), u_docResolution);
vec2 canvasUv = clamp(v_worldPos / docRes, 0.0, 1.0);
@@ -309,7 +280,6 @@ void main() {
}
}
- // 4. Final Alpha computation
float finalAlpha = clamp(tipAlpha * v_alpha, 0.0, 1.0);
if (u_antiAlias == 0) {
finalAlpha = finalAlpha >= 0.5 ? 1.0 : 0.0;
@@ -321,16 +291,11 @@ void main() {
} else if (u_isEraser) {
gl_FragColor = vec4(0.0, 0.0, 0.0, finalAlpha);
} else {
- // Premultiplied alpha for seamless blending
gl_FragColor = vec4(rgb * finalAlpha, finalAlpha);
}
}
`;
-// -------------------------------------------------------------
-// Shaders for Track A: Ribbon Inking Engine (G-Pen / Manga Lines)
-// -------------------------------------------------------------
-
const RIBBON_VERTEX_SHADER_SRC = `
precision highp float;
@@ -382,11 +347,13 @@ void main() {
const MAX_TILE_CHUNK = 2048;
/**
- * WebGL-accelerated GPU brush engine.
- * Executes authentic Clip Studio Paint brush mathematics on the GPU with zero per-call driver queries.
+ * WebGL1/WebGL2 GPU hardware brush rasterizer.
+ * Executes instanced dab batches and ribbon meshes with zero per-draw driver queries.
*/
export class WebGlBrushEngine {
private static instance: WebGlBrushEngine | null = null;
+ private static builtinGrainTable: Uint8Array | null = null;
+ private static builtinGrainSize: number = 512;
private canvas: HTMLCanvasElement | null = null;
private gl: WebGLRenderingContext | WebGL2RenderingContext | null = null;
@@ -400,18 +367,16 @@ export class WebGlBrushEngine {
glVersion: 'None',
};
- // Cached Attribute Locations (Instanced Dab) — zero getAttribLocation calls during draw!
- private aQuadVertexLoc: number = -1;
- private aCenterLoc: number = -1;
- private aSizeLoc: number = -1;
- private aAngleLoc: number = -1;
- private aColorLoc: number = -1;
- private aAlphaLoc: number = -1;
- private aPressureLoc: number = -1;
- private aStrokeDistLoc: number = -1;
- private aFlipLoc: number = -1;
-
- // Cached Uniform Locations (Instanced Dab)
+ private aQuadVertexLoc = -1;
+ private aCenterLoc = -1;
+ private aSizeLoc = -1;
+ private aAngleLoc = -1;
+ private aColorLoc = -1;
+ private aAlphaLoc = -1;
+ private aPressureLoc = -1;
+ private aStrokeDistLoc = -1;
+ private aFlipLoc = -1;
+
private uCanvasResolutionLoc: WebGLUniformLocation | null = null;
private uDocResolutionLoc: WebGLUniformLocation | null = null;
private uDirtyOffsetLoc: WebGLUniformLocation | null = null;
@@ -444,26 +409,22 @@ export class WebGlBrushEngine {
private uIsEraserLoc: WebGLUniformLocation | null = null;
private uIsBgEraserLoc: WebGLUniformLocation | null = null;
- // Cached Locations (Ribbon Mesh)
private uRibbonCanvasResolutionLoc: WebGLUniformLocation | null = null;
private uRibbonDirtyOffsetLoc: WebGLUniformLocation | null = null;
- private aRibbonPosLoc: number = -1;
- private aRibbonNormalDistLoc: number = -1;
- private aRibbonColorLoc: number = -1;
- private aRibbonWidthLoc: number = -1;
+ private aRibbonPosLoc = -1;
+ private aRibbonNormalDistLoc = -1;
+ private aRibbonColorLoc = -1;
+ private aRibbonWidthLoc = -1;
- // Textures cache
private tipTexturesMap = new Map<string, WebGLTexture>();
private builtinPaperTexture: WebGLTexture | null = null;
private canvasLayerTexture: WebGLTexture | null = null;
- // Offscreen GPU FBO for instanced dab rendering (WebGL2 fast path)
private dabFbo: WebGLFramebuffer | null = null;
private dabFboTex: WebGLTexture | null = null;
- private dabFboWidth: number = 0;
- private dabFboHeight: number = 0;
+ private dabFboWidth = 0;
+ private dabFboHeight = 0;
- // Dab geometry & instancing buffers (stride 14 floats)
private quadVertexBuffer: WebGLBuffer | null = null;
private extInstanced: {
drawArraysInstanced: (mode: number, first: number, count: number, instanceCount: number) => void;
@@ -472,10 +433,17 @@ export class WebGlBrushEngine {
private instanceBuffer: WebGLBuffer | null = null;
private instanceArray: Float32Array = new Float32Array(4096 * 14);
- // Ribbon geometry buffers (stride 8)
private ribbonBuffer: WebGLBuffer | null = null;
private ribbonArray: Float32Array = new Float32Array(1024 * 8);
+ public static setBuiltinPaperGrain(table: Uint8Array, size: number): void {
+ WebGlBrushEngine.builtinGrainTable = table;
+ WebGlBrushEngine.builtinGrainSize = size;
+ if (WebGlBrushEngine.instance?.gl && !WebGlBrushEngine.instance.builtinPaperTexture) {
+ WebGlBrushEngine.instance.uploadBuiltinPaperTexture(WebGlBrushEngine.instance.gl);
+ }
+ }
+
private constructor() {
if (typeof document !== 'undefined') {
const c = document.createElement('canvas');
@@ -548,14 +516,8 @@ export class WebGlBrushEngine {
}
const glVersion = (typeof gl.getParameter === 'function' && gl.getParameter(gl.VERSION)) || 'WebGL';
- this.gpuInfo = {
- isSupported: true,
- renderer,
- vendor,
- glVersion,
- };
+ this.gpuInfo = { isSupported: true, renderer, vendor, glVersion };
- // 1. Compile Instanced Dab shader pipeline
const vs = this.compileShader(gl.VERTEX_SHADER, VERTEX_SHADER_SRC);
const fs = this.compileShader(gl.FRAGMENT_SHADER, FRAGMENT_SHADER_SRC);
@@ -567,7 +529,6 @@ export class WebGlBrushEngine {
gl.linkProgram(program);
if (gl.getProgramParameter(program, gl.LINK_STATUS)) {
this.program = program;
- // Cache ALL attribute locations once at link time
this.aQuadVertexLoc = gl.getAttribLocation(program, 'a_quadVertex');
this.aCenterLoc = gl.getAttribLocation(program, 'a_center');
this.aSizeLoc = gl.getAttribLocation(program, 'a_size');
@@ -578,7 +539,6 @@ export class WebGlBrushEngine {
this.aStrokeDistLoc = gl.getAttribLocation(program, 'a_strokeDist');
this.aFlipLoc = gl.getAttribLocation(program, 'a_flip');
- // Cache ALL uniform locations once at link time
this.uCanvasResolutionLoc = gl.getUniformLocation(program, 'u_canvasResolution');
this.uDocResolutionLoc = gl.getUniformLocation(program, 'u_docResolution');
this.uDirtyOffsetLoc = gl.getUniformLocation(program, 'u_dirtyOffset');
@@ -614,10 +574,8 @@ export class WebGlBrushEngine {
}
}
- // 2. Compile Track A Ribbon shader pipeline
const rVs = this.compileShader(gl.VERTEX_SHADER, RIBBON_VERTEX_SHADER_SRC);
const rFs = this.compileShader(gl.FRAGMENT_SHADER, RIBBON_FRAGMENT_SHADER_SRC);
-
if (rVs && rFs) {
const rProgram = gl.createProgram();
if (rProgram) {
@@ -636,7 +594,6 @@ export class WebGlBrushEngine {
}
}
- // Static quad vertex buffer
const quadVertices = new Float32Array([
-0.5, -0.5,
0.5, -0.5,
@@ -651,24 +608,23 @@ export class WebGlBrushEngine {
this.ribbonBuffer = gl.createBuffer();
- // Hardware instanced array support
if ('drawArraysInstanced' in gl) {
this.extInstanced = {
- drawArraysInstanced: (mode: number, first: number, count: number, instanceCount: number) => {
- (gl as any).drawArraysInstanced(mode, first, count, instanceCount);
+ drawArraysInstanced: (mode, first, count, instanceCount) => {
+ (gl as WebGL2RenderingContext).drawArraysInstanced(mode, first, count, instanceCount);
},
- vertexAttribDivisor: (index: number, divisor: number) => {
- (gl as any).vertexAttribDivisor(index, divisor);
+ vertexAttribDivisor: (index, divisor) => {
+ (gl as WebGL2RenderingContext).vertexAttribDivisor(index, divisor);
},
};
} else if (typeof gl.getExtension === 'function') {
const ext = gl.getExtension('ANGLE_instanced_arrays');
if (ext) {
this.extInstanced = {
- drawArraysInstanced: (mode: number, first: number, count: number, instanceCount: number) => {
+ drawArraysInstanced: (mode, first, count, instanceCount) => {
ext.drawArraysInstancedANGLE(mode, first, count, instanceCount);
},
- vertexAttribDivisor: (index: number, divisor: number) => {
+ vertexAttribDivisor: (index, divisor) => {
ext.vertexAttribDivisorANGLE(index, divisor);
},
};
@@ -676,8 +632,9 @@ export class WebGlBrushEngine {
}
this.instanceBuffer = gl.createBuffer();
- // Upload seamless 512x512 cold-press paper grain texture once at startup
- this.uploadBuiltinPaperTexture(gl);
+ if (WebGlBrushEngine.builtinGrainTable) {
+ this.uploadBuiltinPaperTexture(gl);
+ }
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
@@ -689,24 +646,16 @@ export class WebGlBrushEngine {
}
private uploadBuiltinPaperTexture(gl: WebGLRenderingContext): void {
+ const table = WebGlBrushEngine.builtinGrainTable;
+ const size = WebGlBrushEngine.builtinGrainSize;
+ if (!table) return;
try {
const tex = gl.createTexture();
if (!tex) return;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
- // Expand 1-channel 512x512 paperGrainTable to LUMINANCE for WebGL1+2 universal compatibility
- gl.texImage2D(
- gl.TEXTURE_2D,
- 0,
- gl.LUMINANCE,
- GRAIN_SIZE,
- GRAIN_SIZE,
- 0,
- gl.LUMINANCE,
- gl.UNSIGNED_BYTE,
- paperGrainTable
- );
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, size, size, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, table);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
@@ -750,12 +699,8 @@ export class WebGlBrushEngine {
if (this.dabFbo && this.dabFboTex && this.dabFboWidth === width && this.dabFboHeight === height) {
return true;
}
- if (!this.dabFbo) {
- this.dabFbo = gl.createFramebuffer();
- }
- if (!this.dabFboTex) {
- this.dabFboTex = gl.createTexture();
- }
+ if (!this.dabFbo) this.dabFbo = gl.createFramebuffer();
+ if (!this.dabFboTex) this.dabFboTex = gl.createTexture();
if (!this.dabFbo || !this.dabFboTex) return false;
gl.activeTexture(gl.TEXTURE0);
@@ -782,9 +727,6 @@ export class WebGlBrushEngine {
return true;
}
- /**
- * Retrieves or uploads a brush tip or paper texture to GPU memory.
- */
public getOrCreateTipTexture(image: HTMLImageElement, repeatWrap: boolean = false): WebGLTexture | null {
if (!this.gl || !image || !image.src) return null;
if (image.complete === false || (image.naturalWidth || image.width || 0) <= 0) return null;
@@ -815,7 +757,6 @@ export class WebGlBrushEngine {
const texH = image.naturalHeight || image.height || 0;
const isPow2 = texW > 0 && texH > 0 && (texW & (texW - 1)) === 0 && (texH & (texH - 1)) === 0;
if (!repeatWrap && isPow2 && typeof gl.generateMipmap === 'function') {
- // Trilinear mipmapping keeps 128x128 pencil tips crisp and alias-free at 2px-10px sizes
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
} else {
@@ -876,9 +817,6 @@ export class WebGlBrushEngine {
return { r: 0.1, g: 0.1, b: 0.1 };
}
- /**
- * Track A: Ribbon Inking Engine
- */
public renderRibbonSegment(
targetCtx: CanvasRenderingContext2D,
p0: Point,
@@ -1004,13 +942,10 @@ export class WebGlBrushEngine {
const byteStride = 8 * 4;
gl.enableVertexAttribArray(this.aRibbonPosLoc);
gl.vertexAttribPointer(this.aRibbonPosLoc, 2, gl.FLOAT, false, byteStride, 0);
-
gl.enableVertexAttribArray(this.aRibbonNormalDistLoc);
gl.vertexAttribPointer(this.aRibbonNormalDistLoc, 1, gl.FLOAT, false, byteStride, 2 * 4);
-
gl.enableVertexAttribArray(this.aRibbonWidthLoc);
gl.vertexAttribPointer(this.aRibbonWidthLoc, 1, gl.FLOAT, false, byteStride, 3 * 4);
-
gl.enableVertexAttribArray(this.aRibbonColorLoc);
gl.vertexAttribPointer(this.aRibbonColorLoc, 4, gl.FLOAT, false, byteStride, 4 * 4);
@@ -1026,7 +961,7 @@ export class WebGlBrushEngine {
gl.disableVertexAttribArray(this.aRibbonColorLoc);
targetCtx.save();
- targetCtx.globalCompositeOperation = isBgEraser ? 'source-over' : (isEraser ? 'destination-out' : 'source-over');
+ targetCtx.globalCompositeOperation = isBgEraser ? 'source-over' : isEraser ? 'destination-out' : 'source-over';
targetCtx.globalAlpha = 1.0;
targetCtx.drawImage(canvas, 0, 0, dw, dh, sx, sy, dw, dh);
targetCtx.restore();
@@ -1034,11 +969,6 @@ export class WebGlBrushEngine {
return true;
}
- /**
- * Track B: GPU Instanced CSP Stamp Engine
- * Supports unlimited document sizes (>4096px via automatic tile chunking),
- * translated offscreen bake canvases, CSP 4-level AA, 5-mode paper tooth, and Compare-Density wash!
- */
public renderDabsToContext(
targetCtx: CanvasRenderingContext2D,
dabs: GpuDab[],
@@ -1093,7 +1023,6 @@ export class WebGlBrushEngine {
const useOffscreenFbo = this.ensureDabFbo(canvas.width, canvas.height);
- // Pack instance buffer once across all dabs (stride 14 floats)
const stride = 14;
const requiredFloats = dabs.length * stride;
if (this.instanceArray.length < requiredFloats) {
@@ -1105,18 +1034,26 @@ export class WebGlBrushEngine {
for (let i = 0; i < dabs.length; i++) {
const d = dabs[i];
- const sub = computeSubpixelDabDimensions(d.width, d.height, d.alpha, minRenderDim);
+ const renderW = Math.max(minRenderDim, d.width);
+ const renderH = Math.max(minRenderDim, d.height);
+ const scaleW = d.width < minRenderDim ? Math.max(0.04, d.width / renderW) : 1.0;
+ const scaleH = d.height < minRenderDim ? Math.max(0.04, d.height / renderH) : 1.0;
+ const effAlpha =
+ d.width >= minRenderDim && d.height >= minRenderDim
+ ? d.alpha
+ : Math.max(0.003, Math.min(1.0, d.alpha * scaleW * scaleH));
+
const offset = i * stride;
arr[offset + 0] = d.x;
arr[offset + 1] = d.y;
- arr[offset + 2] = sub.renderW;
- arr[offset + 3] = sub.renderH;
+ arr[offset + 2] = renderW;
+ arr[offset + 3] = renderH;
arr[offset + 4] = d.angle;
arr[offset + 5] = d.r;
arr[offset + 6] = d.g;
arr[offset + 7] = d.b;
arr[offset + 8] = 1.0;
- arr[offset + 9] = sub.effAlpha;
+ arr[offset + 9] = effAlpha;
arr[offset + 10] = d.pressure;
arr[offset + 11] = d.strokeDist;
arr[offset + 12] = d.flipX ?? 1.0;
@@ -1129,7 +1066,6 @@ export class WebGlBrushEngine {
}
gl.useProgram(this.program);
-
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
@@ -1156,7 +1092,7 @@ export class WebGlBrushEngine {
? 3
: settings.paperTextureMode === 'outline'
? 4
- : 0; // subtract default
+ : 0;
gl.uniform1i(this.uPaperModeLoc, pMode);
gl.uniform1f(this.uPaperBrightnessLoc, (settings.paperTextureBrightness ?? 0) / 100.0);
gl.uniform1f(this.uPaperContrastLoc, (settings.paperTextureContrast ?? 0) / 100.0);
@@ -1164,15 +1100,17 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uIsEraserLoc, isEraser ? 1 : 0);
gl.uniform1i(this.uIsBgEraserLoc, isBgEraser ? 1 : 0);
- // Bind Paper Texture (custom paper image or built-in 512x512 cold-press grain)
if (paperDensity > 0.001) {
+ if (!this.builtinPaperTexture && WebGlBrushEngine.builtinGrainTable) {
+ this.uploadBuiltinPaperTexture(gl);
+ }
let paperTex: WebGLTexture | null = null;
- let paperW = GRAIN_SIZE;
- let paperH = GRAIN_SIZE;
+ let paperW = WebGlBrushEngine.builtinGrainSize;
+ let paperH = WebGlBrushEngine.builtinGrainSize;
if (settings.paperTextureImage && (settings.paperTextureImage.naturalWidth || settings.paperTextureImage.width)) {
paperTex = this.getOrCreateTipTexture(settings.paperTextureImage, true);
- paperW = settings.paperTextureImage.naturalWidth || settings.paperTextureImage.width || GRAIN_SIZE;
- paperH = settings.paperTextureImage.naturalHeight || settings.paperTextureImage.height || GRAIN_SIZE;
+ paperW = settings.paperTextureImage.naturalWidth || settings.paperTextureImage.width || paperW;
+ paperH = settings.paperTextureImage.naturalHeight || settings.paperTextureImage.height || paperH;
} else {
paperTex = this.builtinPaperTexture;
}
@@ -1189,7 +1127,6 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uHasPaperTexLoc, 0);
}
- // Primary Tip Texture
let tipTex: WebGLTexture | null = null;
if (settings.customTipImage) {
tipTex = this.getOrCreateTipTexture(settings.customTipImage, false);
@@ -1206,7 +1143,6 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uIsColorTipLoc, 0);
}
- // Dual-Brush Tip Texture
let dualTipTex: WebGLTexture | null = null;
if (settings.dualBrush && settings.dualTipImage) {
dualTipTex = this.getOrCreateTipTexture(settings.dualTipImage, false);
@@ -1231,7 +1167,6 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uHasDualTipTextureLoc, 0);
}
- // Optional GPU Color Mixing
const enableColorMix = Boolean(settings.colorMixing) && underlyingCanvas !== undefined;
gl.uniform1i(this.uColorMixingLoc, enableColorMix ? 1 : 0);
gl.uniform1i(this.uPerceptualMixingLoc, settings.perceptualMixing !== false ? 1 : 0);
@@ -1253,7 +1188,6 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uHasCanvasTextureLoc, 0);
}
- // Setup vertex attributes once across tile chunks
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVertexBuffer);
gl.enableVertexAttribArray(this.aQuadVertexLoc);
gl.vertexAttribPointer(this.aQuadVertexLoc, 2, gl.FLOAT, false, 0, 0);
@@ -1313,9 +1247,6 @@ export class WebGlBrushEngine {
targetCtx.imageSmoothingEnabled = false;
}
- // Tile across dirty bounding box in <= 2048x2048 chunks so 70MP B4 600DPI strokes NEVER clip at 4096px.
- // For multi-chunk strokes (e.g. diagonal strokes on 6071x8598), pre-bin dab bounds per chunk so empty
- // chunks are skipped completely and populated chunks use tightened viewports/readbacks.
const chunkCols = Math.ceil(totalW / MAX_TILE_CHUNK);
const chunkRows = Math.ceil(totalH / MAX_TILE_CHUNK);
const isMultiChunk = chunkCols > 1 || chunkRows > 1;
@@ -1326,14 +1257,10 @@ export class WebGlBrushEngine {
if (isMultiChunk) {
const chunkCount = chunkCols * chunkRows;
- cMinX = new Float32Array(chunkCount);
- cMinY = new Float32Array(chunkCount);
- cMaxX = new Float32Array(chunkCount);
- cMaxY = new Float32Array(chunkCount);
- cMinX.fill(Infinity);
- cMinY.fill(Infinity);
- cMaxX.fill(-Infinity);
- cMaxY.fill(-Infinity);
+ cMinX = new Float32Array(chunkCount).fill(Infinity);
+ cMinY = new Float32Array(chunkCount).fill(Infinity);
+ cMaxX = new Float32Array(chunkCount).fill(-Infinity);
+ cMaxY = new Float32Array(chunkCount).fill(-Infinity);
for (let i = 0; i < dabs.length; i++) {
const off = i * stride;
@@ -1377,18 +1304,14 @@ export class WebGlBrushEngine {
if (isMultiChunk && cMinX && cMinY && cMaxX && cMaxY) {
const idx = row * chunkCols + col;
- if (cMinX[idx] >= cMaxX[idx] || cMinY[idx] >= cMaxY[idx]) {
- continue;
- }
+ if (cMinX[idx] >= cMaxX[idx] || cMinY[idx] >= cMaxY[idx]) continue;
rx = Math.max(cx, Math.floor(cMinX[idx]));
ry = Math.max(cy, Math.floor(cMinY[idx]));
const rxEnd = Math.min(chunkMaxX, Math.ceil(cMaxX[idx]));
const ryEnd = Math.min(chunkMaxY, Math.ceil(cMaxY[idx]));
dw = rxEnd - rx;
dh = ryEnd - ry;
- if (dw <= 0 || dh <= 0) {
- continue;
- }
+ if (dw <= 0 || dh <= 0) continue;
}
const viewY = Math.max(0, canvas.height - dh);
@@ -1437,18 +1360,7 @@ export class WebGlBrushEngine {
const gl2 = gl as WebGL2RenderingContext;
gl2.bindFramebuffer(gl2.READ_FRAMEBUFFER, this.dabFbo);
gl2.bindFramebuffer(gl2.DRAW_FRAMEBUFFER, null);
- gl2.blitFramebuffer(
- 0,
- viewY,
- dw,
- viewY + dh,
- 0,
- viewY,
- dw,
- viewY + dh,
- gl2.COLOR_BUFFER_BIT,
- gl2.NEAREST
- );
+ gl2.blitFramebuffer(0, viewY, dw, viewY + dh, 0, viewY, dw, viewY + dh, gl2.COLOR_BUFFER_BIT, gl2.NEAREST);
gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
}
@@ -1470,7 +1382,6 @@ export class WebGlBrushEngine {
this.extInstanced.vertexAttribDivisor(this.aFlipLoc, 0);
gl.disableVertexAttribArray(this.aFlipLoc);
}
-
gl.disableVertexAttribArray(this.aCenterLoc);
gl.disableVertexAttribArray(this.aSizeLoc);
gl.disableVertexAttribArray(this.aAngleLoc);
@@ -1482,200 +1393,4 @@ export class WebGlBrushEngine {
return true;
}
-
- /**
- * Generates deterministic arc-length sampled sub-pixel dabs along a quadratic Bézier curve.
- */
- public generateArcLengthDabs(
- p0: Point,
- control: Point,
- p2: Point,
- settings: BrushSettings,
- color: string,
- startDist: number = 0,
- cumulativeStrokeDist: number = 0
- ): { dabs: GpuDab[]; remainderDist: number; totalStrokeDist: number } {
- const dabs: GpuDab[] = [];
- const rgb = this.parseColor(color);
- const spacingRatio = Math.max(0.02, Math.min(1.0, settings.spacing ?? 0.08));
- const flow = settings.brushDensity ?? settings.flow ?? 0.85;
- const aspect =
- settings.customTipImage && settings.customTipImage.naturalWidth
- ? (settings.customTipImage.naturalHeight || 1) / (settings.customTipImage.naturalWidth || 1)
- : 1.0;
- const baseAngleRad = ((settings.customTipAngle ?? 0) * Math.PI) / 180;
- const angleDynamics = settings.customTipAngleDynamics ?? 'none';
- const baseThickness = settings.thickness ?? 1.0;
- const isVertThickness = Boolean(settings.thicknessVertical);
-
- const chord = Math.hypot(p2.x - p0.x, p2.y - p0.y);
- const avgWidth = Math.max(1, (p0.width + p2.width) / 2);
- const steps = Math.max(8, Math.min(128, Math.ceil(chord / Math.max(0.5, avgWidth * 0.1))));
-
- let accDist = startDist;
- let strokeDist = cumulativeStrokeDist;
-
- let prevX = p0.x;
- let prevY = p0.y;
- let dabSeq = 0;
-
- const dynamics = settings.dynamics;
- const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
- const sizeJitter = Math.max(0, Math.min(1, dynamics?.sizeJitter ?? 0));
- const angleJitter = Math.max(0, Math.min(1, dynamics?.angleJitter ?? 0));
- const roundnessJitter = Math.max(0, Math.min(1, dynamics?.roundnessJitter ?? 0));
- const scatter = Math.max(0, Math.min(5, dynamics?.scatter ?? 0));
- const scatterBothAxes = Boolean(dynamics?.scatterBothAxes);
- const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
- const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
- const secondaryRgb = colorJitterEnabled ? this.parseColor(settings.secondaryColor || '#ffffff') : null;
-
- for (let i = 1; i <= steps; i++) {
- const t = i / steps;
- const it = 1 - t;
-
- const curX = it * it * p0.x + 2 * it * t * control.x + t * t * p2.x;
- const curY = it * it * p0.y + 2 * it * t * control.y + t * t * p2.y;
-
- const dx = curX - prevX;
- const dy = curY - prevY;
- const stepDist = Math.hypot(dx, dy);
-
- accDist += stepDist;
- strokeDist += stepDist;
-
- const effPressure = p0.pressure + (p2.pressure - p0.pressure) * t;
- const rawWidth = p0.width + (p2.width - p0.width) * t;
- const curWidth = Math.max(0.25, rawWidth);
-
- const requiredSpacing = Math.max(0.25, curWidth * spacingRatio);
-
- if (accDist >= requiredSpacing) {
- dabSeq++;
- let baseAngle = baseAngleRad;
- if ((angleDynamics === 'direction' || angleDynamics === 'direction-random') && stepDist > 0.001) {
- baseAngle += Math.atan2(dy, dx);
- }
- if (angleDynamics === 'random' || angleDynamics === 'direction-random') {
- const rScale = settings.customTipRotationRandomScale ?? 1.0;
- baseAngle += (dabHashFloat(curX, curY, dabSeq, 11) - 0.5) * Math.PI * 2 * rScale;
- }
-
- let tx = 1;
- let ty = 0;
- let nx = 0;
- let ny = 1;
- if (stepDist > 0.001) {
- tx = dx / stepDist;
- ty = dy / stepDist;
- nx = -ty;
- ny = tx;
- }
-
- for (let k = 0; k < dabCount; k++) {
- const seedIdx = dabSeq * 16 + k;
- let curDabW = curWidth;
- if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - dabHashFloat(curX, curY, seedIdx, 1) * sizeJitter);
- }
- curDabW = Math.max(0.1, curDabW);
-
- let curDabThickness = baseThickness;
- if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(curX, curY, seedIdx, 2) * roundnessJitter);
- }
-
- let curDabAngle = baseAngle;
- if (angleJitter > 0) {
- curDabAngle += (dabHashFloat(curX, curY, seedIdx, 3) - 0.5) * Math.PI * 2 * angleJitter;
- }
-
- let curDabX = curX;
- let curDabY = curY;
- if (scatter > 0) {
- const perpDist = (dabHashFloat(curX, curY, seedIdx, 4) * 2 - 1) * curWidth * scatter;
- let sOffX = nx * perpDist;
- let sOffY = ny * perpDist;
- if (scatterBothAxes) {
- const tangDist = (dabHashFloat(curX, curY, seedIdx, 5) * 2 - 1) * curWidth * scatter;
- sOffX += tx * tangDist;
- sOffY += ty * tangDist;
- }
- curDabX += sOffX;
- curDabY += sOffY;
- }
-
- let curDabAlpha = flow;
- if (flowJitter > 0) {
- curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(curX, curY, seedIdx, 6) * flowJitter);
- }
-
- let dabR = rgb.r;
- let dabG = rgb.g;
- let dabB = rgb.b;
- if (colorJitterEnabled && dynamics && secondaryRgb) {
- let salt = 20;
- const cd = applyColorDynamics(rgb, secondaryRgb, dynamics, () => dabHashFloat(curX, curY, seedIdx, salt++));
- dabR = cd.r;
- dabG = cd.g;
- dabB = cd.b;
- }
-
- const flips = resolveTipFlipSigns(settings.flipH, settings.flipV, seedIdx, curDabX, curDabY);
- const wOut = isVertThickness ? curDabW * curDabThickness : curDabW;
- const hOut = isVertThickness ? curDabW * aspect : curDabW * aspect * curDabThickness;
-
- if (settings.spray?.enabled) {
- const pCount = settings.spray.density;
- const pSize = Math.max(1, settings.spray.size);
- const radius = curDabW / 2;
- for (let sp = 0; sp < pCount; sp++) {
- const u1 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 31);
- const u2 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 32);
- const r = radius * Math.sqrt(u1) * (1 - (settings.spray.bias || 0) * (1 - u2));
- const th = Math.PI * 2 * dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 33);
- dabs.push({
- x: curDabX + r * Math.cos(th),
- y: curDabY + r * Math.sin(th),
- width: isVertThickness ? pSize * curDabThickness : pSize,
- height: isVertThickness ? pSize * aspect : pSize * aspect * curDabThickness,
- angle: curDabAngle,
- r: dabR,
- g: dabG,
- b: dabB,
- alpha: curDabAlpha,
- pressure: effPressure,
- strokeDist,
- flipX: flips.signX,
- flipY: flips.signY,
- });
- }
- } else {
- dabs.push({
- x: curDabX,
- y: curDabY,
- width: wOut,
- height: hOut,
- angle: curDabAngle,
- r: dabR,
- g: dabG,
- b: dabB,
- alpha: curDabAlpha,
- pressure: effPressure,
- strokeDist,
- flipX: flips.signX,
- flipY: flips.signY,
- });
- }
- }
-
- accDist = 0;
- }
-
- prevX = curX;
- prevY = curY;
- }
-
- return { dabs, remainderDist: accDist, totalStrokeDist: strokeDist };
- }
}
diff --git a/src/hooks/drawing/brushStrokeSession/flushPendingPoints.ts b/src/hooks/drawing/brushStrokeSession/flushPendingPoints.ts
new file mode 100644
index 0000000..ef5fbba
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/flushPendingPoints.ts
@@ -0,0 +1,264 @@
+import { Point } from '../../../types/editor';
+import { calculateStrokeWidth, get2DContext } from '../../../utils/canvasUtils';
+import { canUseWebGlForBrush, flushGpuDabs } from '../../../engine/BrushEngine';
+import { isLinearPressureCurve } from '../../../utils/pressureCurve';
+import { DraftCanvasElement, isBackgroundLayerId } from '../types';
+import {
+ StrokeSessionHelpers,
+ StrokeSessionState,
+ UseBrushStrokeSessionParams,
+} from './types';
+
+export function runFlushPendingPoints(
+ state: StrokeSessionState,
+ params: UseBrushStrokeSessionParams,
+ helpers: StrokeSessionHelpers,
+ skipDisplayArg?: boolean | number
+): void {
+ state.drawRafId = null;
+ if (!params.isDrawingRef.current) return;
+ const isSkipDisplay = skipDisplayArg === true;
+
+ const pipeline = state.strokePipeline;
+ if (pipeline.getPendingCount() === 0) {
+ if (isSkipDisplay) {
+ state.latestPredicted = null;
+ return;
+ }
+ const predData = state.latestPredicted;
+ state.latestPredicted = null;
+ const vRect = helpers.getViewportRect();
+ if (vRect && state.allStrokePoints.length > 0) {
+ helpers.renderPredictedStroke(predData ? predData.predEvents : [], vRect);
+ } else if (state.isPredictedCanvasDirty) {
+ helpers.clearPredictedCanvas();
+ }
+ return;
+ }
+
+ const draftCanvas = params.effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ if (!draftCanvas) return;
+ const draftCtx = get2DContext(draftCanvas);
+ if (!draftCtx) return;
+
+ const bs = helpers.getBrushSettings();
+ const mode = params.colorModeRef.current;
+ const isEraser = helpers.getTool() === 'eraser';
+ const currentLayerId = params.activeLayerIdRef.current;
+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
+ const activeLayer = params.layersRef.current?.find((l) => l.id === currentLayerId);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const isVectorOrMask =
+ activeLayer?.type === 'vector' || params.isMaskModeRef.current;
+ const useWireframeEraser = isVectorOrMask && isEraser && !isBgEraser;
+ const canvas = params.getActiveMaskCanvas();
+ const strokeColor = helpers.resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
+ const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
+ const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
+ const strokeSpacing = bs.spacing ?? 0.08;
+ const hasTaper = Boolean(bs.taper?.useOut || bs.taper?.useIn);
+ const globalCurve = pipeline.getGlobalPressureCurve();
+ const hasCustomGlobalCurve = Boolean(
+ globalCurve && globalCurve.enabled && !isLinearPressureCurve(globalCurve.points)
+ );
+ const hasCustomCurve =
+ hasCustomGlobalCurve || Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
+ const taperEngine = pipeline.getTaperEngine();
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const blurMargin = (1 - strokeHardness) * ((bs.size || 10) * 1.5);
+ const dirtyPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + blurMargin + 24);
+
+ const draftScale = draftCanvas.__draftScale ?? 1.0;
+ const liveAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, draftScale);
+ const liveBrushOpts = helpers.buildLiveBrushOptions(
+ bs,
+ strokeFlow,
+ strokeSpacing,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true,
+ liveAA
+ );
+ const useGpuBatch = !useWireframeEraser && canUseWebGlForBrush(liveBrushOpts);
+
+ const gpuBatch = state.frameGpuDabs;
+ gpuBatch.length = 0;
+
+ const collabActive = Boolean(state.currentStrokeId && params.onCollabStrokeChunkRef.current);
+ const chunkPts: Point[] | null = collabActive ? [] : null;
+ let drewAnySegment = false;
+
+ pipeline.drain({
+ dirtyPadExtra,
+ resolvePoint: (rawX, rawY, rawPressure, stabPressure, pointerType, _vx, _vy, dtMs, out) => {
+ let velocityScale = 1.0;
+ if (bs.velocityDynamics && state.stabilizedPoint) {
+ const dist = Math.hypot(
+ rawX - state.stabilizedPoint.x,
+ rawY - state.stabilizedPoint.y
+ );
+ const speed = dist / Math.max(1, dtMs);
+ velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
+ }
+
+ const baseP = bs.usePressure
+ ? hasCustomCurve
+ ? stabPressure
+ : taperEngine.mapPressure(stabPressure)
+ : rawPressure > 0
+ ? 1.0
+ : 0;
+ const mappedP = bs.usePressure ? taperEngine.smoothPressure(baseP) : baseP;
+ let width = calculateStrokeWidth(
+ bs.size,
+ mappedP,
+ bs.minSizeFactor,
+ bs.usePressure,
+ pointerType,
+ bs.pressureCurveGamma ?? 1.0,
+ velocityScale,
+ bs.pressureCurve
+ );
+ if (isMonochrome && !hasTaper && width < 1.25) {
+ width = 1.25;
+ }
+ out.pressure = mappedP;
+ out.width = width;
+ },
+ onPoint: (sample) => {
+ const pt: Point = {
+ x: sample.x,
+ y: sample.y,
+ pressure: sample.pressure,
+ width: sample.width,
+ tiltX: sample.tiltX,
+ tiltY: sample.tiltY,
+ twist: sample.twist,
+ timestamp: sample.timestamp,
+ isCorner: sample.isCorner,
+ };
+ if (state.allStrokePoints.length > 0) {
+ const prev = state.allStrokePoints[state.allStrokePoints.length - 1];
+ state.strokeTotalDistance += Math.hypot(pt.x - prev.x, pt.y - prev.y);
+ }
+ state.stabilizedPoint = pt;
+ state.lastPointTime = sample.timestamp;
+ state.allStrokePoints.push(pt);
+ state.recentPointsTrail.push({
+ x: pt.x,
+ y: pt.y,
+ t: sample.timestamp || performance.now(),
+ pressure: pt.pressure,
+ width: pt.width,
+ });
+ if (state.recentPointsTrail.length > 16) {
+ state.recentPointsTrail.shift();
+ }
+ if (chunkPts) {
+ chunkPts.push(pt);
+ }
+ },
+ onSegment: (seg) => {
+ drewAnySegment = true;
+ helpers.emitLiveSegment(
+ draftCtx,
+ seg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ useGpuBatch ? gpuBatch : undefined
+ );
+ },
+ });
+
+ if (useGpuBatch && gpuBatch.length > 0) {
+ const liveColor =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ const flushed = flushGpuDabs(draftCtx, gpuBatch, liveColor, liveBrushOpts);
+ if (!flushed) {
+ const pts = state.allStrokePoints;
+ if (pts.length >= 2) {
+ const pA = pts[pts.length - 2];
+ const pB = pts[pts.length - 1];
+ const fallbackSeg = pipeline.getSplineGenerator().generateCornerSegment(pA, pB);
+ helpers.emitLiveSegment(
+ draftCtx,
+ fallbackSeg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ undefined
+ );
+ }
+ }
+ gpuBatch.length = 0;
+ }
+
+ const pDirty = pipeline.dirtyRect;
+ if (Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX)) {
+ const dims = params.dimensionsRef.current;
+ if (!state.dirtyRect) {
+ state.dirtyRect = {
+ minX: Math.max(0, pDirty.minX),
+ minY: Math.max(0, pDirty.minY),
+ maxX: Math.min(dims.width, pDirty.maxX),
+ maxY: Math.min(dims.height, pDirty.maxY),
+ };
+ } else {
+ state.dirtyRect.minX = Math.max(0, Math.min(state.dirtyRect.minX, pDirty.minX));
+ state.dirtyRect.minY = Math.max(0, Math.min(state.dirtyRect.minY, pDirty.minY));
+ state.dirtyRect.maxX = Math.min(dims.width, Math.max(state.dirtyRect.maxX, pDirty.maxX));
+ state.dirtyRect.maxY = Math.min(dims.height, Math.max(state.dirtyRect.maxY, pDirty.maxY));
+ }
+ }
+
+ if (drewAnySegment) {
+ draftCanvas.__draftHasContent = true;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ state.liveNeedsNotify = true;
+ }
+
+ if (state.currentStrokeId && chunkPts && chunkPts.length > 0) {
+ params.onCollabStrokeChunkRef.current?.(state.currentStrokeId, chunkPts);
+ }
+
+ if (!isSkipDisplay && state.liveNeedsNotify) {
+ state.liveNeedsNotify = false;
+ params.activeTileGridRef.current.notifyChange(true);
+ }
+
+ const predData = state.latestPredicted;
+ state.latestPredicted = null;
+ if (!isSkipDisplay) {
+ const vRect = helpers.getViewportRect();
+ if (vRect && state.allStrokePoints.length > 0) {
+ helpers.renderPredictedStroke(predData ? predData.predEvents : [], vRect);
+ } else if (state.isPredictedCanvasDirty) {
+ helpers.clearPredictedCanvas();
+ }
+ }
+}
diff --git a/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts b/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts
new file mode 100644
index 0000000..7c6514c
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts
@@ -0,0 +1,234 @@
+import { BrushSettings, LayerItem } from '../../../types/editor';
+import {
+ screenToCanvasInto,
+ getCanvasToViewportMatrix,
+ get2DContext,
+} from '../../../utils/canvasUtils';
+import { CubicBezierSegment } from '../../../engine/SplineGenerator';
+import {
+ drawBrushCubicBezierSegment,
+ canUseWebGlForBrush,
+ flushGpuDabs,
+ buildBrushRenderOptions,
+} from '../../../engine/BrushEngine';
+import { GpuDab } from '../../../engine/WebGlBrushEngine';
+import { DraftCanvasElement, applySelectionCanvasClip } from '../types';
+import {
+ StrokeSessionHelpers,
+ StrokeSessionState,
+ UseBrushStrokeSessionParams,
+} from './types';
+
+export function emitLiveSegmentToDraft(
+ state: StrokeSessionState,
+ params: UseBrushStrokeSessionParams,
+ helpers: StrokeSessionHelpers,
+ draftCtx: CanvasRenderingContext2D,
+ seg: CubicBezierSegment,
+ bs: BrushSettings,
+ strokeColor: string,
+ strokeHardness: number,
+ strokeFlow: number,
+ strokeSpacing: number,
+ isMonochrome: boolean,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ useWireframeEraser: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ gpuBatch: GpuDab[] | undefined
+): void {
+ const sStart = seg.p0;
+ const c1Pt = seg.c1;
+ const c2Pt = seg.c2;
+ const sEnd = seg.p3;
+
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const segPad = Math.ceil(
+ Math.max(sStart.width, sEnd.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32
+ );
+ const segMinX = Math.min(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) - segPad;
+ const segMinY = Math.min(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) - segPad;
+ const segMaxX = Math.max(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) + segPad;
+ const segMaxY = Math.max(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) + segPad;
+ state.strokePipeline.expandDirtyRectBounds(segMinX, segMinY, segMaxX, segMaxY);
+ helpers.markTouchedTiles(segMinX, segMinY, segMaxX, segMaxY);
+
+ if (useWireframeEraser) {
+ draftCtx.save();
+ draftCtx.lineCap = 'round';
+ draftCtx.lineJoin = 'round';
+ draftCtx.setLineDash([4, 4]);
+ draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
+ draftCtx.lineWidth = Math.max(1, (sStart.width + sEnd.width) / 2);
+ draftCtx.beginPath();
+ draftCtx.moveTo(sStart.x, sStart.y);
+ draftCtx.bezierCurveTo(c1Pt.x, c1Pt.y, c2Pt.x, c2Pt.y, sEnd.x, sEnd.y);
+ draftCtx.stroke();
+ draftCtx.restore();
+ return;
+ }
+
+ const liveColor =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ const draftCanvas = params.effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ const draftScale = draftCanvas?.__draftScale ?? 1.0;
+ const liveAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, draftScale);
+
+ const brushOpts = helpers.buildLiveBrushOptions(
+ bs,
+ strokeFlow,
+ strokeSpacing,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true,
+ liveAA
+ );
+
+ state.stampRemainderDist = drawBrushCubicBezierSegment(
+ draftCtx,
+ sStart,
+ c1Pt,
+ c2Pt,
+ sEnd,
+ liveColor,
+ brushOpts,
+ state.stampRemainderDist,
+ state.liveDabCounter,
+ gpuBatch
+ );
+}
+
+export function renderPredictedStrokeOverlay(
+ state: StrokeSessionState,
+ params: UseBrushStrokeSessionParams,
+ helpers: StrokeSessionHelpers,
+ predEvents: PointerEvent[],
+ vRect: DOMRect
+): void {
+ helpers.clearPredictedCanvas();
+ const bs = helpers.getBrushSettings();
+ if (helpers.getTool() === 'eraser' || bs.isTransparentInk || bs.colorMixing) return;
+ const pipeline = state.strokePipeline;
+ if (pipeline.getKnotCount() < 2) return;
+ const pCanvas = helpers.getPredictedCanvas();
+ if (!pCanvas) return;
+ const pCtx = get2DContext(pCanvas);
+ if (!pCtx) return;
+
+ const dims = params.dimensionsRef.current;
+ const mode = params.colorModeRef.current;
+ const currentLayerId = params.activeLayerIdRef.current;
+ const activeLayer = params.layersRef.current?.find((l) => l.id === currentLayerId);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const strokeColor = helpers.resolveStrokeColor(bs, false, false, isMonochrome, mode);
+ const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
+ const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
+ const strokeSpacing = bs.spacing ?? 0.08;
+
+ const maxPredDist = Math.min(20, Math.max(4, (bs.size || 10) * 1.15));
+ const predCoords = state.predDocCoords;
+ predCoords.length = 0;
+
+ if (predEvents && predEvents.length > 0) {
+ const scratch = state.scratchDocCoord;
+ const pool = state.predCoordPool;
+ const limit = Math.min(predEvents.length, pool.length);
+ for (let i = 0; i < limit; i++) {
+ const ev = predEvents[i];
+ screenToCanvasInto(
+ ev.clientX,
+ ev.clientY,
+ vRect,
+ params.panRef.current,
+ params.zoomRef.current,
+ params.rotationRef.current,
+ dims,
+ scratch,
+ params.flipXRef.current,
+ params.flipYRef.current
+ );
+ const slot = pool[i];
+ slot.x = scratch.x;
+ slot.y = scratch.y;
+ slot.pressure = ev.pressure;
+ predCoords.push(slot);
+ }
+ }
+
+ const scaleX = pCanvas.width / Math.max(1, vRect.width);
+ const scaleY = pCanvas.height / Math.max(1, vRect.height);
+ const matrix = getCanvasToViewportMatrix(
+ params.panRef.current,
+ params.zoomRef.current,
+ params.rotationRef.current,
+ dims,
+ scaleX,
+ scaleY,
+ params.flipXRef.current,
+ params.flipYRef.current
+ );
+
+ pCtx.save();
+ pCtx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);
+ pCtx.beginPath();
+ pCtx.rect(0, 0, dims.width, dims.height);
+ pCtx.clip();
+ applySelectionCanvasClip(pCtx, params.selectionRef.current);
+
+ let predRem = state.stampRemainderDist;
+ const predAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, params.zoomRef.current);
+ const predOpts = buildBrushRenderOptions(bs, {
+ opacity: 1.0,
+ flow: strokeFlow,
+ spacing: strokeSpacing,
+ hardness: strokeHardness,
+ antiAlias: predAA,
+ opacitySensor: helpers.resolveEffectiveOpacitySensor(bs, isMonochrome, false),
+ wetEdge: 0,
+ colorMixing: false,
+ isEraser: false,
+ isBgEraser: false,
+ alphaLocked: false,
+ isTransparentInk: false,
+ });
+
+ const predGpuDabs = state.frameGpuDabs;
+ predGpuDabs.length = 0;
+ const useGpuPred = canUseWebGlForBrush(predOpts);
+
+ state.predDabCounter.count = state.liveDabCounter.count;
+
+ const drew = pipeline.buildPredictedSegments(null, maxPredDist, (seg) => {
+ predRem = drawBrushCubicBezierSegment(
+ pCtx,
+ seg.p0,
+ seg.c1,
+ seg.c2,
+ seg.p3,
+ strokeColor,
+ predOpts,
+ predRem,
+ state.predDabCounter,
+ useGpuPred ? predGpuDabs : undefined
+ );
+ });
+
+ if (useGpuPred && predGpuDabs.length > 0) {
+ flushGpuDabs(pCtx, predGpuDabs, strokeColor, predOpts);
+ predGpuDabs.length = 0;
+ }
+
+ pCtx.restore();
+ if (drew) {
+ state.isPredictedCanvasDirty = true;
+ }
+}
diff --git a/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts
new file mode 100644
index 0000000..dac6a9b
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts
@@ -0,0 +1,393 @@
+import React from 'react';
+import { Point } from '../../../types/editor';
+import { calculateStrokeWidth, get2DContext } from '../../../utils/canvasUtils';
+import { PaintReservoir, LayerPixelSampler } from '../../../utils/colorMixingEngine';
+import { useUiStore } from '../../../stores';
+import { recoveryService } from '../../../services/recoveryService';
+import { isLinearPressureCurve } from '../../../utils/pressureCurve';
+import { DraftCanvasElement, isBackgroundLayerId } from '../types';
+import {
+ StrokeSessionHelpers,
+ StrokeSessionState,
+ UseBrushStrokeSessionParams,
+} from './types';
+import {
+ renderInitialStrokeDot,
+ renderShiftLineInitialSegment,
+ setupDraftCanvasSurface,
+} from './pointerDownInitialStamp';
+
+export function runPointerDown(
+ state: StrokeSessionState,
+ params: UseBrushStrokeSessionParams,
+ helpers: StrokeSessionHelpers,
+ e: React.PointerEvent<HTMLElement>,
+ _coalescedEvents?: PointerEvent[]
+): void {
+ const currentTool = helpers.getTool();
+ const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';
+ if (
+ !isBrushOrEraser ||
+ params.disabled ||
+ e.button !== 0 ||
+ params.activeLayerLockedRef.current ||
+ !params.activeLayerVisibleRef.current
+ ) {
+ return;
+ }
+ e.preventDefault();
+ if (params.isDrawingRef.current) {
+ helpers.abortActiveStroke();
+ }
+
+ const dims = params.dimensionsRef.current;
+ const currentLayerIdCheck = params.activeLayerIdRef.current;
+ if (!currentLayerIdCheck || dims.width <= 0 || dims.height <= 0) return;
+
+ const maskCanvas = params.getActiveMaskCanvas();
+ if (params.isMaskModeRef.current) {
+ params.flushPendingHistoryTasks();
+ if (!maskCanvas) return;
+ }
+
+ if (params.viewportRef.current) {
+ state.cachedViewportRect = params.viewportRef.current.getBoundingClientRect();
+ }
+ const vRect = helpers.getViewportRect();
+ if (!vRect) return;
+
+ const draftCanvas = params.effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ if (!draftCanvas) return;
+
+ if (state.clearDraftRaf !== null) {
+ cancelAnimationFrame(state.clearDraftRaf);
+ state.clearDraftRaf = null;
+ }
+
+ const draftCtx = get2DContext(draftCanvas);
+ if (!draftCtx) return;
+
+ const isEraser = currentTool === 'eraser';
+ const currentLayerId = params.activeLayerIdRef.current;
+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
+ const allLayers = params.layersRef.current || [];
+ const activeLayer = allLayers.find((l) => l.id === currentLayerId);
+ const bs = helpers.getBrushSettings();
+ const mode = params.colorModeRef.current;
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const isVectorLayer = activeLayer?.type === 'vector';
+ const isVectorOrMask = isVectorLayer || params.isMaskModeRef.current;
+ const useWireframeEraser = isVectorOrMask && isEraser && !isBgEraser;
+
+ const draftCompositeOp: GlobalCompositeOperation =
+ isVectorOrMask || isBgEraser
+ ? 'source-over'
+ : isEraser || bs.isTransparentInk
+ ? 'destination-out'
+ : activeLayer?.alphaLocked
+ ? 'source-atop'
+ : 'source-over';
+
+ const draftScale = setupDraftCanvasSurface(
+ params,
+ draftCanvas,
+ draftCtx,
+ vRect,
+ dims,
+ draftCompositeOp,
+ isMonochrome
+ );
+
+ helpers.clearPredictedCanvas();
+
+ if (params.interactionRef.current) {
+ try {
+ params.interactionRef.current.setPointerCapture(e.pointerId);
+ } catch {
+ // Ignore pointer capture errors
+ }
+ }
+ state.activePointerId = e.pointerId;
+ params.isDrawingRef.current = true;
+ recoveryService.setDrawingActive(true);
+
+ const firstEvent = e.nativeEvent;
+ const rawStartPoint = helpers.getCanvasPoint(firstEvent);
+ const isAltOverride = e.altKey;
+ const activeStraightRuler = params.straightRulerRef?.current ?? null;
+ const straightStart = state.straightSnapSession.startStrokePoint(
+ rawStartPoint,
+ activeStraightRuler,
+ params.zoomRef.current || 1.0,
+ isAltOverride
+ );
+ let startPoint = straightStart;
+ if (state.straightSnapSession.isActive()) {
+ state.snapSession.endStroke();
+ helpers.emitConstraintAxisChange(null);
+ } else {
+ state.snapSession.startStroke(rawStartPoint, params.rulerRef.current ?? null, isAltOverride);
+ startPoint = state.snapSession.snapPoint(
+ rawStartPoint,
+ params.rulerRef.current ?? null,
+ isAltOverride
+ );
+ helpers.emitConstraintAxisChange(state.snapSession.getActiveAxis());
+ }
+
+ const strokeColor = helpers.resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
+ const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
+ const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
+ const strokeSpacing = bs.spacing ?? 0.08;
+
+ const globalPressureCurve = useUiStore.getState().appSettings.pressureCurve;
+ const hasCustomGlobalCurve = Boolean(
+ globalPressureCurve &&
+ globalPressureCurve.enabled &&
+ !isLinearPressureCurve(globalPressureCurve.points)
+ );
+
+ const pipeline = state.strokePipeline;
+ pipeline.beginStroke({
+ stabilizerLevel: bs.stabilization ?? 0,
+ zoom: params.zoomRef.current || 1.0,
+ sharpCorners: bs.sharpCorners !== false,
+ brushSize: bs.size,
+ color: strokeColor,
+ pointerId: e.pointerId,
+ globalPressureCurve,
+ });
+
+ const startNow = startPoint.timestamp ?? performance.now();
+ state.lastPointTime = startNow;
+ const hasCustomCurve =
+ hasCustomGlobalCurve || Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
+ const taperEngine = pipeline.getTaperEngine();
+ if (bs.usePressure) {
+ const baseStartP = hasCustomCurve
+ ? startPoint.pressure
+ : taperEngine.mapPressure(startPoint.pressure);
+ const smoothStartP = taperEngine.smoothPressure(baseStartP);
+ startPoint.pressure = smoothStartP;
+ startPoint.width = calculateStrokeWidth(
+ bs.size,
+ smoothStartP,
+ bs.minSizeFactor,
+ bs.usePressure,
+ firstEvent.pointerType,
+ bs.pressureCurveGamma ?? 1.0,
+ 1.0,
+ bs.pressureCurve
+ );
+ }
+ const hasTaper = Boolean(bs.taper?.useOut || bs.taper?.useIn);
+ if (isMonochrome && !hasTaper && startPoint.width < 1.25) {
+ startPoint.width = 1.25;
+ }
+
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const blurMargin = (1 - strokeHardness) * (startPoint.width * 1.5);
+ const r = Math.max(
+ 32,
+ Math.ceil(
+ Math.max(startPoint.width, bs.size || 10) * (2.8 + scatterFactor * 2) + blurMargin + 32
+ )
+ );
+
+ const shiftAction = useUiStore.getState().appSettings.modifierKeys.shift;
+ const prevStrokeEnd = params.lastStrokeEndRef.current;
+ const isShiftLine =
+ Boolean(e.shiftKey) &&
+ shiftAction === 'straight-line' &&
+ !params.isMaskModeRef.current &&
+ prevStrokeEnd !== null &&
+ prevStrokeEnd.layerId === currentLayerId;
+ state.isShiftLineStroke = isShiftLine;
+
+ if (isShiftLine && prevStrokeEnd) {
+ const pLineStart: Point = {
+ x: prevStrokeEnd.x,
+ y: prevStrokeEnd.y,
+ pressure: startPoint.pressure,
+ width: startPoint.width,
+ tiltX: startPoint.tiltX,
+ tiltY: startPoint.tiltY,
+ twist: startPoint.twist,
+ timestamp: startNow - 16,
+ };
+ const pLineMid: Point = {
+ x: (pLineStart.x + startPoint.x) * 0.5,
+ y: (pLineStart.y + startPoint.y) * 0.5,
+ pressure: startPoint.pressure,
+ width: startPoint.width,
+ tiltX: startPoint.tiltX,
+ tiltY: startPoint.tiltY,
+ twist: startPoint.twist,
+ timestamp: startNow - 8,
+ };
+ state.allStrokePoints = [pLineStart, pLineMid, startPoint];
+ pipeline.seedKnot(
+ pLineStart.x,
+ pLineStart.y,
+ pLineStart.pressure,
+ pLineStart.width,
+ pLineStart.tiltX ?? 0,
+ pLineStart.tiltY ?? 0,
+ pLineStart.twist ?? 0,
+ pLineStart.timestamp ?? 0,
+ r
+ );
+ pipeline.seedKnot(
+ pLineMid.x,
+ pLineMid.y,
+ pLineMid.pressure,
+ pLineMid.width,
+ pLineMid.tiltX ?? 0,
+ pLineMid.tiltY ?? 0,
+ pLineMid.twist ?? 0,
+ pLineMid.timestamp ?? 0,
+ r
+ );
+ } else {
+ state.allStrokePoints = [startPoint];
+ pipeline.seedKnot(
+ startPoint.x,
+ startPoint.y,
+ startPoint.pressure,
+ startPoint.width,
+ startPoint.tiltX ?? 0,
+ startPoint.tiltY ?? 0,
+ startPoint.twist ?? 0,
+ startNow,
+ r
+ );
+ }
+
+ state.stabilizedPoint = { ...startPoint };
+ state.lastProcessedPoint.x = startPoint.x;
+ state.lastProcessedPoint.y = startPoint.y;
+ state.hasLastProcessedPoint = true;
+ state.lastQueuedPressure = startPoint.pressure;
+ state.recentPointsTrail = [
+ {
+ x: startPoint.x,
+ y: startPoint.y,
+ t: startNow,
+ pressure: startPoint.pressure,
+ width: startPoint.width,
+ },
+ ];
+ state.strokeTotalDistance =
+ isShiftLine && prevStrokeEnd
+ ? Math.hypot(startPoint.x - prevStrokeEnd.x, startPoint.y - prevStrokeEnd.y)
+ : 0;
+
+ helpers.dispatchPointerStat(startPoint.x, startPoint.y, startPoint.pressure);
+
+ const minInitX =
+ isShiftLine && prevStrokeEnd ? Math.min(startPoint.x, prevStrokeEnd.x) : startPoint.x;
+ const minInitY =
+ isShiftLine && prevStrokeEnd ? Math.min(startPoint.y, prevStrokeEnd.y) : startPoint.y;
+ const maxInitX =
+ isShiftLine && prevStrokeEnd ? Math.max(startPoint.x, prevStrokeEnd.x) : startPoint.x;
+ const maxInitY =
+ isShiftLine && prevStrokeEnd ? Math.max(startPoint.y, prevStrokeEnd.y) : startPoint.y;
+ state.dirtyRect = {
+ minX: Math.max(0, Math.floor(minInitX - r)),
+ minY: Math.max(0, Math.floor(minInitY - r)),
+ maxX: Math.min(dims.width, Math.ceil(maxInitX + r)),
+ maxY: Math.min(dims.height, Math.ceil(maxInitY + r)),
+ };
+ pipeline.expandDirtyRectBounds(
+ state.dirtyRect.minX,
+ state.dirtyRect.minY,
+ state.dirtyRect.maxX,
+ state.dirtyRect.maxY
+ );
+ state.touchedTiles.clear();
+ helpers.markTouchedTiles(
+ state.dirtyRect.minX,
+ state.dirtyRect.minY,
+ state.dirtyRect.maxX,
+ state.dirtyRect.maxY
+ );
+
+ const isWetColor = !isEraser && Boolean(bs.colorMixing);
+ state.isWetColorStroke = isWetColor;
+ state.liveNeedsNotify = false;
+
+ if (isWetColor) {
+ state.layerPixelSampler = new LayerPixelSampler(
+ maskCanvas || dims,
+ currentLayerId,
+ params.activeTileGridRef.current
+ );
+ state.activeReservoir = new PaintReservoir(strokeColor);
+ } else {
+ state.layerPixelSampler = null;
+ state.activeReservoir = null;
+ }
+
+ const strokeId = `stroke-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
+ state.currentStrokeId = strokeId;
+ params.onCollabStrokeStartRef.current?.(strokeId, currentLayerId, bs, currentTool, startPoint);
+
+ state.liveDabCounter.count = 0;
+ state.stampRemainderDist = bs.customTipImage
+ ? Math.max(0.15, startPoint.width * (bs.spacing ?? 0.07))
+ : Math.max(0.12, startPoint.width * (bs.spacing ?? 0.08));
+
+ const firstDotPoint = state.allStrokePoints[0];
+
+ renderInitialStrokeDot(state, helpers, {
+ draftCtx,
+ firstDotPoint,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ draftScale,
+ zoom: params.zoomRef.current,
+ canvas: maskCanvas,
+ activeLayer,
+ });
+
+ if (isShiftLine && prevStrokeEnd) {
+ renderShiftLineInitialSegment(state, helpers, {
+ draftCtx,
+ startPoint,
+ startNow,
+ dirtyRadius: r,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ draftScale,
+ canvas: maskCanvas,
+ activeLayer,
+ });
+ }
+
+ draftCanvas.__draftHasContent = true;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ params.activeTileGridRef.current.notifyChange(true);
+ state.liveNeedsNotify = false;
+
+ if (pipeline.getPendingCount() > 0 && state.drawRafId === null) {
+ state.drawRafId = requestAnimationFrame(helpers.flushPendingPoints);
+ }
+}
diff --git a/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts b/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts
new file mode 100644
index 0000000..6916f21
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts
@@ -0,0 +1,262 @@
+import { BrushSettings, CanvasDimensions, LayerItem, Point } from '../../../types/editor';
+import { getVisibleCanvasBounds } from '../../../utils/canvasUtils';
+import {
+ drawBrushDot,
+ canUseWebGlForBrush,
+ flushGpuDabs,
+} from '../../../engine/BrushEngine';
+import { DraftCanvasElement, applySelectionCanvasClip } from '../types';
+import {
+ StrokeSessionHelpers,
+ StrokeSessionState,
+ UseBrushStrokeSessionParams,
+} from './types';
+
+export function setupDraftCanvasSurface(
+ params: UseBrushStrokeSessionParams,
+ draftCanvas: DraftCanvasElement,
+ draftCtx: CanvasRenderingContext2D,
+ vRect: DOMRect,
+ dims: CanvasDimensions,
+ draftCompositeOp: GlobalCompositeOperation,
+ isMonochrome: boolean
+): number {
+ const rawVis = getVisibleCanvasBounds(
+ vRect,
+ params.panRef.current,
+ params.zoomRef.current,
+ params.rotationRef.current,
+ dims,
+ 128,
+ params.flipXRef.current,
+ params.flipYRef.current
+ );
+ const visMinX = rawVis.maxX > rawVis.minX ? rawVis.minX : 0;
+ const visMinY = rawVis.maxY > rawVis.minY ? rawVis.minY : 0;
+ const visW = Math.max(1, rawVis.maxX > rawVis.minX ? rawVis.maxX - rawVis.minX : dims.width);
+ const visH = Math.max(1, rawVis.maxY > rawVis.minY ? rawVis.maxY - rawVis.minY : dims.height);
+ const MAX_DRAFT_DIM = 3072;
+ const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
+ const screenMatchedScale = Math.max(0.05, (params.zoomRef.current || 1) * dpr * 1.25);
+ const draftScale = Math.min(1.0, screenMatchedScale, MAX_DRAFT_DIM / Math.max(visW, visH));
+ const surfaceW = Math.max(1, Math.ceil(visW * draftScale));
+ const surfaceH = Math.max(1, Math.ceil(visH * draftScale));
+ if (draftCanvas.width !== surfaceW || draftCanvas.height !== surfaceH) {
+ draftCanvas.width = surfaceW;
+ draftCanvas.height = surfaceH;
+ }
+
+ draftCtx.resetTransform();
+ draftCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ draftCanvas.__draftHasContent = false;
+ draftCanvas.__draftCompositeOp = draftCompositeOp;
+ draftCanvas.__draftSpace = 'document';
+ draftCanvas.__draftDocRect = {
+ x: visMinX,
+ y: visMinY,
+ width: surfaceW / draftScale,
+ height: surfaceH / draftScale,
+ };
+ draftCanvas.__draftScale = draftScale;
+ draftCanvas.__draftMonochrome = isMonochrome;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+
+ draftCtx.setTransform(
+ draftScale,
+ 0,
+ 0,
+ draftScale,
+ -visMinX * draftScale,
+ -visMinY * draftScale
+ );
+ draftCtx.save();
+ draftCtx.beginPath();
+ draftCtx.rect(0, 0, dims.width, dims.height);
+ draftCtx.clip();
+ applySelectionCanvasClip(draftCtx, params.selectionRef.current);
+
+ return draftScale;
+}
+
+export interface InitialStampParams {
+ draftCtx: CanvasRenderingContext2D;
+ firstDotPoint: Point;
+ bs: BrushSettings;
+ strokeColor: string;
+ strokeHardness: number;
+ strokeFlow: number;
+ strokeSpacing: number;
+ isMonochrome: boolean;
+ isEraser: boolean;
+ isBgEraser: boolean;
+ useWireframeEraser: boolean;
+ draftScale: number;
+ zoom: number;
+ canvas: HTMLCanvasElement | null;
+ activeLayer: LayerItem | undefined;
+}
+
+export type InitialStampHelpers = Pick<
+ StrokeSessionHelpers,
+ 'resolveLiveAntiAlias' | 'buildLiveBrushOptions' | 'emitLiveSegment'
+>;
+
+export function renderInitialStrokeDot(
+ state: StrokeSessionState,
+ helpers: InitialStampHelpers,
+ opts: InitialStampParams
+): void {
+ const {
+ draftCtx,
+ firstDotPoint,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ draftScale,
+ zoom,
+ canvas,
+ activeLayer,
+ } = opts;
+
+ if (useWireframeEraser) {
+ draftCtx.save();
+ draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
+ draftCtx.setLineDash([3, 3]);
+ draftCtx.lineWidth = Math.max(1, 1.5 / Math.max(0.05, zoom));
+ draftCtx.beginPath();
+ draftCtx.arc(
+ firstDotPoint.x,
+ firstDotPoint.y,
+ Math.max(1, firstDotPoint.width / 2),
+ 0,
+ Math.PI * 2
+ );
+ draftCtx.stroke();
+ draftCtx.restore();
+ return;
+ }
+
+ const liveColor =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ const liveAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, draftScale);
+ const gpuBatch = state.frameGpuDabs;
+ gpuBatch.length = 0;
+
+ const brushOpts = helpers.buildLiveBrushOptions(
+ bs,
+ strokeFlow,
+ strokeSpacing,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true,
+ liveAA
+ );
+ const useGpu = canUseWebGlForBrush(brushOpts);
+ drawBrushDot(draftCtx, firstDotPoint, liveColor, brushOpts, useGpu ? gpuBatch : undefined);
+
+ if (useGpu && gpuBatch.length > 0) {
+ if (!flushGpuDabs(draftCtx, gpuBatch, liveColor, brushOpts)) {
+ drawBrushDot(draftCtx, firstDotPoint, liveColor, brushOpts);
+ }
+ gpuBatch.length = 0;
+ }
+}
+
+export interface ShiftLineSegmentParams extends Omit<InitialStampParams, 'firstDotPoint' | 'zoom'> {
+ startPoint: Point;
+ startNow: number;
+ dirtyRadius: number;
+}
+
+export function renderShiftLineInitialSegment(
+ state: StrokeSessionState,
+ helpers: InitialStampHelpers,
+ opts: ShiftLineSegmentParams
+): void {
+ const {
+ draftCtx,
+ startPoint,
+ startNow,
+ dirtyRadius,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ draftScale,
+ canvas,
+ activeLayer,
+ } = opts;
+
+ const pipeline = state.strokePipeline;
+ const lineSeg = pipeline
+ .getSplineGenerator()
+ .generateCornerSegment(state.allStrokePoints[0], startPoint);
+ const liveAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, draftScale);
+ const liveOpts = helpers.buildLiveBrushOptions(
+ bs,
+ strokeFlow,
+ strokeSpacing,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true,
+ liveAA
+ );
+ const useGpuLine = !useWireframeEraser && canUseWebGlForBrush(liveOpts);
+ const gpuBatch = state.frameGpuDabs;
+ gpuBatch.length = 0;
+
+ helpers.emitLiveSegment(
+ draftCtx,
+ lineSeg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ useGpuLine ? gpuBatch : undefined
+ );
+
+ if (useGpuLine && gpuBatch.length > 0) {
+ const liveColor =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ flushGpuDabs(draftCtx, gpuBatch, liveColor, liveOpts);
+ gpuBatch.length = 0;
+ }
+
+ pipeline.seedKnot(
+ startPoint.x,
+ startPoint.y,
+ startPoint.pressure,
+ startPoint.width,
+ startPoint.tiltX ?? 0,
+ startPoint.tiltY ?? 0,
+ startPoint.twist ?? 0,
+ startNow,
+ dirtyRadius
+ );
+}
diff --git a/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts
new file mode 100644
index 0000000..733d50c
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts
@@ -0,0 +1,208 @@
+import React from 'react';
+import { screenToCanvasInto } from '../../../utils/canvasUtils';
+import { encodePointerType } from '../../../engine/StrokePipeline';
+import { useUiStore } from '../../../stores';
+import { ExtendedPointerEvent } from '../types';
+import {
+ StrokeSessionHelpers,
+ StrokeSessionState,
+ UseBrushStrokeSessionParams,
+} from './types';
+
+export function runPointerMove(
+ state: StrokeSessionState,
+ params: UseBrushStrokeSessionParams,
+ helpers: StrokeSessionHelpers,
+ e: React.PointerEvent<HTMLElement>,
+ coalescedEvents?: PointerEvent[],
+ predictedEvents?: PointerEvent[]
+): void {
+ const extEvent = e as ExtendedPointerEvent;
+ if (!params.isDrawingRef.current || e.pointerId !== state.activePointerId) {
+ const point = helpers.getCanvasPoint(e);
+ helpers.dispatchPointerStat(point.x, point.y, point.pressure);
+ params.onCollabCursorMoveRef.current?.(point.x, point.y, false, helpers.getTool());
+ return;
+ }
+
+ e.preventDefault();
+
+ const vRect = helpers.getViewportRect();
+ if (!vRect) return;
+ const dims = params.dimensionsRef.current;
+
+ const candidateCoalesced: PointerEvent[] | readonly PointerEvent[] | null =
+ coalescedEvents ??
+ extEvent.coalescedEvents ??
+ (typeof e.nativeEvent?.getCoalescedEvents === 'function'
+ ? e.nativeEvent.getCoalescedEvents()
+ : null);
+ let rawCoalesced: PointerEvent[] | readonly PointerEvent[] | null = null;
+ if (candidateCoalesced && candidateCoalesced.length > 0) {
+ const lastC = candidateCoalesced[candidateCoalesced.length - 1];
+ const nativeEvt = e.nativeEvent;
+ if (
+ lastC &&
+ nativeEvt &&
+ Number.isFinite(lastC.clientX) &&
+ Number.isFinite(lastC.clientY) &&
+ Math.hypot(lastC.clientX - nativeEvt.clientX, lastC.clientY - nativeEvt.clientY) <= 1.5
+ ) {
+ rawCoalesced = candidateCoalesced;
+ }
+ }
+ const count = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced.length : 1;
+
+ const pipeline = state.strokePipeline;
+ const scratch = state.scratchDocCoord;
+ const lastProc = state.lastProcessedPoint;
+ const minStepDoc = Math.min(0.25, 0.25 / Math.max(0.05, params.zoomRef.current));
+ const isAltOverride = e.altKey;
+ const isShiftKey = e.shiftKey;
+ const ruler = params.rulerRef.current ?? null;
+ const activeStraightRuler = params.straightRulerRef?.current ?? null;
+ const curPan = params.panRef.current;
+ const curZoom = params.zoomRef.current;
+ const curRot = params.rotationRef.current;
+ const curFlipX = params.flipXRef.current;
+ const curFlipY = params.flipYRef.current;
+
+ let lastQueuedX = 0;
+ let lastQueuedY = 0;
+ let lastQueuedPressure = state.lastQueuedPressure;
+ let hasQueued = false;
+
+ for (let i = 0; i < count; i++) {
+ const cEvent = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced[i] : e.nativeEvent;
+ screenToCanvasInto(
+ cEvent.clientX,
+ cEvent.clientY,
+ vRect,
+ curPan,
+ curZoom,
+ curRot,
+ dims,
+ scratch,
+ curFlipX,
+ curFlipY
+ );
+
+ let cx = scratch.x;
+ let cy = scratch.y;
+ const straightRes = state.straightSnapSession.processPoint(
+ scratch,
+ activeStraightRuler,
+ isAltOverride
+ );
+ if (straightRes.snapped) {
+ cx = straightRes.x;
+ cy = straightRes.y;
+ } else {
+ const snapRes = state.snapSession.processPoint(scratch, ruler, isAltOverride);
+ cx = snapRes.x;
+ cy = snapRes.y;
+ if (snapRes.axis) {
+ helpers.emitConstraintAxisChange(snapRes.axis);
+ } else if (
+ !state.isShiftLineStroke &&
+ isShiftKey &&
+ useUiStore.getState().appSettings.modifierKeys.shift === 'straight-line' &&
+ !ruler?.enabled &&
+ !(activeStraightRuler?.enabled && activeStraightRuler?.snapEnabled) &&
+ state.allStrokePoints.length > 0
+ ) {
+ const originPt = state.allStrokePoints[0];
+ const dx = cx - originPt.x;
+ const dy = cy - originPt.y;
+ const dist = Math.hypot(dx, dy);
+ if (dist > 0.5) {
+ const snapAngle = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);
+ cx = originPt.x + Math.cos(snapAngle) * dist;
+ cy = originPt.y + Math.sin(snapAngle) * dist;
+ }
+ }
+ }
+
+ let cPressure = 0;
+ if (cEvent.pointerType === 'mouse') {
+ cPressure = cEvent.buttons & 1 ? 0.5 : 0;
+ } else {
+ cPressure =
+ cEvent.pressure !== undefined ? Math.max(0, Math.min(1.0, cEvent.pressure)) : 0;
+ }
+
+ if (
+ state.hasLastProcessedPoint &&
+ Math.hypot(cx - lastProc.x, cy - lastProc.y) < minStepDoc &&
+ Math.abs(cPressure - lastQueuedPressure) <= 0.04
+ ) {
+ continue;
+ }
+
+ lastProc.x = cx;
+ lastProc.y = cy;
+ state.hasLastProcessedPoint = true;
+
+ pipeline.enqueueSample(
+ cx,
+ cy,
+ cPressure,
+ cEvent.tiltX ?? 0,
+ cEvent.tiltY ?? 0,
+ cEvent.twist ?? 0,
+ cEvent.timeStamp,
+ encodePointerType(cEvent.pointerType)
+ );
+ lastQueuedX = cx;
+ lastQueuedY = cy;
+ lastQueuedPressure = cPressure;
+ hasQueued = true;
+ }
+
+ state.lastQueuedPressure = lastQueuedPressure;
+
+ const rawPredicted =
+ predictedEvents ??
+ extEvent.predictedEvents ??
+ (typeof e.nativeEvent?.getPredictedEvents === 'function'
+ ? e.nativeEvent.getPredictedEvents()
+ : null);
+
+ if (rawPredicted && rawPredicted.length > 0) {
+ state.latestPredicted = { predEvents: rawPredicted, vRect };
+ } else {
+ state.latestPredicted = null;
+ }
+
+ if (hasQueued) {
+ helpers.dispatchPointerStat(lastQueuedX, lastQueuedY, lastQueuedPressure);
+ params.onCollabCursorMoveRef.current?.(lastQueuedX, lastQueuedY, true, helpers.getTool());
+ }
+
+ if (
+ (pipeline.getPendingCount() > 0 || state.latestPredicted !== null) &&
+ state.drawRafId === null
+ ) {
+ state.drawRafId = requestAnimationFrame(helpers.flushPendingPoints);
+ }
+}
+
+export function runPointerEnter(
+ state: StrokeSessionState,
+ viewportRef: UseBrushStrokeSessionParams['viewportRef'],
+ dispatchPointerStat: StrokeSessionHelpers['dispatchPointerStat']
+): void {
+ if (viewportRef.current) {
+ state.cachedViewportRect = viewportRef.current.getBoundingClientRect();
+ }
+ dispatchPointerStat(null, null, 0);
+}
+
+export function runPointerLeave(
+ isDrawingRef: UseBrushStrokeSessionParams['isDrawingRef'],
+ dispatchPointerStat: StrokeSessionHelpers['dispatchPointerStat']
+): void {
+ if (!isDrawingRef.current) {
+ dispatchPointerStat(null, null, 0);
+ }
+}
diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts b/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts
new file mode 100644
index 0000000..6cff849
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts
@@ -0,0 +1,230 @@
+import {
+ BrushSettings,
+ CanvasSelection,
+ DirtyRect,
+ LayerItem,
+} from '../../../types/editor';
+import { SparseTileGrid, TileFormat } from '../../../utils/tileEngine';
+import { multiplayerService } from '../../../services/multiplayerService';
+import { CubicBezierSegment } from '../../../engine/SplineGenerator';
+import { canUseWebGlForBrush, flushGpuDabs } from '../../../engine/BrushEngine';
+import { PushHistoryStepFn } from '../types';
+import { StrokeSessionHelpers, StrokeSessionState } from './types';
+import { StrokeHistoryToolType } from './pointerUpSpecialCommit';
+
+export function createRasterPostPresentWork(
+ grid: SparseTileGrid,
+ beforeSnapshot: Map<string, { format: TileFormat; data: Uint8Array | null }>,
+ currentLayerId: string,
+ dirtyRect: DirtyRect,
+ toolForHistory: StrokeHistoryToolType,
+ label: string,
+ strokeIdForHistory: string | undefined,
+ enqueueHistoryTask: (task: () => void) => void,
+ pushHistoryStep: PushHistoryStepFn
+): () => void {
+ return () => {
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
+ // Authoritative raster synchronization: emit LZ4 BINARY_TILE immediately before STROKE_FINISH
+ if (tileDeltas.length > 0 && multiplayerService.isConnected()) {
+ multiplayerService.sendTileDeltas(tileDeltas, grid);
+ }
+ enqueueHistoryTask(() => {
+ pushHistoryStep(
+ toolForHistory,
+ label,
+ null,
+ null,
+ currentLayerId,
+ dirtyRect,
+ tileDeltas,
+ undefined,
+ undefined,
+ strokeIdForHistory
+ );
+ });
+ };
+}
+
+export interface DirectDraftCommitParams {
+ state: StrokeSessionState;
+ helpers: Pick<
+ StrokeSessionHelpers,
+ | 'resolveLiveAntiAlias'
+ | 'buildLiveBrushOptions'
+ | 'emitLiveSegment'
+ | 'buildTouchedTileSpans'
+ >;
+ grid: SparseTileGrid;
+ draftCtx: CanvasRenderingContext2D;
+ draftScale: number;
+ draftOriginX: number;
+ draftOriginY: number;
+ dirtyRect: DirtyRect;
+ bs: BrushSettings;
+ currentLayerId: string;
+ activeLayer: LayerItem | undefined;
+ targetFormat: TileFormat;
+ compositeOp: 'source-over' | 'destination-out' | 'source-atop';
+ monoOpts?: {
+ threshold: number;
+ expressBlack: boolean;
+ expressWhite: boolean;
+ };
+ selMaskOpts: {
+ mask: NonNullable<CanvasSelection['mask']>;
+ bounds: CanvasSelection['bounds'];
+ } | null;
+ isEraser: boolean;
+ isBgEraser: boolean;
+ isMonochrome: boolean;
+ strokeColor: string;
+ tailSegments: CubicBezierSegment[];
+ toolForHistory: StrokeHistoryToolType;
+ label: string;
+ strokeIdForHistory: string | undefined;
+ enqueueHistoryTask: (task: () => void) => void;
+ pushHistoryStep: PushHistoryStepFn;
+}
+
+export function commitDirectDraftToTiles(opts: DirectDraftCommitParams): () => void {
+ const {
+ state,
+ helpers,
+ grid,
+ draftCtx,
+ draftScale,
+ draftOriginX,
+ draftOriginY,
+ dirtyRect,
+ bs,
+ currentLayerId,
+ activeLayer,
+ targetFormat,
+ compositeOp,
+ monoOpts,
+ selMaskOpts,
+ isEraser,
+ isBgEraser,
+ isMonochrome,
+ strokeColor,
+ tailSegments,
+ toolForHistory,
+ label,
+ strokeIdForHistory,
+ enqueueHistoryTask,
+ pushHistoryStep,
+ } = opts;
+
+ const { x: sx, y: sy, width: dw, height: dh } = dirtyRect;
+
+ // Fast path: 1:1 draft canvas already has the rendered stroke; emit only sealed tail segments
+ if (tailSegments.length > 0) {
+ const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
+ const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
+ const strokeSpacing = bs.spacing ?? 0.08;
+ const liveAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, draftScale);
+ const liveBrushOpts = helpers.buildLiveBrushOptions(
+ bs,
+ strokeFlow,
+ strokeSpacing,
+ strokeHardness,
+ isMonochrome,
+ null,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true,
+ liveAA
+ );
+ const useGpuTail = canUseWebGlForBrush(liveBrushOpts);
+ const gpuBatch = state.frameGpuDabs;
+ gpuBatch.length = 0;
+
+ for (let i = 0; i < tailSegments.length; i++) {
+ helpers.emitLiveSegment(
+ draftCtx,
+ tailSegments[i],
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ false,
+ null,
+ activeLayer,
+ useGpuTail ? gpuBatch : undefined
+ );
+ }
+
+ if (useGpuTail && gpuBatch.length > 0) {
+ const liveColor =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ const flushed = flushGpuDabs(draftCtx, gpuBatch, liveColor, liveBrushOpts);
+ if (!flushed) {
+ for (let i = 0; i < tailSegments.length; i++) {
+ helpers.emitLiveSegment(
+ draftCtx,
+ tailSegments[i],
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ false,
+ null,
+ activeLayer,
+ undefined
+ );
+ }
+ }
+ gpuBatch.length = 0;
+ }
+ }
+
+ const beforeSnapshot = new Map<
+ string,
+ { format: TileFormat; data: Uint8Array | null }
+ >();
+ const spans = helpers.buildTouchedTileSpans(sx, sy, dw, dh);
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ const spanData = draftCtx.getImageData(
+ sp.x - draftOriginX,
+ sp.y - draftOriginY,
+ sp.width,
+ sp.height
+ );
+ grid.compositeStrokeToTiles({
+ layerId: currentLayerId,
+ strokeData: spanData,
+ destX: sp.x,
+ destY: sp.y,
+ format: targetFormat,
+ compositeOp,
+ opacity: bs.opacity ?? 1.0,
+ monochrome: monoOpts,
+ selectionMask: selMaskOpts,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+
+ return createRasterPostPresentWork(
+ grid,
+ beforeSnapshot,
+ currentLayerId,
+ dirtyRect,
+ toolForHistory,
+ label,
+ strokeIdForHistory,
+ enqueueHistoryTask,
+ pushHistoryStep
+ );
+}
diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts
new file mode 100644
index 0000000..e9b8ca1
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts
@@ -0,0 +1,349 @@
+import React from 'react';
+import { CanvasColorMode, VectorStroke } from '../../../types/editor';
+import { TileFormat } from '../../../utils/tileEngine';
+import { get2DContext, applyParametricTaper } from '../../../utils/canvasUtils';
+import { computeClampedBakeDirtyRect } from '../../../engine/StrokePipeline';
+import { CubicBezierSegment } from '../../../engine/SplineGenerator';
+import { recoveryService } from '../../../services/recoveryService';
+import { DraftCanvasElement, isBackgroundLayerId } from '../types';
+import { commitVectorStrokeOrErase } from '../useVectorDrawing';
+import {
+ StrokeSessionHelpers,
+ StrokeSessionState,
+ UseBrushStrokeSessionParams,
+} from './types';
+import {
+ StrokeHistoryToolType,
+ commitMaskModeStroke,
+ resolveStrokeHistoryLabel,
+} from './pointerUpSpecialCommit';
+import { commitRasterStrokeToTiles } from './pointerUpRasterCommit';
+
+export function runPointerUp(
+ state: StrokeSessionState,
+ params: UseBrushStrokeSessionParams,
+ helpers: StrokeSessionHelpers,
+ e: React.PointerEvent<HTMLElement>
+): void {
+ if (!params.isDrawingRef.current || e.pointerId !== state.activePointerId) {
+ return;
+ }
+
+ e.preventDefault();
+ helpers.clearPredictedCanvas();
+
+ if (params.interactionRef.current && params.interactionRef.current.hasPointerCapture(e.pointerId)) {
+ try {
+ params.interactionRef.current.releasePointerCapture(e.pointerId);
+ } catch {
+ // Ignore release errors
+ }
+ }
+
+ if (state.drawRafId !== null) {
+ cancelAnimationFrame(state.drawRafId);
+ state.drawRafId = null;
+ }
+ helpers.flushPendingPoints(true);
+
+ const bs = helpers.getBrushSettings();
+ const dims = params.dimensionsRef.current;
+ const grid = params.activeTileGridRef.current;
+ const endPoint = helpers.getCanvasPoint(e);
+ const draftCanvas = params.effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ const maskCanvas = params.getActiveMaskCanvas();
+
+ const currentTool = helpers.getTool();
+ const currentLayerId = params.activeLayerIdRef.current;
+ const isEraser = currentTool === 'eraser';
+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
+ const mode = params.colorModeRef.current;
+ const isPencil =
+ !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
+
+ const activeLayer = params.layersRef.current?.find((l) => l.id === currentLayerId);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const strokeColor = helpers.resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
+
+ const pipeline = state.strokePipeline;
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const tailPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + 24);
+ const enableFlickTaper =
+ !isEraser &&
+ !state.isShiftLineStroke &&
+ activeLayer?.type !== 'vector' &&
+ Boolean(bs.taper?.useOut);
+
+ let addedFlickPoints = false;
+ const tailSegments: CubicBezierSegment[] = [];
+ pipeline.finalizeStroke(e.nativeEvent?.timeStamp || e.timeStamp || performance.now(), {
+ enableFlickTaper,
+ dirtyPadExtra: tailPadExtra,
+ onPoint: (sample) => {
+ addedFlickPoints = true;
+ state.allStrokePoints.push({
+ x: sample.x,
+ y: sample.y,
+ pressure: sample.pressure,
+ width: sample.width,
+ tiltX: sample.tiltX,
+ tiltY: sample.tiltY,
+ twist: sample.twist,
+ timestamp: sample.timestamp,
+ isCorner: sample.isCorner,
+ });
+ },
+ onSegment: (seg) => {
+ tailSegments.push({
+ p0: { ...seg.p0 },
+ c1: { ...seg.c1 },
+ c2: { ...seg.c2 },
+ p3: { ...seg.p3 },
+ });
+ const segPad = Math.ceil(
+ Math.max(seg.p0.width, seg.p3.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32
+ );
+ const tMinX = Math.min(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) - segPad;
+ const tMinY = Math.min(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) - segPad;
+ const tMaxX = Math.max(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) + segPad;
+ const tMaxY = Math.max(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) + segPad;
+ pipeline.expandDirtyRectBounds(tMinX, tMinY, tMaxX, tMaxY);
+ helpers.markTouchedTiles(tMinX, tMinY, tMaxX, tMaxY);
+ },
+ });
+
+ const pDirty = pipeline.dirtyRect;
+ const mergedDirty = state.dirtyRect
+ ? {
+ minX: Math.min(
+ state.dirtyRect.minX,
+ Number.isFinite(pDirty.minX) ? pDirty.minX : state.dirtyRect.minX
+ ),
+ minY: Math.min(
+ state.dirtyRect.minY,
+ Number.isFinite(pDirty.minY) ? pDirty.minY : state.dirtyRect.minY
+ ),
+ maxX: Math.max(
+ state.dirtyRect.maxX,
+ Number.isFinite(pDirty.maxX) ? pDirty.maxX : state.dirtyRect.maxX
+ ),
+ maxY: Math.max(
+ state.dirtyRect.maxY,
+ Number.isFinite(pDirty.maxY) ? pDirty.maxY : state.dirtyRect.maxY
+ ),
+ }
+ : Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX)
+ ? { ...pDirty }
+ : null;
+
+ let exitSpeed = 0;
+ if (state.recentPointsTrail.length >= 2) {
+ const trail = state.recentPointsTrail;
+ const sampleIdx = Math.max(0, trail.length - 4);
+ const pA = trail[sampleIdx];
+ const pB = trail[trail.length - 1];
+ const dwellMs = Math.max(0, performance.now() - pB.t);
+ const dt = Math.max(1, pB.t - pA.t + dwellMs);
+ exitSpeed = Math.hypot(pB.x - pA.x, pB.y - pA.y) / dt;
+ }
+
+ const shouldTaper =
+ Boolean(bs.taper?.useIn) || (Boolean(bs.taper?.useOut) && !addedFlickPoints);
+ if (shouldTaper && state.allStrokePoints.length >= 3) {
+ applyParametricTaper(state.allStrokePoints, {
+ useIn: Boolean(bs.taper?.useIn),
+ useOut: Boolean(bs.taper?.useOut) && !addedFlickPoints,
+ minSizeFactor: bs.minSizeFactor,
+ exitSpeed,
+ });
+ }
+
+ const allPoints = state.allStrokePoints;
+ let createdVectorStroke: VectorStroke | undefined;
+ let postPresentWork: (() => void) | null = null;
+
+ if (allPoints.length > 0 && !params.isMaskModeRef.current) {
+ const finalPt = allPoints[allPoints.length - 1];
+ params.lastStrokeEndRef.current = {
+ x: finalPt.x,
+ y: finalPt.y,
+ pressure: finalPt.pressure,
+ width: finalPt.width,
+ layerId: currentLayerId,
+ };
+ }
+
+ if (
+ activeLayer?.type === 'vector' &&
+ allPoints.length > 0 &&
+ dims.width > 0 &&
+ dims.height > 0
+ ) {
+ createdVectorStroke = commitVectorStrokeOrErase({
+ activeLayer,
+ currentLayerId,
+ allPoints,
+ bs,
+ isEraser,
+ isPencil,
+ isMonochrome,
+ strokeColor,
+ dims,
+ grid,
+ mergedDirty,
+ strokeId: state.currentStrokeId,
+ pushHistoryStep: params.pushHistoryStep,
+ });
+ } else if (mergedDirty && allPoints.length > 0 && dims.width > 0 && dims.height > 0) {
+ const hasWetEdge =
+ !isMonochrome && !isEraser && !bs.isTransparentInk && (bs.wetEdge ?? 0) > 0.01;
+ const clampedBakeRect = computeClampedBakeDirtyRect(
+ mergedDirty,
+ dims.width,
+ dims.height,
+ bs.size || 10,
+ hasWetEdge ? bs.wetEdge ?? 0 : 0,
+ bs.wetEdgeRadius ?? 3.0
+ );
+
+ if (clampedBakeRect) {
+ const strokeIdForHistory = state.currentStrokeId || undefined;
+ const label = resolveStrokeHistoryLabel(bs, currentTool, isMonochrome);
+ const dirtyRect = clampedBakeRect;
+ const toolForHistory: StrokeHistoryToolType =
+ currentTool === 'eraser' ? 'eraser' : isPencil ? 'pencil' : 'brush';
+ const targetFormat: TileFormat =
+ isMonochrome && !isBackgroundLayerId(currentLayerId) ? 'monochrome-1bit' : 'color-32bit';
+ const effectiveMode: CanvasColorMode = isMonochrome ? 'monochrome' : mode;
+ const activeSelection = params.selectionRef.current;
+
+ if (params.isMaskModeRef.current && maskCanvas) {
+ commitMaskModeStroke({
+ canvas: maskCanvas,
+ dirtyRect,
+ bs,
+ strokeColor,
+ isEraser,
+ currentTool,
+ allPoints,
+ activeSelection,
+ activeLayer,
+ currentLayerId,
+ toolForHistory,
+ strokeIdForHistory,
+ enqueueHistoryTask: params.enqueueHistoryTask,
+ pushHistoryStep: params.pushHistoryStep,
+ });
+ } else {
+ postPresentWork = commitRasterStrokeToTiles({
+ state,
+ helpers,
+ grid,
+ draftCanvas,
+ dirtyRect,
+ dims,
+ bs,
+ currentTool,
+ currentLayerId,
+ activeLayer,
+ activeSelection,
+ effectiveMode,
+ targetFormat,
+ isEraser,
+ isBgEraser,
+ isMonochrome,
+ hasWetEdge,
+ shouldTaper,
+ strokeColor,
+ allPoints,
+ tailSegments,
+ toolForHistory,
+ label,
+ strokeIdForHistory,
+ enqueueHistoryTask: params.enqueueHistoryTask,
+ pushHistoryStep: params.pushHistoryStep,
+ });
+ }
+ }
+ }
+
+ if (state.clearDraftRaf !== null) {
+ cancelAnimationFrame(state.clearDraftRaf);
+ state.clearDraftRaf = null;
+ }
+ if (draftCanvas) {
+ const dCtx = get2DContext(draftCanvas);
+ if (dCtx) {
+ try {
+ dCtx.restore();
+ } catch {
+ // Ignore restore underflow
+ }
+ dCtx.resetTransform();
+ dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ }
+ draftCanvas.__draftHasContent = false;
+ draftCanvas.__draftCompositeOp = 'source-over';
+ draftCanvas.__draftMonochrome = false;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ }
+ helpers.clearPredictedCanvas();
+
+ grid.notifyChange(true);
+ postPresentWork?.();
+
+ if (state.currentStrokeId) {
+ params.onCollabStrokeFinishRef.current?.(
+ state.currentStrokeId,
+ currentLayerId,
+ endPoint,
+ mergedDirty
+ ? {
+ x: Math.max(0, Math.floor(mergedDirty.minX)),
+ y: Math.max(0, Math.floor(mergedDirty.minY)),
+ width: Math.max(
+ 1,
+ Math.ceil(mergedDirty.maxX) - Math.max(0, Math.floor(mergedDirty.minX))
+ ),
+ height: Math.max(
+ 1,
+ Math.ceil(mergedDirty.maxY) - Math.max(0, Math.floor(mergedDirty.minY))
+ ),
+ }
+ : undefined,
+ createdVectorStroke
+ );
+ state.currentStrokeId = null;
+ }
+
+ state.strokePipeline.abortStroke();
+ state.frameGpuDabs.length = 0;
+ params.isDrawingRef.current = false;
+ recoveryService.setDrawingActive(false);
+ state.activePointerId = null;
+ state.allStrokePoints = [];
+ state.stabilizedPoint = null;
+ state.hasLastProcessedPoint = false;
+ state.dirtyRect = null;
+ state.touchedTiles.clear();
+ state.liveNeedsNotify = false;
+ state.isShiftLineStroke = false;
+ state.layerPixelSampler = null;
+ state.activeReservoir = null;
+ state.snapSession.endStroke();
+ state.straightSnapSession.endStroke();
+ helpers.emitConstraintAxisChange(null);
+
+ if (params.isMaskModeRef.current) {
+ params.onUpdateMaskThumbnailRef.current?.(currentLayerId);
+ grid.notifyChange(true);
+ } else {
+ params.enqueueHistoryTask(() => {
+ params.onUpdateLayerThumbnail(currentLayerId);
+ });
+ }
+}
diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts
new file mode 100644
index 0000000..0090d26
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts
@@ -0,0 +1,419 @@
+import {
+ BrushSettings,
+ CanvasColorMode,
+ CanvasDimensions,
+ CanvasSelection,
+ DirtyRect,
+ LayerItem,
+ Point,
+ ToolType,
+} from '../../../types/editor';
+import {
+ SparseTileGrid,
+ TILE_SIZE,
+ TileFormat,
+ releaseTemporaryCanvas,
+} from '../../../utils/tileEngine';
+import { get2DContext, getReusableBakeCanvas } from '../../../utils/canvasUtils';
+import { CubicBezierSegment } from '../../../engine/SplineGenerator';
+import { applyCspWatercolorEdge, renderCompleteStroke } from '../../../engine/BrushEngine';
+import { binarizeImageDataBuffer } from '../../../utils/colorUtils';
+import { LayerPixelSampler } from '../../../utils/colorMixingEngine';
+import {
+ DraftCanvasElement,
+ PushHistoryStepFn,
+ applySelectionCanvasClip,
+ applySelectionMaskToImageData,
+} from '../types';
+import { StrokeSessionHelpers, StrokeSessionState } from './types';
+import { StrokeHistoryToolType } from './pointerUpSpecialCommit';
+import {
+ commitDirectDraftToTiles,
+ createRasterPostPresentWork,
+} from './pointerUpDirectCommit';
+
+export interface CommitRasterStrokeParams {
+ state: StrokeSessionState;
+ helpers: Pick<
+ StrokeSessionHelpers,
+ | 'markTouchedTiles'
+ | 'resolveLiveAntiAlias'
+ | 'buildLiveBrushOptions'
+ | 'emitLiveSegment'
+ | 'buildTouchedTileSpans'
+ | 'resolveEffectiveOpacitySensor'
+ >;
+ grid: SparseTileGrid;
+ draftCanvas: DraftCanvasElement | null | undefined;
+ dirtyRect: DirtyRect;
+ dims: CanvasDimensions;
+ bs: BrushSettings;
+ currentTool: ToolType;
+ currentLayerId: string;
+ activeLayer: LayerItem | undefined;
+ activeSelection: CanvasSelection | null;
+ effectiveMode: CanvasColorMode;
+ targetFormat: TileFormat;
+ isEraser: boolean;
+ isBgEraser: boolean;
+ isMonochrome: boolean;
+ hasWetEdge: boolean;
+ shouldTaper: boolean;
+ strokeColor: string;
+ allPoints: Point[];
+ tailSegments: CubicBezierSegment[];
+ toolForHistory: StrokeHistoryToolType;
+ label: string;
+ strokeIdForHistory: string | undefined;
+ enqueueHistoryTask: (task: () => void) => void;
+ pushHistoryStep: PushHistoryStepFn;
+}
+
+export function commitRasterStrokeToTiles(
+ opts: CommitRasterStrokeParams
+): (() => void) | null {
+ const {
+ state,
+ helpers,
+ grid,
+ draftCanvas,
+ dirtyRect,
+ dims,
+ bs,
+ currentTool,
+ currentLayerId,
+ activeLayer,
+ activeSelection,
+ effectiveMode,
+ targetFormat,
+ isEraser,
+ isBgEraser,
+ isMonochrome,
+ hasWetEdge,
+ shouldTaper,
+ strokeColor,
+ allPoints,
+ tailSegments,
+ toolForHistory,
+ label,
+ strokeIdForHistory,
+ enqueueHistoryTask,
+ pushHistoryStep,
+ } = opts;
+
+ const { x: sx, y: sy, width: dw, height: dh } = dirtyRect;
+ const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;
+ const draftScale = draftCanvas?.__draftScale ?? 0;
+ const draftDocRect = draftCanvas?.__draftDocRect;
+ const compositeOp: 'source-over' | 'destination-out' | 'source-atop' =
+ (isEraser && !isBgEraser) || bs.isTransparentInk
+ ? 'destination-out'
+ : activeLayer?.alphaLocked
+ ? 'source-atop'
+ : 'source-over';
+ const monoOpts =
+ targetFormat === 'monochrome-1bit'
+ ? {
+ threshold: activeLayer?.monoThreshold ?? 128,
+ expressBlack: activeLayer?.monoExpressBlack ?? true,
+ expressWhite: activeLayer?.monoExpressWhite ?? true,
+ }
+ : undefined;
+ const selMaskOpts = activeSelection?.mask
+ ? { mask: activeSelection.mask, bounds: activeSelection.bounds }
+ : null;
+
+ const draftOriginX = draftDocRect ? Math.round(draftDocRect.x) : 0;
+ const draftOriginY = draftDocRect ? Math.round(draftDocRect.y) : 0;
+ const canDirectDraftCommit = Boolean(
+ draftCanvas &&
+ draftCtx &&
+ Math.abs(draftScale - 1.0) < 1e-6 &&
+ draftDocRect &&
+ Math.abs(draftDocRect.x - draftOriginX) < 1e-6 &&
+ Math.abs(draftDocRect.y - draftOriginY) < 1e-6 &&
+ !hasWetEdge &&
+ !bs.colorMixing &&
+ (bs.postCorrection ?? 0) === 0 &&
+ !shouldTaper &&
+ sx >= draftOriginX &&
+ sy >= draftOriginY &&
+ sx + dw <= draftOriginX + draftCanvas.width &&
+ sy + dh <= draftOriginY + draftCanvas.height
+ );
+
+ // For single taps or small strokes, ensure every tile overlapping the padded bake rect is included
+ if (dw * dh <= 4 * TILE_SIZE * TILE_SIZE) {
+ helpers.markTouchedTiles(sx, sy, sx + dw, sy + dh);
+ }
+
+ if (canDirectDraftCommit && draftCanvas && draftCtx && draftDocRect) {
+ return commitDirectDraftToTiles({
+ state,
+ helpers,
+ grid,
+ draftCtx,
+ draftScale,
+ draftOriginX,
+ draftOriginY,
+ dirtyRect,
+ bs,
+ currentLayerId,
+ activeLayer,
+ targetFormat,
+ compositeOp,
+ monoOpts,
+ selMaskOpts,
+ isEraser,
+ isBgEraser,
+ isMonochrome,
+ strokeColor,
+ tailSegments,
+ toolForHistory,
+ label,
+ strokeIdForHistory,
+ enqueueHistoryTask,
+ pushHistoryStep,
+ });
+ }
+
+ if (!bs.colorMixing) {
+ // Fast isolated 1:1 re-bake: never allocates/unpacks existing tiles via createRegionCanvas
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = get2DContext(bakeCanvas);
+ if (!bCtx) return null;
+
+ bCtx.resetTransform();
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ bCtx.beginPath();
+ bCtx.rect(sx, sy, dw, dh);
+ bCtx.clip();
+ applySelectionCanvasClip(bCtx, activeSelection);
+
+ const effectiveOpacitySensor = helpers.resolveEffectiveOpacitySensor(
+ bs,
+ isMonochrome,
+ isEraser
+ );
+ const bakeBs: BrushSettings =
+ effectiveOpacitySensor && !bs.opacitySensor
+ ? { ...bs, opacitySensor: effectiveOpacitySensor }
+ : bs;
+ const allowGpuMonoBake =
+ isMonochrome && (bakeBs.antiAlias ?? 2) !== 0 && bakeBs.useGpu !== false;
+
+ renderCompleteStroke(
+ bCtx,
+ allPoints,
+ {
+ ...bakeBs,
+ opacity: 1.0,
+ isTransparentInk: false,
+ wetEdge: 0,
+ color: isEraser && !isBgEraser ? '#000000' : bakeBs.color,
+ },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ undefined,
+ false,
+ undefined,
+ allowGpuMonoBake
+ );
+ bCtx.restore();
+
+ if (hasWetEdge) {
+ const bakeImg = bCtx.getImageData(0, 0, dw, dh);
+ applyCspWatercolorEdge(
+ bakeImg,
+ bs.wetEdge ?? 0,
+ bs.wetEdgeRadius ?? 3.0,
+ bs.wetEdgeAlphaPower ?? 25,
+ bs.wetEdgeValuePower ?? 15
+ );
+ bCtx.putImageData(bakeImg, 0, 0);
+ }
+
+ const beforeSnapshot = new Map<
+ string,
+ { format: TileFormat; data: Uint8Array | null }
+ >();
+ const spans = helpers.buildTouchedTileSpans(sx, sy, dw, dh);
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ const spanData = bCtx.getImageData(sp.x - sx, sp.y - sy, sp.width, sp.height);
+ grid.compositeStrokeToTiles({
+ layerId: currentLayerId,
+ strokeData: spanData,
+ destX: sp.x,
+ destY: sp.y,
+ format: targetFormat,
+ compositeOp,
+ opacity: bakeBs.opacity ?? 1.0,
+ monochrome: monoOpts,
+ selectionMask: selMaskOpts,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+
+ return createRasterPostPresentWork(
+ grid,
+ beforeSnapshot,
+ currentLayerId,
+ dirtyRect,
+ toolForHistory,
+ label,
+ strokeIdForHistory,
+ enqueueHistoryTask,
+ pushHistoryStep
+ );
+ }
+
+ // Wet color-mixing path requires existing layer pixels on the same canvas
+ const canPoolRegion = dw <= 2048 && dh <= 2048;
+ let pooledCanvas: HTMLCanvasElement | null = null;
+ if (canPoolRegion && typeof document !== 'undefined') {
+ if (!state.reusableRegionCanvas) {
+ state.reusableRegionCanvas = document.createElement('canvas');
+ }
+ pooledCanvas = state.reusableRegionCanvas;
+ }
+ const regionCanvas = grid.createRegionCanvas(currentLayerId, dirtyRect, pooledCanvas);
+ const rCtx = regionCanvas ? get2DContext(regionCanvas) : null;
+ if (!regionCanvas || !rCtx) return null;
+
+ const beforeSelectionData = activeSelection?.mask ? rCtx.getImageData(0, 0, dw, dh) : null;
+
+ rCtx.save();
+ rCtx.translate(-sx, -sy);
+ rCtx.beginPath();
+ rCtx.rect(sx, sy, dw, dh);
+ rCtx.clip();
+ applySelectionCanvasClip(rCtx, activeSelection);
+
+ const effectiveOpacitySensor = helpers.resolveEffectiveOpacitySensor(
+ bs,
+ isMonochrome,
+ isEraser
+ );
+ const bakeBs: BrushSettings =
+ effectiveOpacitySensor && !bs.opacitySensor
+ ? { ...bs, opacitySensor: effectiveOpacitySensor }
+ : bs;
+
+ const allowGpuMonoBake =
+ isMonochrome && (bakeBs.antiAlias ?? 2) !== 0 && bakeBs.useGpu !== false;
+ const needsIsolatedBake = (bakeBs.opacity ?? 1.0) < 0.999 || hasWetEdge;
+ const bakeSampler = !isEraser
+ ? new LayerPixelSampler(dims, currentLayerId, grid)
+ : undefined;
+
+ if (!needsIsolatedBake) {
+ renderCompleteStroke(
+ rCtx,
+ allPoints,
+ bakeBs,
+ currentTool,
+ effectiveMode,
+ isBgEraser,
+ undefined,
+ Boolean(activeLayer?.alphaLocked),
+ bakeSampler,
+ allowGpuMonoBake
+ );
+ } else {
+ rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bakeBs.opacity ?? 1.0));
+ rCtx.globalCompositeOperation = compositeOp;
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = get2DContext(bakeCanvas);
+ if (bCtx) {
+ bCtx.resetTransform();
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ renderCompleteStroke(
+ bCtx,
+ allPoints,
+ {
+ ...bakeBs,
+ opacity: 1.0,
+ isTransparentInk: false,
+ wetEdge: 0,
+ color: isEraser && !isBgEraser ? '#000000' : bakeBs.color,
+ },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ undefined,
+ false,
+ bakeSampler,
+ allowGpuMonoBake
+ );
+ bCtx.restore();
+
+ if (hasWetEdge) {
+ const bakeImg = bCtx.getImageData(0, 0, dw, dh);
+ applyCspWatercolorEdge(
+ bakeImg,
+ bs.wetEdge ?? 0,
+ bs.wetEdgeRadius ?? 3.0,
+ bs.wetEdgeAlphaPower ?? 25,
+ bs.wetEdgeValuePower ?? 15
+ );
+ bCtx.putImageData(bakeImg, 0, 0);
+ }
+
+ rCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
+ }
+ }
+
+ rCtx.restore();
+
+ if (beforeSelectionData && activeSelection?.mask) {
+ const fullAfter = rCtx.getImageData(0, 0, dw, dh);
+ applySelectionMaskToImageData(beforeSelectionData, fullAfter, sx, sy, activeSelection);
+ rCtx.putImageData(fullAfter, 0, 0);
+ }
+
+ const spans = helpers.buildTouchedTileSpans(sx, sy, dw, dh);
+ const beforeSnapshot = new Map<
+ string,
+ { format: TileFormat; data: Uint8Array | null }
+ >();
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ const subSnap = grid.snapshotTilesInRect(currentLayerId, sp);
+ for (const [k, v] of subSnap) {
+ if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
+ }
+ const spanData = rCtx.getImageData(sp.x - sx, sp.y - sy, sp.width, sp.height);
+ if (targetFormat === 'monochrome-1bit') {
+ binarizeImageDataBuffer(
+ spanData,
+ activeLayer?.monoThreshold ?? 128,
+ activeLayer?.monoExpressBlack ?? true,
+ activeLayer?.monoExpressWhite ?? true
+ );
+ }
+ grid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
+ }
+
+ if (!canPoolRegion) {
+ releaseTemporaryCanvas(regionCanvas);
+ }
+
+ return createRasterPostPresentWork(
+ grid,
+ beforeSnapshot,
+ currentLayerId,
+ dirtyRect,
+ toolForHistory,
+ label,
+ strokeIdForHistory,
+ enqueueHistoryTask,
+ pushHistoryStep
+ );
+}
diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpSpecialCommit.ts b/src/hooks/drawing/brushStrokeSession/pointerUpSpecialCommit.ts
new file mode 100644
index 0000000..c327dfd
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/pointerUpSpecialCommit.ts
@@ -0,0 +1,141 @@
+import {
+ BrushSettings,
+ CanvasSelection,
+ DirtyRect,
+ LayerItem,
+ Point,
+ ToolType,
+} from '../../../types/editor';
+import { get2DContext, getReusableBakeCanvas } from '../../../utils/canvasUtils';
+import { renderCompleteStroke } from '../../../engine/BrushEngine';
+import { multiplayerService } from '../../../services/multiplayerService';
+import {
+ PushHistoryStepFn,
+ applySelectionCanvasClip,
+ applySelectionMaskToImageData,
+} from '../types';
+
+export type StrokeHistoryToolType = 'eraser' | 'pencil' | 'brush';
+
+export function resolveStrokeHistoryLabel(
+ bs: BrushSettings,
+ currentTool: ToolType,
+ isMonochrome: boolean
+): string {
+ if (bs.isTransparentInk) return 'Transparent Ink';
+ if (currentTool === 'eraser') return 'Eraser';
+ if (bs.brushName) return bs.brushName;
+ if (bs.preset === 'pencil-f') return 'Pencil (F)';
+ if (bs.preset === 'pencil-2b') return 'Pencil (2B)';
+ if (bs.preset === 'pencil-4b') return 'Pencil (4B)';
+ if (bs.preset === 'pencil-hb') return 'Pencil (HB)';
+ return isMonochrome ? 'Monochrome Pen' : 'Round Brush';
+}
+
+export interface CommitMaskModeStrokeParams {
+ canvas: HTMLCanvasElement;
+ dirtyRect: DirtyRect;
+ bs: BrushSettings;
+ strokeColor: string;
+ isEraser: boolean;
+ currentTool: ToolType;
+ allPoints: Point[];
+ activeSelection: CanvasSelection | null;
+ activeLayer: LayerItem | undefined;
+ currentLayerId: string;
+ toolForHistory: StrokeHistoryToolType;
+ strokeIdForHistory: string | undefined;
+ enqueueHistoryTask: (task: () => void) => void;
+ pushHistoryStep: PushHistoryStepFn;
+}
+
+export function commitMaskModeStroke({
+ canvas,
+ dirtyRect,
+ bs,
+ strokeColor,
+ isEraser,
+ currentTool,
+ allPoints,
+ activeSelection,
+ activeLayer,
+ currentLayerId,
+ toolForHistory,
+ strokeIdForHistory,
+ enqueueHistoryTask,
+ pushHistoryStep,
+}: CommitMaskModeStrokeParams): void {
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const { x: sx, y: sy, width: dw, height: dh } = dirtyRect;
+ const beforeMaskData = ctx.getImageData(sx, sy, dw, dh);
+ const maskBs: BrushSettings = {
+ ...bs,
+ color: strokeColor,
+ isTransparentInk: false,
+ colorMixing: false,
+ };
+ const maskTool: ToolType = isEraser ? 'brush' : currentTool;
+
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(sx, sy, dw, dh);
+ ctx.clip();
+ applySelectionCanvasClip(ctx, activeSelection);
+
+ if ((bs.opacity ?? 1.0) >= 0.999) {
+ renderCompleteStroke(ctx, allPoints, maskBs, maskTool, 'grayscale', false, canvas, false);
+ } else {
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ ctx.globalCompositeOperation = 'source-over';
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtx) {
+ bCtx.resetTransform();
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ renderCompleteStroke(
+ bCtx,
+ allPoints,
+ { ...maskBs, opacity: 1.0 },
+ maskTool,
+ 'grayscale',
+ false,
+ canvas,
+ false
+ );
+ bCtx.restore();
+ ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
+ }
+ }
+ ctx.restore();
+
+ const afterMaskData = ctx.getImageData(sx, sy, dw, dh);
+ if (activeSelection?.mask) {
+ applySelectionMaskToImageData(beforeMaskData, afterMaskData, sx, sy, activeSelection);
+ ctx.putImageData(afterMaskData, sx, sy);
+ }
+ if (activeLayer) {
+ activeLayer.maskVersion = (activeLayer.maskVersion || 0) + 1;
+ }
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendLayerMaskData(currentLayerId, canvas, dirtyRect);
+ }
+ enqueueHistoryTask(() => {
+ pushHistoryStep(
+ toolForHistory,
+ 'Layer Mask Stroke',
+ beforeMaskData,
+ afterMaskData,
+ currentLayerId,
+ dirtyRect,
+ undefined,
+ undefined,
+ undefined,
+ strokeIdForHistory,
+ true
+ );
+ });
+}
diff --git a/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts b/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts
new file mode 100644
index 0000000..586db4f
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts
@@ -0,0 +1,401 @@
+import React from 'react';
+import {
+ BrushSettings,
+ Point,
+ CanvasDimensions,
+ CanvasColorMode,
+ LayerItem,
+} from '../../../types/editor';
+import { TILE_SIZE } from '../../../utils/tileEngine';
+import { calculateStrokeWidth, screenToCanvas, get2DContext } from '../../../utils/canvasUtils';
+import { enforceColorMode } from '../../../utils/colorUtils';
+import { BrushRenderOptions, buildBrushRenderOptions } from '../../../engine/BrushEngine';
+import { ConstraintAxis } from '../../../types/perspective';
+import { useUiStore } from '../../../stores';
+import { recoveryService } from '../../../services/recoveryService';
+import { evaluateGlobalPressureCurve } from '../../../utils/pressureCurve';
+import { DraftCanvasElement } from '../types';
+import { StrokeSessionState, TouchedTileSpan, UseBrushStrokeSessionParams } from './types';
+
+export function getPredictedCanvasElement(
+ predictedCanvasRef?: React.RefObject<HTMLCanvasElement | null>
+): HTMLCanvasElement | null {
+ if (predictedCanvasRef?.current) return predictedCanvasRef.current;
+ if (typeof document !== 'undefined') {
+ return document.getElementById('ink-predicted-canvas') as HTMLCanvasElement | null;
+ }
+ return null;
+}
+
+export function clearPredictedCanvasSurface(
+ state: StrokeSessionState,
+ getPredictedCanvas: () => HTMLCanvasElement | null
+): void {
+ state.latestPredicted = null;
+ if (!state.isPredictedCanvasDirty) return;
+ const pCanvas = getPredictedCanvas();
+ if (pCanvas) {
+ const pCtx = get2DContext(pCanvas);
+ if (pCtx) {
+ pCtx.resetTransform();
+ pCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
+ }
+ }
+ state.isPredictedCanvasDirty = false;
+}
+
+export function emitConstraintAxisChangeIfNeeded(
+ state: StrokeSessionState,
+ onActiveConstraintAxisChangeRef: React.MutableRefObject<
+ ((axis: ConstraintAxis | null) => void) | undefined
+ >,
+ newAxis: ConstraintAxis | null
+): void {
+ const prev = state.lastEmittedAxis;
+ if (prev === newAxis) return;
+ if (
+ prev &&
+ newAxis &&
+ prev.type === newAxis.type &&
+ prev.origin.x === newAxis.origin.x &&
+ prev.origin.y === newAxis.origin.y &&
+ prev.dir.x === newAxis.dir.x &&
+ prev.dir.y === newAxis.dir.y
+ ) {
+ return;
+ }
+ state.lastEmittedAxis = newAxis;
+ onActiveConstraintAxisChangeRef.current?.(newAxis);
+}
+
+export function markTouchedTilesInRect(
+ dims: CanvasDimensions,
+ touchedTiles: Set<number>,
+ minX: number,
+ minY: number,
+ maxX: number,
+ maxY: number
+): void {
+ const cx0 = Math.max(0, Math.floor(minX));
+ const cy0 = Math.max(0, Math.floor(minY));
+ const cx1 = Math.min(dims.width, Math.ceil(maxX));
+ const cy1 = Math.min(dims.height, Math.ceil(maxY));
+ if (cx1 <= cx0 || cy1 <= cy0) return;
+ const tx0 = Math.floor(cx0 / TILE_SIZE);
+ const ty0 = Math.floor(cy0 / TILE_SIZE);
+ const tx1 = Math.floor((cx1 - 1) / TILE_SIZE);
+ const ty1 = Math.floor((cy1 - 1) / TILE_SIZE);
+ for (let ty = ty0; ty <= ty1; ty++) {
+ for (let tx = tx0; tx <= tx1; tx++) {
+ touchedTiles.add(ty * 65536 + tx);
+ }
+ }
+}
+
+export function getViewportRectCached(
+ state: StrokeSessionState,
+ viewportRef: React.RefObject<HTMLDivElement | null>
+): DOMRect | null {
+ if (!state.cachedViewportRect && viewportRef.current) {
+ state.cachedViewportRect = viewportRef.current.getBoundingClientRect();
+ }
+ return state.cachedViewportRect;
+}
+
+export function dispatchPointerStatThrottled(
+ state: StrokeSessionState,
+ x: number | null,
+ y: number | null,
+ pressure: number
+): void {
+ state.pendingStat = {
+ x: x !== null ? Math.round(x) : null,
+ y: y !== null ? Math.round(y) : null,
+ pressure,
+ };
+ if (state.statRaf === null) {
+ state.statRaf = requestAnimationFrame(() => {
+ state.statRaf = null;
+ if (state.pendingStat) {
+ window.dispatchEvent(
+ new CustomEvent('canvas-pointer-stat', {
+ detail: {
+ ...state.pendingStat,
+ isHovering: state.pendingStat.x !== null,
+ },
+ })
+ );
+ }
+ });
+ }
+}
+
+export function abortActiveStrokeSession(
+ params: Pick<
+ UseBrushStrokeSessionParams,
+ 'isDrawingRef' | 'effectiveDraftCanvasRef' | 'activeTileGridRef' | 'interactionRef'
+ >,
+ state: StrokeSessionState,
+ clearPredictedCanvas: () => void,
+ emitConstraintAxisChange: (axis: ConstraintAxis | null) => void
+): void {
+ if (!params.isDrawingRef.current) return;
+ if (state.drawRafId !== null) {
+ cancelAnimationFrame(state.drawRafId);
+ state.drawRafId = null;
+ }
+ const draftCanvas = params.effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ let clearedActiveDraft = false;
+ if (draftCanvas) {
+ const dCtx = get2DContext(draftCanvas);
+ if (dCtx) {
+ try {
+ dCtx.restore();
+ } catch {
+ // Ignore restore underflow
+ }
+ dCtx.resetTransform();
+ dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ }
+ if (draftCanvas.__draftHasContent) {
+ clearedActiveDraft = true;
+ }
+ draftCanvas.__draftHasContent = false;
+ draftCanvas.__draftCompositeOp = 'source-over';
+ draftCanvas.__draftMonochrome = false;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ }
+ clearPredictedCanvas();
+ if (clearedActiveDraft) {
+ params.activeTileGridRef.current.notifyChange(true);
+ }
+ state.strokePipeline.abortStroke();
+ state.frameGpuDabs.length = 0;
+ if (state.activePointerId !== null && params.interactionRef.current) {
+ try {
+ params.interactionRef.current.releasePointerCapture(state.activePointerId);
+ } catch {
+ // Ignore release errors when capture already ended
+ }
+ }
+ params.isDrawingRef.current = false;
+ recoveryService.setDrawingActive(false);
+ state.activePointerId = null;
+ state.allStrokePoints = [];
+ state.stabilizedPoint = null;
+ state.hasLastProcessedPoint = false;
+ state.dirtyRect = null;
+ state.touchedTiles.clear();
+ state.liveNeedsNotify = false;
+ state.isShiftLineStroke = false;
+ state.layerPixelSampler = null;
+ state.activeReservoir = null;
+ state.snapSession.endStroke();
+ state.straightSnapSession.endStroke();
+ emitConstraintAxisChange(null);
+}
+
+export function computeCanvasPoint(
+ e: React.PointerEvent<HTMLElement> | PointerEvent,
+ params: Pick<
+ UseBrushStrokeSessionParams,
+ 'dimensionsRef' | 'panRef' | 'zoomRef' | 'rotationRef' | 'flipXRef' | 'flipYRef'
+ >,
+ getViewportRect: () => DOMRect | null,
+ getBrushSettings: () => BrushSettings
+): Point {
+ const vRect = getViewportRect();
+ const dims = params.dimensionsRef.current;
+ const bs = getBrushSettings();
+ if (!vRect) {
+ return { x: 0, y: 0, pressure: 0.5, width: bs.size, timestamp: e.timeStamp };
+ }
+
+ const { x, y } = screenToCanvas(
+ e.clientX,
+ e.clientY,
+ vRect,
+ params.panRef.current,
+ params.zoomRef.current,
+ params.rotationRef.current,
+ dims,
+ params.flipXRef.current,
+ params.flipYRef.current
+ );
+
+ let pressure = 0;
+ if (e.pointerType === 'mouse') {
+ pressure = e.buttons & 1 ? 0.5 : 0;
+ } else {
+ const rawP = e.pressure !== undefined ? Math.max(0, Math.min(1.0, e.pressure)) : 0;
+ pressure = evaluateGlobalPressureCurve(rawP, useUiStore.getState().appSettings.pressureCurve);
+ }
+
+ const width = calculateStrokeWidth(
+ bs.size,
+ pressure,
+ bs.minSizeFactor,
+ bs.usePressure,
+ e.pointerType,
+ bs.pressureCurveGamma ?? 1.0,
+ 1.0,
+ bs.pressureCurve
+ );
+
+ return {
+ x,
+ y,
+ pressure,
+ width,
+ tiltX: e.tiltX ?? 0,
+ tiltY: e.tiltY ?? 0,
+ twist: e.twist ?? 0,
+ timestamp: e.timeStamp,
+ };
+}
+
+export function resolveEffectiveOpacitySensorValue(
+ bs: BrushSettings,
+ isMonochrome: boolean,
+ isEraser: boolean
+): BrushSettings['opacitySensor'] {
+ if (bs.opacitySensor) return bs.opacitySensor;
+ if (bs.usePressure && !isMonochrome && !isEraser && (bs.flow ?? 1.0) < 0.99) {
+ return { usePressure: true, pressureMin: 0.2 };
+ }
+ return undefined;
+}
+
+export function resolveLiveAntiAliasValue(
+ bs: BrushSettings,
+ isMonochrome: boolean,
+ scale: number
+): number | undefined {
+ const downscaled = scale < 0.999;
+ if (isMonochrome) {
+ const allowGpuMono = (bs.antiAlias ?? 2) !== 0 && bs.useGpu !== false;
+ if (allowGpuMono || downscaled) {
+ return (bs.antiAlias ?? 2) !== 0 ? bs.antiAlias ?? 2 : 2;
+ }
+ return 0;
+ }
+ if (bs.antiAlias === 0 && downscaled) {
+ return 2;
+ }
+ return bs.antiAlias;
+}
+
+export function buildTouchedTileSpansFromSet(
+ touchedTiles: Set<number>,
+ sx: number,
+ sy: number,
+ dw: number,
+ dh: number
+): TouchedTileSpan[] {
+ if (dw * dh <= TILE_SIZE * TILE_SIZE || touchedTiles.size === 0) {
+ return [{ x: sx, y: sy, width: dw, height: dh }];
+ }
+ const rows = new Map<number, number[]>();
+ for (const key of touchedTiles) {
+ const ty = Math.floor(key / 65536);
+ const tx = key % 65536;
+ let list = rows.get(ty);
+ if (!list) {
+ list = [];
+ rows.set(ty, list);
+ }
+ list.push(tx);
+ }
+ const spans: TouchedTileSpan[] = [];
+ for (const [ty, txList] of rows) {
+ txList.sort((a, b) => a - b);
+ let spanStart = txList[0];
+ let spanEnd = txList[0];
+ const pushClampedSpan = (s0: number, s1: number) => {
+ const rx = Math.max(sx, s0 * TILE_SIZE);
+ const ry = Math.max(sy, ty * TILE_SIZE);
+ const rxEnd = Math.min(sx + dw, (s1 + 1) * TILE_SIZE);
+ const ryEnd = Math.min(sy + dh, (ty + 1) * TILE_SIZE);
+ const rw = rxEnd - rx;
+ const rh = ryEnd - ry;
+ if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ };
+ for (let i = 1; i < txList.length; i++) {
+ if (txList[i] <= spanEnd + 1) {
+ spanEnd = txList[i];
+ } else {
+ pushClampedSpan(spanStart, spanEnd);
+ spanStart = txList[i];
+ spanEnd = txList[i];
+ }
+ }
+ pushClampedSpan(spanStart, spanEnd);
+ }
+ return spans.length > 0 ? spans : [{ x: sx, y: sy, width: dw, height: dh }];
+}
+
+export function createLiveBrushOptions(
+ state: StrokeSessionState,
+ bs: BrushSettings,
+ strokeFlow: number,
+ strokeSpacing: number,
+ strokeHardness: number,
+ isMonochrome: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ isolatedPass: boolean = false,
+ effectiveAntiAlias?: number
+): BrushRenderOptions {
+ return buildBrushRenderOptions(bs, {
+ opacity: isolatedPass ? 1.0 : bs.opacity,
+ flow: strokeFlow,
+ spacing: strokeSpacing,
+ hardness: strokeHardness,
+ antiAlias:
+ effectiveAntiAlias !== undefined ? effectiveAntiAlias : isMonochrome ? 0 : bs.antiAlias,
+ opacitySensor: resolveEffectiveOpacitySensorValue(bs, isMonochrome, isEraser),
+ wetEdge: 0,
+ underlyingCanvas: canvas || undefined,
+ sampler: state.layerPixelSampler || undefined,
+ reservoir: state.activeReservoir || undefined,
+ isEraser: isolatedPass ? false : isEraser && !isBgEraser,
+ isBgEraser: isolatedPass ? false : isBgEraser,
+ alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
+ currentStrokeDist: state.strokeTotalDistance,
+ });
+}
+
+export function resolveStrokeColorValue(
+ isMaskMode: boolean,
+ bs: BrushSettings,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ isMonochrome: boolean,
+ mode: CanvasColorMode
+): string {
+ if (isMaskMode) {
+ if (isEraser) return '#000000';
+ let clean = bs.color.replace('#', '');
+ if (clean.length === 3) {
+ clean = clean
+ .split('')
+ .map((c) => c + c)
+ .join('');
+ }
+ const r = parseInt(clean.slice(0, 2), 16) || 0;
+ const g = parseInt(clean.slice(2, 4), 16) || 0;
+ const b = parseInt(clean.slice(4, 6), 16) || 0;
+ const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
+ const hexVal = gray.toString(16).padStart(2, '0');
+ return `#${hexVal}${hexVal}${hexVal}`;
+ }
+ return isBgEraser
+ ? '#ffffff'
+ : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+}
diff --git a/src/hooks/drawing/brushStrokeSession/types.ts b/src/hooks/drawing/brushStrokeSession/types.ts
new file mode 100644
index 0000000..789f092
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/types.ts
@@ -0,0 +1,277 @@
+import React from 'react';
+import {
+ ToolType,
+ BrushSettings,
+ Point,
+ CanvasDimensions,
+ CanvasSelection,
+ CanvasColorMode,
+ DirtyRect,
+ LayerItem,
+ VectorStroke,
+} from '../../../types/editor';
+import { SparseTileGrid } from '../../../utils/tileEngine';
+import { StrokePipeline } from '../../../engine/StrokePipeline';
+import { CubicBezierSegment } from '../../../engine/SplineGenerator';
+import { BrushRenderOptions } from '../../../engine/BrushEngine';
+import { GpuDab } from '../../../engine/WebGlBrushEngine';
+import { PaintReservoir, LayerPixelSampler } from '../../../utils/colorMixingEngine';
+import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../../types/perspective';
+import { PerspectiveSnapSession } from '../../../utils/perspectiveSnapping';
+import { StraightRulerSnapSession } from '../../../utils/straightRulerMath';
+import { LastStrokeEndState, PushHistoryStepFn } from '../types';
+
+export interface UseBrushStrokeSessionParams {
+ disabled: boolean;
+ activeSessionId?: string | null;
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ interactionRef: React.MutableRefObject<HTMLDivElement | null>;
+ isDrawingRef: React.MutableRefObject<boolean>;
+ lastStrokeEndRef: React.MutableRefObject<LastStrokeEndState | null>;
+ panRef: React.MutableRefObject<{ x: number; y: number }>;
+ zoomRef: React.MutableRefObject<number>;
+ rotationRef: React.MutableRefObject<number>;
+ flipXRef: React.MutableRefObject<boolean>;
+ flipYRef: React.MutableRefObject<boolean>;
+ toolOverrideRef: React.MutableRefObject<ToolType | undefined>;
+ brushSettingsOverrideRef: React.MutableRefObject<BrushSettings | undefined>;
+ colorModeRef: React.MutableRefObject<CanvasColorMode>;
+ activeLayerIdRef: React.MutableRefObject<string>;
+ activeLayerLockedRef: React.MutableRefObject<boolean>;
+ activeLayerVisibleRef: React.MutableRefObject<boolean>;
+ dimensionsRef: React.MutableRefObject<CanvasDimensions>;
+ selectionRef: React.MutableRefObject<CanvasSelection | null>;
+ isMaskModeRef: React.MutableRefObject<boolean>;
+ layersRef: React.MutableRefObject<LayerItem[] | undefined>;
+ effectiveDraftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ predictedCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ activeTileGridRef: React.MutableRefObject<SparseTileGrid>;
+ rulerRef: React.MutableRefObject<PerspectiveRuler | null | undefined>;
+ straightRulerRef?: React.MutableRefObject<StraightRuler | null | undefined>;
+ onActiveConstraintAxisChangeRef: React.MutableRefObject<
+ ((axis: ConstraintAxis | null) => void) | undefined
+ >;
+ onUpdateLayerThumbnail: (layerId: string) => void;
+ onUpdateMaskThumbnailRef: React.MutableRefObject<((layerId: string) => void) | undefined>;
+ onCollabStrokeStartRef: React.MutableRefObject<
+ | ((
+ strokeId: string,
+ layerId: string,
+ brushSettings: BrushSettings,
+ tool: ToolType,
+ startPoint: Point
+ ) => void)
+ | undefined
+ >;
+ onCollabStrokeChunkRef: React.MutableRefObject<
+ ((strokeId: string, points: Point[]) => void) | undefined
+ >;
+ onCollabStrokeFinishRef: React.MutableRefObject<
+ | ((
+ strokeId: string,
+ layerId: string,
+ endPoint: Point,
+ dirtyRect?: DirtyRect,
+ vectorStroke?: VectorStroke
+ ) => void)
+ | undefined
+ >;
+ onCollabCursorMoveRef: React.MutableRefObject<
+ ((x: number, y: number, isDrawing: boolean, tool: ToolType) => void) | undefined
+ >;
+ getActiveMaskCanvas: (layerId?: string) => HTMLCanvasElement | null;
+ pushHistoryStep: PushHistoryStepFn;
+ flushPendingHistoryTasks: () => void;
+ enqueueHistoryTask: (task: () => void) => void;
+}
+
+export interface UseBrushStrokeSessionResult {
+ abortActiveStroke: () => void;
+ handlePointerDown: (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => void;
+ handlePointerMove: (
+ e: React.PointerEvent<HTMLElement>,
+ coalescedEvents?: PointerEvent[],
+ predictedEvents?: PointerEvent[]
+ ) => void;
+ handlePointerUp: (e: React.PointerEvent<HTMLElement>) => void;
+ handlePointerEnter: () => void;
+ handlePointerLeave: () => void;
+}
+
+export interface DirtyBounds {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+}
+
+export interface TouchedTileSpan {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export interface RecentPointSample {
+ x: number;
+ y: number;
+ t: number;
+ pressure: number;
+ width: number;
+}
+
+export interface PredictedFrameData {
+ predEvents: PointerEvent[];
+ vRect: DOMRect;
+}
+
+export interface StrokeSessionState {
+ currentStrokeId: string | null;
+ activePointerId: number | null;
+ isPredictedCanvasDirty: boolean;
+ latestPredicted: PredictedFrameData | null;
+ snapSession: PerspectiveSnapSession;
+ straightSnapSession: StraightRulerSnapSession;
+ lastEmittedAxis: ConstraintAxis | null;
+ allStrokePoints: Point[];
+ strokePipeline: StrokePipeline;
+ frameGpuDabs: GpuDab[];
+ reusableRegionCanvas: HTMLCanvasElement | null;
+ scratchDocCoord: { x: number; y: number };
+ predCoordPool: Array<{ x: number; y: number; pressure?: number }>;
+ predDocCoords: Array<{ x: number; y: number; pressure?: number }>;
+ predDabCounter: { count: number };
+ lastQueuedPressure: number;
+ stabilizedPoint: Point | null;
+ stampRemainderDist: number;
+ liveDabCounter: { count: number };
+ activeReservoir: PaintReservoir | null;
+ layerPixelSampler: LayerPixelSampler | null;
+ isWetColorStroke: boolean;
+ liveNeedsNotify: boolean;
+ isShiftLineStroke: boolean;
+ lastPointTime: number;
+ recentPointsTrail: RecentPointSample[];
+ strokeTotalDistance: number;
+ dirtyRect: DirtyBounds | null;
+ touchedTiles: Set<number>;
+ lastProcessedPoint: { x: number; y: number };
+ hasLastProcessedPoint: boolean;
+ drawRafId: number | null;
+ clearDraftRaf: number | null;
+ statRaf: number | null;
+ pendingStat: { x: number | null; y: number | null; pressure: number } | null;
+ cachedViewportRect: DOMRect | null;
+}
+
+export function createInitialStrokeSessionState(): StrokeSessionState {
+ return {
+ currentStrokeId: null,
+ activePointerId: null,
+ isPredictedCanvasDirty: false,
+ latestPredicted: null,
+ snapSession: new PerspectiveSnapSession(),
+ straightSnapSession: new StraightRulerSnapSession(),
+ lastEmittedAxis: null,
+ allStrokePoints: [],
+ strokePipeline: new StrokePipeline(),
+ frameGpuDabs: [],
+ reusableRegionCanvas: null,
+ scratchDocCoord: { x: 0, y: 0 },
+ predCoordPool: [
+ { x: 0, y: 0, pressure: 0.5 },
+ { x: 0, y: 0, pressure: 0.5 },
+ { x: 0, y: 0, pressure: 0.5 },
+ { x: 0, y: 0, pressure: 0.5 },
+ ],
+ predDocCoords: [],
+ predDabCounter: { count: 0 },
+ lastQueuedPressure: 0.5,
+ stabilizedPoint: null,
+ stampRemainderDist: 0,
+ liveDabCounter: { count: 0 },
+ activeReservoir: null,
+ layerPixelSampler: null,
+ isWetColorStroke: false,
+ liveNeedsNotify: false,
+ isShiftLineStroke: false,
+ lastPointTime: 0,
+ recentPointsTrail: [],
+ strokeTotalDistance: 0,
+ dirtyRect: null,
+ touchedTiles: new Set<number>(),
+ lastProcessedPoint: { x: 0, y: 0 },
+ hasLastProcessedPoint: false,
+ drawRafId: null,
+ clearDraftRaf: null,
+ statRaf: null,
+ pendingStat: null,
+ cachedViewportRect: null,
+ };
+}
+
+export type EmitLiveSegmentFn = (
+ draftCtx: CanvasRenderingContext2D,
+ seg: CubicBezierSegment,
+ bs: BrushSettings,
+ strokeColor: string,
+ strokeHardness: number,
+ strokeFlow: number,
+ strokeSpacing: number,
+ isMonochrome: boolean,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ useWireframeEraser: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ gpuBatch: GpuDab[] | undefined
+) => void;
+
+export type BuildLiveBrushOptionsFn = (
+ bs: BrushSettings,
+ strokeFlow: number,
+ strokeSpacing: number,
+ strokeHardness: number,
+ isMonochrome: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ isolatedPass?: boolean,
+ effectiveAntiAlias?: number
+) => BrushRenderOptions;
+
+export interface StrokeSessionHelpers {
+ getTool: () => ToolType;
+ getBrushSettings: () => BrushSettings;
+ getPredictedCanvas: () => HTMLCanvasElement | null;
+ clearPredictedCanvas: () => void;
+ emitConstraintAxisChange: (newAxis: ConstraintAxis | null) => void;
+ markTouchedTiles: (minX: number, minY: number, maxX: number, maxY: number) => void;
+ getViewportRect: () => DOMRect | null;
+ dispatchPointerStat: (x: number | null, y: number | null, pressure: number) => void;
+ abortActiveStroke: () => void;
+ getCanvasPoint: (e: React.PointerEvent<HTMLElement> | PointerEvent) => Point;
+ resolveEffectiveOpacitySensor: (
+ bs: BrushSettings,
+ isMonochrome: boolean,
+ isEraser: boolean
+ ) => BrushSettings['opacitySensor'];
+ resolveLiveAntiAlias: (
+ bs: BrushSettings,
+ isMonochrome: boolean,
+ scale: number
+ ) => number | undefined;
+ buildTouchedTileSpans: (sx: number, sy: number, dw: number, dh: number) => TouchedTileSpan[];
+ buildLiveBrushOptions: BuildLiveBrushOptionsFn;
+ resolveStrokeColor: (
+ bs: BrushSettings,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ isMonochrome: boolean,
+ mode: CanvasColorMode
+ ) => string;
+ emitLiveSegment: EmitLiveSegmentFn;
+ renderPredictedStroke: (predEvents: PointerEvent[], vRect: DOMRect) => void;
+ flushPendingPoints: (skipDisplayArg?: boolean | number) => void;
+}
diff --git a/src/hooks/drawing/types.ts b/src/hooks/drawing/types.ts
index fd43ca3..59ecec3 100644
--- a/src/hooks/drawing/types.ts
+++ b/src/hooks/drawing/types.ts
@@ -72,8 +72,6 @@ export interface UseCanvasDrawingProps {
activeLayerId: string;
activeLayerLocked?: boolean;
activeLayerVisible?: boolean;
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- layerSourceCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
layers?: LayerItem[];
onUpdateLayerThumbnail: (layerId: string) => void;
isMaskMode?: boolean;
@@ -102,7 +100,6 @@ export interface UseCanvasDrawingProps {
onActiveConstraintAxisChange?: (axis: ConstraintAxis | null) => void;
activeSessionId?: string | null;
tileGrid?: SparseTileGrid;
- materializeLayerCanvas?: (layerId: string) => HTMLCanvasElement | null;
}
export function isBackgroundLayerId(id: string): boolean {
diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.ts
index 3fe0a29..e5e2a55 100644
--- a/src/hooks/drawing/useBrushStrokeSession.ts
+++ b/src/hooks/drawing/useBrushStrokeSession.ts
@@ -3,324 +3,147 @@ import {
ToolType,
BrushSettings,
Point,
- CanvasDimensions,
- CanvasSelection,
CanvasColorMode,
- DirtyRect,
LayerItem,
- VectorStroke,
} from '../../types/editor';
-import { SparseTileGrid, TILE_SIZE, TileFormat, releaseTemporaryCanvas } from '../../utils/tileEngine';
+import { CubicBezierSegment } from '../../engine/SplineGenerator';
+import { BrushRenderOptions } from '../../engine/BrushEngine';
+import { GpuDab } from '../../engine/WebGlBrushEngine';
+import { ConstraintAxis } from '../../types/perspective';
+import { useToolStore, toolStoreActions } from '../../stores';
+import { recoveryService } from '../../services/recoveryService';
+import { isNativeRustAvailable } from '../../utils/nativeBackend';
import {
- calculateStrokeWidth,
- drawSmoothCubicBezierSegment,
- drawDot,
- screenToCanvas,
- screenToCanvasInto,
- getCanvasToViewportMatrix,
- getVisibleCanvasBounds,
- get2DContext,
- getReusableBakeCanvas,
- renderCompleteStroke,
- applyParametricTaper,
-} from '../../utils/canvasUtils';
+ NativeTabletSample,
+ startNativeTablet,
+ subscribeNativeTablet,
+} from '../../utils/nativeTabletInput';
import {
- StrokePipeline,
- computeClampedBakeDirtyRect,
- encodePointerType,
-} from '../../engine/StrokePipeline';
-import { CubicBezierSegment } from '../../engine/SplineGenerator';
-import { applyCspWatercolorEdge } from '../../engine/CspBrushEngine';
-import { enforceColorMode, binarizeImageDataBuffer } from '../../utils/colorUtils';
-import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from '../../utils/pencilEngine';
+ StrokeSessionHelpers,
+ StrokeSessionState,
+ TouchedTileSpan,
+ UseBrushStrokeSessionParams,
+ UseBrushStrokeSessionResult,
+ createInitialStrokeSessionState,
+} from './brushStrokeSession/types';
import {
- drawTexturedCubicBezierSegment,
- drawTexturedDot,
- TexturedBrushOptions,
- RadialMixingOptions,
- canUseWebGlForTexturedBrush,
- canUseWebGlForRadialBrush,
- flushTexturedGpuDabs,
- flushRadialGpuDabs,
-} from '../../utils/stampEngine';
-import { GpuDab } from '../../utils/webglBrushEngine';
-import { PaintReservoir, LayerPixelSampler } from '../../utils/colorMixingEngine';
-import { applyLayerEffects } from '../../utils/layerEffectsEngine';
-import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../types/perspective';
-import { PerspectiveSnapSession } from '../../utils/perspectiveSnapping';
-import { StraightRulerSnapSession } from '../../utils/straightRulerMath';
-import { useToolStore, useUiStore } from '../../stores';
-import { recoveryService } from '../../services/recoveryService';
-import { evaluateGlobalPressureCurve, isLinearPressureCurve } from '../../utils/pressureCurve';
+ abortActiveStrokeSession,
+ buildTouchedTileSpansFromSet,
+ clearPredictedCanvasSurface,
+ computeCanvasPoint,
+ createLiveBrushOptions,
+ dispatchPointerStatThrottled,
+ emitConstraintAxisChangeIfNeeded,
+ getPredictedCanvasElement,
+ getViewportRectCached,
+ markTouchedTilesInRect,
+ resolveEffectiveOpacitySensorValue,
+ resolveLiveAntiAliasValue,
+ resolveStrokeColorValue,
+} from './brushStrokeSession/strokeHelpers';
+import {
+ emitLiveSegmentToDraft,
+ renderPredictedStrokeOverlay,
+} from './brushStrokeSession/liveSegmentEmitter';
+import { runFlushPendingPoints } from './brushStrokeSession/flushPendingPoints';
+import { runPointerDown } from './brushStrokeSession/pointerDownHandler';
import {
- DraftCanvasElement,
- ExtendedPointerEvent,
- LastStrokeEndState,
- PushHistoryStepFn,
- applySelectionCanvasClip,
- applySelectionMaskToImageData,
- isBackgroundLayerId,
-} from './types';
-import { commitVectorStrokeOrErase } from './useVectorDrawing';
+ runPointerEnter,
+ runPointerLeave,
+ runPointerMove,
+} from './brushStrokeSession/pointerMoveHandler';
+import { runPointerUp } from './brushStrokeSession/pointerUpHandler';
+
+export type {
+ UseBrushStrokeSessionParams,
+ UseBrushStrokeSessionResult,
+} from './brushStrokeSession/types';
+
+export function useBrushStrokeSession(
+ params: UseBrushStrokeSessionParams
+): UseBrushStrokeSessionResult {
+ const {
+ disabled,
+ activeSessionId,
+ viewportRef,
+ interactionRef,
+ isDrawingRef,
+ panRef,
+ zoomRef,
+ rotationRef,
+ flipXRef,
+ flipYRef,
+ toolOverrideRef,
+ brushSettingsOverrideRef,
+ dimensionsRef,
+ isMaskModeRef,
+ effectiveDraftCanvasRef,
+ predictedCanvasRef,
+ activeTileGridRef,
+ onActiveConstraintAxisChangeRef,
+ } = params;
-export interface UseBrushStrokeSessionParams {
- disabled: boolean;
- activeSessionId?: string | null;
- viewportRef: React.RefObject<HTMLDivElement | null>;
- interactionRef: React.MutableRefObject<HTMLDivElement | null>;
- isDrawingRef: React.MutableRefObject<boolean>;
- lastStrokeEndRef: React.MutableRefObject<LastStrokeEndState | null>;
- panRef: React.MutableRefObject<{ x: number; y: number }>;
- zoomRef: React.MutableRefObject<number>;
- rotationRef: React.MutableRefObject<number>;
- flipXRef: React.MutableRefObject<boolean>;
- flipYRef: React.MutableRefObject<boolean>;
- toolOverrideRef: React.MutableRefObject<ToolType | undefined>;
- brushSettingsOverrideRef: React.MutableRefObject<BrushSettings | undefined>;
- colorModeRef: React.MutableRefObject<CanvasColorMode>;
- activeLayerIdRef: React.MutableRefObject<string>;
- activeLayerLockedRef: React.MutableRefObject<boolean>;
- activeLayerVisibleRef: React.MutableRefObject<boolean>;
- dimensionsRef: React.MutableRefObject<CanvasDimensions>;
- selectionRef: React.MutableRefObject<CanvasSelection | null>;
- isMaskModeRef: React.MutableRefObject<boolean>;
- layersRef: React.MutableRefObject<LayerItem[] | undefined>;
- layerSourceCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- effectiveDraftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
- predictedCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
- activeTileGridRef: React.MutableRefObject<SparseTileGrid>;
- rulerRef: React.MutableRefObject<PerspectiveRuler | null | undefined>;
- straightRulerRef?: React.MutableRefObject<StraightRuler | null | undefined>;
- onActiveConstraintAxisChangeRef: React.MutableRefObject<
- ((axis: ConstraintAxis | null) => void) | undefined
- >;
- onUpdateLayerThumbnail: (layerId: string) => void;
- onUpdateMaskThumbnailRef: React.MutableRefObject<((layerId: string) => void) | undefined>;
- onCollabStrokeStartRef: React.MutableRefObject<
- | ((
- strokeId: string,
- layerId: string,
- brushSettings: BrushSettings,
- tool: ToolType,
- startPoint: Point
- ) => void)
- | undefined
- >;
- onCollabStrokeChunkRef: React.MutableRefObject<
- ((strokeId: string, points: Point[]) => void) | undefined
- >;
- onCollabStrokeFinishRef: React.MutableRefObject<
- | ((
- strokeId: string,
- layerId: string,
- endPoint: Point,
- dirtyRect?: DirtyRect,
- vectorStroke?: VectorStroke
- ) => void)
- | undefined
- >;
- onCollabCursorMoveRef: React.MutableRefObject<
- ((x: number, y: number, isDrawing: boolean, tool: ToolType) => void) | undefined
- >;
- getCachedLayerCanvas: (layerId?: string) => HTMLCanvasElement | null;
- pushHistoryStep: PushHistoryStepFn;
- flushPendingHistoryTasks: () => void;
- enqueueHistoryTask: (task: () => void) => void;
-}
+ const paramsRef = useRef<UseBrushStrokeSessionParams>(params);
+ paramsRef.current = params;
-export interface UseBrushStrokeSessionResult {
- abortActiveStroke: () => void;
- handlePointerDown: (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => void;
- handlePointerMove: (
- e: React.PointerEvent<HTMLElement>,
- coalescedEvents?: PointerEvent[],
- predictedEvents?: PointerEvent[]
- ) => void;
- handlePointerUp: (e: React.PointerEvent<HTMLElement>) => void;
- handlePointerEnter: () => void;
- handlePointerLeave: () => void;
-}
+ const sessionStateRef = useRef<StrokeSessionState | null>(null);
+ if (!sessionStateRef.current) {
+ sessionStateRef.current = createInitialStrokeSessionState();
+ }
-export function useBrushStrokeSession({
- disabled,
- activeSessionId,
- viewportRef,
- interactionRef,
- isDrawingRef,
- lastStrokeEndRef,
- panRef,
- zoomRef,
- rotationRef,
- flipXRef,
- flipYRef,
- toolOverrideRef,
- brushSettingsOverrideRef,
- colorModeRef,
- activeLayerIdRef,
- activeLayerLockedRef,
- activeLayerVisibleRef,
- dimensionsRef,
- selectionRef,
- isMaskModeRef,
- layersRef,
- layerSourceCanvasesRef,
- effectiveDraftCanvasRef,
- predictedCanvasRef,
- activeTileGridRef,
- rulerRef,
- straightRulerRef,
- onActiveConstraintAxisChangeRef,
- onUpdateLayerThumbnail,
- onUpdateMaskThumbnailRef,
- onCollabStrokeStartRef,
- onCollabStrokeChunkRef,
- onCollabStrokeFinishRef,
- onCollabCursorMoveRef,
- getCachedLayerCanvas,
- pushHistoryStep,
- flushPendingHistoryTasks,
- enqueueHistoryTask,
-}: UseBrushStrokeSessionParams): UseBrushStrokeSessionResult {
const getTool = useCallback(
(): ToolType => toolOverrideRef.current ?? useToolStore.getState().tool,
[toolOverrideRef]
);
+
const getBrushSettings = useCallback(
(): BrushSettings =>
brushSettingsOverrideRef.current ?? useToolStore.getState().brushSettings,
[brushSettingsOverrideRef]
);
- const currentStrokeIdRef = useRef<string | null>(null);
- const isToneStrokeRef = useRef(false);
- const activePointerIdRef = useRef<number | null>(null);
-
- const isPredictedCanvasDirtyRef = useRef(false);
- const latestPredictedRef = useRef<{ predEvents: PointerEvent[]; vRect: DOMRect } | null>(null);
-
- const getPredictedCanvas = useCallback((): HTMLCanvasElement | null => {
- if (predictedCanvasRef?.current) return predictedCanvasRef.current;
- if (typeof document !== 'undefined') {
- return document.getElementById('ink-predicted-canvas') as HTMLCanvasElement | null;
- }
- return null;
- }, [predictedCanvasRef]);
+ const getPredictedCanvas = useCallback(
+ (): HTMLCanvasElement | null => getPredictedCanvasElement(predictedCanvasRef),
+ [predictedCanvasRef]
+ );
const clearPredictedCanvas = useCallback(() => {
- latestPredictedRef.current = null;
- if (!isPredictedCanvasDirtyRef.current) return;
- const pCanvas = getPredictedCanvas();
- if (pCanvas) {
- const pCtx = get2DContext(pCanvas);
- if (pCtx) {
- pCtx.resetTransform();
- pCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
- }
- }
- isPredictedCanvasDirtyRef.current = false;
+ clearPredictedCanvasSurface(sessionStateRef.current!, getPredictedCanvas);
}, [getPredictedCanvas]);
- const snapSessionRef = useRef(new PerspectiveSnapSession());
- const straightSnapSessionRef = useRef(new StraightRulerSnapSession());
- const lastEmittedAxisRef = useRef<ConstraintAxis | null>(null);
const emitConstraintAxisChange = useCallback(
(newAxis: ConstraintAxis | null) => {
- const prev = lastEmittedAxisRef.current;
- if (prev === newAxis) return;
- if (
- prev &&
- newAxis &&
- prev.type === newAxis.type &&
- prev.origin.x === newAxis.origin.x &&
- prev.origin.y === newAxis.origin.y &&
- prev.dir.x === newAxis.dir.x &&
- prev.dir.y === newAxis.dir.y
- ) {
- return;
- }
- lastEmittedAxisRef.current = newAxis;
- onActiveConstraintAxisChangeRef.current?.(newAxis);
+ emitConstraintAxisChangeIfNeeded(
+ sessionStateRef.current!,
+ onActiveConstraintAxisChangeRef,
+ newAxis
+ );
},
[onActiveConstraintAxisChangeRef]
);
- const allStrokePointsRef = useRef<Point[]>([]);
- const strokePipelineRef = useRef(new StrokePipeline());
- const frameGpuDabsRef = useRef<GpuDab[]>([]);
- const reusableRegionCanvasRef = useRef<HTMLCanvasElement | null>(null);
- const scratchDocCoordRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
- const predCoordPoolRef = useRef<Array<{ x: number; y: number; pressure?: number }>>([
- { x: 0, y: 0, pressure: 0.5 },
- { x: 0, y: 0, pressure: 0.5 },
- { x: 0, y: 0, pressure: 0.5 },
- { x: 0, y: 0, pressure: 0.5 },
- ]);
- const predDocCoordsRef = useRef<Array<{ x: number; y: number; pressure?: number }>>([]);
- const predDabCounterRef = useRef<{ count: number }>({ count: 0 });
- const lastQueuedPressureRef = useRef<number>(0.5);
- const stabilizedPointRef = useRef<Point | null>(null);
- const stampRemainderDistRef = useRef<number>(0);
- const liveDabCounterRef = useRef<{ count: number }>({ count: 0 });
- const activeReservoirRef = useRef<PaintReservoir | null>(null);
- const layerPixelSamplerRef = useRef<LayerPixelSampler | null>(null);
- const isWetColorStrokeRef = useRef<boolean>(false);
- const liveNeedsNotifyRef = useRef<boolean>(false);
- const isShiftLineStrokeRef = useRef<boolean>(false);
- const lastPointTimeRef = useRef<number>(0);
- const recentPointsTrailRef = useRef<
- { x: number; y: number; t: number; pressure: number; width: number }[]
- >([]);
- const strokeTotalDistanceRef = useRef<number>(0);
- const dirtyRectRef = useRef<{
- minX: number;
- minY: number;
- maxX: number;
- maxY: number;
- } | null>(null);
- const touchedTilesRef = useRef<Set<number>>(new Set());
- const lastProcessedPointRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
- const hasLastProcessedPointRef = useRef<boolean>(false);
- const drawRafIdRef = useRef<number | null>(null);
- const clearDraftRafRef = useRef<number | null>(null);
-
const markTouchedTiles = useCallback(
(minX: number, minY: number, maxX: number, maxY: number) => {
- const dims = dimensionsRef.current;
- const cx0 = Math.max(0, Math.floor(minX));
- const cy0 = Math.max(0, Math.floor(minY));
- const cx1 = Math.min(dims.width, Math.ceil(maxX));
- const cy1 = Math.min(dims.height, Math.ceil(maxY));
- if (cx1 <= cx0 || cy1 <= cy0) return;
- const tx0 = Math.floor(cx0 / TILE_SIZE);
- const ty0 = Math.floor(cy0 / TILE_SIZE);
- const tx1 = Math.floor((cx1 - 1) / TILE_SIZE);
- const ty1 = Math.floor((cy1 - 1) / TILE_SIZE);
- const set = touchedTilesRef.current;
- for (let ty = ty0; ty <= ty1; ty++) {
- for (let tx = tx0; tx <= tx1; tx++) {
- set.add(ty * 65536 + tx);
- }
- }
+ markTouchedTilesInRect(
+ dimensionsRef.current,
+ sessionStateRef.current!.touchedTiles,
+ minX,
+ minY,
+ maxX,
+ maxY
+ );
},
[dimensionsRef]
);
- const statRafRef = useRef<number | null>(null);
- const pendingStatRef = useRef<{ x: number | null; y: number | null; pressure: number } | null>(
- null
+ const getViewportRect = useCallback(
+ (): DOMRect | null => getViewportRectCached(sessionStateRef.current!, viewportRef),
+ [viewportRef]
);
- const cachedViewportRectRef = useRef<DOMRect | null>(null);
-
- const getViewportRect = useCallback((): DOMRect | null => {
- if (!cachedViewportRectRef.current && viewportRef.current) {
- cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
- }
- return cachedViewportRectRef.current;
- }, [viewportRef]);
useEffect(() => {
const handleResize = () => {
- cachedViewportRectRef.current = null;
+ sessionStateRef.current!.cachedViewportRect = null;
};
window.addEventListener('resize', handleResize);
window.addEventListener('scroll', handleResize, true);
@@ -333,11 +156,12 @@ export function useBrushStrokeSession({
window.removeEventListener('resize', handleResize);
window.removeEventListener('scroll', handleResize, true);
ro?.disconnect();
- if (clearDraftRafRef.current !== null) {
- cancelAnimationFrame(clearDraftRafRef.current);
+ const state = sessionStateRef.current!;
+ if (state.clearDraftRaf !== null) {
+ cancelAnimationFrame(state.clearDraftRaf);
}
- if (drawRafIdRef.current !== null) {
- cancelAnimationFrame(drawRafIdRef.current);
+ if (state.drawRafId !== null) {
+ cancelAnimationFrame(state.drawRafId);
}
recoveryService.setDrawingActive(false);
};
@@ -345,232 +169,57 @@ export function useBrushStrokeSession({
const dispatchPointerStat = useCallback(
(x: number | null, y: number | null, pressure: number) => {
- pendingStatRef.current = {
- x: x !== null ? Math.round(x) : null,
- y: y !== null ? Math.round(y) : null,
- pressure,
- };
- if (statRafRef.current === null) {
- statRafRef.current = requestAnimationFrame(() => {
- statRafRef.current = null;
- if (pendingStatRef.current) {
- window.dispatchEvent(
- new CustomEvent('canvas-pointer-stat', {
- detail: {
- ...pendingStatRef.current,
- isHovering: pendingStatRef.current.x !== null,
- },
- })
- );
- }
- });
- }
+ dispatchPointerStatThrottled(sessionStateRef.current!, x, y, pressure);
},
[]
);
const abortActiveStroke = useCallback(() => {
- if (!isDrawingRef.current) return;
- if (drawRafIdRef.current !== null) {
- cancelAnimationFrame(drawRafIdRef.current);
- drawRafIdRef.current = null;
- }
- const draftCanvas = effectiveDraftCanvasRef?.current as DraftCanvasElement | null | undefined;
- let clearedActiveDraft = false;
- if (draftCanvas) {
- const dCtx = get2DContext(draftCanvas);
- if (dCtx) {
- try {
- dCtx.restore();
- } catch {
- // Ignore restore underflow
- }
- dCtx.resetTransform();
- dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
- }
- if (draftCanvas.__draftHasContent) {
- clearedActiveDraft = true;
- }
- draftCanvas.__draftHasContent = false;
- draftCanvas.__draftCompositeOp = 'source-over';
- draftCanvas.__draftMonochrome = false;
- draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
- }
- clearPredictedCanvas();
- if (clearedActiveDraft) {
- activeTileGridRef.current.notifyChange(true);
- }
- strokePipelineRef.current.abortStroke();
- frameGpuDabsRef.current.length = 0;
- if (activePointerIdRef.current !== null && interactionRef.current) {
- try {
- interactionRef.current.releasePointerCapture(activePointerIdRef.current);
- } catch {
- // Ignore release errors when capture already ended
- }
- }
- isDrawingRef.current = false;
- recoveryService.setDrawingActive(false);
- activePointerIdRef.current = null;
- allStrokePointsRef.current = [];
- stabilizedPointRef.current = null;
- hasLastProcessedPointRef.current = false;
- dirtyRectRef.current = null;
- touchedTilesRef.current.clear();
- liveNeedsNotifyRef.current = false;
- isShiftLineStrokeRef.current = false;
- isToneStrokeRef.current = false;
- layerPixelSamplerRef.current = null;
- activeReservoirRef.current = null;
- snapSessionRef.current.endStroke();
- straightSnapSessionRef.current.endStroke();
- emitConstraintAxisChange(null);
+ abortActiveStrokeSession(
+ { isDrawingRef, effectiveDraftCanvasRef, activeTileGridRef, interactionRef },
+ sessionStateRef.current!,
+ clearPredictedCanvas,
+ emitConstraintAxisChange
+ );
}, [
activeTileGridRef,
clearPredictedCanvas,
effectiveDraftCanvasRef,
emitConstraintAxisChange,
+ interactionRef,
isDrawingRef,
]);
const getCanvasPoint = useCallback(
- (e: React.PointerEvent<HTMLElement> | PointerEvent): Point => {
- const vRect = getViewportRect();
- const dims = dimensionsRef.current;
- const bs = getBrushSettings();
- if (!vRect) {
- return { x: 0, y: 0, pressure: 0.5, width: bs.size, timestamp: e.timeStamp };
- }
-
- const { x, y } = screenToCanvas(
- e.clientX,
- e.clientY,
- vRect,
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims,
- flipXRef.current,
- flipYRef.current
- );
-
- let pressure = 0;
- if (e.pointerType === 'mouse') {
- pressure = e.buttons & 1 ? 0.5 : 0;
- } else {
- const rawP = e.pressure !== undefined ? Math.max(0, Math.min(1.0, e.pressure)) : 0;
- pressure = evaluateGlobalPressureCurve(
- rawP,
- useUiStore.getState().appSettings.pressureCurve
- );
- }
-
- const width = calculateStrokeWidth(
- bs.size,
- pressure,
- bs.minSizeFactor,
- bs.usePressure,
- e.pointerType,
- bs.pressureCurveGamma ?? 1.0,
- 1.0,
- bs.pressureCurve
- );
-
- return {
- x,
- y,
- pressure,
- width,
- tiltX: e.tiltX ?? 0,
- tiltY: e.tiltY ?? 0,
- twist: e.twist ?? 0,
- timestamp: e.timeStamp,
- };
- },
+ (e: React.PointerEvent<HTMLElement> | PointerEvent): Point =>
+ computeCanvasPoint(
+ e,
+ { dimensionsRef, panRef, zoomRef, rotationRef, flipXRef, flipYRef },
+ getViewportRect,
+ getBrushSettings
+ ),
[dimensionsRef, flipXRef, flipYRef, getBrushSettings, getViewportRect, panRef, rotationRef, zoomRef]
);
const resolveEffectiveOpacitySensor = useCallback(
- (bs: BrushSettings, isMonochrome: boolean, isEraser: boolean) => {
- if (bs.opacitySensor) return bs.opacitySensor;
- if (bs.usePressure && !isMonochrome && !isEraser && (bs.flow ?? 1.0) < 0.99) {
- return { usePressure: true, pressureMin: 0.2 };
- }
- return undefined;
- },
+ (bs: BrushSettings, isMonochrome: boolean, isEraser: boolean) =>
+ resolveEffectiveOpacitySensorValue(bs, isMonochrome, isEraser),
[]
);
const resolveLiveAntiAlias = useCallback(
- (bs: BrushSettings, isMonochrome: boolean, scale: number): number | undefined => {
- const downscaled = scale < 0.999;
- if (isMonochrome) {
- const allowGpuMono = (bs.antiAlias ?? 2) !== 0 && bs.useGpu !== false;
- if (allowGpuMono || downscaled) {
- return (bs.antiAlias ?? 2) !== 0 ? (bs.antiAlias ?? 2) : 2;
- }
- return 0;
- }
- if (bs.antiAlias === 0 && downscaled) {
- return 2;
- }
- return bs.antiAlias;
- },
+ (bs: BrushSettings, isMonochrome: boolean, scale: number): number | undefined =>
+ resolveLiveAntiAliasValue(bs, isMonochrome, scale),
[]
);
const buildTouchedTileSpans = useCallback(
- (
- sx: number,
- sy: number,
- dw: number,
- dh: number
- ): Array<{ x: number; y: number; width: number; height: number }> => {
- if (dw * dh <= TILE_SIZE * TILE_SIZE || touchedTilesRef.current.size === 0) {
- return [{ x: sx, y: sy, width: dw, height: dh }];
- }
- const rows = new Map<number, number[]>();
- for (const key of touchedTilesRef.current) {
- const ty = Math.floor(key / 65536);
- const tx = key % 65536;
- let list = rows.get(ty);
- if (!list) {
- list = [];
- rows.set(ty, list);
- }
- list.push(tx);
- }
- const spans: Array<{ x: number; y: number; width: number; height: number }> = [];
- for (const [ty, txList] of rows) {
- txList.sort((a, b) => a - b);
- let spanStart = txList[0];
- let spanEnd = txList[0];
- const pushClampedSpan = (s0: number, s1: number) => {
- const rx = Math.max(sx, s0 * TILE_SIZE);
- const ry = Math.max(sy, ty * TILE_SIZE);
- const rxEnd = Math.min(sx + dw, (s1 + 1) * TILE_SIZE);
- const ryEnd = Math.min(sy + dh, (ty + 1) * TILE_SIZE);
- const rw = rxEnd - rx;
- const rh = ryEnd - ry;
- if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
- };
- for (let i = 1; i < txList.length; i++) {
- if (txList[i] <= spanEnd + 1) {
- spanEnd = txList[i];
- } else {
- pushClampedSpan(spanStart, spanEnd);
- spanStart = txList[i];
- spanEnd = txList[i];
- }
- }
- pushClampedSpan(spanStart, spanEnd);
- }
- return spans.length > 0 ? spans : [{ x: sx, y: sy, width: dw, height: dh }];
- },
+ (sx: number, sy: number, dw: number, dh: number): TouchedTileSpan[] =>
+ buildTouchedTileSpansFromSet(sessionStateRef.current!.touchedTiles, sx, sy, dw, dh),
[]
);
- const buildLiveTexturedOptions = useCallback(
+ const buildLiveBrushOptions = useCallback(
(
bs: BrushSettings,
strokeFlow: number,
@@ -583,121 +232,22 @@ export function useBrushStrokeSession({
isBgEraser: boolean,
isolatedPass: boolean = false,
effectiveAntiAlias?: number
- ): TexturedBrushOptions => ({
- size: bs.size,
- minSizeFactor: bs.minSizeFactor,
- opacity: isolatedPass ? 1.0 : bs.opacity,
- flow: strokeFlow,
- adjustDensityByGap: bs.adjustDensityByGap,
- blendTipsMode: bs.blendTipsMode,
- spacing: strokeSpacing,
- thickness: bs.thickness,
- thicknessVertical: bs.thicknessVertical,
- flipH: bs.flipH,
- flipV: bs.flipV,
- isColorTip: bs.isColorTip,
- angle: bs.customTipAngle,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- hardness: strokeHardness,
- antiAlias: effectiveAntiAlias !== undefined ? effectiveAntiAlias : isMonochrome ? 0 : bs.antiAlias,
- pressureCurve: bs.pressureCurve,
- velocityCurve: bs.velocityCurve,
- usePressure: bs.usePressure,
- useVelocity: bs.useVelocity,
- useTilt: Boolean(bs.useTilt),
- tiltScale: bs.tiltScale,
- sizeSensor: bs.sizeSensor,
- opacitySensor: resolveEffectiveOpacitySensor(bs, isMonochrome, isEraser),
- densitySensor: bs.densitySensor,
- subTips: bs.subTips,
- subTipOrder: bs.subTipOrder,
- subTipImages: bs.subTipImages,
- spray: bs.spray,
- taper: bs.taper,
- colorMixing: bs.colorMixing,
- perceptualMixing: bs.perceptualMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- wetEdge: 0,
- grain: bs.grain ?? bs.textureDensity,
- paperTextureMode: bs.paperTextureMode,
- paperTextureBrightness: bs.paperTextureBrightness,
- paperTextureContrast: bs.paperTextureContrast,
- paperTextureInverted: bs.paperTextureInverted,
- paperTextureImage: bs.paperTextureImage,
- paperTextureScale: bs.paperTextureScale,
- paperTextureRotate: bs.paperTextureRotate,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- useGpu: bs.useGpu !== false,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- isEraser: isolatedPass ? false : isEraser && !isBgEraser,
- isBgEraser: isolatedPass ? false : isBgEraser,
- alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
- isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
- currentStrokeDist: strokeTotalDistanceRef.current,
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- }),
- [resolveEffectiveOpacitySensor]
- );
-
- const buildLiveRadialOptions = useCallback(
- (
- bs: BrushSettings,
- isMonochrome: boolean,
- canvas: HTMLCanvasElement | null,
- activeLayer: LayerItem | undefined,
- isolatedPass: boolean = false,
- effectiveAntiAlias?: number
- ): RadialMixingOptions => ({
- colorMixing: bs.colorMixing,
- perceptualMixing: bs.perceptualMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
- isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- useGpu: bs.useGpu !== false,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- useTilt: Boolean(bs.useTilt),
- tiltScale: bs.tiltScale,
- thicknessVertical: bs.thicknessVertical,
- flipH: bs.flipH,
- flipV: bs.flipV,
- antiAlias: effectiveAntiAlias !== undefined ? effectiveAntiAlias : isMonochrome ? 0 : bs.antiAlias,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- adjustDensityByGap: bs.adjustDensityByGap,
- blendTipsMode: bs.blendTipsMode,
- grain: bs.grain ?? bs.textureDensity,
- paperTextureMode: bs.paperTextureMode,
- paperTextureBrightness: bs.paperTextureBrightness,
- paperTextureContrast: bs.paperTextureContrast,
- paperTextureInverted: bs.paperTextureInverted,
- paperTextureImage: bs.paperTextureImage,
- paperTextureScale: bs.paperTextureScale,
- paperTextureRotate: bs.paperTextureRotate,
- sizeSensor: bs.sizeSensor,
- opacitySensor: resolveEffectiveOpacitySensor(bs, isMonochrome, false),
- densitySensor: bs.densitySensor,
- taper: bs.taper,
- }),
- [resolveEffectiveOpacitySensor]
+ ): BrushRenderOptions =>
+ createLiveBrushOptions(
+ sessionStateRef.current!,
+ bs,
+ strokeFlow,
+ strokeSpacing,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ isolatedPass,
+ effectiveAntiAlias
+ ),
+ []
);
const resolveStrokeColor = useCallback(
@@ -707,30 +257,13 @@ export function useBrushStrokeSession({
isBgEraser: boolean,
isMonochrome: boolean,
mode: CanvasColorMode
- ): string => {
- if (isMaskModeRef.current) {
- if (isEraser) return '#000000';
- let clean = bs.color.replace('#', '');
- if (clean.length === 3) {
- clean = clean
- .split('')
- .map((c) => c + c)
- .join('');
- }
- const r = parseInt(clean.slice(0, 2), 16) || 0;
- const g = parseInt(clean.slice(2, 4), 16) || 0;
- const b = parseInt(clean.slice(4, 6), 16) || 0;
- const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
- const hexVal = gray.toString(16).padStart(2, '0');
- return `#${hexVal}${hexVal}${hexVal}`;
- }
- return isBgEraser
- ? '#ffffff'
- : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
- },
+ ): string =>
+ resolveStrokeColorValue(isMaskModeRef.current, bs, isEraser, isBgEraser, isMonochrome, mode),
[isMaskModeRef]
);
+ const helpersRef = useRef<StrokeSessionHelpers | null>(null);
+
const emitLiveSegment = useCallback(
(
draftCtx: CanvasRenderingContext2D,
@@ -741,7 +274,6 @@ export function useBrushStrokeSession({
strokeFlow: number,
strokeSpacing: number,
isMonochrome: boolean,
- isPencil: boolean,
isEraser: boolean,
isBgEraser: boolean,
useWireframeEraser: boolean,
@@ -749,1327 +281,80 @@ export function useBrushStrokeSession({
activeLayer: LayerItem | undefined,
gpuBatch: GpuDab[] | undefined
) => {
- const sStart = seg.p0;
- const c1Pt = seg.c1;
- const c2Pt = seg.c2;
- const sEnd = seg.p3;
-
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const segPad = Math.ceil(
- Math.max(sStart.width, sEnd.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32
+ emitLiveSegmentToDraft(
+ sessionStateRef.current!,
+ paramsRef.current,
+ helpersRef.current!,
+ draftCtx,
+ seg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ gpuBatch
);
- const segMinX = Math.min(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) - segPad;
- const segMinY = Math.min(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) - segPad;
- const segMaxX = Math.max(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) + segPad;
- const segMaxY = Math.max(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) + segPad;
- strokePipelineRef.current.expandDirtyRectBounds(segMinX, segMinY, segMaxX, segMaxY);
- markTouchedTiles(segMinX, segMinY, segMaxX, segMaxY);
-
- if (useWireframeEraser) {
- draftCtx.save();
- draftCtx.lineCap = 'round';
- draftCtx.lineJoin = 'round';
- draftCtx.setLineDash([4, 4]);
- draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
- draftCtx.lineWidth = Math.max(1, (sStart.width + sEnd.width) / 2);
- draftCtx.beginPath();
- draftCtx.moveTo(sStart.x, sStart.y);
- draftCtx.bezierCurveTo(c1Pt.x, c1Pt.y, c2Pt.x, c2Pt.y, sEnd.x, sEnd.y);
- draftCtx.stroke();
- draftCtx.restore();
- return;
- }
-
- const liveColor =
- (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- const draftCanvas = effectiveDraftCanvasRef?.current as
- | DraftCanvasElement
- | null
- | undefined;
- const draftScale = draftCanvas?.__draftScale ?? 1.0;
- const liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
-
- if (bs.customTipImage) {
- const tipOptions = buildLiveTexturedOptions(
- bs,
- isMonochrome ? 1.0 : bs.flow ?? 1.0,
- bs.spacing ?? 0.08,
- strokeHardness,
- isMonochrome,
- canvas,
- activeLayer,
- isEraser,
- isBgEraser,
- true,
- liveAA
- );
- stampRemainderDistRef.current = drawTexturedCubicBezierSegment(
- draftCtx,
- sStart,
- c1Pt,
- c2Pt,
- sEnd,
- liveColor,
- bs.customTipImage,
- tipOptions,
- stampRemainderDistRef.current,
- liveDabCounterRef.current,
- gpuBatch
- );
- } else if (isPencil) {
- const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- stampRemainderDistRef.current = drawPencilCubicBezierSegment(
- draftCtx,
- sStart,
- c1Pt,
- c2Pt,
- sEnd,
- liveColor,
- grade,
- isMonochrome ? 1.0 : bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- strokeHardness,
- stampRemainderDistRef.current,
- false,
- false,
- bs.useTilt ?? true
- );
- } else {
- const radialMixingOptions = buildLiveRadialOptions(
- bs,
- isMonochrome,
- canvas,
- activeLayer,
- true,
- liveAA
- );
- stampRemainderDistRef.current = drawSmoothCubicBezierSegment(
- draftCtx,
- sStart,
- c1Pt,
- c2Pt,
- sEnd,
- liveColor,
- false,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- stampRemainderDistRef.current,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180,
- radialMixingOptions,
- gpuBatch
- );
- }
},
- [
- buildLiveRadialOptions,
- buildLiveTexturedOptions,
- effectiveDraftCanvasRef,
- markTouchedTiles,
- resolveLiveAntiAlias,
- ]
+ []
);
- const renderPredictedStroke = useCallback(
- (predEvents: PointerEvent[], vRect: DOMRect) => {
- clearPredictedCanvas();
- const bs = getBrushSettings();
- if (getTool() === 'eraser' || bs.isTransparentInk || bs.colorMixing) return;
- const pipeline = strokePipelineRef.current;
- if (pipeline.getKnotCount() < 2) return;
- const pCanvas = getPredictedCanvas();
- if (!pCanvas) return;
- const pCtx = get2DContext(pCanvas);
- if (!pCtx) return;
-
- const dims = dimensionsRef.current;
- const mode = colorModeRef.current;
- const currentLayerId = activeLayerIdRef.current;
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isPencil = !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const strokeColor = resolveStrokeColor(bs, false, false, isMonochrome, mode);
- const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
- const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
- const strokeSpacing = bs.spacing ?? 0.08;
-
- const maxPredDist = Math.min(20, Math.max(4, (bs.size || 10) * 1.15));
- const predCoords = predDocCoordsRef.current;
- predCoords.length = 0;
-
- if (predEvents && predEvents.length > 0) {
- const scratch = scratchDocCoordRef.current;
- const pool = predCoordPoolRef.current;
- const limit = Math.min(predEvents.length, pool.length);
- for (let i = 0; i < limit; i++) {
- const ev = predEvents[i];
- screenToCanvasInto(
- ev.clientX,
- ev.clientY,
- vRect,
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims,
- scratch,
- flipXRef.current,
- flipYRef.current
- );
- const slot = pool[i];
- slot.x = scratch.x;
- slot.y = scratch.y;
- slot.pressure = ev.pressure;
- predCoords.push(slot);
- }
- }
-
- const scaleX = pCanvas.width / Math.max(1, vRect.width);
- const scaleY = pCanvas.height / Math.max(1, vRect.height);
- const matrix = getCanvasToViewportMatrix(
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims,
- scaleX,
- scaleY,
- flipXRef.current,
- flipYRef.current
- );
-
- pCtx.save();
- pCtx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);
- pCtx.beginPath();
- pCtx.rect(0, 0, dims.width, dims.height);
- pCtx.clip();
- applySelectionCanvasClip(pCtx, selectionRef.current);
-
- let predRem = stampRemainderDistRef.current;
- const predAA = resolveLiveAntiAlias(bs, isMonochrome, zoomRef.current);
- const predTipOpts: TexturedBrushOptions | null = bs.customTipImage
- ? {
- size: bs.size,
- minSizeFactor: bs.minSizeFactor,
- opacity: 1.0,
- flow: strokeFlow,
- adjustDensityByGap: bs.adjustDensityByGap,
- spacing: strokeSpacing,
- thickness: bs.thickness,
- thicknessVertical: bs.thicknessVertical,
- flipH: bs.flipH,
- flipV: bs.flipV,
- angle: bs.customTipAngle,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- hardness: strokeHardness,
- antiAlias: predAA,
- pressureCurve: bs.pressureCurve,
- usePressure: bs.usePressure,
- useTilt: Boolean(bs.useTilt),
- tiltScale: bs.tiltScale,
- sizeSensor: bs.sizeSensor,
- opacitySensor: resolveEffectiveOpacitySensor(bs, isMonochrome, false),
- densitySensor: bs.densitySensor,
- subTips: bs.subTips,
- subTipOrder: bs.subTipOrder,
- subTipImages: bs.subTipImages,
- spray: bs.spray,
- wetEdge: 0,
- grain: bs.grain ?? bs.textureDensity,
- paperTextureMode: bs.paperTextureMode,
- paperTextureBrightness: bs.paperTextureBrightness,
- paperTextureContrast: bs.paperTextureContrast,
- paperTextureInverted: bs.paperTextureInverted,
- paperTextureImage: bs.paperTextureImage,
- paperTextureScale: bs.paperTextureScale,
- paperTextureRotate: bs.paperTextureRotate,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- useGpu: bs.useGpu !== false,
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- }
- : null;
- const predRadialOpts: RadialMixingOptions = {
- useGpu: bs.useGpu !== false,
- antiAlias: predAA,
- useTilt: Boolean(bs.useTilt),
- tiltScale: bs.tiltScale,
- adjustDensityByGap: bs.adjustDensityByGap,
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- grain: bs.grain ?? bs.textureDensity,
- paperTextureMode: bs.paperTextureMode,
- paperTextureBrightness: bs.paperTextureBrightness,
- paperTextureContrast: bs.paperTextureContrast,
- paperTextureInverted: bs.paperTextureInverted,
- paperTextureImage: bs.paperTextureImage,
- paperTextureScale: bs.paperTextureScale,
- paperTextureRotate: bs.paperTextureRotate,
- sizeSensor: bs.sizeSensor,
- opacitySensor: resolveEffectiveOpacitySensor(bs, isMonochrome, false),
- densitySensor: bs.densitySensor,
- };
-
- const predGpuDabs = frameGpuDabsRef.current;
- predGpuDabs.length = 0;
- const useGpuPred = bs.customTipImage
- ? Boolean(predTipOpts && canUseWebGlForTexturedBrush(predTipOpts))
- : !isPencil && canUseWebGlForRadialBrush(predRadialOpts);
-
- predDabCounterRef.current.count = liveDabCounterRef.current.count;
-
- const drew = pipeline.buildPredictedSegments(null, maxPredDist, (seg) => {
- if (bs.customTipImage && predTipOpts) {
- predRem = drawTexturedCubicBezierSegment(
- pCtx,
- seg.p0,
- seg.c1,
- seg.c2,
- seg.p3,
- strokeColor,
- bs.customTipImage,
- predTipOpts,
- predRem,
- predDabCounterRef.current,
- useGpuPred ? predGpuDabs : undefined
- );
- } else if (isPencil) {
- const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- predRem = drawPencilCubicBezierSegment(
- pCtx,
- seg.p0,
- seg.c1,
- seg.c2,
- seg.p3,
- strokeColor,
- grade,
- isMonochrome ? 1.0 : bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- strokeHardness,
- predRem,
- false,
- false
- );
- } else {
- predRem = drawSmoothCubicBezierSegment(
- pCtx,
- seg.p0,
- seg.c1,
- seg.c2,
- seg.p3,
- strokeColor,
- false,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- predRem,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180,
- predRadialOpts,
- useGpuPred ? predGpuDabs : undefined
- );
- }
- });
-
- if (useGpuPred && predGpuDabs.length > 0) {
- if (bs.customTipImage && predTipOpts) {
- flushTexturedGpuDabs(pCtx, predGpuDabs, bs.customTipImage, strokeColor, predTipOpts);
- } else {
- flushRadialGpuDabs(
- pCtx,
- predGpuDabs,
- strokeColor,
- strokeHardness,
- false,
- false,
- predRadialOpts
- );
- }
- predGpuDabs.length = 0;
- }
-
- pCtx.restore();
- if (drew) {
- isPredictedCanvasDirtyRef.current = true;
- }
- },
- [
- activeLayerIdRef,
- clearPredictedCanvas,
- colorModeRef,
- dimensionsRef,
- flipXRef,
- flipYRef,
- getBrushSettings,
- getPredictedCanvas,
- getTool,
- layersRef,
- panRef,
- resolveEffectiveOpacitySensor,
- resolveLiveAntiAlias,
- resolveStrokeColor,
- rotationRef,
- selectionRef,
- zoomRef,
- ]
- );
+ const renderPredictedStroke = useCallback((predEvents: PointerEvent[], vRect: DOMRect) => {
+ renderPredictedStrokeOverlay(
+ sessionStateRef.current!,
+ paramsRef.current,
+ helpersRef.current!,
+ predEvents,
+ vRect
+ );
+ }, []);
const flushPendingPoints = useCallback((skipDisplayArg?: boolean | number) => {
- drawRafIdRef.current = null;
- if (!isDrawingRef.current) return;
- const isSkipDisplay = skipDisplayArg === true;
-
- const pipeline = strokePipelineRef.current;
- if (pipeline.getPendingCount() === 0) {
- if (isSkipDisplay) {
- latestPredictedRef.current = null;
- return;
- }
- const predData = latestPredictedRef.current;
- latestPredictedRef.current = null;
- const vRect = getViewportRect();
- if (vRect && allStrokePointsRef.current.length > 0) {
- renderPredictedStroke(predData ? predData.predEvents : [], vRect);
- } else if (isPredictedCanvasDirtyRef.current) {
- clearPredictedCanvas();
- }
- return;
- }
-
- const draftCanvas = effectiveDraftCanvasRef?.current as
- | DraftCanvasElement
- | null
- | undefined;
- if (!draftCanvas) return;
- const draftCtx = get2DContext(draftCanvas);
- if (!draftCtx) return;
-
- const bs = getBrushSettings();
- const mode = colorModeRef.current;
- const isEraser = getTool() === 'eraser';
- const currentLayerId = activeLayerIdRef.current;
- const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const isVectorOrToneOrMask =
- activeLayer?.type === 'vector' || isToneStrokeRef.current || isMaskModeRef.current;
- const useWireframeEraser = isVectorOrToneOrMask && isEraser && !isBgEraser;
- const canvas = getCachedLayerCanvas();
- const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
- const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
- const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
- const strokeSpacing = bs.spacing ?? 0.08;
- const hasTaper = Boolean(bs.taper?.useOut || bs.taper?.useIn);
- const globalCurve = pipeline.getGlobalPressureCurve();
- const hasCustomGlobalCurve = Boolean(
- globalCurve && globalCurve.enabled && !isLinearPressureCurve(globalCurve.points)
+ runFlushPendingPoints(
+ sessionStateRef.current!,
+ paramsRef.current,
+ helpersRef.current!,
+ skipDisplayArg
);
- const hasCustomCurve =
- hasCustomGlobalCurve || Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
- const taperEngine = pipeline.getTaperEngine();
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const blurMargin = (1 - strokeHardness) * ((bs.size || 10) * 1.5);
- const dirtyPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + blurMargin + 24);
-
- const draftScale = draftCanvas.__draftScale ?? 1.0;
- const liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
- const liveTipOpts = bs.customTipImage
- ? buildLiveTexturedOptions(
- bs,
- isMonochrome ? 1.0 : bs.flow ?? 1.0,
- strokeSpacing,
- strokeHardness,
- isMonochrome,
- canvas,
- activeLayer,
- isEraser,
- isBgEraser,
- true,
- liveAA
- )
- : null;
- const liveRadialOpts =
- !bs.customTipImage && !isPencil
- ? buildLiveRadialOptions(
- bs,
- isMonochrome,
- canvas,
- activeLayer,
- true,
- liveAA
- )
- : null;
- const useGpuBatch =
- !useWireframeEraser &&
- (bs.customTipImage
- ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
- : !isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts)));
-
- const gpuBatch = frameGpuDabsRef.current;
- gpuBatch.length = 0;
-
- const collabActive = Boolean(currentStrokeIdRef.current && onCollabStrokeChunkRef.current);
- const chunkPts: Point[] | null = collabActive ? [] : null;
- let drewAnySegment = false;
-
- pipeline.drain({
- dirtyPadExtra,
- resolvePoint: (rawX, rawY, rawPressure, stabPressure, pointerType, _vx, _vy, dtMs, out) => {
- let velocityScale = 1.0;
- if (bs.velocityDynamics && stabilizedPointRef.current) {
- const dist = Math.hypot(
- rawX - stabilizedPointRef.current.x,
- rawY - stabilizedPointRef.current.y
- );
- const speed = dist / Math.max(1, dtMs);
- velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
- }
-
- const baseP = bs.usePressure
- ? hasCustomCurve
- ? stabPressure
- : taperEngine.mapPressure(stabPressure)
- : rawPressure > 0
- ? 1.0
- : 0;
- const mappedP = bs.usePressure ? taperEngine.smoothPressure(baseP) : baseP;
- let width = calculateStrokeWidth(
- bs.size,
- mappedP,
- bs.minSizeFactor,
- bs.usePressure,
- pointerType,
- bs.pressureCurveGamma ?? 1.0,
- velocityScale,
- bs.pressureCurve
- );
- if (isMonochrome && !hasTaper && width < 1.25) {
- width = 1.25;
- }
- out.pressure = mappedP;
- out.width = width;
- },
- onPoint: (sample) => {
- const pt: Point = {
- x: sample.x,
- y: sample.y,
- pressure: sample.pressure,
- width: sample.width,
- tiltX: sample.tiltX,
- tiltY: sample.tiltY,
- twist: sample.twist,
- timestamp: sample.timestamp,
- isCorner: sample.isCorner,
- };
- if (allStrokePointsRef.current.length > 0) {
- const prev = allStrokePointsRef.current[allStrokePointsRef.current.length - 1];
- strokeTotalDistanceRef.current += Math.hypot(pt.x - prev.x, pt.y - prev.y);
- }
- stabilizedPointRef.current = pt;
- lastPointTimeRef.current = sample.timestamp;
- allStrokePointsRef.current.push(pt);
- recentPointsTrailRef.current.push({
- x: pt.x,
- y: pt.y,
- t: sample.timestamp || performance.now(),
- pressure: pt.pressure,
- width: pt.width,
- });
- if (recentPointsTrailRef.current.length > 16) {
- recentPointsTrailRef.current.shift();
- }
- if (chunkPts) {
- chunkPts.push(pt);
- }
- },
- onSegment: (seg) => {
- drewAnySegment = true;
- emitLiveSegment(
- draftCtx,
- seg,
- bs,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isMonochrome,
- isPencil,
- isEraser,
- isBgEraser,
- useWireframeEraser,
- canvas,
- activeLayer,
- useGpuBatch ? gpuBatch : undefined
- );
- },
- });
-
- if (useGpuBatch && gpuBatch.length > 0) {
- const liveColor =
- (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- let flushed = false;
- if (bs.customTipImage && liveTipOpts) {
- flushed = flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, liveTipOpts);
- } else if (liveRadialOpts) {
- flushed = flushRadialGpuDabs(
- draftCtx,
- gpuBatch,
- liveColor,
- strokeHardness,
- false,
- false,
- liveRadialOpts
- );
- }
- if (!flushed) {
- const pts = allStrokePointsRef.current;
- if (pts.length >= 2) {
- const pA = pts[pts.length - 2];
- const pB = pts[pts.length - 1];
- const fallbackSeg = pipeline.getSplineGenerator().generateCornerSegment(pA, pB);
- emitLiveSegment(
- draftCtx,
- fallbackSeg,
- bs,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isMonochrome,
- isPencil,
- isEraser,
- isBgEraser,
- useWireframeEraser,
- canvas,
- activeLayer,
- undefined
- );
- }
- }
- gpuBatch.length = 0;
- }
+ }, []);
- const pDirty = pipeline.dirtyRect;
- if (Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX)) {
- const dims = dimensionsRef.current;
- if (!dirtyRectRef.current) {
- dirtyRectRef.current = {
- minX: Math.max(0, pDirty.minX),
- minY: Math.max(0, pDirty.minY),
- maxX: Math.min(dims.width, pDirty.maxX),
- maxY: Math.min(dims.height, pDirty.maxY),
- };
- } else {
- dirtyRectRef.current.minX = Math.max(0, Math.min(dirtyRectRef.current.minX, pDirty.minX));
- dirtyRectRef.current.minY = Math.max(0, Math.min(dirtyRectRef.current.minY, pDirty.minY));
- dirtyRectRef.current.maxX = Math.min(dims.width, Math.max(dirtyRectRef.current.maxX, pDirty.maxX));
- dirtyRectRef.current.maxY = Math.min(dims.height, Math.max(dirtyRectRef.current.maxY, pDirty.maxY));
- }
- }
-
- if (drewAnySegment) {
- draftCanvas.__draftHasContent = true;
- draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
- liveNeedsNotifyRef.current = true;
- }
-
- if (currentStrokeIdRef.current && chunkPts && chunkPts.length > 0) {
- onCollabStrokeChunkRef.current?.(currentStrokeIdRef.current, chunkPts);
- }
-
- if (!isSkipDisplay && liveNeedsNotifyRef.current) {
- liveNeedsNotifyRef.current = false;
- activeTileGridRef.current.notifyChange(true);
- }
-
- const predData = latestPredictedRef.current;
- latestPredictedRef.current = null;
- if (!isSkipDisplay) {
- const vRect = getViewportRect();
- if (vRect && allStrokePointsRef.current.length > 0) {
- renderPredictedStroke(predData ? predData.predEvents : [], vRect);
- } else if (isPredictedCanvasDirtyRef.current) {
- clearPredictedCanvas();
- }
- }
- }, [
- activeLayerIdRef,
- activeTileGridRef,
- buildLiveRadialOptions,
- buildLiveTexturedOptions,
- clearPredictedCanvas,
- colorModeRef,
- dimensionsRef,
- effectiveDraftCanvasRef,
- emitLiveSegment,
- getBrushSettings,
- getCachedLayerCanvas,
+ helpersRef.current = {
getTool,
+ getBrushSettings,
+ getPredictedCanvas,
+ clearPredictedCanvas,
+ emitConstraintAxisChange,
+ markTouchedTiles,
getViewportRect,
- isDrawingRef,
- isMaskModeRef,
- layersRef,
- onCollabStrokeChunkRef,
- renderPredictedStroke,
+ dispatchPointerStat,
+ abortActiveStroke,
+ getCanvasPoint,
+ resolveEffectiveOpacitySensor,
resolveLiveAntiAlias,
+ buildTouchedTileSpans,
+ buildLiveBrushOptions,
resolveStrokeColor,
- ]);
+ emitLiveSegment,
+ renderPredictedStroke,
+ flushPendingPoints,
+ };
const handlePointerDown = useCallback(
- (e: React.PointerEvent<HTMLElement>, _coalescedEvents?: PointerEvent[]) => {
- const currentTool = getTool();
- const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';
- if (
- !isBrushOrEraser ||
- disabled ||
- e.button !== 0 ||
- activeLayerLockedRef.current ||
- !activeLayerVisibleRef.current
- ) {
- return;
- }
- e.preventDefault();
- if (isDrawingRef.current) {
- abortActiveStroke();
- }
-
- const dims = dimensionsRef.current;
- const currentLayerIdCheck = activeLayerIdRef.current;
- if (!currentLayerIdCheck || dims.width <= 0 || dims.height <= 0) return;
-
- const canvas = getCachedLayerCanvas();
- const activeLayerPre = (layersRef.current || []).find((l) => l.id === currentLayerIdCheck);
- if (isMaskModeRef.current || canvas !== null || Boolean(activeLayerPre?.toneEnabled)) {
- flushPendingHistoryTasks();
- }
- if (isMaskModeRef.current && !canvas) return;
-
- if (viewportRef.current) {
- cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
- }
- const vRect = getViewportRect();
- if (!vRect) return;
-
- const draftCanvas = effectiveDraftCanvasRef?.current as
- | DraftCanvasElement
- | null
- | undefined;
- if (!draftCanvas) return;
-
- if (clearDraftRafRef.current !== null) {
- cancelAnimationFrame(clearDraftRafRef.current);
- clearDraftRafRef.current = null;
- }
-
- const draftCtx = get2DContext(draftCanvas);
- if (!draftCtx) return;
-
- const isEraser = currentTool === 'eraser';
- const currentLayerId = activeLayerIdRef.current;
- const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
- const allLayers = layersRef.current || [];
- const activeLayer = allLayers.find((l) => l.id === currentLayerId);
- const bs = getBrushSettings();
- const mode = colorModeRef.current;
- const isPencil =
- !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isTone = Boolean(activeLayer?.toneEnabled);
- const isVectorLayer = activeLayer?.type === 'vector';
- const isVectorOrToneOrMask = isVectorLayer || isTone || isMaskModeRef.current;
- const useWireframeEraser = isVectorOrToneOrMask && isEraser && !isBgEraser;
- isToneStrokeRef.current = isTone;
-
- const draftCompositeOp: GlobalCompositeOperation =
- isVectorOrToneOrMask || isBgEraser
- ? 'source-over'
- : isEraser || bs.isTransparentInk
- ? 'destination-out'
- : activeLayer?.alphaLocked
- ? 'source-atop'
- : 'source-over';
-
- const rawVis = getVisibleCanvasBounds(
- vRect,
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims,
- 128,
- flipXRef.current,
- flipYRef.current
- );
- const visMinX = rawVis.maxX > rawVis.minX ? rawVis.minX : 0;
- const visMinY = rawVis.maxY > rawVis.minY ? rawVis.minY : 0;
- const visW = Math.max(1, rawVis.maxX > rawVis.minX ? rawVis.maxX - rawVis.minX : dims.width);
- const visH = Math.max(1, rawVis.maxY > rawVis.minY ? rawVis.maxY - rawVis.minY : dims.height);
- const MAX_DRAFT_DIM = 3072;
- const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
- const screenMatchedScale = Math.max(0.05, (zoomRef.current || 1) * dpr * 1.25);
- const draftScale = Math.min(1.0, screenMatchedScale, MAX_DRAFT_DIM / Math.max(visW, visH));
- const surfaceW = Math.max(1, Math.ceil(visW * draftScale));
- const surfaceH = Math.max(1, Math.ceil(visH * draftScale));
- if (draftCanvas.width !== surfaceW || draftCanvas.height !== surfaceH) {
- draftCanvas.width = surfaceW;
- draftCanvas.height = surfaceH;
- }
-
- draftCtx.resetTransform();
- draftCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
- draftCanvas.__draftHasContent = false;
- draftCanvas.__draftCompositeOp = draftCompositeOp;
- draftCanvas.__draftSpace = 'document';
- draftCanvas.__draftDocRect = {
- x: visMinX,
- y: visMinY,
- width: surfaceW / draftScale,
- height: surfaceH / draftScale,
- };
- draftCanvas.__draftScale = draftScale;
- draftCanvas.__draftMonochrome = isMonochrome;
- draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
-
- draftCtx.setTransform(
- draftScale,
- 0,
- 0,
- draftScale,
- -visMinX * draftScale,
- -visMinY * draftScale
- );
- draftCtx.save();
- draftCtx.beginPath();
- draftCtx.rect(0, 0, dims.width, dims.height);
- draftCtx.clip();
- applySelectionCanvasClip(draftCtx, selectionRef.current);
-
- clearPredictedCanvas();
-
- if (isTone) {
- let sourceCanvas = layerSourceCanvasesRef?.current?.get(currentLayerId) || null;
- if (!sourceCanvas) {
- sourceCanvas = document.createElement('canvas');
- sourceCanvas.width = dims.width;
- sourceCanvas.height = dims.height;
- if (canvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.drawImage(canvas, 0, 0);
- } else {
- activeTileGridRef.current.renderLayerToCanvas(currentLayerId, sourceCanvas);
- }
- layerSourceCanvasesRef?.current?.set(currentLayerId, sourceCanvas);
- }
- }
-
- if (interactionRef.current) {
- try {
- interactionRef.current.setPointerCapture(e.pointerId);
- } catch {
- // Ignore pointer capture errors
- }
- }
- activePointerIdRef.current = e.pointerId;
- isDrawingRef.current = true;
- recoveryService.setDrawingActive(true);
-
- const firstEvent = e.nativeEvent;
- const rawStartPoint = getCanvasPoint(firstEvent);
- const isAltOverride = e.altKey;
- const activeStraightRuler = straightRulerRef?.current ?? null;
- const straightStart = straightSnapSessionRef.current.startStrokePoint(
- rawStartPoint,
- activeStraightRuler,
- zoomRef.current || 1.0,
- isAltOverride
- );
- let startPoint = straightStart;
- if (straightSnapSessionRef.current.isActive()) {
- snapSessionRef.current.endStroke();
- emitConstraintAxisChange(null);
- } else {
- snapSessionRef.current.startStroke(
- rawStartPoint,
- rulerRef.current ?? null,
- isAltOverride
- );
- startPoint = snapSessionRef.current.snapPoint(
- rawStartPoint,
- rulerRef.current ?? null,
- isAltOverride
- );
- emitConstraintAxisChange(snapSessionRef.current.getActiveAxis());
- }
-
- const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
- const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
- const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
- const strokeSpacing = bs.spacing ?? 0.08;
-
- const globalPressureCurve = useUiStore.getState().appSettings.pressureCurve;
- const hasCustomGlobalCurve = Boolean(
- globalPressureCurve &&
- globalPressureCurve.enabled &&
- !isLinearPressureCurve(globalPressureCurve.points)
- );
-
- const pipeline = strokePipelineRef.current;
- pipeline.beginStroke({
- stabilizerLevel: bs.stabilization ?? 0,
- zoom: zoomRef.current || 1.0,
- sharpCorners: bs.sharpCorners !== false,
- brushSize: bs.size,
- color: strokeColor,
- pointerId: e.pointerId,
- globalPressureCurve,
- });
-
- const startNow = startPoint.timestamp ?? performance.now();
- lastPointTimeRef.current = startNow;
- const hasCustomCurve =
- hasCustomGlobalCurve || Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
- const taperEngine = pipeline.getTaperEngine();
- if (bs.usePressure) {
- const baseStartP = hasCustomCurve
- ? startPoint.pressure
- : taperEngine.mapPressure(startPoint.pressure);
- const smoothStartP = taperEngine.smoothPressure(baseStartP);
- startPoint.pressure = smoothStartP;
- startPoint.width = calculateStrokeWidth(
- bs.size,
- smoothStartP,
- bs.minSizeFactor,
- bs.usePressure,
- firstEvent.pointerType,
- bs.pressureCurveGamma ?? 1.0,
- 1.0,
- bs.pressureCurve
- );
- }
- const hasTaper = Boolean(bs.taper?.useOut || bs.taper?.useIn);
- if (isMonochrome && !hasTaper && startPoint.width < 1.25) {
- startPoint.width = 1.25;
- }
-
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const blurMargin = (1 - strokeHardness) * (startPoint.width * 1.5);
- const r = Math.max(
- 32,
- Math.ceil(
- Math.max(startPoint.width, bs.size || 10) * (2.8 + scatterFactor * 2) + blurMargin + 32
- )
+ (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => {
+ runPointerDown(
+ sessionStateRef.current!,
+ paramsRef.current,
+ helpersRef.current!,
+ e,
+ coalescedEvents
);
-
- const shiftAction = useUiStore.getState().appSettings.modifierKeys.shift;
- const prevStrokeEnd = lastStrokeEndRef.current;
- const isShiftLine =
- Boolean(e.shiftKey) &&
- shiftAction === 'straight-line' &&
- !isMaskModeRef.current &&
- prevStrokeEnd !== null &&
- prevStrokeEnd.layerId === currentLayerId;
- isShiftLineStrokeRef.current = isShiftLine;
-
- if (isShiftLine && prevStrokeEnd) {
- const pLineStart: Point = {
- x: prevStrokeEnd.x,
- y: prevStrokeEnd.y,
- pressure: startPoint.pressure,
- width: startPoint.width,
- tiltX: startPoint.tiltX,
- tiltY: startPoint.tiltY,
- twist: startPoint.twist,
- timestamp: startNow - 16,
- };
- const pLineMid: Point = {
- x: (pLineStart.x + startPoint.x) * 0.5,
- y: (pLineStart.y + startPoint.y) * 0.5,
- pressure: startPoint.pressure,
- width: startPoint.width,
- tiltX: startPoint.tiltX,
- tiltY: startPoint.tiltY,
- twist: startPoint.twist,
- timestamp: startNow - 8,
- };
- allStrokePointsRef.current = [pLineStart, pLineMid, startPoint];
- pipeline.seedKnot(
- pLineStart.x,
- pLineStart.y,
- pLineStart.pressure,
- pLineStart.width,
- pLineStart.tiltX ?? 0,
- pLineStart.tiltY ?? 0,
- pLineStart.twist ?? 0,
- pLineStart.timestamp ?? 0,
- r
- );
- pipeline.seedKnot(
- pLineMid.x,
- pLineMid.y,
- pLineMid.pressure,
- pLineMid.width,
- pLineMid.tiltX ?? 0,
- pLineMid.tiltY ?? 0,
- pLineMid.twist ?? 0,
- pLineMid.timestamp ?? 0,
- r
- );
- } else {
- allStrokePointsRef.current = [startPoint];
- pipeline.seedKnot(
- startPoint.x,
- startPoint.y,
- startPoint.pressure,
- startPoint.width,
- startPoint.tiltX ?? 0,
- startPoint.tiltY ?? 0,
- startPoint.twist ?? 0,
- startNow,
- r
- );
- }
-
- stabilizedPointRef.current = { ...startPoint };
- lastProcessedPointRef.current.x = startPoint.x;
- lastProcessedPointRef.current.y = startPoint.y;
- hasLastProcessedPointRef.current = true;
- lastQueuedPressureRef.current = startPoint.pressure;
- recentPointsTrailRef.current = [
- {
- x: startPoint.x,
- y: startPoint.y,
- t: startNow,
- pressure: startPoint.pressure,
- width: startPoint.width,
- },
- ];
- strokeTotalDistanceRef.current =
- isShiftLine && prevStrokeEnd
- ? Math.hypot(startPoint.x - prevStrokeEnd.x, startPoint.y - prevStrokeEnd.y)
- : 0;
-
- dispatchPointerStat(startPoint.x, startPoint.y, startPoint.pressure);
-
- const minInitX =
- isShiftLine && prevStrokeEnd ? Math.min(startPoint.x, prevStrokeEnd.x) : startPoint.x;
- const minInitY =
- isShiftLine && prevStrokeEnd ? Math.min(startPoint.y, prevStrokeEnd.y) : startPoint.y;
- const maxInitX =
- isShiftLine && prevStrokeEnd ? Math.max(startPoint.x, prevStrokeEnd.x) : startPoint.x;
- const maxInitY =
- isShiftLine && prevStrokeEnd ? Math.max(startPoint.y, prevStrokeEnd.y) : startPoint.y;
- dirtyRectRef.current = {
- minX: Math.max(0, Math.floor(minInitX - r)),
- minY: Math.max(0, Math.floor(minInitY - r)),
- maxX: Math.min(dims.width, Math.ceil(maxInitX + r)),
- maxY: Math.min(dims.height, Math.ceil(maxInitY + r)),
- };
- pipeline.expandDirtyRectBounds(
- dirtyRectRef.current.minX,
- dirtyRectRef.current.minY,
- dirtyRectRef.current.maxX,
- dirtyRectRef.current.maxY
- );
- touchedTilesRef.current.clear();
- markTouchedTiles(
- dirtyRectRef.current.minX,
- dirtyRectRef.current.minY,
- dirtyRectRef.current.maxX,
- dirtyRectRef.current.maxY
- );
-
- const isWetColor = !isEraser && Boolean(bs.colorMixing);
- isWetColorStrokeRef.current = isWetColor;
- liveNeedsNotifyRef.current = false;
-
- if (isWetColor) {
- layerPixelSamplerRef.current = new LayerPixelSampler(
- canvas || dims,
- currentLayerId,
- activeTileGridRef.current
- );
- activeReservoirRef.current = new PaintReservoir(strokeColor);
- } else {
- layerPixelSamplerRef.current = null;
- activeReservoirRef.current = null;
- }
-
- const strokeId = `stroke-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
- currentStrokeIdRef.current = strokeId;
- onCollabStrokeStartRef.current?.(strokeId, currentLayerId, bs, currentTool, startPoint);
-
- liveDabCounterRef.current.count = 0;
- stampRemainderDistRef.current = bs.customTipImage
- ? Math.max(0.15, startPoint.width * (bs.spacing ?? 0.07))
- : isPencil
- ? Math.max(0.25, startPoint.width * (bs.spacing ?? 0.07))
- : Math.max(0.12, startPoint.width * (bs.spacing ?? 0.08));
-
- const firstDotPoint = allStrokePointsRef.current[0];
-
- if (useWireframeEraser) {
- draftCtx.save();
- draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
- draftCtx.setLineDash([3, 3]);
- draftCtx.lineWidth = Math.max(1, 1.5 / Math.max(0.05, zoomRef.current));
- draftCtx.beginPath();
- draftCtx.arc(
- firstDotPoint.x,
- firstDotPoint.y,
- Math.max(1, firstDotPoint.width / 2),
- 0,
- Math.PI * 2
- );
- draftCtx.stroke();
- draftCtx.restore();
- } else {
- const liveColor =
- (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- const liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
- const gpuBatch = frameGpuDabsRef.current;
- gpuBatch.length = 0;
-
- if (bs.customTipImage) {
- const tipOptions = buildLiveTexturedOptions(
- bs,
- isMonochrome ? 1.0 : bs.flow ?? 1.0,
- strokeSpacing,
- strokeHardness,
- isMonochrome,
- canvas,
- activeLayer,
- isEraser,
- isBgEraser,
- true,
- liveAA
- );
- const useGpu = canUseWebGlForTexturedBrush(tipOptions);
- drawTexturedDot(
- draftCtx,
- firstDotPoint,
- liveColor,
- bs.customTipImage,
- tipOptions,
- useGpu ? gpuBatch : undefined
- );
- if (useGpu && gpuBatch.length > 0) {
- if (
- !flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, tipOptions)
- ) {
- drawTexturedDot(draftCtx, firstDotPoint, liveColor, bs.customTipImage, tipOptions);
- }
- gpuBatch.length = 0;
- }
- } else if (isPencil) {
- const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- drawPencilDot(
- draftCtx,
- firstDotPoint,
- liveColor,
- grade,
- isMonochrome ? 1.0 : bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- strokeHardness,
- false,
- false
- );
- } else {
- const radialMixingOptions = buildLiveRadialOptions(
- bs,
- isMonochrome,
- canvas,
- activeLayer,
- true,
- liveAA
- );
- const useGpu = canUseWebGlForRadialBrush(radialMixingOptions);
- drawDot(
- draftCtx,
- firstDotPoint,
- liveColor,
- false,
- strokeHardness,
- strokeFlow,
- radialMixingOptions,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180,
- useGpu ? gpuBatch : undefined
- );
- if (useGpu && gpuBatch.length > 0) {
- if (
- !flushRadialGpuDabs(
- draftCtx,
- gpuBatch,
- liveColor,
- strokeHardness,
- false,
- false,
- radialMixingOptions
- )
- ) {
- drawDot(
- draftCtx,
- firstDotPoint,
- liveColor,
- false,
- strokeHardness,
- strokeFlow,
- radialMixingOptions,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180
- );
- }
- gpuBatch.length = 0;
- }
- }
- }
-
- if (isShiftLine && prevStrokeEnd) {
- const lineSeg = pipeline
- .getSplineGenerator()
- .generateCornerSegment(allStrokePointsRef.current[0], startPoint);
- const liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
- const liveTipOpts = bs.customTipImage
- ? buildLiveTexturedOptions(
- bs,
- isMonochrome ? 1.0 : bs.flow ?? 1.0,
- strokeSpacing,
- strokeHardness,
- isMonochrome,
- canvas,
- activeLayer,
- isEraser,
- isBgEraser,
- true,
- liveAA
- )
- : null;
- const liveRadialOpts =
- !bs.customTipImage && !isPencil
- ? buildLiveRadialOptions(
- bs,
- isMonochrome,
- canvas,
- activeLayer,
- true,
- liveAA
- )
- : null;
- const useGpuLine =
- !useWireframeEraser &&
- (bs.customTipImage
- ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
- : !isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts)));
- const gpuBatch = frameGpuDabsRef.current;
- gpuBatch.length = 0;
- emitLiveSegment(
- draftCtx,
- lineSeg,
- bs,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isMonochrome,
- isPencil,
- isEraser,
- isBgEraser,
- useWireframeEraser,
- canvas,
- activeLayer,
- useGpuLine ? gpuBatch : undefined
- );
- if (useGpuLine && gpuBatch.length > 0) {
- const liveColor =
- (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- if (bs.customTipImage && liveTipOpts) {
- flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, liveTipOpts);
- } else if (liveRadialOpts) {
- flushRadialGpuDabs(
- draftCtx,
- gpuBatch,
- liveColor,
- strokeHardness,
- false,
- false,
- liveRadialOpts
- );
- }
- gpuBatch.length = 0;
- }
- pipeline.seedKnot(
- startPoint.x,
- startPoint.y,
- startPoint.pressure,
- startPoint.width,
- startPoint.tiltX ?? 0,
- startPoint.tiltY ?? 0,
- startPoint.twist ?? 0,
- startNow,
- r
- );
- }
-
- draftCanvas.__draftHasContent = true;
- draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
- activeTileGridRef.current.notifyChange(true);
- liveNeedsNotifyRef.current = false;
-
- if (pipeline.getPendingCount() > 0 && drawRafIdRef.current === null) {
- drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
- }
},
- [
- abortActiveStroke,
- activeLayerIdRef,
- activeLayerLockedRef,
- activeLayerVisibleRef,
- activeTileGridRef,
- buildLiveRadialOptions,
- buildLiveTexturedOptions,
- clearPredictedCanvas,
- colorModeRef,
- dimensionsRef,
- disabled,
- dispatchPointerStat,
- effectiveDraftCanvasRef,
- emitConstraintAxisChange,
- emitLiveSegment,
- flipXRef,
- flipYRef,
- flushPendingHistoryTasks,
- flushPendingPoints,
- getBrushSettings,
- getCachedLayerCanvas,
- getCanvasPoint,
- getTool,
- getViewportRect,
- interactionRef,
- isDrawingRef,
- isMaskModeRef,
- lastStrokeEndRef,
- layerSourceCanvasesRef,
- layersRef,
- markTouchedTiles,
- onCollabStrokeStartRef,
- panRef,
- resolveLiveAntiAlias,
- resolveStrokeColor,
- rotationRef,
- rulerRef,
- selectionRef,
- straightRulerRef,
- viewportRef,
- zoomRef,
- ]
+ []
);
const handlePointerMove = useCallback(
@@ -2078,1237 +363,154 @@ export function useBrushStrokeSession({
coalescedEvents?: PointerEvent[],
predictedEvents?: PointerEvent[]
) => {
- const extEvent = e as ExtendedPointerEvent;
- if (!isDrawingRef.current || e.pointerId !== activePointerIdRef.current) {
- const point = getCanvasPoint(e);
- dispatchPointerStat(point.x, point.y, point.pressure);
- onCollabCursorMoveRef.current?.(point.x, point.y, false, getTool());
- return;
- }
-
- e.preventDefault();
-
- const vRect = getViewportRect();
- if (!vRect) return;
- const dims = dimensionsRef.current;
-
- const candidateCoalesced: PointerEvent[] | readonly PointerEvent[] | null =
- coalescedEvents ??
- extEvent.coalescedEvents ??
- (typeof e.nativeEvent?.getCoalescedEvents === 'function'
- ? e.nativeEvent.getCoalescedEvents()
- : null);
- let rawCoalesced: PointerEvent[] | readonly PointerEvent[] | null = null;
- if (candidateCoalesced && candidateCoalesced.length > 0) {
- const lastC = candidateCoalesced[candidateCoalesced.length - 1];
- const nativeEvt = e.nativeEvent;
- if (
- lastC &&
- nativeEvt &&
- Number.isFinite(lastC.clientX) &&
- Number.isFinite(lastC.clientY) &&
- Math.hypot(lastC.clientX - nativeEvt.clientX, lastC.clientY - nativeEvt.clientY) <= 1.5
- ) {
- rawCoalesced = candidateCoalesced;
- }
- }
- const count = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced.length : 1;
-
- const pipeline = strokePipelineRef.current;
- const scratch = scratchDocCoordRef.current;
- const lastProc = lastProcessedPointRef.current;
- const minStepDoc = Math.min(0.25, 0.25 / Math.max(0.05, zoomRef.current));
- const isAltOverride = e.altKey;
- const isShiftKey = e.shiftKey;
- const ruler = rulerRef.current ?? null;
- const activeStraightRuler = straightRulerRef?.current ?? null;
- const curPan = panRef.current;
- const curZoom = zoomRef.current;
- const curRot = rotationRef.current;
- const curFlipX = flipXRef.current;
- const curFlipY = flipYRef.current;
-
- let lastQueuedX = 0;
- let lastQueuedY = 0;
- let lastQueuedPressure = lastQueuedPressureRef.current;
- let hasQueued = false;
-
- for (let i = 0; i < count; i++) {
- const cEvent = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced[i] : e.nativeEvent;
- screenToCanvasInto(
- cEvent.clientX,
- cEvent.clientY,
- vRect,
- curPan,
- curZoom,
- curRot,
- dims,
- scratch,
- curFlipX,
- curFlipY
- );
-
- let cx = scratch.x;
- let cy = scratch.y;
- const straightRes = straightSnapSessionRef.current.processPoint(
- scratch,
- activeStraightRuler,
- isAltOverride
- );
- if (straightRes.snapped) {
- cx = straightRes.x;
- cy = straightRes.y;
- } else {
- const snapRes = snapSessionRef.current.processPoint(scratch, ruler, isAltOverride);
- cx = snapRes.x;
- cy = snapRes.y;
- if (snapRes.axis) {
- emitConstraintAxisChange(snapRes.axis);
- } else if (
- !isShiftLineStrokeRef.current &&
- isShiftKey &&
- useUiStore.getState().appSettings.modifierKeys.shift === 'straight-line' &&
- !ruler?.enabled &&
- !(activeStraightRuler?.enabled && activeStraightRuler?.snapEnabled) &&
- allStrokePointsRef.current.length > 0
- ) {
- const originPt = allStrokePointsRef.current[0];
- const dx = cx - originPt.x;
- const dy = cy - originPt.y;
- const dist = Math.hypot(dx, dy);
- if (dist > 0.5) {
- const snapAngle = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);
- cx = originPt.x + Math.cos(snapAngle) * dist;
- cy = originPt.y + Math.sin(snapAngle) * dist;
- }
- }
- }
-
- let cPressure = 0;
- if (cEvent.pointerType === 'mouse') {
- cPressure = cEvent.buttons & 1 ? 0.5 : 0;
- } else {
- cPressure =
- cEvent.pressure !== undefined ? Math.max(0, Math.min(1.0, cEvent.pressure)) : 0;
- }
-
- if (
- hasLastProcessedPointRef.current &&
- Math.hypot(cx - lastProc.x, cy - lastProc.y) < minStepDoc &&
- Math.abs(cPressure - lastQueuedPressure) <= 0.04
- ) {
- continue;
- }
-
- lastProc.x = cx;
- lastProc.y = cy;
- hasLastProcessedPointRef.current = true;
-
- pipeline.enqueueSample(
- cx,
- cy,
- cPressure,
- cEvent.tiltX ?? 0,
- cEvent.tiltY ?? 0,
- cEvent.twist ?? 0,
- cEvent.timeStamp,
- encodePointerType(cEvent.pointerType)
- );
- lastQueuedX = cx;
- lastQueuedY = cy;
- lastQueuedPressure = cPressure;
- hasQueued = true;
- }
-
- lastQueuedPressureRef.current = lastQueuedPressure;
-
- const rawPredicted =
- predictedEvents ??
- extEvent.predictedEvents ??
- (typeof e.nativeEvent?.getPredictedEvents === 'function'
- ? e.nativeEvent.getPredictedEvents()
- : null);
-
- if (rawPredicted && rawPredicted.length > 0) {
- latestPredictedRef.current = { predEvents: rawPredicted, vRect };
- } else {
- latestPredictedRef.current = null;
- }
-
- if (hasQueued) {
- dispatchPointerStat(lastQueuedX, lastQueuedY, lastQueuedPressure);
- onCollabCursorMoveRef.current?.(lastQueuedX, lastQueuedY, true, getTool());
- }
-
- if (
- (pipeline.getPendingCount() > 0 || latestPredictedRef.current !== null) &&
- drawRafIdRef.current === null
- ) {
- drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
- }
+ runPointerMove(
+ sessionStateRef.current!,
+ paramsRef.current,
+ helpersRef.current!,
+ e,
+ coalescedEvents,
+ predictedEvents
+ );
},
- [
- dimensionsRef,
- dispatchPointerStat,
- emitConstraintAxisChange,
- flipXRef,
- flipYRef,
- flushPendingPoints,
- getCanvasPoint,
- getTool,
- getViewportRect,
- isDrawingRef,
- onCollabCursorMoveRef,
- panRef,
- rotationRef,
- rulerRef,
- straightRulerRef,
- zoomRef,
- ]
+ []
);
- const handlePointerUp = useCallback(
- (e: React.PointerEvent<HTMLElement>) => {
- if (!isDrawingRef.current || e.pointerId !== activePointerIdRef.current) {
- return;
- }
-
- e.preventDefault();
- clearPredictedCanvas();
+ const handlePointerUp = useCallback((e: React.PointerEvent<HTMLElement>) => {
+ runPointerUp(sessionStateRef.current!, paramsRef.current, helpersRef.current!, e);
+ }, []);
- if (interactionRef.current && interactionRef.current.hasPointerCapture(e.pointerId)) {
- try {
- interactionRef.current.releasePointerCapture(e.pointerId);
- } catch {
- // Ignore release errors
- }
- }
-
- if (drawRafIdRef.current !== null) {
- cancelAnimationFrame(drawRafIdRef.current);
- drawRafIdRef.current = null;
- }
- flushPendingPoints(true);
-
- const bs = getBrushSettings();
- const dims = dimensionsRef.current;
- const grid = activeTileGridRef.current;
- const endPoint = getCanvasPoint(e);
- const draftCanvas = effectiveDraftCanvasRef?.current as
- | DraftCanvasElement
- | null
- | undefined;
- const canvas = getCachedLayerCanvas() as DraftCanvasElement | null;
- if (canvas) {
- canvas.__isBlank = false;
- canvas.__isSolidWhite = false;
- }
-
- const currentTool = getTool();
- const currentLayerId = activeLayerIdRef.current;
- const isEraser = currentTool === 'eraser';
- const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
- const mode = colorModeRef.current;
- const isPencil =
- !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
-
- const isTone = isToneStrokeRef.current;
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isToneLayer = Boolean(activeLayer?.toneEnabled);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;
- const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
-
- const pipeline = strokePipelineRef.current;
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const tailPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + 24);
- const enableFlickTaper =
- !isEraser &&
- !isShiftLineStrokeRef.current &&
- activeLayer?.type !== 'vector' &&
- Boolean(bs.taper?.useOut);
-
- let addedFlickPoints = false;
- const tailSegments: CubicBezierSegment[] = [];
- pipeline.finalizeStroke(e.nativeEvent?.timeStamp || e.timeStamp || performance.now(), {
- enableFlickTaper,
- dirtyPadExtra: tailPadExtra,
- onPoint: (sample) => {
- addedFlickPoints = true;
- allStrokePointsRef.current.push({
- x: sample.x,
- y: sample.y,
- pressure: sample.pressure,
- width: sample.width,
- tiltX: sample.tiltX,
- tiltY: sample.tiltY,
- twist: sample.twist,
- timestamp: sample.timestamp,
- isCorner: sample.isCorner,
- });
- },
- onSegment: (seg) => {
- tailSegments.push({
- p0: { ...seg.p0 },
- c1: { ...seg.c1 },
- c2: { ...seg.c2 },
- p3: { ...seg.p3 },
- });
- const segPad = Math.ceil(
- Math.max(seg.p0.width, seg.p3.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32
- );
- const tMinX = Math.min(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) - segPad;
- const tMinY = Math.min(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) - segPad;
- const tMaxX = Math.max(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) + segPad;
- const tMaxY = Math.max(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) + segPad;
- pipeline.expandDirtyRectBounds(tMinX, tMinY, tMaxX, tMaxY);
- markTouchedTiles(tMinX, tMinY, tMaxX, tMaxY);
- },
- });
-
- const pDirty = pipeline.dirtyRect;
- const mergedDirty = dirtyRectRef.current
- ? {
- minX: Math.min(
- dirtyRectRef.current.minX,
- Number.isFinite(pDirty.minX) ? pDirty.minX : dirtyRectRef.current.minX
- ),
- minY: Math.min(
- dirtyRectRef.current.minY,
- Number.isFinite(pDirty.minY) ? pDirty.minY : dirtyRectRef.current.minY
- ),
- maxX: Math.max(
- dirtyRectRef.current.maxX,
- Number.isFinite(pDirty.maxX) ? pDirty.maxX : dirtyRectRef.current.maxX
- ),
- maxY: Math.max(
- dirtyRectRef.current.maxY,
- Number.isFinite(pDirty.maxY) ? pDirty.maxY : dirtyRectRef.current.maxY
- ),
- }
- : Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX)
- ? { ...pDirty }
- : null;
-
- let exitSpeed = 0;
- if (recentPointsTrailRef.current.length >= 2) {
- const trail = recentPointsTrailRef.current;
- const sampleIdx = Math.max(0, trail.length - 4);
- const pA = trail[sampleIdx];
- const pB = trail[trail.length - 1];
- const dwellMs = Math.max(0, performance.now() - pB.t);
- const dt = Math.max(1, pB.t - pA.t + dwellMs);
- exitSpeed = Math.hypot(pB.x - pA.x, pB.y - pA.y) / dt;
- }
-
- const shouldTaper =
- Boolean(bs.taper?.useIn) || (Boolean(bs.taper?.useOut) && !addedFlickPoints);
- if (shouldTaper && allStrokePointsRef.current.length >= 3) {
- applyParametricTaper(allStrokePointsRef.current, {
- useIn: Boolean(bs.taper?.useIn),
- useOut: Boolean(bs.taper?.useOut) && !addedFlickPoints,
- minSizeFactor: bs.minSizeFactor,
- exitSpeed,
- });
- }
-
- const allPoints = allStrokePointsRef.current;
- let createdVectorStroke: VectorStroke | undefined;
- let postPresentWork: (() => void) | null = null;
-
- if (allPoints.length > 0 && !isMaskModeRef.current) {
- const finalPt = allPoints[allPoints.length - 1];
- lastStrokeEndRef.current = {
- x: finalPt.x,
- y: finalPt.y,
- pressure: finalPt.pressure,
- width: finalPt.width,
- layerId: currentLayerId,
- };
- }
-
- if (
- activeLayer?.type === 'vector' &&
- allPoints.length > 0 &&
- dims.width > 0 &&
- dims.height > 0
- ) {
- createdVectorStroke = commitVectorStrokeOrErase({
- activeLayer,
- currentLayerId,
- allPoints,
- bs,
- isEraser,
- isPencil,
- isMonochrome,
- strokeColor,
- dims,
- grid,
- canvas,
- mergedDirty,
- strokeId: currentStrokeIdRef.current,
- pushHistoryStep,
- });
- } else if (mergedDirty && allPoints.length > 0 && dims.width > 0 && dims.height > 0) {
- const hasWetEdge =
- !isMonochrome && !isEraser && !bs.isTransparentInk && (bs.wetEdge ?? 0) > 0.01;
- const clampedBakeRect = computeClampedBakeDirtyRect(
- mergedDirty,
- dims.width,
- dims.height,
- bs.size || 10,
- hasWetEdge ? bs.wetEdge ?? 0 : 0,
- bs.wetEdgeRadius ?? 3.0
- );
-
- if (clampedBakeRect) {
- const strokeIdForHistory = currentStrokeIdRef.current || undefined;
- const { x: sx, y: sy, width: dw, height: dh } = clampedBakeRect;
- let label = 'Brush Stroke';
- if (bs.isTransparentInk) {
- label = 'Transparent Ink';
- } else if (currentTool === 'eraser') {
- label = 'Eraser';
- } else if (bs.brushName) {
- label = bs.brushName;
- } else if (bs.preset === 'pencil-f') {
- label = 'Pencil (F)';
- } else if (bs.preset === 'pencil-2b') {
- label = 'Pencil (2B)';
- } else if (bs.preset === 'pencil-4b') {
- label = 'Pencil (4B)';
- } else if (bs.preset === 'pencil-hb') {
- label = 'Pencil (HB)';
- } else {
- label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
- }
-
- const dirtyRect = clampedBakeRect;
- const toolForHistory =
- currentTool === 'eraser' ? 'eraser' : isPencil ? 'pencil' : 'brush';
- const targetFormat: TileFormat =
- isMonochrome && !isBackgroundLayerId(currentLayerId)
- ? 'monochrome-1bit'
- : 'color-32bit';
- const effectiveMode: CanvasColorMode = isMonochrome ? 'monochrome' : mode;
- const activeSelection = selectionRef.current;
+ const handlePointerEnter = useCallback(() => {
+ runPointerEnter(sessionStateRef.current!, viewportRef, dispatchPointerStat);
+ }, [dispatchPointerStat, viewportRef]);
- if (isMaskModeRef.current && canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- const beforeMaskData = ctx.getImageData(sx, sy, dw, dh);
- const maskBs: BrushSettings = {
- ...bs,
- color: strokeColor,
- isTransparentInk: false,
- colorMixing: false,
- };
- const maskTool: ToolType = isEraser ? 'brush' : currentTool;
+ const handlePointerLeave = useCallback(() => {
+ runPointerLeave(isDrawingRef, dispatchPointerStat);
+ }, [dispatchPointerStat, isDrawingRef]);
- ctx.save();
- ctx.beginPath();
- ctx.rect(sx, sy, dw, dh);
- ctx.clip();
- applySelectionCanvasClip(ctx, activeSelection);
+ // Native low-latency Windows tablet input bridge (WinTab / Windows Ink via Rust Channel).
+ // Bypasses browser PointerEvents for brush/eraser pen strokes on Tauri desktop.
+ useEffect(() => {
+ if (!isNativeRustAvailable()) return;
- if ((bs.opacity ?? 1.0) >= 0.999) {
- renderCompleteStroke(
- ctx,
- allPoints,
- maskBs,
- maskTool,
- 'grayscale',
- false,
- canvas,
- false
- );
- } else {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- ctx.globalCompositeOperation = 'source-over';
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtx = bakeCanvas.getContext('2d', { alpha: true });
- if (bCtx) {
- bCtx.resetTransform();
- bCtx.clearRect(0, 0, dw, dh);
- bCtx.save();
- bCtx.translate(-sx, -sy);
- renderCompleteStroke(
- bCtx,
- allPoints,
- { ...maskBs, opacity: 1.0 },
- maskTool,
- 'grayscale',
- false,
- canvas,
- false
- );
- bCtx.restore();
- ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
- }
- ctx.restore();
+ const NATIVE_PEN_POINTER_ID = -1001;
+ let nativeStrokeActive = false;
+ let prevToolBeforeEraserFlip: ToolType | null = null;
+ const modKeys = { shift: false, alt: false };
- const afterMaskData = ctx.getImageData(sx, sy, dw, dh);
- if (activeSelection?.mask) {
- applySelectionMaskToImageData(
- beforeMaskData,
- afterMaskData,
- sx,
- sy,
- activeSelection
- );
- ctx.putImageData(afterMaskData, sx, sy);
- }
- if (activeLayer) {
- activeLayer.maskVersion = (activeLayer.maskVersion || 0) + 1;
- }
- enqueueHistoryTask(() => {
- pushHistoryStep(
- toolForHistory,
- 'Layer Mask Stroke',
- beforeMaskData,
- afterMaskData,
- currentLayerId,
- dirtyRect,
- undefined,
- undefined,
- undefined,
- strokeIdForHistory,
- true
- );
- });
- }
- } else if (isToneLayer && sourceCanvas) {
- if (!grid.isLayerIngested(currentLayerId)) {
- grid.ingestCanvas(currentLayerId, sourceCanvas, targetFormat);
- }
- const sCtx = get2DContext(sourceCanvas);
- const beforeSelectionData =
- activeSelection?.mask && sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
- if (sCtx) {
- sCtx.save();
- sCtx.beginPath();
- sCtx.rect(sx, sy, dw, dh);
- sCtx.clip();
- applySelectionCanvasClip(sCtx, activeSelection);
-
- const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999;
- if (!needsIsolatedBake) {
- renderCompleteStroke(
- sCtx,
- allPoints,
- bs,
- currentTool,
- effectiveMode,
- isBgEraser,
- sourceCanvas,
- Boolean(activeLayer?.alphaLocked)
- );
- } else {
- sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
- sCtx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- sCtx.globalCompositeOperation = 'source-atop';
- } else {
- sCtx.globalCompositeOperation = 'source-over';
- }
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
- if (bCtxBake) {
- bCtxBake.resetTransform();
- bCtxBake.clearRect(0, 0, dw, dh);
- bCtxBake.save();
- bCtxBake.translate(-sx, -sy);
- renderCompleteStroke(
- bCtxBake,
- allPoints,
- {
- ...bs,
- opacity: 1.0,
- isTransparentInk: false,
- color: isEraser && !isBgEraser ? '#000000' : bs.color,
- },
- isEraser && !isBgEraser ? 'brush' : currentTool,
- effectiveMode,
- isBgEraser,
- sourceCanvas,
- false
- );
- bCtxBake.restore();
- sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
- }
- sCtx.restore();
- }
+ const onKeyDown = (ev: KeyboardEvent) => {
+ modKeys.shift = ev.shiftKey;
+ modKeys.alt = ev.altKey;
+ };
+ const onKeyUp = (ev: KeyboardEvent) => {
+ modKeys.shift = ev.shiftKey;
+ modKeys.alt = ev.altKey;
+ };
+ window.addEventListener('keydown', onKeyDown, true);
+ window.addEventListener('keyup', onKeyUp, true);
+
+ const makeSyntheticEvent = (s: NativeTabletSample): React.PointerEvent<HTMLElement> => {
+ const evt: any = {
+ pointerId: NATIVE_PEN_POINTER_ID,
+ pointerType: 'pen',
+ button: 0,
+ buttons: s.buttons & 1 ? 1 : 0,
+ clientX: s.clientX,
+ clientY: s.clientY,
+ pressure: s.pressure,
+ tiltX: s.tiltX,
+ tiltY: s.tiltY,
+ twist: s.twist,
+ timeStamp: s.timestamp,
+ shiftKey: modKeys.shift,
+ altKey: modKeys.alt,
+ ctrlKey: false,
+ metaKey: false,
+ preventDefault() {},
+ stopPropagation() {},
+ };
+ evt.nativeEvent = evt;
+ return evt as React.PointerEvent<HTMLElement>;
+ };
- const beforeSnapshot = grid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
- if (afterData && beforeSelectionData && activeSelection?.mask && sCtx) {
- applySelectionMaskToImageData(
- beforeSelectionData,
- afterData,
- sx,
- sy,
- activeSelection
- );
- sCtx.putImageData(afterData, sx, sy);
- }
+ const isPointOverCanvasViewport = (x: number, y: number): boolean => {
+ const vp = viewportRef.current;
+ if (!vp) return false;
+ const rect = vp.getBoundingClientRect();
+ if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return false;
+ const topEl = typeof document !== 'undefined' ? document.elementFromPoint(x, y) : null;
+ if (!topEl) return true;
+ if (!vp.contains(topEl)) return false;
+ // Do not hijack clicks on floating UI pills / buttons inside viewport
+ if (topEl.closest('button, input, select, textarea, [data-floating-ui]')) return false;
+ return true;
+ };
- if (activeLayer && canvas) {
- const freq = activeLayer.toneFrequency ?? 60;
- const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
- const cellMargin = isEraser ? Math.ceil(cellSize * 2 + 32) : 0;
- const fxX = Math.max(0, sx - cellMargin);
- const fxY = Math.max(0, sy - cellMargin);
- const fxW = Math.min(canvas.width, sx + dw + cellMargin) - fxX;
- const fxH = Math.min(canvas.height, sy + dh + cellMargin) - fxY;
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dimensionsRef.current.dpi ?? 600,
- { x: fxX, y: fxY, width: fxW, height: fxH }
- );
- }
+ void startNativeTablet('auto');
- if (afterData) {
- grid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
- }
- const tileDeltas = grid.computeDeltasFromSnapshot(
- beforeSnapshot,
- currentLayerId,
- dirtyRect
- );
+ const unsubscribe = subscribeNativeTablet((batch) => {
+ const state = sessionStateRef.current;
+ const helpers = helpersRef.current;
+ if (!state || !helpers) return;
- enqueueHistoryTask(() => {
- pushHistoryStep(
- toolForHistory,
- label,
- null,
- null,
- currentLayerId,
- dirtyRect,
- tileDeltas,
- undefined,
- undefined,
- strokeIdForHistory
- );
- });
- } else {
- const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;
- const draftScale = draftCanvas?.__draftScale ?? 0;
- const draftDocRect = draftCanvas?.__draftDocRect;
- const compositeOp: 'source-over' | 'destination-out' | 'source-atop' =
- (isEraser && !isBgEraser) || bs.isTransparentInk
- ? 'destination-out'
- : activeLayer?.alphaLocked
- ? 'source-atop'
- : 'source-over';
- const monoOpts =
- targetFormat === 'monochrome-1bit'
- ? {
- threshold: activeLayer?.monoThreshold ?? 128,
- expressBlack: activeLayer?.monoExpressBlack ?? true,
- expressWhite: activeLayer?.monoExpressWhite ?? true,
- }
- : undefined;
- const selMaskOpts = activeSelection?.mask
- ? { mask: activeSelection.mask, bounds: activeSelection.bounds }
- : null;
+ const curTool = helpers.getTool();
+ const isBrushOrEraser = curTool === 'brush' || curTool === 'eraser';
- const draftOriginX = draftDocRect ? Math.round(draftDocRect.x) : 0;
- const draftOriginY = draftDocRect ? Math.round(draftDocRect.y) : 0;
- const canDirectDraftCommit = Boolean(
- draftCanvas &&
- draftCtx &&
- Math.abs(draftScale - 1.0) < 1e-6 &&
- draftDocRect &&
- Math.abs(draftDocRect.x - draftOriginX) < 1e-6 &&
- Math.abs(draftDocRect.y - draftOriginY) < 1e-6 &&
- !hasWetEdge &&
- !bs.colorMixing &&
- (bs.postCorrection ?? 0) === 0 &&
- !shouldTaper &&
- sx >= draftOriginX &&
- sy >= draftOriginY &&
- sx + dw <= draftOriginX + draftCanvas.width &&
- sy + dh <= draftOriginY + draftCanvas.height
- );
+ let i = 0;
+ while (i < batch.length) {
+ const s = batch[i];
- // For single taps or small strokes, ensure every tile overlapping the padded bake rect is included
- if (dw * dh <= 4 * TILE_SIZE * TILE_SIZE) {
- markTouchedTiles(sx, sy, sx + dw, sy + dh);
+ if (s.phase === 1) {
+ // Pen down
+ if (isBrushOrEraser && isPointOverCanvasViewport(s.clientX, s.clientY)) {
+ const isTailEraser = (s.buttons & 8) !== 0;
+ if (isTailEraser && curTool !== 'eraser') {
+ prevToolBeforeEraserFlip = curTool;
+ toolStoreActions.selectTool('eraser');
}
-
- if (canDirectDraftCommit && draftCanvas && draftCtx && draftDocRect) {
- // Fast path: 1:1 draft canvas already has the rendered stroke; emit only sealed tail segments
- if (tailSegments.length > 0) {
- const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
- const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
- const strokeSpacing = bs.spacing ?? 0.08;
- const liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
- const liveTipOpts = bs.customTipImage
- ? buildLiveTexturedOptions(
- bs,
- isMonochrome ? 1.0 : bs.flow ?? 1.0,
- strokeSpacing,
- strokeHardness,
- isMonochrome,
- canvas,
- activeLayer,
- isEraser,
- isBgEraser,
- true,
- liveAA
- )
- : null;
- const liveRadialOpts =
- !bs.customTipImage && !isPencil
- ? buildLiveRadialOptions(
- bs,
- isMonochrome,
- canvas,
- activeLayer,
- true,
- liveAA
- )
- : null;
- const useGpuTail = bs.customTipImage
- ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
- : !isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts));
- const gpuBatch = frameGpuDabsRef.current;
- gpuBatch.length = 0;
-
- for (let i = 0; i < tailSegments.length; i++) {
- emitLiveSegment(
- draftCtx,
- tailSegments[i],
- bs,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isMonochrome,
- isPencil,
- isEraser,
- isBgEraser,
- false,
- canvas,
- activeLayer,
- useGpuTail ? gpuBatch : undefined
- );
- }
-
- if (useGpuTail && gpuBatch.length > 0) {
- const liveColor =
- (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- let flushed = false;
- if (bs.customTipImage && liveTipOpts) {
- flushed = flushTexturedGpuDabs(
- draftCtx,
- gpuBatch,
- bs.customTipImage,
- liveColor,
- liveTipOpts
- );
- } else if (liveRadialOpts) {
- flushed = flushRadialGpuDabs(
- draftCtx,
- gpuBatch,
- liveColor,
- strokeHardness,
- false,
- false,
- liveRadialOpts
- );
- }
- if (!flushed) {
- for (let i = 0; i < tailSegments.length; i++) {
- emitLiveSegment(
- draftCtx,
- tailSegments[i],
- bs,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isMonochrome,
- isPencil,
- isEraser,
- isBgEraser,
- false,
- canvas,
- activeLayer,
- undefined
- );
- }
- }
- gpuBatch.length = 0;
- }
- }
-
- const beforeSnapshot = new Map<
- string,
- { format: TileFormat; data: Uint8Array | null }
- >();
- const spans = buildTouchedTileSpans(sx, sy, dw, dh);
- for (let i = 0; i < spans.length; i++) {
- const sp = spans[i];
- const spanData = draftCtx.getImageData(
- sp.x - draftOriginX,
- sp.y - draftOriginY,
- sp.width,
- sp.height
- );
- grid.compositeStrokeToTiles({
- layerId: currentLayerId,
- strokeData: spanData,
- destX: sp.x,
- destY: sp.y,
- format: targetFormat,
- compositeOp,
- opacity: bs.opacity ?? 1.0,
- monochrome: monoOpts,
- selectionMask: selMaskOpts,
- snapshotOut: beforeSnapshot,
- suppressNotify: true,
- });
- }
-
- postPresentWork = () => {
- const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
- enqueueHistoryTask(() => {
- if (canvas) {
- grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
- }
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
- }
- }
- pushHistoryStep(
- toolForHistory,
- label,
- null,
- null,
- currentLayerId,
- dirtyRect,
- tileDeltas,
- undefined,
- undefined,
- strokeIdForHistory
- );
- });
- };
- } else if (!bs.colorMixing) {
- // Fast isolated 1:1 re-bake: never allocates/unpacks existing tiles via createRegionCanvas
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtx = get2DContext(bakeCanvas);
- if (bCtx) {
- bCtx.resetTransform();
- bCtx.clearRect(0, 0, dw, dh);
- bCtx.save();
- bCtx.translate(-sx, -sy);
- bCtx.beginPath();
- bCtx.rect(sx, sy, dw, dh);
- bCtx.clip();
- applySelectionCanvasClip(bCtx, activeSelection);
-
- const effectiveOpacitySensor = resolveEffectiveOpacitySensor(
- bs,
- isMonochrome,
- isEraser
- );
- const bakeBs: BrushSettings =
- effectiveOpacitySensor && !bs.opacitySensor
- ? { ...bs, opacitySensor: effectiveOpacitySensor }
- : bs;
- const allowGpuMonoBake =
- isMonochrome && (bakeBs.antiAlias ?? 2) !== 0 && bakeBs.useGpu !== false;
-
- renderCompleteStroke(
- bCtx,
- allPoints,
- {
- ...bakeBs,
- opacity: 1.0,
- isTransparentInk: false,
- wetEdge: 0,
- color: isEraser && !isBgEraser ? '#000000' : bakeBs.color,
- },
- isEraser && !isBgEraser ? 'brush' : currentTool,
- effectiveMode,
- isBgEraser,
- canvas || undefined,
- false,
- undefined,
- allowGpuMonoBake
- );
- bCtx.restore();
-
- if (hasWetEdge) {
- const bakeImg = bCtx.getImageData(0, 0, dw, dh);
- applyCspWatercolorEdge(
- bakeImg,
- bs.wetEdge ?? 0,
- bs.wetEdgeRadius ?? 3.0,
- bs.wetEdgeAlphaPower ?? 25,
- bs.wetEdgeValuePower ?? 15
- );
- bCtx.putImageData(bakeImg, 0, 0);
- }
-
- const beforeSnapshot = new Map<
- string,
- { format: TileFormat; data: Uint8Array | null }
- >();
- const spans = buildTouchedTileSpans(sx, sy, dw, dh);
- for (let i = 0; i < spans.length; i++) {
- const sp = spans[i];
- const spanData = bCtx.getImageData(sp.x - sx, sp.y - sy, sp.width, sp.height);
- grid.compositeStrokeToTiles({
- layerId: currentLayerId,
- strokeData: spanData,
- destX: sp.x,
- destY: sp.y,
- format: targetFormat,
- compositeOp,
- opacity: bakeBs.opacity ?? 1.0,
- monochrome: monoOpts,
- selectionMask: selMaskOpts,
- snapshotOut: beforeSnapshot,
- suppressNotify: true,
- });
- }
-
- postPresentWork = () => {
- const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
- enqueueHistoryTask(() => {
- if (canvas) {
- grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
- }
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
- }
- }
- pushHistoryStep(
- toolForHistory,
- label,
- null,
- null,
- currentLayerId,
- dirtyRect,
- tileDeltas,
- undefined,
- undefined,
- strokeIdForHistory
- );
- });
- };
- }
- } else {
- // Wet color-mixing path requires existing layer pixels on the same canvas
- const canPoolRegion = dw <= 2048 && dh <= 2048;
- let pooledCanvas: HTMLCanvasElement | null = null;
- if (canPoolRegion && typeof document !== 'undefined') {
- if (!reusableRegionCanvasRef.current) {
- reusableRegionCanvasRef.current = document.createElement('canvas');
- }
- pooledCanvas = reusableRegionCanvasRef.current;
- }
- const regionCanvas = grid.createRegionCanvas(currentLayerId, dirtyRect, pooledCanvas);
- const rCtx = regionCanvas ? get2DContext(regionCanvas) : null;
- if (regionCanvas && rCtx) {
- const beforeSelectionData = activeSelection?.mask
- ? rCtx.getImageData(0, 0, dw, dh)
- : null;
-
- rCtx.save();
- rCtx.translate(-sx, -sy);
- rCtx.beginPath();
- rCtx.rect(sx, sy, dw, dh);
- rCtx.clip();
- applySelectionCanvasClip(rCtx, activeSelection);
-
- const effectiveOpacitySensor = resolveEffectiveOpacitySensor(
- bs,
- isMonochrome,
- isEraser
- );
- const bakeBs: BrushSettings =
- effectiveOpacitySensor && !bs.opacitySensor
- ? { ...bs, opacitySensor: effectiveOpacitySensor }
- : bs;
-
- const allowGpuMonoBake =
- isMonochrome && (bakeBs.antiAlias ?? 2) !== 0 && bakeBs.useGpu !== false;
- const needsIsolatedBake = (bakeBs.opacity ?? 1.0) < 0.999 || hasWetEdge;
- const bakeSampler = !isEraser
- ? new LayerPixelSampler(canvas || dims, currentLayerId, grid)
- : undefined;
-
- if (!needsIsolatedBake) {
- renderCompleteStroke(
- rCtx,
- allPoints,
- bakeBs,
- currentTool,
- effectiveMode,
- isBgEraser,
- canvas || undefined,
- Boolean(activeLayer?.alphaLocked),
- bakeSampler,
- allowGpuMonoBake
- );
- } else {
- rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bakeBs.opacity ?? 1.0));
- rCtx.globalCompositeOperation = compositeOp;
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtx = get2DContext(bakeCanvas);
- if (bCtx) {
- bCtx.resetTransform();
- bCtx.clearRect(0, 0, dw, dh);
- bCtx.save();
- bCtx.translate(-sx, -sy);
- renderCompleteStroke(
- bCtx,
- allPoints,
- {
- ...bakeBs,
- opacity: 1.0,
- isTransparentInk: false,
- wetEdge: 0,
- color: isEraser && !isBgEraser ? '#000000' : bakeBs.color,
- },
- isEraser && !isBgEraser ? 'brush' : currentTool,
- effectiveMode,
- isBgEraser,
- canvas || undefined,
- false,
- bakeSampler,
- allowGpuMonoBake
- );
- bCtx.restore();
-
- if (hasWetEdge) {
- const bakeImg = bCtx.getImageData(0, 0, dw, dh);
- applyCspWatercolorEdge(
- bakeImg,
- bs.wetEdge ?? 0,
- bs.wetEdgeRadius ?? 3.0,
- bs.wetEdgeAlphaPower ?? 25,
- bs.wetEdgeValuePower ?? 15
- );
- bCtx.putImageData(bakeImg, 0, 0);
- }
-
- rCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
- }
-
- rCtx.restore();
-
- if (beforeSelectionData && activeSelection?.mask) {
- const fullAfter = rCtx.getImageData(0, 0, dw, dh);
- applySelectionMaskToImageData(
- beforeSelectionData,
- fullAfter,
- sx,
- sy,
- activeSelection
- );
- rCtx.putImageData(fullAfter, 0, 0);
- }
-
- const spans = buildTouchedTileSpans(sx, sy, dw, dh);
- const beforeSnapshot = new Map<
- string,
- { format: TileFormat; data: Uint8Array | null }
- >();
- for (let i = 0; i < spans.length; i++) {
- const sp = spans[i];
- const subSnap = grid.snapshotTilesInRect(currentLayerId, sp);
- for (const [k, v] of subSnap) {
- if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
- }
- const spanData = rCtx.getImageData(sp.x - sx, sp.y - sy, sp.width, sp.height);
- if (targetFormat === 'monochrome-1bit') {
- binarizeImageDataBuffer(
- spanData,
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
- );
- }
- grid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
- }
-
- if (!canPoolRegion) {
- releaseTemporaryCanvas(regionCanvas);
- }
-
- postPresentWork = () => {
- const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
- enqueueHistoryTask(() => {
- if (canvas) {
- grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
- }
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
- }
- }
- pushHistoryStep(
- toolForHistory,
- label,
- null,
- null,
- currentLayerId,
- dirtyRect,
- tileDeltas,
- undefined,
- undefined,
- strokeIdForHistory
- );
- });
- };
- }
+ nativeStrokeActive = true;
+ runPointerDown(state, paramsRef.current, helpers, makeSyntheticEvent(s));
+ }
+ i++;
+ } else if (s.phase === 2) {
+ // Batch all contiguous drag samples in this hardware burst
+ const coalesced: PointerEvent[] = [];
+ while (i < batch.length && batch[i].phase === 2) {
+ coalesced.push(makeSyntheticEvent(batch[i]) as unknown as PointerEvent);
+ i++;
+ }
+ if (nativeStrokeActive && coalesced.length > 0) {
+ const last = coalesced[coalesced.length - 1] as unknown as React.PointerEvent<HTMLElement>;
+ runPointerMove(state, paramsRef.current, helpers, last, coalesced);
+ }
+ } else if (s.phase === 3 || s.phase === 4) {
+ // Pen up or leave
+ if (nativeStrokeActive) {
+ nativeStrokeActive = false;
+ runPointerUp(state, paramsRef.current, helpers, makeSyntheticEvent(s));
+ if (prevToolBeforeEraserFlip !== null) {
+ const prev = prevToolBeforeEraserFlip;
+ prevToolBeforeEraserFlip = null;
+ toolStoreActions.selectTool(prev);
}
}
- }
- }
-
- if (clearDraftRafRef.current !== null) {
- cancelAnimationFrame(clearDraftRafRef.current);
- clearDraftRafRef.current = null;
- }
- if (draftCanvas) {
- const dCtx = get2DContext(draftCanvas);
- if (dCtx) {
- try {
- dCtx.restore();
- } catch {
- // Ignore restore underflow
+ i++;
+ } else {
+ // Hover (phase 0)
+ if (!nativeStrokeActive && isPointOverCanvasViewport(s.clientX, s.clientY)) {
+ const pt = helpers.getCanvasPoint(makeSyntheticEvent(s));
+ helpers.dispatchPointerStat(pt.x, pt.y, pt.pressure);
}
- dCtx.resetTransform();
- dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ i++;
}
- draftCanvas.__draftHasContent = false;
- draftCanvas.__draftCompositeOp = 'source-over';
- draftCanvas.__draftMonochrome = false;
- draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
- }
- clearPredictedCanvas();
-
- grid.notifyChange(true);
- postPresentWork?.();
-
- if (currentStrokeIdRef.current) {
- onCollabStrokeFinishRef.current?.(
- currentStrokeIdRef.current,
- currentLayerId,
- endPoint,
- mergedDirty
- ? {
- x: Math.max(0, Math.floor(mergedDirty.minX)),
- y: Math.max(0, Math.floor(mergedDirty.minY)),
- width: Math.max(
- 1,
- Math.ceil(mergedDirty.maxX) - Math.max(0, Math.floor(mergedDirty.minX))
- ),
- height: Math.max(
- 1,
- Math.ceil(mergedDirty.maxY) - Math.max(0, Math.floor(mergedDirty.minY))
- ),
- }
- : undefined,
- createdVectorStroke
- );
- currentStrokeIdRef.current = null;
}
+ });
- strokePipelineRef.current.abortStroke();
- frameGpuDabsRef.current.length = 0;
- isDrawingRef.current = false;
- recoveryService.setDrawingActive(false);
- activePointerIdRef.current = null;
- allStrokePointsRef.current = [];
- stabilizedPointRef.current = null;
- hasLastProcessedPointRef.current = false;
- dirtyRectRef.current = null;
- touchedTilesRef.current.clear();
- liveNeedsNotifyRef.current = false;
- isShiftLineStrokeRef.current = false;
- isToneStrokeRef.current = false;
- layerPixelSamplerRef.current = null;
- activeReservoirRef.current = null;
- snapSessionRef.current.endStroke();
- straightSnapSessionRef.current.endStroke();
- emitConstraintAxisChange(null);
-
- if (isMaskModeRef.current) {
- onUpdateMaskThumbnailRef.current?.(currentLayerId);
- grid.notifyChange(true);
- } else {
- enqueueHistoryTask(() => {
- onUpdateLayerThumbnail(currentLayerId);
- });
- }
- },
- [
- activeLayerIdRef,
- activeTileGridRef,
- buildLiveRadialOptions,
- buildLiveTexturedOptions,
- buildTouchedTileSpans,
- clearPredictedCanvas,
- colorModeRef,
- dimensionsRef,
- effectiveDraftCanvasRef,
- emitConstraintAxisChange,
- emitLiveSegment,
- enqueueHistoryTask,
- flushPendingPoints,
- getBrushSettings,
- getCachedLayerCanvas,
- getCanvasPoint,
- getTool,
- interactionRef,
- isDrawingRef,
- isMaskModeRef,
- lastStrokeEndRef,
- layerSourceCanvasesRef,
- layersRef,
- markTouchedTiles,
- onCollabStrokeFinishRef,
- onUpdateLayerThumbnail,
- onUpdateMaskThumbnailRef,
- pushHistoryStep,
- resolveEffectiveOpacitySensor,
- resolveLiveAntiAlias,
- resolveStrokeColor,
- selectionRef,
- ]
- );
-
- const handlePointerEnter = useCallback(() => {
- if (viewportRef.current) {
- cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
- }
- dispatchPointerStat(null, null, 0);
- }, [dispatchPointerStat, viewportRef]);
-
- const handlePointerLeave = useCallback(() => {
- if (!isDrawingRef.current) {
- dispatchPointerStat(null, null, 0);
- }
- }, [dispatchPointerStat, isDrawingRef]);
+ return () => {
+ unsubscribe();
+ window.removeEventListener('keydown', onKeyDown, true);
+ window.removeEventListener('keyup', onKeyUp, true);
+ };
+ }, [viewportRef]);
return {
abortActiveStroke,
diff --git a/src/hooks/drawing/useDrawingHistory.ts b/src/hooks/drawing/useDrawingHistory.ts
index d2a974f..1d6bb00 100644
--- a/src/hooks/drawing/useDrawingHistory.ts
+++ b/src/hooks/drawing/useDrawingHistory.ts
@@ -18,10 +18,10 @@ import {
} from '../../utils/tileEngine';
import { UndoCacheManager, globalUndoCache } from '../../utils/undoCache';
import { documentStore } from '../../utils/documentStore';
+import { multiplayerService } from '../../services/multiplayerService';
import { recoveryService } from '../../services/recoveryService';
import { renderVectorLayer } from '../../utils/vectorEngine';
import { createCanvasThumbnail, formatTime, get2DContext } from '../../utils/canvasUtils';
-import { applyLayerEffects } from '../../utils/layerEffectsEngine';
import { isBackgroundLayerId, LastStrokeEndState, PushHistoryStepFn } from './types';
type IdleCallbackWindow = Window & {
@@ -39,8 +39,6 @@ export interface UseDrawingHistoryParams {
activeLayerIdRef: React.MutableRefObject<string>;
colorModeRef: React.MutableRefObject<CanvasColorMode>;
layersRef: React.MutableRefObject<LayerItem[] | undefined>;
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- layerSourceCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
onUpdateLayerThumbnail: (layerId: string) => void;
onUpdateMaskThumbnailRef: React.MutableRefObject<((layerId: string) => void) | undefined>;
isDrawingRef: React.MutableRefObject<boolean>;
@@ -52,6 +50,7 @@ export interface SelectiveUndoResult {
strokeId?: string;
layerId: string;
tileDeltas?: TileDelta[];
+ syncedRemotely?: boolean;
}
export interface UseDrawingHistoryResult {
@@ -86,8 +85,6 @@ export function useDrawingHistory({
activeLayerIdRef,
colorModeRef,
layersRef,
- layerCanvasesRef,
- layerSourceCanvasesRef,
onUpdateLayerThumbnail,
onUpdateMaskThumbnailRef,
isDrawingRef,
@@ -325,6 +322,18 @@ export function useDrawingHistory({
const sessionKey = docId || recoveryService.getCurrentSessionId() || 'default-session';
recoveryService.logStrokeDelta(sessionKey, tileDeltas, vectorDelta, targetLayerId);
}
+
+ // Broadcast authoritative LZ4 BINARY_TILEs after any local raster op (fill, transform, liquify, filter, tonal, shape, etc.)
+ // Strokes are already broadcast immediately on pointerup and deduped via WeakSet inside sendTileDeltas.
+ if (
+ !peerId &&
+ !isMaskEdit &&
+ tileDeltas &&
+ tileDeltas.length > 0 &&
+ multiplayerService.isConnected()
+ ) {
+ multiplayerService.sendTileDeltas(tileDeltas, grid);
+ }
},
[colorModeRef, dimensionsRef, ensureInitialHistory, layersRef, persistSessionHistory, syncHistoryState]
);
@@ -419,10 +428,7 @@ export function useDrawingHistory({
const item = historyRef.current[i];
if (item) {
const targetLayerId = item.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
- const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
- const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
const deltas = await undoCache.resolveDeltas(item);
if (item.isMaskEdit && targetLayer?.maskCanvas) {
@@ -439,89 +445,77 @@ export function useDrawingHistory({
mCtx.putImageData(item.beforeImageData, mx, my);
targetLayer.maskVersion = (targetLayer.maskVersion || 0) + 1;
onUpdateMaskThumbnailRef.current?.(targetLayerId);
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendLayerMaskData(
+ targetLayerId,
+ targetLayer.maskCanvas,
+ item.dirtyRect
+ );
+ }
}
} else if (item.vectorStrokesDelta && targetLayer) {
targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
- const tempVec = canvas || document.createElement('canvas');
- if (!canvas) {
- tempVec.width = dims.width;
- tempVec.height = dims.height;
+ const isMono = targetLayer.expressionColor === 'monochrome';
+ grid.clearLayer(targetLayerId);
+ if (targetLayer.vectorStrokes.length > 0) {
+ let minX = dims.width;
+ let minY = dims.height;
+ let maxX = 0;
+ let maxY = 0;
+ for (const st of targetLayer.vectorStrokes) {
+ if (st.deleted || !st.bounds) continue;
+ const pad = Math.ceil(Math.max(16, st.baseWidth || 10));
+ if (st.bounds.minX - pad < minX) minX = st.bounds.minX - pad;
+ if (st.bounds.minY - pad < minY) minY = st.bounds.minY - pad;
+ if (st.bounds.maxX + pad > maxX) maxX = st.bounds.maxX + pad;
+ if (st.bounds.maxY + pad > maxY) maxY = st.bounds.maxY + pad;
+ }
+ const vx = Math.max(0, Math.floor(minX));
+ const vy = Math.max(0, Math.floor(minY));
+ const vw = Math.max(0, Math.min(dims.width, Math.ceil(maxX)) - vx);
+ const vh = Math.max(0, Math.min(dims.height, Math.ceil(maxY)) - vy);
+ if (vw > 0 && vh > 0) {
+ const tempVec = document.createElement('canvas');
+ tempVec.width = vw;
+ tempVec.height = vh;
+ const cCtx = get2DContext(tempVec);
+ if (cCtx) {
+ cCtx.save();
+ cCtx.translate(-vx, -vy);
+ renderVectorLayer(cCtx, targetLayer.vectorStrokes);
+ cCtx.restore();
+ const subData = cCtx.getImageData(0, 0, vw, vh);
+ grid.writeImageData(
+ targetLayerId,
+ subData,
+ vx,
+ vy,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ releaseTemporaryCanvas(tempVec);
+ }
}
- const cCtx = get2DContext(tempVec);
- if (cCtx) {
- cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
- renderVectorLayer(cCtx, targetLayer.vectorStrokes);
- const isMono = targetLayer.expressionColor === 'monochrome';
- grid.clearLayer(targetLayerId);
- grid.ingestCanvas(
- targetLayerId,
- tempVec,
- isMono ? 'monochrome-1bit' : 'color-32bit'
- );
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendLayerUpdate(targetLayerId, {
+ vectorStrokes: targetLayer.vectorStrokes,
+ });
}
- if (!canvas) releaseTemporaryCanvas(tempVec);
} else if (deltas && deltas.length > 0) {
grid.applyTileDeltas(deltas, 'undo');
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendTileDeltas(deltas, grid, { force: true });
+ }
const affectedLayerIds = new Set<string>();
for (const d of deltas) {
affectedLayerIds.add(parseTileKey(d.key).layerId);
}
- if (affectedLayerIds.size === 0) {
- affectedLayerIds.add(targetLayerId);
- }
for (const lid of affectedLayerIds) {
- const lCanvas = layerCanvasesRef.current.get(lid) || null;
- const lSourceCanvas = layerSourceCanvasesRef?.current?.get(lid);
- const lLayer = layersRef.current?.find((l) => l.id === lid);
- const lIsTone = Boolean(lLayer?.toneEnabled && lSourceCanvas);
- if (lIsTone && lSourceCanvas) {
- grid.renderLayerToCanvas(lid, lSourceCanvas, item.dirtyRect);
- if (lCanvas && lLayer) {
- applyLayerEffects(
- lSourceCanvas,
- lCanvas,
- lLayer,
- dimensionsRef.current.dpi ?? 600,
- item.dirtyRect
- );
- }
- } else if (lCanvas) {
- grid.renderLayerToCanvas(lid, lCanvas, item.dirtyRect);
- if (lSourceCanvas) {
- grid.renderLayerToCanvas(lid, lSourceCanvas, item.dirtyRect);
- }
- }
if (lid !== targetLayerId) {
onUpdateLayerThumbnail(lid);
}
}
- } else if (isToneStep && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- if (item.dirtyRect && item.beforeImageData) {
- sCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);
- } else if (item.beforeImageData) {
- sCtx.putImageData(item.beforeImageData, 0, 0);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- sCtx.fillStyle = '#ffffff';
- sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- }
- }
- }
-
- if (canvas && targetLayer) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- targetLayer,
- dimensionsRef.current.dpi ?? 600,
- item.dirtyRect
- );
- }
} else {
const isMono =
!isBackgroundLayerId(targetLayerId) &&
@@ -555,13 +549,6 @@ export function useDrawingHistory({
grid.clearLayer(targetLayerId);
}
}
-
- if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- }
- if (sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- }
}
onUpdateLayerThumbnail(targetLayerId);
@@ -573,10 +560,7 @@ export function useDrawingHistory({
const dataToApply = item?.afterImageData || item?.imageData;
if (item) {
const targetLayerId = item.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
- const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
- const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
const deltas = await undoCache.resolveDeltas(item);
if (item.isMaskEdit && targetLayer?.maskCanvas) {
@@ -593,89 +577,77 @@ export function useDrawingHistory({
mCtx.putImageData(dataToApply, mx, my);
targetLayer.maskVersion = (targetLayer.maskVersion || 0) + 1;
onUpdateMaskThumbnailRef.current?.(targetLayerId);
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendLayerMaskData(
+ targetLayerId,
+ targetLayer.maskCanvas,
+ item.dirtyRect
+ );
+ }
}
} else if (item.vectorStrokesDelta && targetLayer) {
targetLayer.vectorStrokes = item.vectorStrokesDelta.after;
- const tempVec = canvas || document.createElement('canvas');
- if (!canvas) {
- tempVec.width = dims.width;
- tempVec.height = dims.height;
+ const isMono = targetLayer.expressionColor === 'monochrome';
+ grid.clearLayer(targetLayerId);
+ if (targetLayer.vectorStrokes.length > 0) {
+ let minX = dims.width;
+ let minY = dims.height;
+ let maxX = 0;
+ let maxY = 0;
+ for (const st of targetLayer.vectorStrokes) {
+ if (st.deleted || !st.bounds) continue;
+ const pad = Math.ceil(Math.max(16, st.baseWidth || 10));
+ if (st.bounds.minX - pad < minX) minX = st.bounds.minX - pad;
+ if (st.bounds.minY - pad < minY) minY = st.bounds.minY - pad;
+ if (st.bounds.maxX + pad > maxX) maxX = st.bounds.maxX + pad;
+ if (st.bounds.maxY + pad > maxY) maxY = st.bounds.maxY + pad;
+ }
+ const vx = Math.max(0, Math.floor(minX));
+ const vy = Math.max(0, Math.floor(minY));
+ const vw = Math.max(0, Math.min(dims.width, Math.ceil(maxX)) - vx);
+ const vh = Math.max(0, Math.min(dims.height, Math.ceil(maxY)) - vy);
+ if (vw > 0 && vh > 0) {
+ const tempVec = document.createElement('canvas');
+ tempVec.width = vw;
+ tempVec.height = vh;
+ const cCtx = get2DContext(tempVec);
+ if (cCtx) {
+ cCtx.save();
+ cCtx.translate(-vx, -vy);
+ renderVectorLayer(cCtx, targetLayer.vectorStrokes);
+ cCtx.restore();
+ const subData = cCtx.getImageData(0, 0, vw, vh);
+ grid.writeImageData(
+ targetLayerId,
+ subData,
+ vx,
+ vy,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ releaseTemporaryCanvas(tempVec);
+ }
}
- const cCtx = get2DContext(tempVec);
- if (cCtx) {
- cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
- renderVectorLayer(cCtx, targetLayer.vectorStrokes);
- const isMono = targetLayer.expressionColor === 'monochrome';
- grid.clearLayer(targetLayerId);
- grid.ingestCanvas(
- targetLayerId,
- tempVec,
- isMono ? 'monochrome-1bit' : 'color-32bit'
- );
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendLayerUpdate(targetLayerId, {
+ vectorStrokes: targetLayer.vectorStrokes,
+ });
}
- if (!canvas) releaseTemporaryCanvas(tempVec);
} else if (deltas && deltas.length > 0) {
grid.applyTileDeltas(deltas, 'redo');
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendTileDeltas(deltas, grid, { force: true });
+ }
const affectedLayerIds = new Set<string>();
for (const d of deltas) {
affectedLayerIds.add(parseTileKey(d.key).layerId);
}
- if (affectedLayerIds.size === 0) {
- affectedLayerIds.add(targetLayerId);
- }
for (const lid of affectedLayerIds) {
- const lCanvas = layerCanvasesRef.current.get(lid) || null;
- const lSourceCanvas = layerSourceCanvasesRef?.current?.get(lid);
- const lLayer = layersRef.current?.find((l) => l.id === lid);
- const lIsTone = Boolean(lLayer?.toneEnabled && lSourceCanvas);
- if (lIsTone && lSourceCanvas) {
- grid.renderLayerToCanvas(lid, lSourceCanvas, item.dirtyRect);
- if (lCanvas && lLayer) {
- applyLayerEffects(
- lSourceCanvas,
- lCanvas,
- lLayer,
- dimensionsRef.current.dpi ?? 600,
- item.dirtyRect
- );
- }
- } else if (lCanvas) {
- grid.renderLayerToCanvas(lid, lCanvas, item.dirtyRect);
- if (lSourceCanvas) {
- grid.renderLayerToCanvas(lid, lSourceCanvas, item.dirtyRect);
- }
- }
if (lid !== targetLayerId) {
onUpdateLayerThumbnail(lid);
}
}
- } else if (isToneStep && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- if (item.dirtyRect && dataToApply) {
- sCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);
- } else if (dataToApply) {
- sCtx.putImageData(dataToApply, 0, 0);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- sCtx.fillStyle = '#ffffff';
- sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- }
- }
- }
-
- if (canvas && targetLayer) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- targetLayer,
- dimensionsRef.current.dpi ?? 600,
- item.dirtyRect
- );
- }
} else {
const isMono =
!isBackgroundLayerId(targetLayerId) &&
@@ -709,13 +681,6 @@ export function useDrawingHistory({
grid.clearLayer(targetLayerId);
}
}
-
- if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- }
- if (sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- }
}
onUpdateLayerThumbnail(targetLayerId);
@@ -740,8 +705,6 @@ export function useDrawingHistory({
dimensionsRef,
flushPendingHistoryTasks,
isDrawingRef,
- layerCanvasesRef,
- layerSourceCanvasesRef,
layersRef,
onUpdateLayerThumbnail,
onUpdateMaskThumbnailRef,
@@ -817,14 +780,13 @@ export function useDrawingHistory({
const item = history[targetItemIdx];
const targetLayerId = item.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
- const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
- const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
const grid = activeTileGridRef.current;
const undoCache = activeUndoCacheRef.current;
const dims = dimensionsRef.current;
let resolvedDeltas: TileDelta[] | null = null;
+ let syncedRemotely = false;
+ const isLocalUndo = !peerIdToUndo || peerIdToUndo === 'local';
if (item.isMaskEdit && targetLayer?.maskCanvas) {
const mCtx = get2DContext(targetLayer.maskCanvas);
@@ -840,44 +802,68 @@ export function useDrawingHistory({
mCtx.putImageData(item.beforeImageData, mx, my);
targetLayer.maskVersion = (targetLayer.maskVersion || 0) + 1;
onUpdateMaskThumbnailRef.current?.(targetLayerId);
+ if (isLocalUndo && multiplayerService.isConnected()) {
+ multiplayerService.sendLayerMaskData(
+ targetLayerId,
+ targetLayer.maskCanvas,
+ item.dirtyRect
+ );
+ syncedRemotely = true;
+ }
}
} else if (item.vectorStrokesDelta && targetLayer) {
targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
- const tempVec = canvas || document.createElement('canvas');
- if (!canvas) {
- tempVec.width = dims.width;
- tempVec.height = dims.height;
+ const isMono = targetLayer.expressionColor === 'monochrome';
+ grid.clearLayer(targetLayerId);
+ if (targetLayer.vectorStrokes.length > 0) {
+ let minX = dims.width;
+ let minY = dims.height;
+ let maxX = 0;
+ let maxY = 0;
+ for (const st of targetLayer.vectorStrokes) {
+ if (st.deleted || !st.bounds) continue;
+ const pad = Math.ceil(Math.max(16, st.baseWidth || 10));
+ if (st.bounds.minX - pad < minX) minX = st.bounds.minX - pad;
+ if (st.bounds.minY - pad < minY) minY = st.bounds.minY - pad;
+ if (st.bounds.maxX + pad > maxX) maxX = st.bounds.maxX + pad;
+ if (st.bounds.maxY + pad > maxY) maxY = st.bounds.maxY + pad;
+ }
+ const vx = Math.max(0, Math.floor(minX));
+ const vy = Math.max(0, Math.floor(minY));
+ const vw = Math.max(0, Math.min(dims.width, Math.ceil(maxX)) - vx);
+ const vh = Math.max(0, Math.min(dims.height, Math.ceil(maxY)) - vy);
+ if (vw > 0 && vh > 0) {
+ const tempVec = document.createElement('canvas');
+ tempVec.width = vw;
+ tempVec.height = vh;
+ const cCtx = get2DContext(tempVec);
+ if (cCtx) {
+ cCtx.save();
+ cCtx.translate(-vx, -vy);
+ renderVectorLayer(cCtx, targetLayer.vectorStrokes);
+ cCtx.restore();
+ const subData = cCtx.getImageData(0, 0, vw, vh);
+ grid.writeImageData(
+ targetLayerId,
+ subData,
+ vx,
+ vy,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ releaseTemporaryCanvas(tempVec);
+ }
}
- const cCtx = get2DContext(tempVec);
- if (cCtx) {
- cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
- renderVectorLayer(cCtx, targetLayer.vectorStrokes);
- const isMono = targetLayer.expressionColor === 'monochrome';
- grid.clearLayer(targetLayerId);
- grid.ingestCanvas(targetLayerId, tempVec, isMono ? 'monochrome-1bit' : 'color-32bit');
+ if (isLocalUndo && multiplayerService.isConnected()) {
+ multiplayerService.sendLayerUpdate(targetLayerId, {
+ vectorStrokes: targetLayer.vectorStrokes,
+ });
+ syncedRemotely = true;
}
- if (!canvas) releaseTemporaryCanvas(tempVec);
} else {
resolvedDeltas = await undoCache.resolveDeltas(item);
if (resolvedDeltas && resolvedDeltas.length > 0) {
grid.applyTileDeltas(resolvedDeltas, 'undo');
- if (isToneStep && sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- if (canvas && targetLayer) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- targetLayer,
- dimensionsRef.current.dpi ?? 600,
- item.dirtyRect
- );
- }
- } else if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- if (sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- }
- }
} else if (item.beforeImageData) {
const isMono =
!isBackgroundLayerId(targetLayerId) &&
@@ -902,12 +888,6 @@ export function useDrawingHistory({
by,
isMono ? 'monochrome-1bit' : 'color-32bit'
);
- if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- }
- if (sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- }
}
}
@@ -926,6 +906,7 @@ export function useDrawingHistory({
strokeId: item.strokeId,
layerId: targetLayerId,
tileDeltas: resolvedDeltas ?? undefined,
+ syncedRemotely,
};
});
@@ -941,8 +922,6 @@ export function useDrawingHistory({
dimensionsRef,
flushPendingHistoryTasks,
isDrawingRef,
- layerCanvasesRef,
- layerSourceCanvasesRef,
layersRef,
onUpdateLayerThumbnail,
onUpdateMaskThumbnailRef,
@@ -970,6 +949,9 @@ export function useDrawingHistory({
const beforeStrokes = [...(activeLayer.vectorStrokes || [])];
activeLayer.vectorStrokes = [];
vectorDelta = { before: beforeStrokes, after: [] };
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendLayerUpdate(activeLayerId, { vectorStrokes: [] });
+ }
}
if (isBg) {
@@ -985,32 +967,6 @@ export function useDrawingHistory({
isBg ? fullRect : undefined
);
- const canvas = layerCanvasesRef.current.get(activeLayerId);
- if (canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- if (isBg) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- } else {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- }
- }
- }
-
- const sourceCanvas = layerSourceCanvasesRef?.current?.get(activeLayerId);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- if (isBg) {
- sCtx.fillStyle = '#ffffff';
- sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- }
- }
- }
-
onUpdateLayerThumbnail(activeLayerId);
pushHistoryStep(
'clear',
@@ -1027,8 +983,6 @@ export function useDrawingHistory({
activeLayerId,
activeLayerLocked,
dimensionsRef,
- layerCanvasesRef,
- layerSourceCanvasesRef,
layersRef,
onUpdateLayerThumbnail,
pushHistoryStep,
diff --git a/src/hooks/drawing/useSelectionTools.ts b/src/hooks/drawing/useSelectionTools.ts
index d899de5..35705dc 100644
--- a/src/hooks/drawing/useSelectionTools.ts
+++ b/src/hooks/drawing/useSelectionTools.ts
@@ -3,19 +3,25 @@ import {
CanvasColorMode,
CanvasDimensions,
CanvasSelection,
+ DirtyRect,
LayerItem,
TransformSession,
} from '../../types/editor';
import { documentStore } from '../../utils/documentStore';
-import { SparseTileGrid } from '../../utils/tileEngine';
-import { compositeVisibleLayers } from '../../utils/floodFill';
+import {
+ SparseTileGrid,
+ TileFormat,
+ TileSnapshotEntry,
+ releaseTemporaryCanvas,
+} from '../../utils/tileEngine';
import {
isPointInSelection,
- liftSelectionToFloating,
- commitFloatingSelection,
computePolygonBounds,
- getCanvasContentBounds,
- floodSelectWand,
+ floodSelectWandOnTileGrid,
+ clearSelectionInTileGrid,
+ fillSelectionInTileGrid,
+ liftSelectionFromTileGrid,
+ commitFloatingSelectionToTileGrid,
expandSelection,
contractSelection,
featherSelection,
@@ -30,12 +36,139 @@ import {
createDefaultPerspectiveQuad,
createDefaultMeshPoints,
} from '../../utils/transformEngine';
-import { applyScreentone } from '../../utils/screentoneEngine';
-import { applyLayerEffects } from '../../utils/layerEffectsEngine';
import { get2DContext } from '../../utils/canvasUtils';
import { useToolStore, toolStoreActions } from '../../stores';
import { PushHistoryStepFn } from './types';
+function computeTransformDestRect(
+ session: TransformSession,
+ docW: number,
+ docH: number
+): DirtyRect | null {
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+
+ const includePt = (px: number, py: number) => {
+ if (px < minX) minX = px;
+ if (py < minY) minY = py;
+ if (px > maxX) maxX = px;
+ if (py > maxY) maxY = py;
+ };
+
+ if (session.mode === 'perspective' && session.perspectiveQuad) {
+ for (const p of session.perspectiveQuad) includePt(p.x, p.y);
+ } else if (session.mode === 'mesh' && session.meshPoints) {
+ for (const row of session.meshPoints) {
+ for (const p of row) includePt(p.x, p.y);
+ }
+ } else {
+ const cx = session.x + session.width / 2;
+ const cy = session.y + session.height / 2;
+ const rad = (session.rotation * Math.PI) / 180;
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+ const hw = session.width / 2;
+ const hh = session.height / 2;
+ const corners: [number, number][] = [
+ [-hw, -hh],
+ [hw, -hh],
+ [hw, hh],
+ [-hw, hh],
+ ];
+ for (const [lx, ly] of corners) {
+ includePt(cx + lx * cos - ly * sin, cy + lx * sin + ly * cos);
+ }
+ }
+
+ const x0 = Math.max(0, Math.floor(minX - 2));
+ const y0 = Math.max(0, Math.floor(minY - 2));
+ const x1 = Math.min(docW, Math.ceil(maxX + 2));
+ const y1 = Math.min(docH, Math.ceil(maxY + 2));
+ if (x1 <= x0 || y1 <= y0) return null;
+ return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
+}
+
+function compositeTransformedIntoTileGrid(
+ grid: SparseTileGrid,
+ layerId: string,
+ sourceCanvas: HTMLCanvasElement,
+ session: TransformSession,
+ dimensions: CanvasDimensions,
+ targetFormat: TileFormat,
+ beforeSnapshot: Map<string, TileSnapshotEntry>
+): DirtyRect | null {
+ const destRect = computeTransformDestRect(session, dimensions.width, dimensions.height);
+ if (!destRect) return null;
+
+ const CHUNK = 1024;
+ const chunkCanvas = document.createElement('canvas');
+ chunkCanvas.width = Math.min(CHUNK, destRect.width);
+ chunkCanvas.height = Math.min(CHUNK, destRect.height);
+ const cCtx = get2DContext(chunkCanvas);
+ if (!cCtx) {
+ releaseTemporaryCanvas(chunkCanvas);
+ return null;
+ }
+
+ try {
+ const x1 = destRect.x + destRect.width;
+ const y1 = destRect.y + destRect.height;
+
+ for (let cy = destRect.y; cy < y1; cy += CHUNK) {
+ const ch = Math.min(CHUNK, y1 - cy);
+ for (let cx = destRect.x; cx < x1; cx += CHUNK) {
+ const cw = Math.min(CHUNK, x1 - cx);
+ if (chunkCanvas.width !== cw) chunkCanvas.width = cw;
+ if (chunkCanvas.height !== ch) chunkCanvas.height = ch;
+
+ cCtx.setTransform(1, 0, 0, 1, 0, 0);
+ cCtx.clearRect(0, 0, cw, ch);
+ cCtx.save();
+ cCtx.translate(-cx, -cy);
+
+ if (session.mode === 'perspective' && session.perspectiveQuad) {
+ renderPerspectiveQuad(cCtx, sourceCanvas, session.perspectiveQuad, 24);
+ } else if (session.mode === 'mesh' && session.meshPoints) {
+ renderMeshWarp(cCtx, sourceCanvas, session.meshPoints, 6);
+ } else {
+ const midX = session.x + session.width / 2;
+ const midY = session.y + session.height / 2;
+ cCtx.translate(midX, midY);
+ cCtx.rotate((session.rotation * Math.PI) / 180);
+ cCtx.scale(session.flipH ? -1 : 1, session.flipV ? -1 : 1);
+ cCtx.drawImage(
+ sourceCanvas,
+ -session.width / 2,
+ -session.height / 2,
+ session.width,
+ session.height
+ );
+ }
+ cCtx.restore();
+
+ const img = cCtx.getImageData(0, 0, cw, ch);
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: img,
+ destX: cx,
+ destY: cy,
+ format: targetFormat,
+ compositeOp: 'source-over',
+ opacity: 1.0,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+ }
+ } finally {
+ releaseTemporaryCanvas(chunkCanvas);
+ }
+
+ return destRect;
+}
+
export interface UseSelectionToolsParams {
dimensions: CanvasDimensions;
colorMode: CanvasColorMode;
@@ -43,10 +176,6 @@ export interface UseSelectionToolsParams {
activeLayer: LayerItem | undefined;
activeLayerId: string;
selectedLayerIds: string[];
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- layerSourceCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- getActiveCanvas: () => HTMLCanvasElement | null;
- materializeLayerCanvas?: (layerId: string) => HTMLCanvasElement | null;
tileGrid?: SparseTileGrid;
flushPendingHistoryTasks?: () => void;
updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
@@ -87,10 +216,6 @@ export function useSelectionTools({
activeLayer,
activeLayerId,
selectedLayerIds,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- getActiveCanvas,
- materializeLayerCanvas,
tileGrid,
flushPendingHistoryTasks,
updateLayerThumbnail,
@@ -105,55 +230,17 @@ export function useSelectionTools({
[tileGrid]
);
- const markCanvasPopulated = useCallback((c: HTMLCanvasElement | null | undefined) => {
- if (!c) return;
- (c as unknown as { __isBlank?: boolean }).__isBlank = false;
- (c as unknown as { __isSolidWhite?: boolean }).__isSolidWhite = false;
- }, []);
-
- /**
- * Flushes any deferred brush/history tasks and synchronizes a layer's cached 2D canvas
- * from the authoritative SparseTileGrid so selection & transform never read stale tiles.
- */
- const getSyncedLayerCanvas = useCallback(
- (layerId: string): HTMLCanvasElement | null => {
- flushPendingHistoryTasks?.();
- const canvas =
- layerCanvasesRef.current.get(layerId) ??
- materializeLayerCanvas?.(layerId) ??
- (layerId === activeLayerId ? getActiveCanvas() : null);
- if (!canvas) return null;
-
- const grid = getGrid();
+ const resolveLayerFormat = useCallback(
+ (layerId: string): TileFormat => {
+ const isBg = layerId === 'layer-bg' || layerId.startsWith('layer-bg');
+ if (isBg) return 'color-32bit';
const lyr = layers.find((l) => l.id === layerId);
- const src = layerSourceCanvasesRef.current?.get(layerId);
- const hasTiles = grid.hasLayerTiles(layerId);
-
- if (lyr?.toneEnabled && src) {
- grid.renderLayerToCanvas(layerId, src);
- if (hasTiles) markCanvasPopulated(src);
- markCanvasPopulated(canvas);
- } else {
- grid.renderLayerToCanvas(layerId, canvas);
- if (hasTiles) markCanvasPopulated(canvas);
- if (src) {
- grid.renderLayerToCanvas(layerId, src);
- if (hasTiles) markCanvasPopulated(src);
- }
+ if (colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome') {
+ return 'monochrome-1bit';
}
- return canvas;
+ return 'color-32bit';
},
- [
- flushPendingHistoryTasks,
- layerCanvasesRef,
- materializeLayerCanvas,
- activeLayerId,
- getActiveCanvas,
- getGrid,
- layers,
- layerSourceCanvasesRef,
- markCanvasPopulated,
- ]
+ [colorMode, layers]
);
const selectionMaskCanvasRef = useRef<HTMLCanvasElement | null>(null);
@@ -181,41 +268,29 @@ export function useSelectionTools({
const handleCommitFloatingSelection = useCallback(() => {
if (!selection?.floating) return;
const targetLayerId = selection.floating.layerId || activeLayerId;
- const canvas =
- layerCanvasesRef.current.get(targetLayerId) ||
- materializeLayerCanvas?.(targetLayerId) ||
- getActiveCanvas();
- if (!canvas) return;
+ const grid = getGrid();
+ const targetFormat = resolveLayerFormat(targetLayerId);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- commitFloatingSelection(canvas, selection.floating, sourceCanvas);
- markCanvasPopulated(canvas);
- markCanvasPopulated(sourceCanvas);
+ const { dirtyRect, tileDeltas } = commitFloatingSelectionToTileGrid({
+ grid,
+ layerId: targetLayerId,
+ dimensions,
+ floating: selection.floating,
+ targetFormat,
+ });
- const grid = getGrid();
- const ctx = get2DContext(canvas);
- if (ctx) {
- const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- if (selection.floating.beforeImageData) {
- pushHistoryStep(
- 'selection-move',
- 'Move Selection',
- selection.floating.beforeImageData,
- afterData,
- targetLayerId
- );
- } else {
- const lyr = layers.find((l) => l.id === targetLayerId);
- const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
- grid.writeImageData(
- targetLayerId,
- afterData,
- 0,
- 0,
- isMono ? 'monochrome-1bit' : 'color-32bit'
- );
- }
- grid.notifyChange(true);
+ releaseTemporaryCanvas(selection.floating.canvas);
+
+ if (tileDeltas.length > 0) {
+ pushHistoryStep(
+ 'selection-move',
+ 'Move Selection',
+ null,
+ null,
+ targetLayerId,
+ dirtyRect,
+ tileDeltas
+ );
}
updateLayerThumbnail(targetLayerId, true);
@@ -223,14 +298,9 @@ export function useSelectionTools({
}, [
selection,
activeLayerId,
- layers,
- colorMode,
- layerCanvasesRef,
- materializeLayerCanvas,
- getActiveCanvas,
- layerSourceCanvasesRef,
- markCanvasPopulated,
+ dimensions,
getGrid,
+ resolveLayerFormat,
pushHistoryStep,
updateLayerThumbnail,
]);
@@ -244,211 +314,106 @@ export function useSelectionTools({
const handleClearSelection = useCallback(() => {
if (!selection) return;
+ flushPendingHistoryTasks?.();
const grid = getGrid();
+
if (selection.floating) {
const targetLayerId = selection.floating.layerId || activeLayerId;
- const canvas =
- layerCanvasesRef.current.get(targetLayerId) ||
- materializeLayerCanvas?.(targetLayerId) ||
- getActiveCanvas();
- if (canvas && selection.floating.beforeImageData) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ if (selection.floating.beforeTileSnapshot) {
+ const tileDeltas = grid.computeDeltasFromSnapshot(
+ selection.floating.beforeTileSnapshot,
+ targetLayerId
+ );
+ if (tileDeltas.length > 0) {
pushHistoryStep(
'clear',
'Clear Selection',
- selection.floating.beforeImageData,
- afterData,
- targetLayerId
+ null,
+ null,
+ targetLayerId,
+ selection.bounds,
+ tileDeltas
);
- grid.notifyChange(true);
}
}
+ releaseTemporaryCanvas(selection.floating.canvas);
+ grid.notifyChange(true);
+ updateLayerThumbnail(targetLayerId, true);
setSelection(null);
return;
}
- const canvas = getSyncedLayerCanvas(activeLayerId);
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
+ const targetFormat = resolveLayerFormat(activeLayerId);
+ const { dirtyRect, tileDeltas } = clearSelectionInTileGrid({
+ grid,
+ layerId: activeLayerId,
+ dimensions,
+ selection,
+ isBackground: isBg,
+ targetFormat,
+ });
- const clearOn = (target: HTMLCanvasElement) => {
- const c = get2DContext(target);
- if (!c) return;
- c.save();
- c.setTransform(1, 0, 0, 1, 0, 0);
- if (selection.mask && selection.maskWidth && selection.maskHeight) {
- const maskCanvas = document.createElement('canvas');
- maskCanvas.width = selection.maskWidth;
- maskCanvas.height = selection.maskHeight;
- const mCtx = maskCanvas.getContext('2d');
- if (mCtx) {
- const mImg = mCtx.createImageData(selection.maskWidth, selection.maskHeight);
- const count = Math.min(selection.mask.length, selection.maskWidth * selection.maskHeight);
- for (let i = 0; i < count; i++) {
- if (isBg) {
- mImg.data[i * 4] = 255;
- mImg.data[i * 4 + 1] = 255;
- mImg.data[i * 4 + 2] = 255;
- }
- mImg.data[i * 4 + 3] = selection.mask[i];
- }
- mCtx.putImageData(mImg, 0, 0);
- c.globalCompositeOperation = isBg ? 'source-over' : 'destination-out';
- c.drawImage(maskCanvas, 0, 0);
- }
- } else if (selection.type === 'rect') {
- if (isBg) {
- c.fillStyle = '#ffffff';
- c.fillRect(
- selection.bounds.x,
- selection.bounds.y,
- selection.bounds.width,
- selection.bounds.height
- );
- } else {
- c.clearRect(
- selection.bounds.x,
- selection.bounds.y,
- selection.bounds.width,
- selection.bounds.height
- );
- }
- } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
- c.beginPath();
- c.moveTo(selection.polygon[0].x, selection.polygon[0].y);
- for (let i = 1; i < selection.polygon.length; i++) {
- c.lineTo(selection.polygon[i].x, selection.polygon[i].y);
- }
- c.closePath();
- if (isBg) {
- c.fillStyle = '#ffffff';
- c.fill();
- } else {
- c.globalCompositeOperation = 'destination-out';
- c.fillStyle = 'rgba(0, 0, 0, 1)';
- c.fill();
- }
- }
- c.restore();
- };
-
- clearOn(canvas);
- if (sourceCanvas) clearOn(sourceCanvas);
- markCanvasPopulated(canvas);
- markCanvasPopulated(sourceCanvas);
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ if (tileDeltas.length > 0) {
+ pushHistoryStep(
+ 'clear',
+ 'Clear Selection',
+ null,
+ null,
+ activeLayerId,
+ dirtyRect ?? undefined,
+ tileDeltas
+ );
+ }
updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep('clear', 'Clear Selection', beforeImageData, afterImageData, activeLayerId);
- grid.notifyChange(true);
}, [
selection,
+ flushPendingHistoryTasks,
getGrid,
- getSyncedLayerCanvas,
- getActiveCanvas,
- materializeLayerCanvas,
activeLayerId,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- markCanvasPopulated,
+ dimensions,
+ resolveLayerFormat,
updateLayerThumbnail,
pushHistoryStep,
]);
const handleFillSelectionColor = useCallback(() => {
if (!selection) return;
- const canvas = getSyncedLayerCanvas(activeLayerId);
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
+ flushPendingHistoryTasks?.();
+ const grid = getGrid();
const primaryColor = useToolStore.getState().primaryColor;
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
-
- const fillOn = (target: HTMLCanvasElement) => {
- const c = get2DContext(target);
- if (!c) return;
- c.save();
- c.setTransform(1, 0, 0, 1, 0, 0);
- if (selection.mask && selection.maskWidth && selection.maskHeight) {
- const maskCanvas = document.createElement('canvas');
- maskCanvas.width = selection.maskWidth;
- maskCanvas.height = selection.maskHeight;
- const mCtx = maskCanvas.getContext('2d');
- if (mCtx) {
- mCtx.fillStyle = primaryColor;
- mCtx.fillRect(0, 0, selection.maskWidth, selection.maskHeight);
- const mImg = mCtx.getImageData(0, 0, selection.maskWidth, selection.maskHeight);
- const count = Math.min(selection.mask.length, selection.maskWidth * selection.maskHeight);
- for (let i = 0; i < count; i++) {
- mImg.data[i * 4 + 3] = Math.round((mImg.data[i * 4 + 3] * selection.mask[i]) / 255);
- }
- mCtx.putImageData(mImg, 0, 0);
- c.drawImage(maskCanvas, 0, 0);
- }
- } else {
- c.fillStyle = primaryColor;
- if (selection.type === 'rect') {
- c.fillRect(
- selection.bounds.x,
- selection.bounds.y,
- selection.bounds.width,
- selection.bounds.height
- );
- } else if (
- selection.type === 'lasso' &&
- selection.polygon &&
- selection.polygon.length >= 3
- ) {
- c.beginPath();
- c.moveTo(selection.polygon[0].x, selection.polygon[0].y);
- for (let i = 1; i < selection.polygon.length; i++) {
- c.lineTo(selection.polygon[i].x, selection.polygon[i].y);
- }
- c.closePath();
- c.fill();
- }
- }
- c.restore();
- };
-
- fillOn(canvas);
- markCanvasPopulated(canvas);
- if (sourceCanvas) {
- fillOn(sourceCanvas);
- markCanvasPopulated(sourceCanvas);
- if (activeLayer?.toneEnabled) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dimensions.dpi ?? 600,
- selection.bounds
- );
- }
- }
+ const targetFormat = resolveLayerFormat(activeLayerId);
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const { dirtyRect, tileDeltas } = fillSelectionInTileGrid({
+ grid,
+ layerId: activeLayerId,
+ dimensions,
+ selection,
+ colorCss: primaryColor,
+ targetFormat,
+ alphaLocked: Boolean(activeLayer?.alphaLocked),
+ });
+
+ if (tileDeltas.length > 0) {
+ pushHistoryStep(
+ 'fill',
+ 'Fill Selection',
+ null,
+ null,
+ activeLayerId,
+ dirtyRect ?? undefined,
+ tileDeltas
+ );
+ }
updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep('fill', 'Fill Selection', beforeImageData, afterImageData, activeLayerId);
- getGrid().notifyChange(true);
}, [
selection,
- getSyncedLayerCanvas,
+ flushPendingHistoryTasks,
+ getGrid,
activeLayerId,
activeLayer,
- layerSourceCanvasesRef,
- markCanvasPopulated,
- getGrid,
- dimensions.dpi,
+ dimensions,
+ resolveLayerFormat,
updateLayerThumbnail,
pushHistoryStep,
]);
@@ -579,39 +544,33 @@ export function useSelectionTools({
return;
}
+ flushPendingHistoryTasks?.();
const grid = getGrid();
if (selection) {
let floatCanvas = selection.floating?.canvas;
const targetLayerId = selection.floating?.layerId || activeLayerId;
const isBg = targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg');
- const canvas = floatCanvas
- ? layerCanvasesRef.current.get(targetLayerId) ||
- materializeLayerCanvas?.(targetLayerId) ||
- getActiveCanvas()
- : getSyncedLayerCanvas(targetLayerId);
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
+ const targetFormat = resolveLayerFormat(targetLayerId);
let floatX = selection.floating?.x ?? selection.bounds.x;
let floatY = selection.floating?.y ?? selection.bounds.y;
- let beforeData = selection.floating?.beforeImageData;
+ let beforeTileSnapshot = selection.floating?.beforeTileSnapshot;
if (!floatCanvas) {
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const lifted = liftSelectionToFloating(canvas, selection, sourceCanvas, isBg);
+ const lifted = liftSelectionFromTileGrid({
+ grid,
+ layerId: targetLayerId,
+ dimensions,
+ selection,
+ isBackground: isBg,
+ targetFormat,
+ });
if (!lifted) return;
floatCanvas = lifted.floatingCanvas;
floatX = lifted.bounds.x;
floatY = lifted.bounds.y;
- beforeData = lifted.beforeImageData;
- markCanvasPopulated(canvas);
- markCanvasPopulated(sourceCanvas);
- const targetLayer = layers.find((l) => l.id === targetLayerId);
- const isMono = colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
- grid.ingestCanvas(targetLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
+ beforeTileSnapshot = lifted.beforeTileSnapshot;
updateLayerThumbnail(targetLayerId, true);
}
@@ -626,7 +585,7 @@ export function useSelectionTools({
active: true,
layerId: targetLayerId,
sourceCanvas: floatCanvas,
- beforeImageData: beforeData || ctx.getImageData(0, 0, canvas.width, canvas.height),
+ beforeTileSnapshot: beforeTileSnapshot ?? new Map(),
bounds: { x: floatX, y: floatY, width: floatCanvas.width, height: floatCanvas.height },
x: floatX,
y: floatY,
@@ -650,26 +609,14 @@ export function useSelectionTools({
: [];
if (isMultiLayer && multiTargetLayers.length > 1) {
- const layerBeforeImages = new Map<string, ImageData>();
- const layerSourceCanvases = new Map<string, HTMLCanvasElement>();
-
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const lyr of multiTargetLayers) {
- const c = getSyncedLayerCanvas(lyr.id);
- if (!c) continue;
- const cCtx = get2DContext(c);
- if (!cCtx) continue;
- const bData = cCtx.getImageData(0, 0, c.width, c.height);
- layerBeforeImages.set(lyr.id, bData);
-
- const cb = getCanvasContentBounds(
- c,
- lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg')
- );
+ const isLayerBg = lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg');
+ const cb = grid.getLayerContentBounds(lyr.id, dimensions, isLayerBg);
if (cb) {
minX = Math.min(minX, cb.x);
minY = Math.min(minY, cb.y);
@@ -683,13 +630,16 @@ export function useSelectionTools({
return;
}
- const b = {
+ const b: DirtyRect = {
x: Math.max(0, minX),
y: Math.max(0, minY),
width: Math.max(1, maxX - minX),
height: Math.max(1, maxY - minY),
};
+ const layerBeforeSnapshots = new Map<string, Map<string, TileSnapshotEntry>>();
+ const layerSourceCanvases = new Map<string, HTMLCanvasElement>();
+
const compositeCanvas = document.createElement('canvas');
compositeCanvas.width = b.width;
compositeCanvas.height = b.height;
@@ -697,19 +647,9 @@ export function useSelectionTools({
const orderedLayers = multiTargetLayers.slice().reverse();
for (const lyr of orderedLayers) {
- const c = layerCanvasesRef.current.get(lyr.id);
- if (!c) continue;
- const cCtx = get2DContext(c);
- if (!cCtx) continue;
-
- const sCanvas = document.createElement('canvas');
- sCanvas.width = b.width;
- sCanvas.height = b.height;
- const sCtx = get2DContext(sCanvas);
- if (sCtx) {
- sCtx.drawImage(c, -b.x, -b.y);
- layerSourceCanvases.set(lyr.id, sCanvas);
- }
+ const sCanvas = grid.createRegionCanvas(lyr.id, b);
+ if (!sCanvas) continue;
+ layerSourceCanvases.set(lyr.id, sCanvas);
if (compCtx) {
compCtx.save();
@@ -719,35 +659,9 @@ export function useSelectionTools({
}
const isLayerBg = lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg');
- cCtx.save();
- cCtx.setTransform(1, 0, 0, 1, 0, 0);
- if (isLayerBg) {
- cCtx.fillStyle = '#ffffff';
- cCtx.fillRect(b.x, b.y, b.width, b.height);
- } else {
- cCtx.clearRect(b.x, b.y, b.width, b.height);
- }
- cCtx.restore();
- markCanvasPopulated(c);
-
- const existingSrc = layerSourceCanvasesRef.current?.get(lyr.id);
- if (existingSrc) {
- const escCtx = get2DContext(existingSrc);
- if (escCtx) {
- escCtx.save();
- escCtx.setTransform(1, 0, 0, 1, 0, 0);
- if (isLayerBg) {
- escCtx.fillStyle = '#ffffff';
- escCtx.fillRect(b.x, b.y, b.width, b.height);
- } else {
- escCtx.clearRect(b.x, b.y, b.width, b.height);
- }
- escCtx.restore();
- }
- markCanvasPopulated(existingSrc);
- }
- const isMono = colorMode === 'monochrome' || lyr.expressionColor === 'monochrome';
- grid.ingestCanvas(lyr.id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ const beforeSnap = new Map<string, TileSnapshotEntry>();
+ grid.clearRectInLayer(lyr.id, b, isLayerBg, beforeSnap, true);
+ layerBeforeSnapshots.set(lyr.id, beforeSnap);
updateLayerThumbnail(lyr.id, true);
}
grid.notifyChange(true);
@@ -758,10 +672,9 @@ export function useSelectionTools({
layerId: activeLayerId,
layerIds: multiTargetLayers.map((l) => l.id),
layerSourceCanvases,
- layerBeforeImages,
+ layerBeforeSnapshots,
sourceCanvas: compositeCanvas,
- beforeImageData:
- layerBeforeImages.get(activeLayerId) || Array.from(layerBeforeImages.values())[0],
+ beforeTileSnapshot: layerBeforeSnapshots.get(activeLayerId),
bounds: { x: b.x, y: b.y, width: b.width, height: b.height },
x: b.x,
y: b.y,
@@ -782,63 +695,22 @@ export function useSelectionTools({
}
const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
- const canvas = getSyncedLayerCanvas(activeLayerId);
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const contentBounds = getCanvasContentBounds(canvas, isBg);
+ const contentBounds = grid.getLayerContentBounds(activeLayerId, dimensions, isBg);
let b = contentBounds;
if (!b) {
if (isBg) {
- b = { x: 0, y: 0, width: canvas.width, height: canvas.height };
+ b = { x: 0, y: 0, width: dimensions.width, height: dimensions.height };
} else {
showToast('Active layer is empty');
return;
}
}
- const sourceCanvas = document.createElement('canvas');
- sourceCanvas.width = b.width;
- sourceCanvas.height = b.height;
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- const sliceData = ctx.getImageData(b.x, b.y, b.width, b.height);
- sCtx.putImageData(sliceData, 0, 0);
- }
-
- ctx.save();
- ctx.setTransform(1, 0, 0, 1, 0, 0);
- if (isBg) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(b.x, b.y, b.width, b.height);
- } else {
- ctx.clearRect(b.x, b.y, b.width, b.height);
- }
- ctx.restore();
- markCanvasPopulated(canvas);
-
- const existingSourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- if (existingSourceCanvas) {
- const escCtx = get2DContext(existingSourceCanvas);
- if (escCtx) {
- escCtx.save();
- escCtx.setTransform(1, 0, 0, 1, 0, 0);
- if (isBg) {
- escCtx.fillStyle = '#ffffff';
- escCtx.fillRect(b.x, b.y, b.width, b.height);
- } else {
- escCtx.clearRect(b.x, b.y, b.width, b.height);
- }
- escCtx.restore();
- }
- markCanvasPopulated(existingSourceCanvas);
- }
+ const sourceCanvas = grid.createRegionCanvas(activeLayerId, b);
+ if (!sourceCanvas) return;
- const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- grid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
+ const beforeTileSnapshot = new Map<string, TileSnapshotEntry>();
+ grid.clearRectInLayer(activeLayerId, b, isBg, beforeTileSnapshot, false);
updateLayerThumbnail(activeLayerId, true);
const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
@@ -846,7 +718,7 @@ export function useSelectionTools({
active: true,
layerId: activeLayerId,
sourceCanvas,
- beforeImageData,
+ beforeTileSnapshot,
bounds: { x: b.x, y: b.y, width: b.width, height: b.height },
x: b.x,
y: b.y,
@@ -866,19 +738,15 @@ export function useSelectionTools({
toolStoreActions.setToolRaw('transform');
}, [
transformSession,
+ flushPendingHistoryTasks,
getGrid,
- getSyncedLayerCanvas,
- materializeLayerCanvas,
- getActiveCanvas,
- markCanvasPopulated,
+ resolveLayerFormat,
+ dimensions,
selection,
activeLayerId,
activeLayer,
- colorMode,
selectedLayerIds,
layers,
- layerCanvasesRef,
- layerSourceCanvasesRef,
updateLayerThumbnail,
showToast,
]);
@@ -893,164 +761,85 @@ export function useSelectionTools({
transformSession.layerSourceCanvases
) {
for (const lId of transformSession.layerIds) {
- const c = layerCanvasesRef.current.get(lId) || materializeLayerCanvas?.(lId);
const sCanvas = transformSession.layerSourceCanvases.get(lId);
- if (!c || !sCanvas) continue;
- const cCtx = get2DContext(c);
- if (!cCtx) continue;
-
- const drawLayerTransformed = (targetCtx: CanvasRenderingContext2D) => {
- targetCtx.save();
- targetCtx.setTransform(1, 0, 0, 1, 0, 0);
- if (transformSession.mode === 'perspective' && transformSession.perspectiveQuad) {
- renderPerspectiveQuad(targetCtx, sCanvas, transformSession.perspectiveQuad, 24);
- } else if (transformSession.mode === 'mesh' && transformSession.meshPoints) {
- renderMeshWarp(targetCtx, sCanvas, transformSession.meshPoints, 6);
- } else {
- const cx = transformSession.x + transformSession.width / 2;
- const cy = transformSession.y + transformSession.height / 2;
- targetCtx.translate(cx, cy);
- targetCtx.rotate((transformSession.rotation * Math.PI) / 180);
- targetCtx.scale(transformSession.flipH ? -1 : 1, transformSession.flipV ? -1 : 1);
- targetCtx.drawImage(
- sCanvas,
- -transformSession.width / 2,
- -transformSession.height / 2,
- transformSession.width,
- transformSession.height
- );
- }
- targetCtx.restore();
- };
-
- drawLayerTransformed(cCtx);
- markCanvasPopulated(c);
-
- const existingSrc = layerSourceCanvasesRef.current?.get(lId);
- if (existingSrc) {
- const sCtx = get2DContext(existingSrc);
- if (sCtx) drawLayerTransformed(sCtx);
- markCanvasPopulated(existingSrc);
- }
+ if (!sCanvas) continue;
+ const targetFormat = resolveLayerFormat(lId);
+ const beforeSnap = new Map<string, TileSnapshotEntry>(
+ transformSession.layerBeforeSnapshots?.get(lId) ?? []
+ );
- const lyr = layers.find((l) => l.id === lId);
- if (lyr?.toneEnabled && existingSrc) {
- applyScreentone(existingSrc, c, {
- frequency: lyr.toneFrequency ?? 60,
- angle: lyr.toneAngle ?? 45,
- dotShape: lyr.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
+ const destRect = compositeTransformedIntoTileGrid(
+ grid,
+ lId,
+ sCanvas,
+ transformSession,
+ dimensions,
+ targetFormat,
+ beforeSnap
+ );
- const beforeDataForLayer = transformSession.layerBeforeImages?.get(lId);
- const afterDataForLayer = cCtx.getImageData(0, 0, c.width, c.height);
- const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
- grid.ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
- if (beforeDataForLayer) {
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnap, lId);
+ if (tileDeltas.length > 0) {
pushHistoryStep(
'transform',
'Batch Free Transform',
- beforeDataForLayer,
- afterDataForLayer,
- lId
+ null,
+ null,
+ lId,
+ destRect ?? undefined,
+ tileDeltas
);
}
+ releaseTemporaryCanvas(sCanvas);
updateLayerThumbnail(lId, true);
}
+ releaseTemporaryCanvas(transformSession.sourceCanvas);
grid.notifyChange(true);
setTransformSession(null);
toolStoreActions.setToolRaw('brush');
return;
}
- const canvas =
- layerCanvasesRef.current.get(transformSession.layerId) ||
- materializeLayerCanvas?.(transformSession.layerId) ||
- getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const sourceCanvas = layerSourceCanvasesRef.current?.get(transformSession.layerId);
-
- const drawTransformed = (targetCtx: CanvasRenderingContext2D) => {
- targetCtx.save();
- targetCtx.setTransform(1, 0, 0, 1, 0, 0);
- if (transformSession.mode === 'perspective' && transformSession.perspectiveQuad) {
- renderPerspectiveQuad(
- targetCtx,
- transformSession.sourceCanvas,
- transformSession.perspectiveQuad,
- 24
- );
- } else if (transformSession.mode === 'mesh' && transformSession.meshPoints) {
- renderMeshWarp(targetCtx, transformSession.sourceCanvas, transformSession.meshPoints, 6);
- } else {
- const cx = transformSession.x + transformSession.width / 2;
- const cy = transformSession.y + transformSession.height / 2;
- targetCtx.translate(cx, cy);
- targetCtx.rotate((transformSession.rotation * Math.PI) / 180);
- targetCtx.scale(transformSession.flipH ? -1 : 1, transformSession.flipV ? -1 : 1);
- targetCtx.drawImage(
- transformSession.sourceCanvas,
- -transformSession.width / 2,
- -transformSession.height / 2,
- transformSession.width,
- transformSession.height
- );
- }
- targetCtx.restore();
- };
-
- drawTransformed(ctx);
- markCanvasPopulated(canvas);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) drawTransformed(sCtx);
- markCanvasPopulated(sourceCanvas);
- }
-
- const layer = layers.find((l) => l.id === transformSession.layerId);
- if (layer?.toneEnabled && sourceCanvas) {
- applyScreentone(sourceCanvas, canvas, {
- frequency: layer.toneFrequency ?? 60,
- angle: layer.toneAngle ?? 45,
- dotShape: layer.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
+ const targetLayerId = transformSession.layerId;
+ const targetFormat = resolveLayerFormat(targetLayerId);
+ const beforeSnap = new Map<string, TileSnapshotEntry>(
+ transformSession.beforeTileSnapshot ?? []
+ );
+
+ const destRect = compositeTransformedIntoTileGrid(
+ grid,
+ targetLayerId,
+ transformSession.sourceCanvas,
+ transformSession,
+ dimensions,
+ targetFormat,
+ beforeSnap
+ );
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- if (transformSession.beforeImageData) {
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnap, targetLayerId);
+ if (tileDeltas.length > 0) {
pushHistoryStep(
'transform',
'Free Transform',
- transformSession.beforeImageData,
- afterImageData,
- transformSession.layerId
+ null,
+ null,
+ targetLayerId,
+ destRect ?? undefined,
+ tileDeltas
);
- } else {
- const isMono = colorMode === 'monochrome' || layer?.expressionColor === 'monochrome';
- grid.ingestCanvas(transformSession.layerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
}
- grid.notifyChange(true);
- updateLayerThumbnail(transformSession.layerId, true);
+ releaseTemporaryCanvas(transformSession.sourceCanvas);
+ grid.notifyChange(true);
+ updateLayerThumbnail(targetLayerId, true);
setTransformSession(null);
toolStoreActions.setToolRaw('brush');
}, [
transformSession,
getGrid,
- colorMode,
- layerCanvasesRef,
- materializeLayerCanvas,
- getActiveCanvas,
- markCanvasPopulated,
- layers,
- layerSourceCanvasesRef,
- dimensions.dpi,
+ resolveLayerFormat,
+ dimensions,
pushHistoryStep,
updateLayerThumbnail,
]);
@@ -1059,90 +848,31 @@ export function useSelectionTools({
if (!transformSession) return;
const grid = getGrid();
- if (transformSession.layerBeforeImages && transformSession.layerBeforeImages.size > 0) {
- for (const [lId, beforeData] of transformSession.layerBeforeImages.entries()) {
- const c = layerCanvasesRef.current.get(lId) || materializeLayerCanvas?.(lId);
- if (c && beforeData) {
- const ctx = get2DContext(c);
- ctx?.putImageData(beforeData, 0, 0);
- markCanvasPopulated(c);
-
- const lyr = layers.find((l) => l.id === lId);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(lId);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.putImageData(beforeData, 0, 0);
- markCanvasPopulated(sourceCanvas);
-
- if (lyr?.toneEnabled) {
- applyScreentone(sourceCanvas, c, {
- frequency: lyr.toneFrequency ?? 60,
- angle: lyr.toneAngle ?? 45,
- dotShape: lyr.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
- }
- const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
- grid.ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
- updateLayerThumbnail(lId, true);
+ if (transformSession.layerBeforeSnapshots && transformSession.layerBeforeSnapshots.size > 0) {
+ for (const [lId, beforeSnap] of transformSession.layerBeforeSnapshots.entries()) {
+ grid.restoreLayerSnapshot(lId, beforeSnap, true);
+ updateLayerThumbnail(lId, true);
+ }
+ if (transformSession.layerSourceCanvases) {
+ for (const sCanvas of transformSession.layerSourceCanvases.values()) {
+ releaseTemporaryCanvas(sCanvas);
}
}
+ releaseTemporaryCanvas(transformSession.sourceCanvas);
grid.notifyChange(true);
setTransformSession(null);
toolStoreActions.setToolRaw('brush');
return;
}
- const canvas =
- layerCanvasesRef.current.get(transformSession.layerId) ||
- materializeLayerCanvas?.(transformSession.layerId) ||
- getActiveCanvas();
- if (canvas && transformSession.beforeImageData) {
- const ctx = get2DContext(canvas);
- ctx?.putImageData(transformSession.beforeImageData, 0, 0);
- markCanvasPopulated(canvas);
-
- const layer = layers.find((l) => l.id === transformSession.layerId);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(transformSession.layerId);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.putImageData(transformSession.beforeImageData, 0, 0);
- markCanvasPopulated(sourceCanvas);
-
- if (layer?.toneEnabled) {
- applyScreentone(sourceCanvas, canvas, {
- frequency: layer.toneFrequency ?? 60,
- angle: layer.toneAngle ?? 45,
- dotShape: layer.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
- }
- const isMono = colorMode === 'monochrome' || layer?.expressionColor === 'monochrome';
- grid.ingestCanvas(
- transformSession.layerId,
- canvas,
- isMono ? 'monochrome-1bit' : 'color-32bit'
- );
- grid.notifyChange(true);
+ if (transformSession.beforeTileSnapshot) {
+ grid.restoreLayerSnapshot(transformSession.layerId, transformSession.beforeTileSnapshot, false);
updateLayerThumbnail(transformSession.layerId, true);
}
+ releaseTemporaryCanvas(transformSession.sourceCanvas);
setTransformSession(null);
toolStoreActions.setToolRaw('brush');
- }, [
- transformSession,
- getGrid,
- colorMode,
- layerCanvasesRef,
- materializeLayerCanvas,
- getActiveCanvas,
- markCanvasPopulated,
- layers,
- layerSourceCanvasesRef,
- dimensions.dpi,
- updateLayerThumbnail,
- ]);
+ }, [transformSession, getGrid, updateLayerThumbnail]);
const handleSelectionPointerDown = useCallback(
(e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
@@ -1158,29 +888,18 @@ export function useSelectionTools({
const py = Math.floor(pt.y);
if (px < 0 || px >= dimensions.width || py < 0 || py >= dimensions.height) return true;
- let sampleCanvas: HTMLCanvasElement | null = null;
- if (wandSettings.referMode === 'all') {
- flushPendingHistoryTasks?.();
- sampleCanvas = compositeVisibleLayers(layers, layerCanvasesRef.current, dimensions, getGrid());
- } else if (wandSettings.referMode === 'reference') {
- const refLayer = layers.find((l) => l.isReference && l.visible);
- if (refLayer) {
- sampleCanvas = getSyncedLayerCanvas(refLayer.id);
- } else {
- sampleCanvas = getSyncedLayerCanvas(activeLayerId);
- }
- } else {
- sampleCanvas = getSyncedLayerCanvas(activeLayerId);
- }
-
- if (!sampleCanvas) return true;
- const sCtx = get2DContext(sampleCanvas);
- if (!sCtx) return true;
-
+ flushPendingHistoryTasks?.();
const w = dimensions.width;
const h = dimensions.height;
- const sampleImageData = sCtx.getImageData(0, 0, w, h);
- const { mask, bounds } = floodSelectWand(sampleImageData, w, h, px, py, wandSettings);
+ const { mask, bounds } = floodSelectWandOnTileGrid({
+ grid: getGrid(),
+ layers,
+ activeLayerId,
+ dimensions,
+ startX: px,
+ startY: py,
+ settings: wandSettings,
+ });
if (!bounds || bounds.width === 0 || bounds.height === 0) {
setSelection(null);
@@ -1287,19 +1006,19 @@ export function useSelectionTools({
e.preventDefault();
if (selection && isPointInSelection(pt.x, pt.y, selection)) {
if (!selection.floating) {
- const canvas = getSyncedLayerCanvas(activeLayerId);
- if (!canvas) return true;
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+ flushPendingHistoryTasks?.();
+ const grid = getGrid();
const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
- const lifted = liftSelectionToFloating(canvas, selection, sourceCanvas, isBg);
+ const targetFormat = resolveLayerFormat(activeLayerId);
+ const lifted = liftSelectionFromTileGrid({
+ grid,
+ layerId: activeLayerId,
+ dimensions,
+ selection,
+ isBackground: isBg,
+ targetFormat,
+ });
if (lifted) {
- markCanvasPopulated(canvas);
- markCanvasPopulated(sourceCanvas);
- const grid = getGrid();
- const isMono =
- colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- grid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
const floatingObj = {
canvas: lifted.floatingCanvas,
@@ -1308,7 +1027,7 @@ export function useSelectionTools({
origX: lifted.bounds.x,
origY: lifted.bounds.y,
layerId: activeLayerId,
- beforeImageData: lifted.beforeImageData,
+ beforeTileSnapshot: lifted.beforeTileSnapshot,
};
setSelection({
...selection,
@@ -1367,15 +1086,10 @@ export function useSelectionTools({
handleCommitFloatingSelection,
flushPendingHistoryTasks,
getGrid,
- getSyncedLayerCanvas,
- markCanvasPopulated,
+ resolveLayerFormat,
dimensions,
layers,
- layerCanvasesRef,
activeLayerId,
- layerSourceCanvasesRef,
- colorMode,
- activeLayer,
updateLayerThumbnail,
]
);
diff --git a/src/hooks/drawing/useShapeAndFillTools.ts b/src/hooks/drawing/useShapeAndFillTools.ts
index 7b4d60e..c351e37 100644
--- a/src/hooks/drawing/useShapeAndFillTools.ts
+++ b/src/hooks/drawing/useShapeAndFillTools.ts
@@ -13,23 +13,22 @@ import {
TileDelta,
} from '../../types/editor';
import { documentStore } from '../../utils/documentStore';
-import { TileFormat } from '../../utils/tileEngine';
+import { TileFormat, TileSnapshotEntry } from '../../utils/tileEngine';
import {
- executeFloodFill,
- compositeVisibleLayers,
- compositeReferenceLayers,
- executeLassoFill,
+ executeFloodFillOnTileGridAsync,
+ executeLassoFillOnTileGrid,
} from '../../utils/floodFill';
import {
- applyLiquifyStep,
+ applyLiquifyStepOnTileGrid,
+ applyLiquifyStepOnTileGridAsync,
createLiquifySelectionMask,
resolveLiquifyTargetLayers,
DirtyRect,
} from '../../utils/liquifyEngine';
-import { rasterizeShapeToCanvas, resolveShapeFillColor } from '../../utils/shapeEngine';
-import { applyLayerEffects } from '../../utils/layerEffectsEngine';
+import { isNativeRustAvailable } from '../../utils/nativeBackend';
+import { rasterizeShapeToTileGrid, resolveShapeFillColor } from '../../utils/shapeEngine';
import { createSelectionMask } from '../../utils/tonalEngine';
-import { get2DContext, sampleCompositedColor } from '../../utils/canvasUtils';
+import { sampleCompositedColor } from '../../utils/canvasUtils';
import { createDefaultSpeechBalloon } from '../../utils/balloonEngine';
import {
createRectFrame,
@@ -64,13 +63,9 @@ export interface UseShapeAndFillToolsParams {
activeLayerId: string;
selectedLayerIds?: string[];
selection: CanvasSelection | null;
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- layerSourceCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- materializeLayerCanvas?: (layerId: string) => HTMLCanvasElement | null;
flushPendingHistoryTasks?: () => void;
isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
getEffectiveOpacity: (layer: LayerItem) => number;
- getActiveCanvas: () => HTMLCanvasElement | null;
getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => { x: number; y: number };
setActiveLayerId: (id: string) => void;
upsertTextLayer: (textData: TextLayerData, editingLayerId?: string | null) => LayerItem;
@@ -121,12 +116,8 @@ export interface UseShapeAndFillToolsResult {
interface LiquifyLayerSession {
layer: LayerItem;
layerId: string;
- isTone: boolean;
- sourceCanvas?: HTMLCanvasElement;
- displayCanvas: HTMLCanvasElement;
- workCanvas: HTMLCanvasElement;
- initialImageData: ImageData | null;
- beforeTileSnapshot: Map<string, { format: TileFormat; data: Uint8Array | null }>;
+ targetFormat: TileFormat;
+ beforeTileSnapshot: Map<string, TileSnapshotEntry>;
dirtyRect: DirtyRect | null;
}
@@ -148,13 +139,9 @@ export function useShapeAndFillTools({
activeLayerId,
selectedLayerIds = [],
selection,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- materializeLayerCanvas,
flushPendingHistoryTasks,
isLayerEffectivelyVisible,
getEffectiveOpacity,
- getActiveCanvas,
getCanvasCoords,
setActiveLayerId,
upsertTextLayer,
@@ -173,6 +160,7 @@ export function useShapeAndFillTools({
const [shapeDragPreview, setShapeDragPreview] = useState<ShapeDragPreview | null>(null);
const isPipetteSamplingRef = useRef<boolean>(false);
+ const liquifyInFlightRef = useRef<boolean>(false);
const lassoFillPointsRef = useRef<Array<{ x: number; y: number }>>([]);
const frameStartRef = useRef<{ x: number; y: number } | null>(null);
const shapeDragRef = useRef<{
@@ -291,7 +279,7 @@ export function useShapeAndFillTools({
(pt: { x: number; y: number }) => {
const sampled = sampleCompositedColor(
layers,
- layerCanvasesRef.current,
+ documentStore.getActiveTileGrid(),
pt.x,
pt.y,
isLayerEffectivelyVisible,
@@ -306,7 +294,6 @@ export function useShapeAndFillTools({
},
[
layers,
- layerCanvasesRef,
isLayerEffectivelyVisible,
getEffectiveOpacity,
dimensions.width,
@@ -364,39 +351,6 @@ export function useShapeAndFillTools({
setEditingBalloonLayerId(null);
}, [editingBalloonLayerId, deleteLayer]);
- const syncLiquifySessionDirty = useCallback(
- (session: LiquifyLayerSession, dirty: DirtyRect) => {
- if (dirty.width <= 0 || dirty.height <= 0) return;
- session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);
- const grid = documentStore.getActiveTileGrid();
- const isMono =
- colorMode === 'monochrome' || session.layer.expressionColor === 'monochrome';
- const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
-
- if (session.isTone && session.sourceCanvas) {
- applyLayerEffects(
- session.sourceCanvas,
- session.displayCanvas,
- session.layer,
- dimensions.dpi ?? 600,
- dirty
- );
- const sCtx = get2DContext(session.sourceCanvas);
- if (sCtx) {
- const subData = sCtx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
- grid.writeImageData(session.layerId, subData, dirty.x, dirty.y, targetFormat);
- }
- } else {
- const dCtx = get2DContext(session.workCanvas);
- if (dCtx) {
- const subData = dCtx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
- grid.writeImageData(session.layerId, subData, dirty.x, dirty.y, targetFormat);
- }
- }
- },
- [colorMode, dimensions.dpi]
- );
-
const startLiquifyLoop = useCallback(() => {
if (liquifyRafIdRef.current) cancelAnimationFrame(liquifyRafIdRef.current);
@@ -411,36 +365,77 @@ export function useShapeAndFillTools({
}
const { pt, pressure } = liquifyLastPointerPosRef.current;
const liquifySettings = useToolStore.getState().liquifySettings;
+ const grid = documentStore.getActiveTileGrid();
+
+ if (isNativeRustAvailable()) {
+ if (!liquifyInFlightRef.current) {
+ liquifyInFlightRef.current = true;
+ const sessions = liquifySessionsRef.current.slice();
+ void (async () => {
+ try {
+ let anyDirty = false;
+ for (const session of sessions) {
+ const dirty = await applyLiquifyStepOnTileGridAsync({
+ grid,
+ layerId: session.layerId,
+ dimensions,
+ targetFormat: session.targetFormat,
+ cx: pt.x,
+ cy: pt.y,
+ prevX: pt.x,
+ prevY: pt.y,
+ settings: liquifySettings,
+ pressure,
+ beforeTileSnapshot: session.beforeTileSnapshot,
+ selectionMask: liquifySelectionMaskRef.current,
+ });
+ if (dirty) {
+ session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);
+ anyDirty = true;
+ }
+ }
+ if (anyDirty) grid.notifyChange(true);
+ } finally {
+ liquifyInFlightRef.current = false;
+ }
+ })();
+ }
+ liquifyRafIdRef.current = requestAnimationFrame(tick);
+ return;
+ }
+
let anyDirty = false;
for (const session of liquifySessionsRef.current) {
- const dirty = applyLiquifyStep({
- canvas: session.workCanvas,
- sourceCanvas: session.isTone ? session.sourceCanvas : undefined,
+ const dirty = applyLiquifyStepOnTileGrid({
+ grid,
+ layerId: session.layerId,
+ dimensions,
+ targetFormat: session.targetFormat,
cx: pt.x,
cy: pt.y,
prevX: pt.x,
prevY: pt.y,
settings: liquifySettings,
pressure,
- initialImageData: session.initialImageData,
+ beforeTileSnapshot: session.beforeTileSnapshot,
selectionMask: liquifySelectionMaskRef.current,
});
if (dirty) {
- syncLiquifySessionDirty(session, dirty);
+ session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);
anyDirty = true;
}
}
if (anyDirty) {
- documentStore.getActiveTileGrid().notifyChange(true);
+ grid.notifyChange(true);
}
liquifyRafIdRef.current = requestAnimationFrame(tick);
};
liquifyRafIdRef.current = requestAnimationFrame(tick);
- }, [syncLiquifySessionDirty]);
+ }, [dimensions]);
const handleShapeFillPointerDown = useCallback(
(e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
@@ -501,6 +496,7 @@ export function useShapeAndFillTools({
if (tool === 'liquify') {
e.preventDefault();
+ flushPendingHistoryTasks?.();
const isMulti = Boolean(liquifySettings.multiLayer);
const targetLayers = resolveLiquifyTargetLayers(
layers,
@@ -514,60 +510,20 @@ export function useShapeAndFillTools({
}
const grid = documentStore.getActiveTileGrid();
- const needInitialImage = liquifySettings.mode === 'reconstruct';
const sessions: LiquifyLayerSession[] = [];
for (const layer of targetLayers) {
const targetId = layer.id;
- const displayCanvas =
- layerCanvasesRef.current.get(targetId) ?? materializeLayerCanvas?.(targetId) ?? null;
- if (!displayCanvas) continue;
-
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetId);
- const isTone = Boolean(layer.toneEnabled && sourceCanvas);
- const workCanvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
-
- // Skip strictly blank layers in multi-layer mode to avoid wasted work
- if (
- isMulti &&
- targetLayers.length > 1 &&
- (workCanvas as unknown as { __isBlank?: boolean }).__isBlank &&
- !grid.hasLayerTiles(targetId)
- ) {
- continue;
- }
-
- const ctx = get2DContext(workCanvas);
- if (!ctx) continue;
-
- const isMono = colorMode === 'monochrome' || layer.expressionColor === 'monochrome';
+ if (!grid.hasLayerTiles(targetId)) continue;
+ const isBg = targetId === 'layer-bg' || targetId.startsWith('layer-bg');
+ const isMono = !isBg && (colorMode === 'monochrome' || layer.expressionColor === 'monochrome');
const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
- if (
- !grid.hasLayerTiles(targetId) &&
- !(workCanvas as unknown as { __isBlank?: boolean }).__isBlank
- ) {
- grid.ingestCanvas(targetId, workCanvas, targetFormat);
- }
-
- const beforeTileSnapshot = grid.snapshotTilesInRect(targetId, {
- x: 0,
- y: 0,
- width: workCanvas.width,
- height: workCanvas.height,
- });
- const initialImageData = needInitialImage
- ? ctx.getImageData(0, 0, workCanvas.width, workCanvas.height)
- : null;
sessions.push({
layer,
layerId: targetId,
- isTone,
- sourceCanvas,
- displayCanvas,
- workCanvas,
- initialImageData,
- beforeTileSnapshot,
+ targetFormat,
+ beforeTileSnapshot: new Map<string, TileSnapshotEntry>(),
dirtyRect: null,
});
}
@@ -579,8 +535,8 @@ export function useShapeAndFillTools({
liquifySessionsRef.current = sessions;
liquifySelectionMaskRef.current = createLiquifySelectionMask(
selection,
- sessions[0].workCanvas.width,
- sessions[0].workCanvas.height
+ dimensions.width,
+ dimensions.height
);
liquifyLastPointerPosRef.current = { pt, pressure: e.pressure || 1.0 };
@@ -600,20 +556,22 @@ export function useShapeAndFillTools({
) {
let anyDirty = false;
for (const session of sessions) {
- const dirty = applyLiquifyStep({
- canvas: session.workCanvas,
- sourceCanvas: session.isTone ? session.sourceCanvas : undefined,
+ const dirty = applyLiquifyStepOnTileGrid({
+ grid,
+ layerId: session.layerId,
+ dimensions,
+ targetFormat: session.targetFormat,
cx: pt.x,
cy: pt.y,
prevX: pt.x,
prevY: pt.y,
settings: liquifySettings,
pressure: e.pressure || 1.0,
- initialImageData: session.initialImageData,
+ beforeTileSnapshot: session.beforeTileSnapshot,
selectionMask: liquifySelectionMaskRef.current,
});
if (dirty) {
- syncLiquifySessionDirty(session, dirty);
+ session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);
anyDirty = true;
}
}
@@ -637,9 +595,8 @@ export function useShapeAndFillTools({
if (px < 0 || px >= dimensions.width || py < 0 || py >= dimensions.height) return true;
flushPendingHistoryTasks?.();
- const canvas = getActiveCanvas();
if (
- !canvas ||
+ !activeLayerId ||
activeLayer?.locked ||
(activeLayer && !isLayerEffectivelyVisible(activeLayer))
) {
@@ -647,65 +604,53 @@ export function useShapeAndFillTools({
}
const grid = documentStore.getActiveTileGrid();
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- if (!activeLayer?.toneEnabled) {
- grid.renderLayerToCanvas(activeLayerId, canvas);
- }
- if (sourceCanvas) {
- grid.renderLayerToCanvas(activeLayerId, sourceCanvas);
- }
-
- const ctx = get2DContext(canvas);
- if (!ctx) return true;
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
-
- let refCanvas: HTMLCanvasElement;
- if (fillSettings.method === 'refer-all') {
- refCanvas = compositeVisibleLayers(layers, layerCanvasesRef.current, dimensions, grid);
- } else if (fillSettings.method === 'refer-reference') {
- refCanvas = compositeReferenceLayers(layers, layerCanvasesRef.current, dimensions, grid);
- } else {
- refCanvas = canvas;
- }
+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
+ const isMono =
+ !isBg && (colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome');
+ const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+ const referMode =
+ fillSettings.method === 'refer-all'
+ ? 'refer-all'
+ : fillSettings.method === 'refer-reference'
+ ? 'refer-reference'
+ : 'active';
const selMask = selection
- ? createSelectionMask(selection, canvas.width, canvas.height)
+ ? createSelectionMask(selection, dimensions.width, dimensions.height)
: null;
- const fillRes = executeFloodFill(
- canvas,
- refCanvas,
- px,
- py,
- primaryColor,
- fillSettings.tolerance,
- sourceCanvas,
- {
+
+ const targetLayerId = activeLayerId;
+ void executeFloodFillOnTileGridAsync({
+ grid,
+ targetLayerId,
+ layers,
+ dimensions,
+ startX: px,
+ startY: py,
+ fillColorHex: primaryColor,
+ tolerance: fillSettings.tolerance,
+ referMode,
+ targetFormat,
+ options: {
closeGap: fillSettings.closeGap ?? 0,
areaScale: fillSettings.areaScale ?? 0,
antiAlias: fillSettings.antiAlias ?? true,
selectionMask: selMask,
+ },
+ }).then((fillRes) => {
+ if (fillRes.modified && fillRes.tileDeltas.length > 0) {
+ pushHistoryStep(
+ 'fill',
+ 'Bucket Fill',
+ null,
+ null,
+ targetLayerId,
+ fillRes.dirtyRect ?? undefined,
+ fillRes.tileDeltas
+ );
+ updateLayerThumbnail(targetLayerId, true);
}
- );
- (canvas as unknown as { __isBlank?: boolean; __isSolidWhite?: boolean }).__isBlank = false;
- (canvas as unknown as { __isSolidWhite?: boolean }).__isSolidWhite = false;
- if (sourceCanvas) {
- (sourceCanvas as unknown as { __isBlank?: boolean }).__isBlank = false;
- (sourceCanvas as unknown as { __isSolidWhite?: boolean }).__isSolidWhite = false;
- }
- if (activeLayer?.toneEnabled && sourceCanvas) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dimensions.dpi ?? 600,
- fillRes.dirtyRect ?? undefined
- );
- }
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep('fill', 'Bucket Fill', beforeImageData, afterImageData, activeLayerId);
- grid.notifyChange(true);
+ });
return true;
}
@@ -781,16 +726,11 @@ export function useShapeAndFillTools({
activeLayerId,
selectedLayerIds,
isLayerEffectivelyVisible,
- layerSourceCanvasesRef,
- layerCanvasesRef,
- materializeLayerCanvas,
flushPendingHistoryTasks,
selection,
dimensions,
colorMode,
startLiquifyLoop,
- syncLiquifySessionDirty,
- getActiveCanvas,
layers,
updateLayerThumbnail,
pushHistoryStep,
@@ -845,6 +785,54 @@ export function useShapeAndFillTools({
const dist = Math.hypot(pt.x - prev.x, pt.y - prev.y);
const stepDist = Math.max(2, (liquifySettings.size / 2) * 0.25);
const numSteps = Math.max(1, Math.ceil(dist / stepDist));
+ const grid = documentStore.getActiveTileGrid();
+
+ if (isNativeRustAvailable()) {
+ if (!liquifyInFlightRef.current) {
+ liquifyInFlightRef.current = true;
+ const sessions = liquifySessionsRef.current.slice();
+ prevLiquifyPointRef.current = pt;
+ void (async () => {
+ try {
+ let anyDirty = false;
+ for (const session of sessions) {
+ let layerDirty: DirtyRect | null = null;
+ for (let i = 1; i <= numSteps; i++) {
+ const t = i / numSteps;
+ const cx = prev.x + (pt.x - prev.x) * t;
+ const cy = prev.y + (pt.y - prev.y) * t;
+ const px = prev.x + (pt.x - prev.x) * ((i - 1) / numSteps);
+ const py = prev.y + (pt.y - prev.y) * ((i - 1) / numSteps);
+ const dirty = await applyLiquifyStepOnTileGridAsync({
+ grid,
+ layerId: session.layerId,
+ dimensions,
+ targetFormat: session.targetFormat,
+ cx,
+ cy,
+ prevX: px,
+ prevY: py,
+ settings: liquifySettings,
+ pressure,
+ beforeTileSnapshot: session.beforeTileSnapshot,
+ selectionMask: liquifySelectionMaskRef.current,
+ });
+ if (dirty) layerDirty = mergeDirtyRects(layerDirty, dirty);
+ }
+ if (layerDirty) {
+ session.dirtyRect = mergeDirtyRects(session.dirtyRect, layerDirty);
+ anyDirty = true;
+ }
+ }
+ if (anyDirty) grid.notifyChange(true);
+ } finally {
+ liquifyInFlightRef.current = false;
+ }
+ })();
+ }
+ return true;
+ }
+
let anyDirty = false;
for (const session of liquifySessionsRef.current) {
@@ -856,16 +844,18 @@ export function useShapeAndFillTools({
const px = prev.x + (pt.x - prev.x) * ((i - 1) / numSteps);
const py = prev.y + (pt.y - prev.y) * ((i - 1) / numSteps);
- const dirty = applyLiquifyStep({
- canvas: session.workCanvas,
- sourceCanvas: session.isTone ? session.sourceCanvas : undefined,
+ const dirty = applyLiquifyStepOnTileGrid({
+ grid,
+ layerId: session.layerId,
+ dimensions,
+ targetFormat: session.targetFormat,
cx,
cy,
prevX: px,
prevY: py,
settings: liquifySettings,
pressure,
- initialImageData: session.initialImageData,
+ beforeTileSnapshot: session.beforeTileSnapshot,
selectionMask: liquifySelectionMaskRef.current,
});
@@ -875,7 +865,7 @@ export function useShapeAndFillTools({
}
if (layerDirty) {
- syncLiquifySessionDirty(session, layerDirty);
+ session.dirtyRect = mergeDirtyRects(session.dirtyRect, layerDirty);
anyDirty = true;
}
}
@@ -883,7 +873,7 @@ export function useShapeAndFillTools({
prevLiquifyPointRef.current = pt;
if (anyDirty) {
- documentStore.getActiveTileGrid().notifyChange(true);
+ grid.notifyChange(true);
}
return true;
}
@@ -905,7 +895,7 @@ export function useShapeAndFillTools({
return false;
},
- [getCanvasCoords, handleSampleColor, syncLiquifySessionDirty]
+ [dimensions, getCanvasCoords, handleSampleColor]
);
const handleShapeFillPointerUp = useCallback(
@@ -944,9 +934,7 @@ export function useShapeAndFillTools({
setShapeDragPreview(null);
if (!drag) return true;
- const canvas = getActiveCanvas();
if (
- !canvas ||
!activeLayer ||
activeLayer.type !== 'raster' ||
activeLayer.locked ||
@@ -955,29 +943,10 @@ export function useShapeAndFillTools({
return true;
}
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- const isTone = Boolean(activeLayer.toneEnabled && sourceCanvas);
- const workCanvas = isTone && sourceCanvas ? sourceCanvas : canvas;
- const ctx = get2DContext(workCanvas);
- if (!ctx) return true;
-
+ flushPendingHistoryTasks?.();
const isMono =
colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
- const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
const grid = documentStore.getActiveTileGrid();
- if (
- !grid.hasLayerTiles(activeLayerId) &&
- !(workCanvas as unknown as { __isBlank?: boolean }).__isBlank
- ) {
- grid.ingestCanvas(activeLayerId, workCanvas, targetFormat);
- }
- const beforeSnapshot = grid.snapshotTilesInRect(activeLayerId, {
- x: 0,
- y: 0,
- width: workCanvas.width,
- height: workCanvas.height,
- });
-
const fillColor = resolveShapeFillColor(shapeSettings, primaryColor, secondaryColor);
const finalPreview: ShapeDragPreview = {
start: drag.start,
@@ -987,34 +956,20 @@ export function useShapeAndFillTools({
settings: shapeSettings,
};
- const dirty = rasterizeShapeToCanvas(
- canvas,
+ const { dirtyRect, tileDeltas } = rasterizeShapeToTileGrid(
+ grid,
+ activeLayerId,
+ dimensions,
finalPreview,
primaryColor,
fillColor,
selection,
colorMode,
isMono,
- isTone ? sourceCanvas : null
+ Boolean(activeLayer.alphaLocked)
);
- if (dirty && dirty.width > 0 && dirty.height > 0) {
- (canvas as unknown as { __isBlank?: boolean }).__isBlank = false;
- if (sourceCanvas) {
- (sourceCanvas as unknown as { __isBlank?: boolean }).__isBlank = false;
- }
- if (isTone && sourceCanvas) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dimensions.dpi ?? 600,
- dirty
- );
- }
- const subData = ctx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
- grid.writeImageData(activeLayerId, subData, dirty.x, dirty.y, targetFormat);
- const deltas = grid.computeDeltasFromSnapshot(beforeSnapshot, activeLayerId, dirty);
+ if (dirtyRect && tileDeltas.length > 0) {
const shapeName =
shapeSettings.shape.charAt(0).toUpperCase() + shapeSettings.shape.slice(1);
pushHistoryStep(
@@ -1023,8 +978,8 @@ export function useShapeAndFillTools({
null,
null,
activeLayerId,
- dirty,
- deltas.length > 0 ? deltas : undefined
+ dirtyRect,
+ tileDeltas
);
grid.notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
@@ -1104,35 +1059,36 @@ export function useShapeAndFillTools({
const pts = [...lassoFillPointsRef.current];
lassoFillPointsRef.current = [];
flushPendingHistoryTasks?.();
- const canvas = getActiveCanvas();
- if (!canvas) return true;
+ if (!activeLayerId || activeLayer?.locked) return true;
+
const grid = documentStore.getActiveTileGrid();
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- if (!activeLayer?.toneEnabled) {
- grid.renderLayerToCanvas(activeLayerId, canvas);
- }
- if (sourceCanvas) {
- grid.renderLayerToCanvas(activeLayerId, sourceCanvas);
- }
- const ctx = get2DContext(canvas);
- if (!ctx) return true;
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
-
- executeLassoFill(canvas, pts, primaryColor, sourceCanvas);
- (canvas as unknown as { __isBlank?: boolean }).__isBlank = false;
- (canvas as unknown as { __isSolidWhite?: boolean }).__isSolidWhite = false;
- if (sourceCanvas) {
- (sourceCanvas as unknown as { __isBlank?: boolean }).__isBlank = false;
- (sourceCanvas as unknown as { __isSolidWhite?: boolean }).__isSolidWhite = false;
- }
- if (activeLayer?.toneEnabled && sourceCanvas) {
- applyLayerEffects(sourceCanvas, canvas, activeLayer, dimensions.dpi ?? 600);
- }
+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
+ const isMono =
+ !isBg && (colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome');
+ const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep('fill', 'Lasso Fill', beforeImageData, afterImageData, activeLayerId);
- grid.notifyChange(true);
+ const res = executeLassoFillOnTileGrid({
+ grid,
+ targetLayerId: activeLayerId,
+ dimensions,
+ polygon: pts,
+ fillColorHex: primaryColor,
+ targetFormat,
+ alphaLocked: Boolean(activeLayer?.alphaLocked),
+ });
+
+ if (res.modified && res.tileDeltas.length > 0) {
+ pushHistoryStep(
+ 'fill',
+ 'Lasso Fill',
+ null,
+ null,
+ activeLayerId,
+ res.dirtyRect ?? undefined,
+ res.tileDeltas
+ );
+ updateLayerThumbnail(activeLayerId, true);
+ }
return true;
}
@@ -1227,13 +1183,10 @@ export function useShapeAndFillTools({
activeLayer,
layers,
isLayerEffectivelyVisible,
- layerSourceCanvasesRef,
- layerCanvasesRef,
pushHistoryStep,
updateLayerThumbnail,
- getActiveCanvas,
flushPendingHistoryTasks,
- dimensions.dpi,
+ dimensions,
selection,
colorMode,
createFrameFolder,
diff --git a/src/hooks/drawing/useVectorDrawing.ts b/src/hooks/drawing/useVectorDrawing.ts
index 67ef48a..c543c60 100644
--- a/src/hooks/drawing/useVectorDrawing.ts
+++ b/src/hooks/drawing/useVectorDrawing.ts
@@ -10,6 +10,7 @@ import {
} from '../../types/editor';
import { SparseTileGrid, releaseTemporaryCanvas } from '../../utils/tileEngine';
import { documentStore } from '../../utils/documentStore';
+import { multiplayerService } from '../../services/multiplayerService';
import {
applyVectorEraser,
computeStrokeBounds,
@@ -35,7 +36,6 @@ export interface CommitVectorStrokeArgs {
strokeColor: string;
dims: CanvasDimensions;
grid: SparseTileGrid;
- canvas: HTMLCanvasElement | null;
mergedDirty: { minX: number; minY: number; maxX: number; maxY: number } | null;
strokeId: string | null;
pushHistoryStep: PushHistoryStepFn;
@@ -52,7 +52,6 @@ export function commitVectorStrokeOrErase({
strokeColor,
dims,
grid,
- canvas,
mergedDirty,
strokeId,
pushHistoryStep,
@@ -116,14 +115,6 @@ export function commitVectorStrokeOrErase({
);
}
releaseTemporaryCanvas(tempVec);
- if (canvas) {
- grid.renderLayerToCanvas(currentLayerId, canvas, {
- x: vx,
- y: vy,
- width: vw,
- height: vh,
- });
- }
}
pushHistoryStep(
@@ -140,6 +131,9 @@ export function commitVectorStrokeOrErase({
undefined,
strokeId || undefined
);
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendLayerUpdate(currentLayerId, { vectorStrokes: updatedStrokes });
+ }
return undefined;
}
@@ -189,14 +183,6 @@ export function commitVectorStrokeOrErase({
);
}
releaseTemporaryCanvas(tempVec);
- if (canvas) {
- grid.renderLayerToCanvas(currentLayerId, canvas, {
- x: vx,
- y: vy,
- width: vw,
- height: vh,
- });
- }
}
pushHistoryStep(
@@ -220,8 +206,8 @@ export function commitVectorStrokeOrErase({
export interface UseVectorDrawingParams {
activeLayer: LayerItem | undefined;
activeLayerId: string;
+ dimensions: CanvasDimensions;
colorMode: CanvasColorMode;
- getActiveCanvas: () => HTMLCanvasElement | null;
getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => { x: number; y: number };
updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
pushHistoryStep: PushHistoryStepFn;
@@ -238,8 +224,8 @@ export interface UseVectorDrawingResult {
export function useVectorDrawing({
activeLayer,
activeLayerId,
+ dimensions,
colorMode,
- getActiveCanvas,
getCanvasCoords,
updateLayerThumbnail,
pushHistoryStep,
@@ -277,6 +263,19 @@ export function useVectorDrawing({
const vectorEditSettings = useToolStore.getState().vectorEditSettings;
const radius = vectorEditSettings.radius || 35;
let updated = false;
+ let dirtyMinX = Infinity;
+ let dirtyMinY = Infinity;
+ let dirtyMaxX = -Infinity;
+ let dirtyMaxY = -Infinity;
+
+ const expandDirty = (st: VectorStroke) => {
+ if (!st.bounds) return;
+ const pad = Math.ceil(Math.max(16, (st.baseWidth || 10) * 1.5));
+ if (st.bounds.minX - pad < dirtyMinX) dirtyMinX = st.bounds.minX - pad;
+ if (st.bounds.minY - pad < dirtyMinY) dirtyMinY = st.bounds.minY - pad;
+ if (st.bounds.maxX + pad > dirtyMaxX) dirtyMaxX = st.bounds.maxX + pad;
+ if (st.bounds.maxY + pad > dirtyMaxY) dirtyMaxY = st.bounds.maxY + pad;
+ };
const newStrokes = activeLayer.vectorStrokes.map((stroke) => {
if (stroke.deleted) return stroke;
@@ -289,41 +288,56 @@ export function useVectorDrawing({
return stroke;
}
+ let nextStroke = stroke;
if (vectorEditSettings.mode === 'pinch') {
if (Math.hypot(delta.x, delta.y) > 0.05) {
updated = true;
- return pinchVectorStroke(stroke, pt, radius, delta);
+ nextStroke = pinchVectorStroke(stroke, pt, radius, delta);
}
} else if (vectorEditSettings.mode === 'width') {
updated = true;
- return modifyStrokeWidth(stroke, pt, radius, vectorEditSettings.widthFactor);
+ nextStroke = modifyStrokeWidth(stroke, pt, radius, vectorEditSettings.widthFactor);
} else if (vectorEditSettings.mode === 'simplify') {
updated = true;
- return simplifyVectorStroke(stroke, vectorEditSettings.simplifyTolerance);
+ nextStroke = simplifyVectorStroke(stroke, vectorEditSettings.simplifyTolerance);
}
- return stroke;
+ if (nextStroke !== stroke) {
+ expandDirty(stroke);
+ expandDirty(nextStroke);
+ }
+ return nextStroke;
});
if (updated) {
activeLayer.vectorStrokes = newStrokes;
- const canvas = getActiveCanvas();
- if (canvas) {
- const ctx = get2DContext(canvas);
+ const grid = documentStore.getActiveTileGrid();
+ const isMono =
+ colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ const vx = Math.max(0, Math.floor(dirtyMinX));
+ const vy = Math.max(0, Math.floor(dirtyMinY));
+ const vx1 = Math.min(dimensions.width, Math.ceil(dirtyMaxX));
+ const vy1 = Math.min(dimensions.height, Math.ceil(dirtyMaxY));
+ const vw = vx1 - vx;
+ const vh = vy1 - vy;
+
+ if (vw > 0 && vh > 0) {
+ const temp = document.createElement('canvas');
+ temp.width = vw;
+ temp.height = vh;
+ const ctx = get2DContext(temp);
if (ctx) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.save();
+ ctx.translate(-vx, -vy);
renderVectorLayer(ctx, newStrokes);
- const isMono =
- colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
- documentStore
- .getActiveTileGrid()
- .ingestCanvas(
- activeLayerId,
- canvas,
- isMono ? 'monochrome-1bit' : 'color-32bit'
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(activeLayerId, true);
+ ctx.restore();
+ const subData = ctx.getImageData(0, 0, vw, vh);
+ grid.writeImageData(activeLayerId, subData, vx, vy, targetFormat);
}
+ releaseTemporaryCanvas(temp);
+ grid.notifyChange(true);
+ updateLayerThumbnail(activeLayerId, true);
}
}
return true;
@@ -332,7 +346,8 @@ export function useVectorDrawing({
activeLayer,
activeLayerId,
colorMode,
- getActiveCanvas,
+ dimensions.height,
+ dimensions.width,
getCanvasCoords,
updateLayerThumbnail,
]
@@ -343,6 +358,7 @@ export function useVectorDrawing({
isVectorEditingRef.current = false;
const vectorEditSettings = useToolStore.getState().vectorEditSettings;
if (activeLayer?.vectorStrokes && vectorEditBeforeStrokesRef.current) {
+ const updatedStrokes = [...activeLayer.vectorStrokes];
pushHistoryStep(
'brush',
`Correct Line (${vectorEditSettings.mode})`,
@@ -353,9 +369,12 @@ export function useVectorDrawing({
undefined,
{
before: vectorEditBeforeStrokesRef.current,
- after: [...activeLayer.vectorStrokes],
+ after: updatedStrokes,
}
);
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendLayerUpdate(activeLayerId, { vectorStrokes: updatedStrokes });
+ }
documentStore.getActiveTileGrid().notifyChange(true);
}
vectorEditBeforeStrokesRef.current = null;
diff --git a/src/hooks/layerManager/layerTreeOps.ts b/src/hooks/layerManager/layerTreeOps.ts
new file mode 100644
index 0000000..2f797d1
--- /dev/null
+++ b/src/hooks/layerManager/layerTreeOps.ts
@@ -0,0 +1,332 @@
+import { LayerItem, isFolderLikeLayer } from '../../types/editor';
+
+export function isBackgroundLayerId(id: string): boolean {
+ return id === 'layer-bg' || id.startsWith('layer-bg');
+}
+
+// Helper to generate the next collaborative layer name (e.g. "Artist 1", "Artist 2", "Alex 1")
+export function getNextCollabLayerName(username: string, layers: LayerItem[]): string {
+ const cleanName = (username || 'User').trim();
+ let maxNum = 0;
+ const escaped = cleanName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const regex = new RegExp(`^${escaped}\\s*(\\d*)$`, 'i');
+
+ layers.forEach((l) => {
+ const match = l.name.match(regex);
+ if (match) {
+ const num = match[1] ? parseInt(match[1], 10) : 1;
+ if (!isNaN(num) && num > maxNum) {
+ maxNum = num;
+ }
+ }
+ });
+
+ return `${cleanName} ${maxNum + 1}`;
+}
+
+// Pure selection computation for single, Shift (range), and Ctrl/Cmd (toggle) clicks
+export function computeLayerSelection(
+ layers: LayerItem[],
+ currentSelectedIds: string[],
+ activeId: string,
+ pivotId: string | null,
+ targetId: string,
+ isShift: boolean,
+ isCtrl: boolean
+): { nextSelectedIds: string[]; nextActiveId: string; nextPivotId: string } {
+ const targetIndex = layers.findIndex((l) => l.id === targetId);
+ if (targetIndex === -1) {
+ return {
+ nextSelectedIds: currentSelectedIds,
+ nextActiveId: activeId,
+ nextPivotId: pivotId || activeId,
+ };
+ }
+
+ if (isShift) {
+ const effectivePivot = pivotId || activeId || targetId;
+ const pivotIndex = layers.findIndex((l) => l.id === effectivePivot);
+ const safePivotIdx = pivotIndex >= 0 ? pivotIndex : targetIndex;
+ const start = Math.min(safePivotIdx, targetIndex);
+ const end = Math.max(safePivotIdx, targetIndex);
+ const rangeIds = layers.slice(start, end + 1).map((l) => l.id);
+
+ if (isCtrl) {
+ return {
+ nextSelectedIds: Array.from(new Set([...currentSelectedIds, ...rangeIds])),
+ nextActiveId: targetId,
+ nextPivotId: effectivePivot,
+ };
+ } else {
+ return {
+ nextSelectedIds: rangeIds,
+ nextActiveId: targetId,
+ nextPivotId: effectivePivot,
+ };
+ }
+ } else if (isCtrl) {
+ const exists = currentSelectedIds.includes(targetId);
+ if (exists) {
+ const next = currentSelectedIds.filter((item) => item !== targetId);
+ const nextActive = activeId === targetId && next.length > 0 ? next[next.length - 1] : activeId;
+ return {
+ nextSelectedIds: next,
+ nextActiveId: nextActive,
+ nextPivotId: targetId,
+ };
+ } else {
+ return {
+ nextSelectedIds: [...currentSelectedIds, targetId],
+ nextActiveId: targetId,
+ nextPivotId: targetId,
+ };
+ }
+ } else {
+ return {
+ nextSelectedIds: [targetId],
+ nextActiveId: targetId,
+ nextPivotId: targetId,
+ };
+ }
+}
+
+// Pure batch deletion helper
+export function computeBatchDeleteLayers(
+ layers: LayerItem[],
+ selectedIds: string[],
+ activeId: string
+): { nextLayers: LayerItem[]; deletedIds: string[]; nextActiveId: string } {
+ let targets = [...selectedIds];
+ if (targets.length === 0 && activeId) {
+ targets = [activeId];
+ }
+ if (targets.length === 0) {
+ return { nextLayers: layers, deletedIds: [], nextActiveId: activeId };
+ }
+
+ const targetSet = new Set(targets);
+ const allToDelete = new Set<string>();
+
+ const collectDescendants = (parentId: string) => {
+ for (const l of layers) {
+ if (l.parentId === parentId) {
+ allToDelete.add(l.id);
+ if (isFolderLikeLayer(l)) collectDescendants(l.id);
+ }
+ }
+ };
+
+ for (const id of targetSet) {
+ allToDelete.add(id);
+ const item = layers.find((l) => l.id === id);
+ if (isFolderLikeLayer(item)) {
+ collectDescendants(id);
+ }
+ }
+
+ // Ensure we don't delete all raster layers if user tries to delete everything
+ const remainingRaster = layers.filter((l) => l.type === 'raster' && !allToDelete.has(l.id));
+ if (remainingRaster.length === 0) {
+ const preserved = layers.find((l) => l.id === 'layer-bg' || l.id.startsWith('layer-bg')) || layers.find((l) => l.type === 'raster');
+ if (preserved) {
+ allToDelete.delete(preserved.id);
+ }
+ }
+
+ const nextLayers = layers.filter((l) => !allToDelete.has(l.id));
+ const nextActive = nextLayers.find((l) => l.type === 'raster') || nextLayers[0];
+ const nextActiveId = nextActive ? nextActive.id : '';
+
+ return {
+ nextLayers,
+ deletedIds: Array.from(allToDelete),
+ nextActiveId,
+ };
+}
+
+// Pure group selected layers helper
+export function computeGroupLayers(
+ layers: LayerItem[],
+ selectedIds: string[],
+ activeId: string,
+ customFolderId?: string
+): { nextLayers: LayerItem[]; newFolder: LayerItem } | null {
+ let targets = [...selectedIds];
+ if (targets.length === 0 && activeId) {
+ targets = [activeId];
+ }
+ if (targets.length === 0) return null;
+
+ const targetSet = new Set(targets);
+ const selectedItems = layers.filter((l) => targetSet.has(l.id));
+ if (selectedItems.length === 0) return null;
+
+ const indices = selectedItems.map((l) => layers.indexOf(l)).filter((idx) => idx >= 0);
+ const minIdx = Math.min(...indices);
+
+ const firstParent = selectedItems[0].parentId;
+ const allSameParent = selectedItems.every((l) => l.parentId === firstParent);
+ const folderParentId = allSameParent ? firstParent : null;
+
+ const folderId = customFolderId || `folder-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ let count = 1;
+ layers.forEach((l) => {
+ if (l.type === 'folder' && l.name.startsWith('Folder ')) {
+ const num = parseInt(l.name.replace('Folder ', ''), 10);
+ if (!isNaN(num) && num >= count) count = num + 1;
+ }
+ });
+
+ const newFolder: LayerItem = {
+ id: folderId,
+ name: `Folder ${count}`,
+ type: 'folder',
+ visible: true,
+ opacity: 1,
+ blendMode: 'pass-through',
+ locked: false,
+ collapsed: false,
+ parentId: folderParentId,
+ thumbnailUrl: '',
+ };
+
+ const movingIds = new Set<string>();
+ const getDescendants = (parentId: string) => {
+ for (const l of layers) {
+ if (l.parentId === parentId) {
+ movingIds.add(l.id);
+ if (isFolderLikeLayer(l)) getDescendants(l.id);
+ }
+ }
+ };
+ for (const item of selectedItems) {
+ movingIds.add(item.id);
+ if (isFolderLikeLayer(item)) getDescendants(item.id);
+ }
+
+ const movingItems = layers
+ .filter((l) => movingIds.has(l.id))
+ .map((l) => {
+ if (!l.parentId || !movingIds.has(l.parentId)) {
+ return { ...l, parentId: folderId };
+ }
+ return l;
+ });
+
+ const remaining = layers.filter((l) => !movingIds.has(l.id));
+ const targetInsertIdx = Math.min(minIdx, remaining.length);
+
+ const nextLayers = [
+ ...remaining.slice(0, targetInsertIdx),
+ newFolder,
+ ...movingItems,
+ ...remaining.slice(targetInsertIdx),
+ ];
+
+ return { nextLayers, newFolder };
+}
+
+// Pure drag-and-drop / reordering helper
+export function computeBatchReorderLayers(
+ layers: LayerItem[],
+ selectedIds: string[],
+ draggedId: string,
+ targetId: string,
+ position: 'above' | 'below' | 'inside'
+): LayerItem[] {
+ if (draggedId === targetId) return layers;
+
+ const isMultiDrag = selectedIds.length > 1 && selectedIds.includes(draggedId);
+ const rootIds = isMultiDrag ? selectedIds : [draggedId];
+
+ const targetIdx = layers.findIndex((l) => l.id === targetId);
+ if (targetIdx < 0) return layers;
+ const targetItem = layers[targetIdx];
+
+ const getDescendantIds = (parentId: string): string[] => {
+ const ids: string[] = [];
+ for (const item of layers) {
+ if (item.parentId === parentId) {
+ ids.push(item.id);
+ ids.push(...getDescendantIds(item.id));
+ }
+ }
+ return ids;
+ };
+
+ const movingIds = new Set<string>();
+ for (const id of rootIds) {
+ movingIds.add(id);
+ const item = layers.find((l) => l.id === id);
+ if (isFolderLikeLayer(item)) {
+ getDescendantIds(id).forEach((descId) => movingIds.add(descId));
+ }
+ }
+
+ if (movingIds.has(targetId)) return layers;
+
+ let currCheck: LayerItem | undefined = targetItem;
+ while (currCheck) {
+ if (movingIds.has(currCheck.id)) return layers;
+ currCheck = layers.find((l) => l.id === currCheck?.parentId);
+ }
+
+ const newParentId = (position === 'inside' && isFolderLikeLayer(targetItem))
+ ? targetItem.id
+ : targetItem.parentId;
+
+ const movingItems = layers
+ .filter((l) => movingIds.has(l.id))
+ .map((l) => {
+ if (!l.parentId || !movingIds.has(l.parentId)) {
+ return { ...l, parentId: newParentId };
+ }
+ return l;
+ });
+
+ const remaining = layers.filter((l) => !movingIds.has(l.id));
+ const newTargetIdx = remaining.findIndex((l) => l.id === targetId);
+ if (newTargetIdx < 0) return layers;
+
+ let insertIdx = newTargetIdx;
+ if (position === 'above') {
+ insertIdx = newTargetIdx;
+ } else if (position === 'below' || position === 'inside') {
+ insertIdx = newTargetIdx + 1;
+ }
+
+ remaining.splice(insertIdx, 0, ...movingItems);
+ return remaining;
+}
+
+// Pure batch visibility toggle
+export function computeBatchVisibility(
+ layers: LayerItem[],
+ selectedIds: string[],
+ targetId: string
+): LayerItem[] {
+ const isMulti = selectedIds.length > 1 && selectedIds.includes(targetId);
+ if (!isMulti) {
+ return layers.map((l) => (l.id === targetId ? { ...l, visible: !l.visible } : l));
+ }
+ const target = layers.find((l) => l.id === targetId);
+ const newVisible = target ? !target.visible : true;
+ const selectedSet = new Set(selectedIds);
+ return layers.map((l) => (selectedSet.has(l.id) ? { ...l, visible: newVisible } : l));
+}
+
+// Pure batch lock toggle
+export function computeBatchLock(
+ layers: LayerItem[],
+ selectedIds: string[],
+ targetId: string
+): LayerItem[] {
+ const isMulti = selectedIds.length > 1 && selectedIds.includes(targetId);
+ if (!isMulti) {
+ return layers.map((l) => (l.id === targetId ? { ...l, locked: !l.locked } : l));
+ }
+ const target = layers.find((l) => l.id === targetId);
+ const newLocked = target ? !target.locked : true;
+ const selectedSet = new Set(selectedIds);
+ return layers.map((l) => (selectedSet.has(l.id) ? { ...l, locked: newLocked } : l));
+}
diff --git a/src/hooks/layerManager/types.ts b/src/hooks/layerManager/types.ts
new file mode 100644
index 0000000..5497866
--- /dev/null
+++ b/src/hooks/layerManager/types.ts
@@ -0,0 +1,34 @@
+import { Dispatch, MutableRefObject, SetStateAction } from 'react';
+import {
+ CanvasDimensions,
+ LayerItem,
+} from '../../types/editor';
+import { SparseTileGrid } from '../../utils/tileEngine';
+
+export interface UseLayerManagerProps {
+ dimensions: CanvasDimensions;
+ activeSessionId?: string | null;
+ tileGrid?: SparseTileGrid;
+}
+
+export interface LayerManagerContext {
+ dimensions: CanvasDimensions;
+ activeTileGridRef: MutableRefObject<SparseTileGrid>;
+ dimensionsRef: MutableRefObject<CanvasDimensions>;
+ activeSessionIdRef: MutableRefObject<string | null>;
+ defaultToneFrequencyRef: MutableRefObject<number>;
+ thumbDebounceTimersRef: MutableRefObject<Map<string, ReturnType<typeof setTimeout>>>;
+ layers: LayerItem[];
+ setLayers: Dispatch<SetStateAction<LayerItem[]>>;
+ layersRef: MutableRefObject<LayerItem[]>;
+ activeLayerId: string;
+ setActiveLayerId: (id: string) => void;
+ activeLayerIdRef: MutableRefObject<string>;
+ selectedLayerIds: string[];
+ setSelectedLayerIds: (ids: string[] | ((prev: string[]) => string[])) => void;
+ selectedLayerIdsRef: MutableRefObject<string[]>;
+}
+
+export interface LayerCanvasRegistryApi {
+ updateLayerThumbnail: (id: string, immediate?: boolean) => void;
+}
diff --git a/src/hooks/layerManager/useLayerCanvasRegistry.ts b/src/hooks/layerManager/useLayerCanvasRegistry.ts
new file mode 100644
index 0000000..5b53445
--- /dev/null
+++ b/src/hooks/layerManager/useLayerCanvasRegistry.ts
@@ -0,0 +1,68 @@
+import { useCallback, useEffect } from 'react';
+import { createCanvasThumbnail } from '../../utils/canvasUtils';
+import { isBackgroundLayerId } from './layerTreeOps';
+import { LayerCanvasRegistryApi, LayerManagerContext } from './types';
+
+export function useLayerCanvasRegistry(ctx: LayerManagerContext): LayerCanvasRegistryApi {
+ const {
+ dimensions,
+ activeTileGridRef,
+ dimensionsRef,
+ activeSessionIdRef,
+ thumbDebounceTimersRef,
+ setLayers,
+ } = ctx;
+
+ // Cleanup debounce timers on unmount
+ useEffect(() => {
+ const timers = thumbDebounceTimersRef.current;
+ return () => {
+ for (const timer of timers.values()) {
+ clearTimeout(timer);
+ }
+ timers.clear();
+ };
+ }, [thumbDebounceTimersRef]);
+
+ // Update a single layer's thumbnail directly from SparseTileGrid LOD 3 (zero full-canvas read)
+ const updateLayerThumbnail = useCallback((id: string, immediate: boolean = false) => {
+ const capturedGrid = activeTileGridRef.current;
+ const capturedDocId = activeSessionIdRef.current;
+ const run = () => {
+ if (capturedDocId !== activeSessionIdRef.current) return;
+ const dims = dimensionsRef.current;
+ const thumb = createCanvasThumbnail(
+ { grid: capturedGrid, layerId: id, dimensions: dims },
+ !isBackgroundLayerId(id)
+ );
+
+ if (!thumb) return;
+
+ setLayers((prev) => {
+ const existingLayer = prev.find((l) => l.id === id);
+ if (!existingLayer || existingLayer.thumbnailUrl === thumb) return prev;
+ return prev.map((l) => (l.id === id ? { ...l, thumbnailUrl: thumb } : l));
+ });
+ };
+
+ const existing = thumbDebounceTimersRef.current.get(id);
+ if (existing) clearTimeout(existing);
+
+ if (immediate) {
+ thumbDebounceTimersRef.current.delete(id);
+ run();
+ } else {
+ const isLargeDoc = dimensions.width * dimensions.height > 1024 * 1024;
+ const delayMs = isLargeDoc ? 900 : 350;
+ const timer = setTimeout(() => {
+ thumbDebounceTimersRef.current.delete(id);
+ run();
+ }, delayMs);
+ thumbDebounceTimersRef.current.set(id, timer);
+ }
+ }, [dimensions, activeSessionIdRef, activeTileGridRef, dimensionsRef, setLayers, thumbDebounceTimersRef]);
+
+ return {
+ updateLayerThumbnail,
+ };
+}
diff --git a/src/hooks/layerManager/useLayerClipboard.ts b/src/hooks/layerManager/useLayerClipboard.ts
new file mode 100644
index 0000000..5c08e9f
--- /dev/null
+++ b/src/hooks/layerManager/useLayerClipboard.ts
@@ -0,0 +1,467 @@
+import { useRef, useCallback } from 'react';
+import {
+ BlendMode,
+ CanvasSelection,
+ LayerItem,
+ isFolderLikeLayer,
+} from '../../types/editor';
+import { createCanvasThumbnail } from '../../utils/canvasUtils';
+import { LayerInsertTarget, sanitizeImportedLayerName } from '../../utils/fileDropImport';
+import { HalftoneDotShape } from '../../utils/screentoneEngine';
+import { fillSelectionInTileGrid } from '../../utils/selectionUtils';
+import { TileDelta, TileFormat, releaseTemporaryCanvas } from '../../utils/tileEngine';
+import { LayerManagerContext } from './types';
+
+export function useLayerClipboard(ctx: LayerManagerContext) {
+ const {
+ dimensions,
+ activeTileGridRef,
+ dimensionsRef,
+ defaultToneFrequencyRef,
+ layers,
+ setLayers,
+ layersRef,
+ activeLayerId,
+ setActiveLayerId,
+ activeLayerIdRef,
+ } = ctx;
+
+ // Internal Layer Clipboard (tile-backed; zero full-doc HTMLCanvasElement allocation)
+ const layerClipboardRef = useRef<{
+ name: string;
+ type: LayerItem['type'];
+ blendMode: BlendMode;
+ opacity: number;
+ tileSnapshot: {
+ format: TileFormat;
+ tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }>;
+ };
+ } | null>(null);
+
+ const insertNewLayerItem = useCallback(
+ (
+ newId: string,
+ layerName: string,
+ blendMode: BlendMode,
+ opacity: number,
+ thumb: string,
+ layerOverrides?: Partial<LayerItem>,
+ insertTarget?: LayerInsertTarget
+ ) => {
+ setLayers((prev) => {
+ const getSubtreeEndIndex = (list: LayerItem[], folderIndex: number): number => {
+ const folderId = list[folderIndex].id;
+ const subtreeIds = new Set<string>([folderId]);
+ let endIdx = folderIndex + 1;
+ while (endIdx < list.length) {
+ const item = list[endIdx];
+ if (item.parentId && subtreeIds.has(item.parentId)) {
+ subtreeIds.add(item.id);
+ endIdx++;
+ } else {
+ break;
+ }
+ }
+ return endIdx;
+ };
+
+ let insertIdx = 0;
+ let resolvedParentId: string | null = null;
+ let expandFolderId: string | null = null;
+
+ const targetIdx = insertTarget?.targetLayerId
+ ? prev.findIndex((l) => l.id === insertTarget.targetLayerId)
+ : -1;
+
+ if (targetIdx >= 0) {
+ const targetItem = prev[targetIdx];
+ const pos = insertTarget?.position || (isFolderLikeLayer(targetItem) ? 'inside' : 'above');
+ if (pos === 'inside' && isFolderLikeLayer(targetItem)) {
+ resolvedParentId = targetItem.id;
+ insertIdx = targetIdx + 1;
+ if (targetItem.collapsed) expandFolderId = targetItem.id;
+ } else if (pos === 'below') {
+ resolvedParentId = targetItem.parentId;
+ insertIdx = isFolderLikeLayer(targetItem)
+ ? getSubtreeEndIndex(prev, targetIdx)
+ : targetIdx + 1;
+ } else {
+ resolvedParentId = targetItem.parentId;
+ insertIdx = targetIdx;
+ }
+ } else {
+ const activeIdx = prev.findIndex((l) => l.id === activeLayerIdRef.current);
+ const activeItem = activeIdx >= 0 ? prev[activeIdx] : undefined;
+ if (activeItem && isFolderLikeLayer(activeItem)) {
+ resolvedParentId = activeItem.id;
+ insertIdx = activeIdx + 1;
+ if (activeItem.collapsed) expandFolderId = activeItem.id;
+ } else {
+ resolvedParentId = activeItem?.parentId || null;
+ insertIdx = activeIdx >= 0 ? activeIdx : 0;
+ }
+ }
+
+ const newLayer: LayerItem = {
+ id: newId,
+ name: layerName,
+ type: layerOverrides?.type || 'raster',
+ visible: true,
+ opacity,
+ blendMode,
+ locked: false,
+ collapsed: false,
+ parentId: layerOverrides?.parentId !== undefined ? layerOverrides.parentId : resolvedParentId,
+ thumbnailUrl: thumb,
+ ...layerOverrides,
+ };
+
+ const nextLayers = expandFolderId
+ ? prev.map((l) => (l.id === expandFolderId ? { ...l, collapsed: false } : l))
+ : [...prev];
+ nextLayers.splice(insertIdx, 0, newLayer);
+ layersRef.current = nextLayers;
+ return nextLayers;
+ });
+ },
+ [activeLayerIdRef, layersRef, setLayers]
+ );
+
+ // Paste a canvas directly into SparseTileGrid as a new raster layer (no duplicate full canvas retained)
+ const pasteLayerFromCanvas = useCallback(
+ (
+ sourceCanvas: HTMLCanvasElement,
+ layerName: string = 'Pasted Layer',
+ blendMode: BlendMode = 'normal',
+ opacity: number = 1,
+ customId?: string,
+ layerOverrides?: Partial<LayerItem>,
+ insertTarget?: LayerInsertTarget
+ ) => {
+ const newId = customId || `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ const grid = activeTileGridRef.current;
+ const isMono = layerOverrides?.expressionColor === 'monochrome';
+ grid.ingestCanvas(newId, sourceCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
+
+ const dims = dimensionsRef.current;
+ const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dims }, true);
+ insertNewLayerItem(newId, layerName, blendMode, opacity, thumb, layerOverrides, insertTarget);
+ setActiveLayerId(newId);
+ return newId;
+ },
+ [activeTileGridRef, dimensionsRef, insertNewLayerItem, setActiveLayerId]
+ );
+
+ // Fill selection with non-destructive screentone layer directly in SparseTileGrid (GPU renders dots)
+ const fillScreentoneSelection = useCallback(
+ (
+ selection: CanvasSelection | null,
+ density: number = 40,
+ frequency: number = defaultToneFrequencyRef.current ?? 60,
+ angle: number = 45,
+ dotShape: HalftoneDotShape = 'circle',
+ densityType: 'specified' | 'image' = 'specified'
+ ): { id: string; tileDeltas: TileDelta[] } => {
+ const resolvedFreq = frequency || defaultToneFrequencyRef.current || 60;
+ const resolvedDensity = Math.max(1, Math.min(100, Math.round(density <= 1.0 && density > 0 ? density * 100 : density)));
+ const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ const grid = activeTileGridRef.current;
+
+ // Continuous source value: black ink in 'specified' mode, grayscale value in 'image' mode
+ const grayVal = densityType === 'specified' ? 0 : Math.round(255 * (1 - resolvedDensity / 100));
+ const fillCss = `rgb(${grayVal},${grayVal},${grayVal})`;
+
+ let tileDeltas: TileDelta[] = [];
+ if (selection) {
+ const res = fillSelectionInTileGrid({
+ grid,
+ layerId: newId,
+ dimensions,
+ selection,
+ colorCss: fillCss,
+ targetFormat: 'color-32bit',
+ });
+ tileDeltas = res.tileDeltas;
+ } else {
+ const beforeSnapshot = grid.snapshotLayerTiles(newId);
+ grid.fillLayerSolidColor(newId, dimensions.width, dimensions.height, fillCss, 'color-32bit');
+ tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, newId);
+ }
+
+ const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions }, true);
+ const newLayer: LayerItem = {
+ id: newId,
+ name: 'Screen Tone',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ collapsed: false,
+ parentId: null,
+ thumbnailUrl: thumb,
+ toneEnabled: true,
+ toneFrequency: resolvedFreq,
+ toneAngle: angle,
+ toneDotShape: dotShape,
+ toneDensity: resolvedDensity,
+ toneDensityType: densityType,
+ };
+
+ setLayers((prev) => {
+ const activeIdx = prev.findIndex((l) => l.id === activeLayerId);
+ const activeItem = prev[activeIdx];
+ const parentId = activeItem?.type === 'folder' ? activeItem.id : (activeItem?.parentId || null);
+ newLayer.parentId = parentId;
+
+ let name = 'Screen Tone';
+ let count = 1;
+ prev.forEach((l) => {
+ if (l.name.startsWith('Screen Tone')) {
+ const num = parseInt(l.name.replace('Screen Tone', '').trim(), 10);
+ if (!isNaN(num) && num >= count) {
+ count = num + 1;
+ } else if (num === 1 || count === 1) {
+ count = Math.max(count, 2);
+ }
+ }
+ });
+ if (count > 1) {
+ name = `Screen Tone ${count}`;
+ }
+ newLayer.name = name;
+
+ const insertIdx = activeIdx >= 0 ? activeIdx : 0;
+ let nextLayers = [...prev];
+ nextLayers.splice(insertIdx, 0, newLayer);
+
+ const hasBg = prev.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');
+ if (!hasBg) {
+ const bgId = `layer-bg-${Date.now()}`;
+ grid.fillLayerSolidWhite(bgId, dimensions.width, dimensions.height, 'color-32bit');
+ const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions }, false);
+ const bgLayer: LayerItem = {
+ id: bgId,
+ name: 'Background',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: true,
+ parentId: null,
+ thumbnailUrl: bgThumb,
+ };
+ nextLayers = [...nextLayers, bgLayer];
+ }
+
+ return nextLayers;
+ });
+
+ grid.notifyChange(true);
+ setActiveLayerId(newId);
+ return { id: newId, tileDeltas };
+ },
+ [activeLayerId, activeTileGridRef, defaultToneFrequencyRef, dimensions, setActiveLayerId, setLayers]
+ );
+
+ // Copy selected layer into sparse tile snapshot (zero retained full-doc HTMLCanvasElement)
+ const copyLayer = useCallback(
+ (targetId?: string): LayerItem | null => {
+ const id = targetId || activeLayerId;
+ const targetLayer = layers.find((l) => l.id === id);
+ if (!targetLayer) return null;
+
+ const grid = activeTileGridRef.current;
+ const tileSnapshot = grid.copyLayerTilesSnapshot(id);
+
+ layerClipboardRef.current = {
+ name: targetLayer.name,
+ type: targetLayer.type,
+ blendMode: targetLayer.blendMode,
+ opacity: targetLayer.opacity,
+ tileSnapshot,
+ };
+
+ // Best-effort export to system clipboard (only bounded tight region to avoid 278MB transient spikes)
+ try {
+ if (navigator.clipboard && window.isSecureContext) {
+ const dims = dimensionsRef.current;
+ const bounds = grid.getLayerContentBounds(id, dims, false);
+ if (bounds && bounds.width * bounds.height <= 4096 * 4096) {
+ const temp = grid.createRegionCanvas(id, bounds);
+ if (temp) {
+ temp.toBlob((blob) => {
+ releaseTemporaryCanvas(temp);
+ if (blob && navigator.clipboard && window.isSecureContext) {
+ navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]).catch(() => {});
+ }
+ });
+ }
+ }
+ }
+ } catch {
+ // Ignore clipboard write restrictions
+ }
+
+ return targetLayer;
+ },
+ [activeLayerId, activeTileGridRef, dimensionsRef, layers]
+ );
+
+ // Paste layer from internal sparse tile clipboard or system clipboard
+ const pasteLayer = useCallback(async (): Promise<{ success: boolean; layerName?: string }> => {
+ // 1. Check internal tile-backed clipboard (zero full-doc canvas)
+ if (layerClipboardRef.current) {
+ const data = layerClipboardRef.current;
+ const newName = `${data.name} Copy`;
+ const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ const grid = activeTileGridRef.current;
+ grid.pasteLayerTilesSnapshot(newId, data.tileSnapshot);
+ const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dimensionsRef.current }, true);
+ insertNewLayerItem(newId, newName, data.blendMode, data.opacity, thumb);
+ setActiveLayerId(newId);
+ return { success: true, layerName: newName };
+ }
+
+ // 2. Check system clipboard
+ try {
+ if (navigator.clipboard && navigator.clipboard.read) {
+ const items = await navigator.clipboard.read();
+ for (const item of items) {
+ const imageType = item.types.find((t) => t.startsWith('image/'));
+ if (imageType) {
+ const blob = await item.getType(imageType);
+ const img = new Image();
+ const url = URL.createObjectURL(blob);
+ await new Promise<void>((resolve, reject) => {
+ img.onload = () => resolve();
+ img.onerror = reject;
+ img.src = url;
+ });
+
+ const scale = Math.min(1, Math.min(dimensions.width / img.naturalWidth, dimensions.height / img.naturalHeight));
+ const dw = Math.max(1, Math.round(img.naturalWidth * scale));
+ const dh = Math.max(1, Math.round(img.naturalHeight * scale));
+ const dx = Math.round((dimensions.width - dw) / 2);
+ const dy = Math.round((dimensions.height - dh) / 2);
+
+ const tight = document.createElement('canvas');
+ tight.width = dw;
+ tight.height = dh;
+ const c2d = tight.getContext('2d', { willReadFrequently: true });
+ const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ const grid = activeTileGridRef.current;
+ if (c2d) {
+ c2d.drawImage(img, 0, 0, dw, dh);
+ const imgData = c2d.getImageData(0, 0, dw, dh);
+ grid.writeImageData(newId, imgData, dx, dy, 'color-32bit');
+ }
+ URL.revokeObjectURL(url);
+ releaseTemporaryCanvas(tight);
+
+ const newName = 'Pasted Image';
+ const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions }, true);
+ insertNewLayerItem(newId, newName, 'normal', 1, thumb);
+ setActiveLayerId(newId);
+ grid.notifyChange(true);
+ return { success: true, layerName: newName };
+ }
+ }
+ }
+ } catch (err) {
+ console.warn('System clipboard read failed:', err);
+ }
+
+ return { success: false };
+ }, [activeTileGridRef, dimensions, dimensionsRef, insertNewLayerItem, setActiveLayerId]);
+
+ // Import an image file directly as a centered/fitted raster layer (tight-sized canvas -> tiles)
+ const importImageFileAsLayer = useCallback(
+ async (file: File, insertTarget?: LayerInsertTarget): Promise<{ id: string; name: string }> => {
+ const decodeImage = (): Promise<HTMLImageElement> =>
+ new Promise((resolve, reject) => {
+ const canUseObjectUrl = typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function';
+ if (canUseObjectUrl) {
+ const url = URL.createObjectURL(file);
+ const img = new Image();
+ img.onload = () => {
+ URL.revokeObjectURL(url);
+ resolve(img);
+ };
+ img.onerror = () => {
+ URL.revokeObjectURL(url);
+ reject(new Error(`Failed to decode image "${file.name}".`));
+ };
+ img.src = url;
+ return;
+ }
+
+ const reader = new FileReader();
+ reader.onload = (e) => {
+ const img = new Image();
+ img.onload = () => resolve(img);
+ img.onerror = () => reject(new Error(`Failed to decode image "${file.name}".`));
+ img.src = e.target?.result as string;
+ };
+ reader.onerror = () => reject(new Error(`Failed to read file "${file.name}".`));
+ reader.readAsDataURL(file);
+ });
+
+ const img = await decodeImage();
+ const natW = img.naturalWidth || img.width;
+ const natH = img.naturalHeight || img.height;
+ if (natW <= 0 || natH <= 0) {
+ throw new Error(`Image "${file.name}" has invalid dimensions.`);
+ }
+
+ const dims = dimensionsRef.current;
+ const scale = Math.min(1, dims.width / natW, dims.height / natH);
+ const dw = Math.max(1, Math.round(natW * scale));
+ const dh = Math.max(1, Math.round(natH * scale));
+ const dx = Math.round((dims.width - dw) / 2);
+ const dy = Math.round((dims.height - dh) / 2);
+
+ const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ const grid = activeTileGridRef.current;
+ const tight = document.createElement('canvas');
+ tight.width = dw;
+ tight.height = dh;
+ const c2d = tight.getContext('2d', { willReadFrequently: true });
+ if (c2d) {
+ c2d.imageSmoothingEnabled = true;
+ c2d.imageSmoothingQuality = 'high';
+ c2d.drawImage(img, 0, 0, dw, dh);
+ const imgData = c2d.getImageData(0, 0, dw, dh);
+ grid.writeImageData(newId, imgData, dx, dy, 'color-32bit');
+ }
+ releaseTemporaryCanvas(tight);
+
+ const layerName = sanitizeImportedLayerName(file.name);
+ const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dims }, true);
+ insertNewLayerItem(newId, layerName, 'normal', 1, thumb, undefined, insertTarget);
+ setActiveLayerId(newId);
+ grid.notifyChange(true);
+ return { id: newId, name: layerName };
+ },
+ [activeTileGridRef, dimensionsRef, insertNewLayerItem, setActiveLayerId]
+ );
+
+ // Paste a photo from file
+ const pasteLayerFromFile = useCallback(
+ async (file: File, insertTarget?: LayerInsertTarget): Promise<string> => {
+ const { name } = await importImageFileAsLayer(file, insertTarget);
+ return name;
+ },
+ [importImageFileAsLayer]
+ );
+
+ return {
+ pasteLayerFromCanvas,
+ fillScreentoneSelection,
+ copyLayer,
+ pasteLayer,
+ importImageFileAsLayer,
+ pasteLayerFromFile,
+ };
+}
diff --git a/src/hooks/layerManager/useLayerCollabSync.ts b/src/hooks/layerManager/useLayerCollabSync.ts
new file mode 100644
index 0000000..a9ac68f
--- /dev/null
+++ b/src/hooks/layerManager/useLayerCollabSync.ts
@@ -0,0 +1,496 @@
+import { useCallback } from 'react';
+import {
+ CanvasDimensions,
+ LayerItem,
+ hasTileBackedLayer,
+} from '../../types/editor';
+import {
+ LayerClearableField,
+ LayerMaskDataMessage,
+ WireLayerItem,
+} from '../../types/multiplayer';
+import { createCanvasThumbnail, get2DContext } from '../../utils/canvasUtils';
+import {
+ applyMaskDataToCanvas,
+ applyRemoteLayerPatch,
+ deepEqualWireValue,
+ mergeRemoteWireLayerIntoLocal,
+} from '../../utils/collabSyncUtils';
+import { documentStore } from '../../utils/documentStore';
+import { SparseTileGrid, releaseTemporaryCanvas } from '../../utils/tileEngine';
+import { renderVectorLayer } from '../../utils/vectorEngine';
+import { syncVectorObjectLayerToGrid } from '../../utils/vectorLayerRenderer';
+import { computeBatchDeleteLayers, isBackgroundLayerId } from './layerTreeOps';
+import { LayerManagerContext } from './types';
+
+function rerenderVectorLayerToGrid(
+ layer: LayerItem,
+ dims: CanvasDimensions,
+ grid: SparseTileGrid
+): void {
+ if (typeof document === 'undefined' || dims.width <= 0 || dims.height <= 0) return;
+ const strokes = layer.vectorStrokes || [];
+ const isMono = layer.expressionColor === 'monochrome';
+ const format = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ grid.clearLayer(layer.id);
+ grid.setLayerFormat(layer.id, format);
+ grid.markLayerIngested(layer.id);
+
+ if (strokes.length === 0) return;
+
+ let minX = dims.width;
+ let minY = dims.height;
+ let maxX = 0;
+ let maxY = 0;
+ for (const st of strokes) {
+ if (st.deleted || !st.bounds) continue;
+ const pad = Math.ceil(Math.max(16, (st.baseWidth || 10) * 1.5));
+ if (st.bounds.minX - pad < minX) minX = st.bounds.minX - pad;
+ if (st.bounds.minY - pad < minY) minY = st.bounds.minY - pad;
+ if (st.bounds.maxX + pad > maxX) maxX = st.bounds.maxX + pad;
+ if (st.bounds.maxY + pad > maxY) maxY = st.bounds.maxY + pad;
+ }
+
+ const vx = Math.max(0, Math.floor(minX));
+ const vy = Math.max(0, Math.floor(minY));
+ const vw = Math.max(0, Math.min(dims.width, Math.ceil(maxX)) - vx);
+ const vh = Math.max(0, Math.min(dims.height, Math.ceil(maxY)) - vy);
+ if (vw <= 0 || vh <= 0) return;
+
+ const temp = document.createElement('canvas');
+ temp.width = vw;
+ temp.height = vh;
+ const ctx = get2DContext(temp);
+ if (ctx) {
+ ctx.save();
+ ctx.translate(-vx, -vy);
+ renderVectorLayer(ctx, strokes);
+ ctx.restore();
+ const imgData = ctx.getImageData(0, 0, vw, vh);
+ grid.writeImageData(layer.id, imgData, vx, vy, format, true);
+ }
+ releaseTemporaryCanvas(temp);
+}
+
+function resolveTileFormatForLayer(layer: Pick<LayerItem, 'id' | 'expressionColor'>) {
+ if (isBackgroundLayerId(layer.id)) return 'color-32bit' as const;
+ if (layer.expressionColor === 'monochrome') return 'monochrome-1bit' as const;
+ if (layer.expressionColor === 'gray') return 'grayscale-8bit' as const;
+ return 'color-32bit' as const;
+}
+
+export function useLayerCollabSync(
+ ctx: LayerManagerContext,
+ updateLayerThumbnail?: (id: string, immediate?: boolean) => void
+) {
+ const {
+ activeTileGridRef,
+ dimensionsRef,
+ activeSessionIdRef,
+ thumbDebounceTimersRef,
+ setLayers,
+ layersRef,
+ activeLayerIdRef,
+ setActiveLayerId,
+ setSelectedLayerIds,
+ } = ctx;
+
+ // Add a layer that originated from a remote peer (raster pixels arrive via BINARY_TILE)
+ const addRemoteLayer = useCallback(
+ (
+ wireLayer: LayerItem | WireLayerItem,
+ insertIndex?: number,
+ onCommitted?: (nextLayers: LayerItem[]) => void
+ ) => {
+ const grid = activeTileGridRef.current;
+ const dims = dimensionsRef.current;
+ const hydrated = mergeRemoteWireLayerIntoLocal(undefined, wireLayer as WireLayerItem, dims);
+
+ if (hasTileBackedLayer(hydrated)) {
+ grid.setLayerFormat(hydrated.id, resolveTileFormatForLayer(hydrated));
+ grid.markLayerIngested(hydrated.id);
+ }
+
+ if (
+ (hydrated.type === 'text' && hydrated.textData) ||
+ (hydrated.type === 'balloon' && hydrated.balloonData)
+ ) {
+ syncVectorObjectLayerToGrid(hydrated, dims, grid);
+ } else if (hydrated.type === 'vector' && hydrated.vectorStrokes?.length) {
+ rerenderVectorLayerToGrid(hydrated, dims, grid);
+ }
+
+ setLayers((prev) => {
+ if (prev.some((l) => l.id === hydrated.id)) {
+ onCommitted?.(prev);
+ return prev;
+ }
+ const next = [...prev];
+ if (insertIndex !== undefined && insertIndex >= 0 && insertIndex <= next.length) {
+ next.splice(insertIndex, 0, hydrated);
+ } else {
+ const bgIdx = next.findIndex((l) => isBackgroundLayerId(l.id));
+ if (bgIdx >= 0) {
+ next.splice(bgIdx, 0, hydrated);
+ } else {
+ next.push(hydrated);
+ }
+ }
+ layersRef.current = next;
+ onCommitted?.(next);
+ return next;
+ });
+
+ grid.notifyChange(true);
+ if (hydrated.type === 'text' || hydrated.type === 'balloon' || hydrated.type === 'vector') {
+ updateLayerThumbnail?.(hydrated.id, true);
+ }
+ },
+ [activeTileGridRef, dimensionsRef, layersRef, setLayers, updateLayerThumbnail]
+ );
+
+ // Delete a layer or folder subtree triggered remotely
+ const deleteRemoteLayer = useCallback(
+ (layerId: string, onCommitted?: (nextLayers: LayerItem[]) => void) => {
+ const grid = activeTileGridRef.current;
+ setLayers((prev) => {
+ const res = computeBatchDeleteLayers(prev, [layerId], activeLayerIdRef.current);
+ if (res.deletedIds.length === 0) {
+ onCommitted?.(prev);
+ return prev;
+ }
+ for (const delId of res.deletedIds) {
+ const timer = thumbDebounceTimersRef.current.get(delId);
+ if (timer) {
+ clearTimeout(timer);
+ thumbDebounceTimersRef.current.delete(delId);
+ }
+ const deletedLayer = prev.find((l) => l.id === delId);
+ if (deletedLayer?.maskCanvas) {
+ releaseTemporaryCanvas(deletedLayer.maskCanvas);
+ }
+ grid.clearLayer(delId);
+ }
+ if (res.deletedIds.includes(activeLayerIdRef.current)) {
+ setActiveLayerId(res.nextActiveId);
+ } else {
+ setSelectedLayerIds((prevSel) => prevSel.filter((sid) => !res.deletedIds.includes(sid)));
+ }
+ layersRef.current = res.nextLayers;
+ onCommitted?.(res.nextLayers);
+ return res.nextLayers;
+ });
+ grid.notifyChange(true);
+ },
+ [
+ activeLayerIdRef,
+ activeTileGridRef,
+ layersRef,
+ setActiveLayerId,
+ setLayers,
+ setSelectedLayerIds,
+ thumbDebounceTimersRef,
+ ]
+ );
+
+ // Apply an incremental remote property patch (blendMode, clipped, alphaLocked, styles, text, balloon, frames, vectorStrokes, etc.)
+ const applyRemoteLayerUpdate = useCallback(
+ (
+ layerId: string,
+ patch: Partial<WireLayerItem>,
+ clearedFields?: LayerClearableField[],
+ onCommitted?: (nextLayers: LayerItem[]) => void
+ ) => {
+ const grid = activeTileGridRef.current;
+ const dims = dimensionsRef.current;
+ let needsTextBalloonRender: LayerItem | null = null;
+ let needsVectorRender: LayerItem | null = null;
+ let needsMaskThumb = false;
+
+ setLayers((prev) => {
+ let found = false;
+ const next = prev.map((l) => {
+ if (l.id !== layerId) return l;
+ found = true;
+ const updated = applyRemoteLayerPatch(l, patch, clearedFields, dims);
+ if (
+ (updated.type === 'text' && updated.textData && !deepEqualWireValue(l.textData, updated.textData)) ||
+ (updated.type === 'balloon' && updated.balloonData && !deepEqualWireValue(l.balloonData, updated.balloonData))
+ ) {
+ needsTextBalloonRender = updated;
+ }
+ if (
+ updated.type === 'vector' &&
+ patch.vectorStrokes !== undefined &&
+ !deepEqualWireValue(l.vectorStrokes, updated.vectorStrokes)
+ ) {
+ needsVectorRender = updated;
+ }
+ if (updated.maskCanvas && !l.maskCanvas) {
+ needsMaskThumb = true;
+ updated.maskThumbnailUrl = createCanvasThumbnail(updated.maskCanvas, false);
+ }
+ return updated;
+ });
+ if (!found) {
+ onCommitted?.(prev);
+ return prev;
+ }
+ layersRef.current = next;
+ onCommitted?.(next);
+ return next;
+ });
+
+ if (needsTextBalloonRender) {
+ syncVectorObjectLayerToGrid(needsTextBalloonRender, dims, grid);
+ updateLayerThumbnail?.(layerId, true);
+ } else if (needsVectorRender) {
+ rerenderVectorLayerToGrid(needsVectorRender, dims, grid);
+ updateLayerThumbnail?.(layerId, true);
+ } else if (needsMaskThumb) {
+ grid.notifyChange(true);
+ } else {
+ grid.notifyChange(true);
+ }
+ },
+ [activeTileGridRef, dimensionsRef, layersRef, setLayers, updateLayerThumbnail]
+ );
+
+ // Apply an authoritative full layer tree sync (reorder, group, multi-delete, duplicate, mergeDown, split-folder, batch ops)
+ const applyRemoteLayerTree = useCallback(
+ (
+ wireLayers: WireLayerItem[],
+ removedLayerIds?: string[],
+ onCommitted?: (nextLayers: LayerItem[]) => void
+ ) => {
+ const grid = activeTileGridRef.current;
+ const dims = dimensionsRef.current;
+ const toRenderTextBalloon: LayerItem[] = [];
+ const toRenderVector: LayerItem[] = [];
+
+ setLayers((prev) => {
+ const prevById = new Map(prev.map((l) => [l.id, l]));
+ const nextIds = new Set(wireLayers.map((l) => l.id));
+
+ const removedSet = new Set<string>(removedLayerIds || []);
+ for (const oldLayer of prev) {
+ if (!nextIds.has(oldLayer.id)) {
+ removedSet.add(oldLayer.id);
+ }
+ }
+
+ for (const remId of removedSet) {
+ const timer = thumbDebounceTimersRef.current.get(remId);
+ if (timer) {
+ clearTimeout(timer);
+ thumbDebounceTimersRef.current.delete(remId);
+ }
+ const oldLayer = prevById.get(remId);
+ if (oldLayer?.maskCanvas) {
+ releaseTemporaryCanvas(oldLayer.maskCanvas);
+ }
+ grid.clearLayer(remId);
+ }
+
+ const next: LayerItem[] = wireLayers.map((wire) => {
+ const existing = prevById.get(wire.id);
+ const merged = mergeRemoteWireLayerIntoLocal(existing, wire, dims);
+ if (!existing && hasTileBackedLayer(merged)) {
+ grid.setLayerFormat(merged.id, resolveTileFormatForLayer(merged));
+ grid.markLayerIngested(merged.id);
+ }
+ if (merged.maskCanvas && !existing?.maskCanvas) {
+ merged.maskThumbnailUrl = createCanvasThumbnail(merged.maskCanvas, false);
+ }
+ if (
+ (merged.type === 'text' &&
+ merged.textData &&
+ (!existing || !deepEqualWireValue(existing.textData, merged.textData))) ||
+ (merged.type === 'balloon' &&
+ merged.balloonData &&
+ (!existing || !deepEqualWireValue(existing.balloonData, merged.balloonData)))
+ ) {
+ toRenderTextBalloon.push(merged);
+ }
+ if (
+ merged.type === 'vector' &&
+ merged.vectorStrokes &&
+ (!existing || !deepEqualWireValue(existing.vectorStrokes, merged.vectorStrokes))
+ ) {
+ toRenderVector.push(merged);
+ }
+ return merged;
+ });
+
+ if (!nextIds.has(activeLayerIdRef.current)) {
+ const fallback =
+ next.find((l) => l.type === 'raster' && !isBackgroundLayerId(l.id))?.id ||
+ next[0]?.id ||
+ '';
+ setActiveLayerId(fallback);
+ } else {
+ setSelectedLayerIds((prevSel) => {
+ const filtered = prevSel.filter((id) => nextIds.has(id));
+ return filtered.length > 0 ? filtered : [activeLayerIdRef.current];
+ });
+ }
+
+ layersRef.current = next;
+ onCommitted?.(next);
+ return next;
+ });
+
+ for (const layer of toRenderTextBalloon) {
+ syncVectorObjectLayerToGrid(layer, dims, grid);
+ updateLayerThumbnail?.(layer.id, true);
+ }
+ for (const layer of toRenderVector) {
+ rerenderVectorLayerToGrid(layer, dims, grid);
+ updateLayerThumbnail?.(layer.id, true);
+ }
+
+ grid.notifyChange(true);
+ },
+ [
+ activeLayerIdRef,
+ activeTileGridRef,
+ dimensionsRef,
+ layersRef,
+ setActiveLayerId,
+ setLayers,
+ setSelectedLayerIds,
+ thumbDebounceTimersRef,
+ updateLayerThumbnail,
+ ]
+ );
+
+ // Apply binary grayscale mask patch/full mask received via BINARY_MASK
+ const applyRemoteMaskData = useCallback(
+ (msg: LayerMaskDataMessage, onCommitted?: (nextLayers: LayerItem[]) => void) => {
+ const dims = dimensionsRef.current;
+ const grid = activeTileGridRef.current;
+
+ setLayers((prev) => {
+ let changed = false;
+ const next = prev.map((l) => {
+ if (l.id !== msg.layerId) return l;
+ const updatedCanvas = applyMaskDataToCanvas(l.maskCanvas, dims, msg);
+ if (!updatedCanvas) return l;
+ changed = true;
+ const thumb = createCanvasThumbnail(updatedCanvas, false);
+ return {
+ ...l,
+ maskCanvas: updatedCanvas,
+ maskEnabled: l.maskEnabled ?? true,
+ maskLinked: l.maskLinked ?? true,
+ maskThumbnailUrl: thumb,
+ maskVersion: (l.maskVersion || 0) + 1,
+ };
+ });
+ if (!changed) {
+ onCommitted?.(prev);
+ return prev;
+ }
+ layersRef.current = next;
+ onCommitted?.(next);
+ return next;
+ });
+
+ grid.notifyChange(true);
+ },
+ [activeTileGridRef, dimensionsRef, layersRef, setLayers]
+ );
+
+ // Sync document metadata from remote host (raster pixels stream via BINARY_TILE, masks via BINARY_MASK)
+ const syncRemoteDocument = useCallback(
+ (
+ syncedLayers: Array<LayerItem | WireLayerItem>,
+ assignedLayerId?: string,
+ targetDocumentId?: string,
+ syncDims?: CanvasDimensions,
+ onCommitted?: (nextLayers: LayerItem[]) => void
+ ) => {
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
+ }
+ thumbDebounceTimersRef.current.clear();
+
+ let grid = activeTileGridRef.current;
+ if (targetDocumentId) {
+ const session =
+ documentStore.setActiveDocument(targetDocumentId) ??
+ documentStore.getOrCreateSession(targetDocumentId);
+ activeSessionIdRef.current = targetDocumentId;
+ activeTileGridRef.current = session.tileGrid;
+ grid = session.tileGrid;
+ }
+ if (syncDims) {
+ dimensionsRef.current = syncDims;
+ }
+
+ const dims = syncDims || dimensionsRef.current;
+ grid.clearAll();
+
+ const hydratedLayers: LayerItem[] = syncedLayers.map((raw) => {
+ const hydrated = mergeRemoteWireLayerIntoLocal(undefined, raw as WireLayerItem, dims);
+ if (hydrated.maskCanvas) {
+ hydrated.maskThumbnailUrl = createCanvasThumbnail(hydrated.maskCanvas, false);
+ }
+ return hydrated;
+ });
+
+ setLayers(hydratedLayers);
+ layersRef.current = hydratedLayers;
+ onCommitted?.(hydratedLayers);
+
+ if (assignedLayerId && hydratedLayers.some((l) => l.id === assignedLayerId)) {
+ setActiveLayerId(assignedLayerId);
+ } else {
+ const topRaster = hydratedLayers.find(
+ (l) => l.type === 'raster' && !isBackgroundLayerId(l.id)
+ );
+ if (topRaster) {
+ setActiveLayerId(topRaster.id);
+ } else if (hydratedLayers[0]) {
+ setActiveLayerId(hydratedLayers[0].id);
+ }
+ }
+
+ hydratedLayers.forEach((layer) => {
+ if (hasTileBackedLayer(layer)) {
+ grid.setLayerFormat(layer.id, resolveTileFormatForLayer(layer));
+ grid.markLayerIngested(layer.id);
+ }
+ if (
+ (layer.type === 'text' && layer.textData) ||
+ (layer.type === 'balloon' && layer.balloonData)
+ ) {
+ syncVectorObjectLayerToGrid(layer, dims, grid);
+ } else if (layer.type === 'vector' && layer.vectorStrokes?.length) {
+ rerenderVectorLayerToGrid(layer, dims, grid);
+ }
+ });
+
+ grid.notifyChange(true);
+ },
+ [
+ activeSessionIdRef,
+ activeTileGridRef,
+ dimensionsRef,
+ layersRef,
+ setActiveLayerId,
+ setLayers,
+ thumbDebounceTimersRef,
+ ]
+ );
+
+ return {
+ addRemoteLayer,
+ deleteRemoteLayer,
+ applyRemoteLayerUpdate,
+ applyRemoteLayerTree,
+ applyRemoteMaskData,
+ syncRemoteDocument,
+ };
+}
diff --git a/src/hooks/layerManager/useLayerCrud.ts b/src/hooks/layerManager/useLayerCrud.ts
new file mode 100644
index 0000000..ee33045
--- /dev/null
+++ b/src/hooks/layerManager/useLayerCrud.ts
@@ -0,0 +1,415 @@
+import { useCallback } from 'react';
+import {
+ LayerItem,
+ LayerType,
+ isFolderLikeLayer,
+ hasTileBackedLayer,
+} from '../../types/editor';
+import { get2DContext } from '../../utils/canvasUtils';
+import { releaseTemporaryCanvas } from '../../utils/tileEngine';
+import {
+ computeBatchDeleteLayers,
+ computeBatchReorderLayers,
+ computeGroupLayers,
+} from './layerTreeOps';
+import { LayerManagerContext } from './types';
+
+export function useLayerCrud(ctx: LayerManagerContext) {
+ const {
+ activeTileGridRef,
+ thumbDebounceTimersRef,
+ layers,
+ setLayers,
+ layersRef,
+ setActiveLayerId,
+ activeLayerIdRef,
+ setSelectedLayerIds,
+ selectedLayerIdsRef,
+ } = ctx;
+
+ // Add a new raster layer, folder, frame-folder, text, balloon, or adjustment layer
+ const addLayer = useCallback(
+ (
+ type: LayerType = 'raster',
+ explicitParentId?: string | null,
+ customName?: string,
+ customId?: string,
+ selectNewLayer: boolean = true
+ ): LayerItem => {
+ const id = customId || `${type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ const currentLayers = layersRef.current;
+ const currentActiveIdx = currentLayers.findIndex((l) => l.id === activeLayerIdRef.current);
+ const currentActiveLayer = currentLayers[currentActiveIdx];
+
+ let initialParentId: string | null = null;
+ if (explicitParentId !== undefined) {
+ initialParentId = explicitParentId;
+ } else if (currentActiveLayer) {
+ initialParentId = isFolderLikeLayer(currentActiveLayer) ? currentActiveLayer.id : currentActiveLayer.parentId;
+ }
+
+ const resolveLayerName = (list: LayerItem[]) => {
+ if (customName) return customName;
+ let count = 1;
+ const prefix =
+ type === 'folder' ? 'Folder ' :
+ type === 'frame-folder' ? 'Frame ' :
+ type === 'vector' ? 'Vector ' :
+ type === 'frame' ? 'Frame ' :
+ type === 'text' ? 'Text ' :
+ type === 'balloon' ? 'Balloon ' :
+ type === 'adjustment' ? 'Adjustment ' : 'Layer ';
+ list.forEach((l) => {
+ if (l.type === type && l.name.startsWith(prefix)) {
+ const num = parseInt(l.name.replace(prefix, ''), 10);
+ if (!isNaN(num) && num >= count) {
+ count = num + 1;
+ }
+ }
+ });
+ return `${prefix}${count}`;
+ };
+
+ const createdLayer: LayerItem = {
+ id,
+ name: resolveLayerName(currentLayers),
+ type,
+ visible: true,
+ opacity: 1,
+ blendMode: type === 'folder' ? 'pass-through' : 'normal',
+ locked: false,
+ collapsed: false,
+ parentId: initialParentId,
+ thumbnailUrl: '',
+ expressionColor:
+ currentActiveLayer?.expressionColor === 'monochrome'
+ ? 'monochrome'
+ : currentActiveLayer?.expressionColor === 'gray'
+ ? 'gray'
+ : 'color',
+ monoThreshold: currentActiveLayer?.monoThreshold ?? 128,
+ monoExpressBlack: currentActiveLayer?.monoExpressBlack ?? true,
+ monoExpressWhite: currentActiveLayer?.monoExpressWhite ?? true,
+ };
+
+ setLayers((prev) => {
+ if (prev.some((l) => l.id === id)) return prev;
+ const activeIdx = prev.findIndex((l) => l.id === activeLayerIdRef.current);
+ const activeLayer = prev[activeIdx];
+
+ let parentId: string | null = null;
+ if (explicitParentId !== undefined) {
+ parentId = explicitParentId;
+ } else if (activeLayer) {
+ parentId = isFolderLikeLayer(activeLayer) ? activeLayer.id : activeLayer.parentId;
+ }
+
+ const newLayer: LayerItem = {
+ ...createdLayer,
+ name: resolveLayerName(prev),
+ parentId,
+ };
+
+ const insertIndex = activeIdx >= 0 ? activeIdx : 0;
+ const nextLayers = [...prev];
+ nextLayers.splice(insertIndex, 0, newLayer);
+ layersRef.current = nextLayers;
+ return nextLayers;
+ });
+
+ if (hasTileBackedLayer({ type })) {
+ const grid = activeTileGridRef.current;
+ const isMono = createdLayer.expressionColor === 'monochrome';
+ grid.setLayerFormat(id, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.markLayerIngested(id);
+ }
+
+ if (selectNewLayer) {
+ setActiveLayerId(id);
+ }
+ return createdLayer;
+ },
+ [activeLayerIdRef, activeTileGridRef, layersRef, setActiveLayerId, setLayers]
+ );
+
+ // Duplicate an existing layer or folder hierarchy with a single click
+ const duplicateLayer = useCallback((id: string) => {
+ setLayers((prev) => {
+ const sourceIdx = prev.findIndex((l) => l.id === id);
+ if (sourceIdx < 0) return prev;
+ const grid = activeTileGridRef.current;
+
+ const cloneSingleLayer = (source: LayerItem, newParentId: string | null, nameSuffix: string = ' Copy'): LayerItem => {
+ const newId = `${source.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+
+ if (hasTileBackedLayer(source)) {
+ grid.cloneLayer(source.id, newId);
+ }
+
+ let newMaskCanvas: HTMLCanvasElement | undefined;
+ let newMaskThumb: string | undefined;
+ if (source.maskCanvas) {
+ newMaskCanvas = document.createElement('canvas');
+ newMaskCanvas.width = source.maskCanvas.width;
+ newMaskCanvas.height = source.maskCanvas.height;
+ const mCtx = get2DContext(newMaskCanvas);
+ if (mCtx) mCtx.drawImage(source.maskCanvas, 0, 0);
+ newMaskThumb = source.maskThumbnailUrl;
+ }
+
+ return {
+ ...source,
+ id: newId,
+ name: `${source.name}${nameSuffix}`,
+ parentId: newParentId,
+ thumbnailUrl: source.thumbnailUrl,
+ maskCanvas: newMaskCanvas,
+ maskThumbnailUrl: newMaskThumb,
+ maskVersion: source.maskCanvas ? 1 : undefined,
+ vectorStrokes: source.vectorStrokes ? JSON.parse(JSON.stringify(source.vectorStrokes)) : undefined,
+ comicFrames: source.comicFrames ? JSON.parse(JSON.stringify(source.comicFrames)) : undefined,
+ textData: source.textData ? JSON.parse(JSON.stringify(source.textData)) : undefined,
+ balloonData: source.balloonData ? JSON.parse(JSON.stringify(source.balloonData)) : undefined,
+ balloons: source.balloons ? JSON.parse(JSON.stringify(source.balloons)) : undefined,
+ adjustmentData: source.adjustmentData ? JSON.parse(JSON.stringify(source.adjustmentData)) : undefined,
+ styles: source.styles ? JSON.parse(JSON.stringify(source.styles)) : undefined,
+ };
+ };
+
+ const source = prev[sourceIdx];
+ if (!isFolderLikeLayer(source)) {
+ const newLayer = cloneSingleLayer(source, source.parentId, ' Copy');
+ const nextLayers = [...prev];
+ nextLayers.splice(sourceIdx, 0, newLayer);
+ setActiveLayerId(newLayer.id);
+ return nextLayers;
+ }
+
+ // Recursively duplicate folder or frame-folder and all nested descendants in stack order
+ const clonedItems: LayerItem[] = [];
+ const cloneFolderSubtree = (folder: LayerItem, targetParentId: string | null, isRootFolder: boolean) => {
+ const folderCopy = cloneSingleLayer(folder, targetParentId, isRootFolder ? ' Copy' : '');
+ clonedItems.push(folderCopy);
+ const directChildren = prev.filter((l) => l.parentId === folder.id);
+ for (const child of directChildren) {
+ if (isFolderLikeLayer(child)) {
+ cloneFolderSubtree(child, folderCopy.id, false);
+ } else {
+ clonedItems.push(cloneSingleLayer(child, folderCopy.id, ' Copy'));
+ }
+ }
+ };
+
+ cloneFolderSubtree(source, source.parentId, true);
+ const nextLayers = [...prev];
+ nextLayers.splice(sourceIdx, 0, ...clonedItems);
+ if (clonedItems[0]) {
+ setActiveLayerId(clonedItems[0].id);
+ }
+ return nextLayers;
+ });
+ }, [activeTileGridRef, setActiveLayerId, setLayers]);
+
+ // Delete a layer or folder (including nested folder hierarchies)
+ const deleteLayer = useCallback((id: string) => {
+ setLayers((prev) => {
+ const res = computeBatchDeleteLayers(prev, [id], activeLayerIdRef.current);
+ if (res.deletedIds.length === 0) return prev;
+ const grid = activeTileGridRef.current;
+
+ for (const delId of res.deletedIds) {
+ const timer = thumbDebounceTimersRef.current.get(delId);
+ if (timer) {
+ clearTimeout(timer);
+ thumbDebounceTimersRef.current.delete(delId);
+ }
+
+ const deletedLayer = prev.find((l) => l.id === delId);
+ if (deletedLayer?.maskCanvas) {
+ releaseTemporaryCanvas(deletedLayer.maskCanvas);
+ }
+
+ grid.clearLayer(delId);
+ }
+
+ if (res.deletedIds.includes(activeLayerIdRef.current)) {
+ setActiveLayerId(res.nextActiveId);
+ } else {
+ setSelectedLayerIds((prevSelected) => prevSelected.filter((sid) => !res.deletedIds.includes(sid)));
+ }
+ return res.nextLayers;
+ });
+ }, [activeLayerIdRef, activeTileGridRef, setActiveLayerId, setLayers, setSelectedLayerIds, thumbDebounceTimersRef]);
+
+ // Delete all selected layers or folders
+ const deleteSelectedLayers = useCallback(() => {
+ setLayers((prev) => {
+ const res = computeBatchDeleteLayers(prev, selectedLayerIdsRef.current, activeLayerIdRef.current);
+ if (res.deletedIds.length === 0) return prev;
+ const grid = activeTileGridRef.current;
+
+ for (const delId of res.deletedIds) {
+ const timer = thumbDebounceTimersRef.current.get(delId);
+ if (timer) {
+ clearTimeout(timer);
+ thumbDebounceTimersRef.current.delete(delId);
+ }
+
+ const deletedLayer = prev.find((l) => l.id === delId);
+ if (deletedLayer?.maskCanvas) {
+ releaseTemporaryCanvas(deletedLayer.maskCanvas);
+ }
+
+ grid.clearLayer(delId);
+ }
+
+ setActiveLayerId(res.nextActiveId);
+ return res.nextLayers;
+ });
+ }, [activeLayerIdRef, activeTileGridRef, selectedLayerIdsRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]);
+
+ // Group all currently selected layers into a new folder
+ const groupSelectedLayers = useCallback(() => {
+ setLayers((prev) => {
+ const res = computeGroupLayers(prev, selectedLayerIdsRef.current, activeLayerIdRef.current);
+ if (!res) return prev;
+
+ setActiveLayerId(res.newFolder.id);
+ return res.nextLayers;
+ });
+ }, [activeLayerIdRef, selectedLayerIdsRef, setActiveLayerId, setLayers]);
+
+ // Rename a layer
+ const renameLayer = useCallback((id: string, newName: string) => {
+ if (!newName.trim()) return;
+ setLayers((prev) =>
+ prev.map((l) => (l.id === id ? { ...l, name: newName.trim() } : l))
+ );
+ }, [setLayers]);
+
+ // Move layer up or down in visual stack
+ const moveLayer = useCallback((id: string, direction: 'up' | 'down') => {
+ setLayers((prev) => {
+ const idx = prev.findIndex((l) => l.id === id);
+ if (idx < 0) return prev;
+
+ const targetIdx = direction === 'up' ? idx - 1 : idx + 1;
+ if (targetIdx < 0 || targetIdx >= prev.length) return prev;
+
+ const next = [...prev];
+ const [item] = next.splice(idx, 1);
+ next.splice(targetIdx, 0, item);
+ return next;
+ });
+ }, [setLayers]);
+
+ // Move layer into a specific folder or to root
+ const moveLayerToFolder = useCallback((id: string, targetFolderId: string | null) => {
+ setLayers((prev) => {
+ const item = prev.find((l) => l.id === id);
+ if (!item || item.id === targetFolderId) return prev;
+
+ // If moving a folder into itself, ignore
+ if (isFolderLikeLayer(item) && targetFolderId) {
+ let curr: LayerItem | undefined = prev.find((l) => l.id === targetFolderId);
+ while (curr) {
+ if (curr.id === id) return prev;
+ curr = prev.find((l) => l.id === curr?.parentId);
+ }
+ }
+
+ return prev.map((l) => (l.id === id ? { ...l, parentId: targetFolderId } : l));
+ });
+ }, [setLayers]);
+
+ // Reorder layer via drag-and-drop (supports multi-layer selection)
+ const reorderLayers = useCallback((draggedId: string, targetId: string, position: 'above' | 'below' | 'inside') => {
+ setLayers((prev) => computeBatchReorderLayers(prev, selectedLayerIdsRef.current, draggedId, targetId, position));
+ }, [selectedLayerIdsRef, setLayers]);
+
+ // Move selected layers into a target parent folder or index
+ const moveSelectedLayers = useCallback((targetParentId: string | null, targetIndex?: number) => {
+ setLayers((prev) => {
+ const selectedIds = selectedLayerIdsRef.current.length > 0
+ ? selectedLayerIdsRef.current
+ : activeLayerIdRef.current ? [activeLayerIdRef.current] : [];
+ if (selectedIds.length === 0) return prev;
+
+ const getDescendantIds = (parentId: string): string[] => {
+ const ids: string[] = [];
+ for (const item of prev) {
+ if (item.parentId === parentId) {
+ ids.push(item.id);
+ ids.push(...getDescendantIds(item.id));
+ }
+ }
+ return ids;
+ };
+
+ const movingIds = new Set<string>();
+ for (const id of selectedIds) {
+ movingIds.add(id);
+ const item = prev.find((l) => l.id === id);
+ if (isFolderLikeLayer(item)) {
+ getDescendantIds(id).forEach((descId) => movingIds.add(descId));
+ }
+ }
+
+ if (targetParentId && movingIds.has(targetParentId)) return prev;
+
+ const movingItems = prev
+ .filter((l) => movingIds.has(l.id))
+ .map((l) => {
+ if (!l.parentId || !movingIds.has(l.parentId)) {
+ return { ...l, parentId: targetParentId };
+ }
+ return l;
+ });
+
+ const remaining = prev.filter((l) => !movingIds.has(l.id));
+
+ let insertIdx = remaining.length;
+ if (typeof targetIndex === 'number') {
+ insertIdx = Math.max(0, Math.min(remaining.length, targetIndex));
+ } else if (targetParentId) {
+ const parentIdx = remaining.findIndex((l) => l.id === targetParentId);
+ insertIdx = parentIdx >= 0 ? parentIdx + 1 : remaining.length;
+ }
+
+ remaining.splice(insertIdx, 0, ...movingItems);
+ return remaining;
+ });
+ }, [activeLayerIdRef, selectedLayerIdsRef, setLayers]);
+
+ // Calculate effective opacity accounting for parent folders
+ const getEffectiveOpacity = useCallback((layer: LayerItem): number => {
+ if (!layer.parentId) return layer.opacity;
+ const parent = layers.find((l) => l.id === layer.parentId);
+ if (!parent) return layer.opacity;
+ return layer.opacity * getEffectiveOpacity(parent);
+ }, [layers]);
+
+ // Check if layer is visible accounting for parent folders
+ const isLayerEffectivelyVisible = useCallback((layer: LayerItem): boolean => {
+ if (!layer.visible) return false;
+ if (!layer.parentId) return true;
+ const parent = layers.find((l) => l.id === layer.parentId);
+ if (!parent) return true;
+ return isLayerEffectivelyVisible(parent);
+ }, [layers]);
+
+ return {
+ addLayer,
+ duplicateLayer,
+ deleteLayer,
+ deleteSelectedLayers,
+ groupSelectedLayers,
+ renameLayer,
+ moveLayer,
+ moveLayerToFolder,
+ reorderLayers,
+ moveSelectedLayers,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ };
+}
diff --git a/src/hooks/layerManager/useLayerDocumentOps.ts b/src/hooks/layerManager/useLayerDocumentOps.ts
new file mode 100644
index 0000000..a954fed
--- /dev/null
+++ b/src/hooks/layerManager/useLayerDocumentOps.ts
@@ -0,0 +1,304 @@
+import { useCallback } from 'react';
+import {
+ CanvasColorMode,
+ CanvasDimensions,
+ LayerItem,
+ LoadedDocument,
+ hasTileBackedLayer,
+} from '../../types/editor';
+import { createCanvasThumbnail } from '../../utils/canvasUtils';
+import { documentStore } from '../../utils/documentStore';
+import { multiplayerService } from '../../services/multiplayerService';
+import { releaseTemporaryCanvas } from '../../utils/tileEngine';
+import { isBackgroundLayerId } from './layerTreeOps';
+import { LayerCanvasRegistryApi, LayerManagerContext } from './types';
+
+export function useLayerDocumentOps(
+ ctx: LayerManagerContext,
+ canvasRegistry: Pick<LayerCanvasRegistryApi, 'updateLayerThumbnail'>
+) {
+ const {
+ activeTileGridRef,
+ dimensionsRef,
+ activeSessionIdRef,
+ defaultToneFrequencyRef,
+ thumbDebounceTimersRef,
+ setLayers,
+ layersRef,
+ activeLayerId,
+ setActiveLayerId,
+ setSelectedLayerIds,
+ } = ctx;
+ const { updateLayerThumbnail } = canvasRegistry;
+
+ // Clear active layer content directly in SparseTileGrid (zero forced full canvas allocation)
+ const clearActiveLayer = useCallback(() => {
+ const grid = activeTileGridRef.current;
+ const dims = dimensionsRef.current;
+ const isBg = isBackgroundLayerId(activeLayerId);
+
+ if (isBg) {
+ grid.fillLayerSolidWhite(activeLayerId, dims.width, dims.height, 'color-32bit');
+ } else {
+ grid.clearLayer(activeLayerId);
+ grid.markLayerIngested(activeLayerId);
+ }
+
+ grid.notifyChange(true);
+ updateLayerThumbnail(activeLayerId);
+ }, [activeLayerId, activeTileGridRef, dimensionsRef, updateLayerThumbnail]);
+
+ // Merge active raster layer down onto the raster layer directly below it (tile-by-tile, zero full-doc canvas)
+ const mergeDown = useCallback(
+ (targetLayerId?: string): { targetId: string; removedId: string } | null => {
+ const currentLayers = layersRef.current;
+ const srcId = targetLayerId || activeLayerId;
+ const srcIdx = currentLayers.findIndex((l) => l.id === srcId);
+ if (srcIdx < 0) return null;
+
+ const srcLayer = currentLayers[srcIdx];
+ if (!srcLayer || srcLayer.type !== 'raster' || srcLayer.locked) return null;
+
+ // Find the next raster layer below (higher index in top-to-bottom stack)
+ let dstIdx = -1;
+ for (let i = srcIdx + 1; i < currentLayers.length; i++) {
+ if (currentLayers[i].type === 'raster') {
+ dstIdx = i;
+ break;
+ }
+ }
+ if (dstIdx < 0) return null;
+ const dstLayer = currentLayers[dstIdx];
+ if (dstLayer.locked) return null;
+
+ const grid = activeTileGridRef.current;
+ const dstFormat =
+ dstLayer.expressionColor === 'monochrome'
+ ? 'monochrome-1bit'
+ : dstLayer.expressionColor === 'gray'
+ ? 'grayscale-8bit'
+ : 'color-32bit';
+
+ grid.mergeLayersInGrid(srcLayer.id, dstLayer.id, {
+ opacity: srcLayer.opacity,
+ blendMode: srcLayer.blendMode,
+ visible: srcLayer.visible,
+ maskCanvas: srcLayer.maskCanvas,
+ maskEnabled: srcLayer.maskEnabled,
+ dimensions: dimensionsRef.current,
+ dstFormat,
+ });
+
+ if (multiplayerService.isConnected()) {
+ multiplayerService.streamLayerTiles(dstLayer.id, grid, { force: true });
+ }
+
+ if (srcLayer.maskCanvas) {
+ releaseTemporaryCanvas(srcLayer.maskCanvas);
+ }
+
+ const nextLayers = currentLayers.filter((l) => l.id !== srcLayer.id);
+ layersRef.current = nextLayers;
+ setLayers(nextLayers);
+ setActiveLayerId(dstLayer.id);
+ setSelectedLayerIds([dstLayer.id]);
+
+ updateLayerThumbnail(dstLayer.id);
+ return { targetId: dstLayer.id, removedId: srcLayer.id };
+ },
+ [activeLayerId, activeTileGridRef, dimensionsRef, layersRef, setActiveLayerId, setLayers, setSelectedLayerIds, updateLayerThumbnail]
+ );
+
+ // Switch active document tab in O(1): binds session's SparseTileGrid without clearing or re-slicing
+ const switchDocumentSession = useCallback(
+ (documentId: string, nextLayers: LayerItem[], nextActiveLayerId: string, nextDims?: CanvasDimensions) => {
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
+ }
+ thumbDebounceTimersRef.current.clear();
+
+ const session = documentStore.setActiveDocument(documentId) ?? documentStore.getOrCreateSession(documentId);
+ activeSessionIdRef.current = documentId;
+ activeTileGridRef.current = session.tileGrid;
+ if (nextDims) {
+ dimensionsRef.current = nextDims;
+ }
+
+ setLayers(nextLayers);
+ layersRef.current = nextLayers;
+ const resolvedActiveId =
+ nextActiveLayerId && nextLayers.some((l) => l.id === nextActiveLayerId)
+ ? nextActiveLayerId
+ : (nextLayers.find((l) => l.type === 'raster')?.id || nextLayers[0]?.id || '');
+ setActiveLayerId(resolvedActiveId);
+ session.tileGrid.notifyChange(true);
+ },
+ [activeSessionIdRef, activeTileGridRef, dimensionsRef, layersRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]
+ );
+
+ // Reset layers to a fresh canvas with specified background color (allocated directly in SparseTileGrid)
+ const resetToNewCanvas = useCallback(
+ (
+ _dims: CanvasDimensions,
+ backgroundColor: string = '#ffffff',
+ _mode: CanvasColorMode = 'color',
+ defaultToneFrequency: number = 60,
+ targetDocumentId?: string
+ ) => {
+ defaultToneFrequencyRef.current = Math.max(20, Math.min(85, Math.round(defaultToneFrequency || 60)));
+ dimensionsRef.current = _dims;
+
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
+ }
+ thumbDebounceTimersRef.current.clear();
+
+ let grid = activeTileGridRef.current;
+ if (targetDocumentId) {
+ const session = documentStore.setActiveDocument(targetDocumentId) ?? documentStore.getOrCreateSession(targetDocumentId);
+ activeSessionIdRef.current = targetDocumentId;
+ activeTileGridRef.current = session.tileGrid;
+ grid = session.tileGrid;
+ }
+
+ grid.clearAll();
+
+ const now = Date.now();
+ const bgId = `layer-bg-${now}`;
+ const topId = `layer-1-${now}`;
+
+ // Initialize background directly in SparseTileGrid without creating full-size HTMLCanvasElement
+ if (backgroundColor !== 'transparent') {
+ grid.fillLayerSolidColor(bgId, _dims.width, _dims.height, backgroundColor, 'color-32bit');
+ } else {
+ grid.setLayerFormat(bgId, 'color-32bit');
+ grid.markLayerIngested(bgId);
+ }
+
+ // Empty top layer: 0 tiles, 0 HTMLCanvasElement allocated
+ const topFormat = _mode === 'monochrome' ? 'monochrome-1bit' : 'color-32bit';
+ grid.setLayerFormat(topId, topFormat);
+ grid.markLayerIngested(topId);
+
+ const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: _dims }, false);
+
+ const initialLayers: LayerItem[] = [
+ {
+ id: topId,
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ thumbnailUrl: '',
+ toneFrequency: defaultToneFrequencyRef.current,
+ expressionColor: _mode === 'monochrome' ? 'monochrome' : _mode === 'grayscale' ? 'gray' : 'color',
+ monoThreshold: 128,
+ monoExpressBlack: true,
+ monoExpressWhite: true,
+ },
+ {
+ id: bgId,
+ name: 'Background',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: true,
+ parentId: null,
+ thumbnailUrl: bgThumb,
+ },
+ ];
+
+ setLayers(initialLayers);
+ layersRef.current = initialLayers;
+ setActiveLayerId(topId);
+ grid.notifyChange(true);
+ return { layers: initialLayers, activeLayerId: topId };
+ },
+ [activeSessionIdRef, activeTileGridRef, defaultToneFrequencyRef, dimensionsRef, layersRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]
+ );
+
+ // Clear all layers and canvas references when no document is active
+ const clearDocument = useCallback(() => {
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
+ }
+ thumbDebounceTimersRef.current.clear();
+ setLayers([]);
+ layersRef.current = [];
+ setActiveLayerId('');
+ }, [layersRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]);
+
+ // Import an external document (from PSD, CSP, Image, or Crash Recovery) into its own isolated session.
+ // Any legacy import canvases are immediately ingested into SparseTileGrid and released.
+ const loadDocument = useCallback(
+ (doc: LoadedDocument, targetDocumentId?: string, skipIngest: boolean = false) => {
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
+ }
+ thumbDebounceTimersRef.current.clear();
+
+ dimensionsRef.current = doc.dimensions;
+ let grid = activeTileGridRef.current;
+ if (targetDocumentId) {
+ const session = documentStore.setActiveDocument(targetDocumentId) ?? documentStore.getOrCreateSession(targetDocumentId);
+ activeSessionIdRef.current = targetDocumentId;
+ activeTileGridRef.current = session.tileGrid;
+ grid = session.tileGrid;
+ }
+
+ const restoredFormats = doc.tileGrid ? doc.tileGrid.getAllLayerFormats() : null;
+ if (!skipIngest) {
+ if (doc.tileGrid && doc.tileGrid !== grid) {
+ grid.restoreFromSnapshot(doc.tileGrid.getAllTiles(), restoredFormats || undefined);
+ doc.tileGrid.clearAll();
+ } else if (!doc.tileGrid) {
+ grid.clearAll();
+ }
+ }
+
+ for (const l of doc.layers) {
+ if (hasTileBackedLayer(l)) {
+ const existingFormat = restoredFormats?.get(l.id);
+ const inferredFormat =
+ existingFormat ??
+ (l.expressionColor === 'monochrome'
+ ? 'monochrome-1bit'
+ : l.expressionColor === 'gray'
+ ? 'grayscale-8bit'
+ : 'color-32bit');
+ grid.setLayerFormat(l.id, inferredFormat);
+ grid.markLayerIngested(l.id);
+ }
+ }
+
+ if (!skipIngest && doc.layerCanvases) {
+ doc.layerCanvases.forEach((c, id) => {
+ const layerMeta = doc.layers.find((l) => l.id === id);
+ const isMono = layerMeta?.expressionColor === 'monochrome';
+ grid.ingestCanvas(id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ releaseTemporaryCanvas(c);
+ });
+ }
+
+ setLayers(doc.layers);
+ layersRef.current = doc.layers;
+ const topRaster = doc.layers.find((l) => l.type === 'raster');
+ setActiveLayerId(topRaster ? topRaster.id : doc.layers[0]?.id || '');
+ grid.notifyChange(true);
+ },
+ [activeSessionIdRef, activeTileGridRef, dimensionsRef, layersRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]
+ );
+
+ return {
+ clearActiveLayer,
+ mergeDown,
+ switchDocumentSession,
+ resetToNewCanvas,
+ clearDocument,
+ loadDocument,
+ };
+}
diff --git a/src/hooks/layerManager/useLayerEffects.ts b/src/hooks/layerManager/useLayerEffects.ts
new file mode 100644
index 0000000..26465dc
--- /dev/null
+++ b/src/hooks/layerManager/useLayerEffects.ts
@@ -0,0 +1,362 @@
+import { useCallback } from 'react';
+import { ExpressionColor, LayerItem } from '../../types/editor';
+import { createCanvasThumbnail } from '../../utils/canvasUtils';
+import {
+ applyExpressionColorToImageData,
+ applyLayerTintToImageData,
+} from '../../utils/layerEffectsEngine';
+import { HalftoneDotShape } from '../../utils/screentoneEngine';
+import { TILE_SIZE, TileDelta, TileSnapshotEntry } from '../../utils/tileEngine';
+import { LayerCanvasRegistryApi, LayerManagerContext } from './types';
+
+export function useLayerEffects(
+ ctx: LayerManagerContext,
+ canvasRegistry: Pick<LayerCanvasRegistryApi, 'updateLayerThumbnail'>
+) {
+ const {
+ activeTileGridRef,
+ dimensionsRef,
+ defaultToneFrequencyRef,
+ layers,
+ setLayers,
+ } = ctx;
+ const { updateLayerThumbnail } = canvasRegistry;
+
+ // Toggle non-destructive screentone effect (rendered live on GPU by ViewportCompositor from raw tile data)
+ const toggleTone = useCallback((id: string) => {
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+
+ const newEnabled = !target.toneEnabled;
+ const updatedLayer: LayerItem = {
+ ...target,
+ toneEnabled: newEnabled,
+ toneFrequency: target.toneFrequency ?? defaultToneFrequencyRef.current ?? 60,
+ toneAngle: target.toneAngle ?? 45,
+ toneDotShape: target.toneDotShape ?? 'circle',
+ toneDensity: target.toneDensity ?? 40,
+ toneDensityType: target.toneDensityType ?? 'specified',
+ };
+
+ const grid = activeTileGridRef.current;
+ let nextLayers = prev.map((l) => (l.id === id ? updatedLayer : l));
+
+ // Ensure white paper background exists when enabling screentone on a transparent doc
+ const hasBg = prev.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');
+ if (newEnabled && !hasBg) {
+ const bgId = `layer-bg-${Date.now()}`;
+ const dims = dimensionsRef.current;
+ grid.fillLayerSolidWhite(bgId, dims.width, dims.height, 'color-32bit');
+ const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: dims }, false);
+ const bgLayer: LayerItem = {
+ id: bgId,
+ name: 'Background',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: true,
+ parentId: null,
+ thumbnailUrl: bgThumb,
+ };
+ nextLayers = [...nextLayers, bgLayer];
+ }
+
+ grid.notifyChange(true);
+ updateLayerThumbnail(id, false);
+ return nextLayers;
+ });
+ }, [activeTileGridRef, defaultToneFrequencyRef, dimensionsRef, setLayers, updateLayerThumbnail]);
+
+ // Update screentone frequency (Lines / LPI, 20 to 85)
+ const setToneFrequency = useCallback((id: string, frequency: number) => {
+ const clampedFreq = Math.max(20, Math.min(85, Math.round(frequency)));
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? { ...l, toneFrequency: clampedFreq } : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Update screentone angle (0 to 90 degrees)
+ const setToneAngle = useCallback((id: string, angle: number) => {
+ const clampedAngle = Math.max(0, Math.min(90, Math.round(angle)));
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? { ...l, toneAngle: clampedAngle } : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Update screentone dot shape (default: circle)
+ const setToneDotShape = useCallback((id: string, dotShape: HalftoneDotShape) => {
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? { ...l, toneDotShape: dotShape } : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Update screentone density (1 to 100%)
+ const setToneDensity = useCallback((id: string, density: number) => {
+ const clampedDensity = Math.max(1, Math.min(100, Math.round(density)));
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? { ...l, toneDensity: clampedDensity } : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Update screentone density mode ('specified' vs 'image')
+ const setToneDensityType = useCallback((id: string, densityType: 'specified' | 'image') => {
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? { ...l, toneDensityType: densityType } : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Toggle non-destructive Layer Color (Tint) effect (rendered on GPU)
+ const toggleLayerColor = useCallback((id: string) => {
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+
+ const updatedLayer: LayerItem = {
+ ...target,
+ layerColorEnabled: !target.layerColorEnabled,
+ layerColor: target.layerColor || '#1c73c2',
+ layerSubColor: target.layerSubColor || '#ffffff',
+ };
+ activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? updatedLayer : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Update Layer Color (Tint primary color)
+ const setLayerColor = useCallback((id: string, color: string) => {
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+ if (target.layerColorEnabled) activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? { ...l, layerColor: color } : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Update Layer Sub Color (Tint secondary color)
+ const setLayerSubColor = useCallback((id: string, color: string) => {
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+ if (target.layerColorEnabled) activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? { ...l, layerSubColor: color } : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Update non-destructive Expression Color preview ('color' | 'gray' | 'monochrome')
+ const setLayerExpressionColor = useCallback((id: string, mode: ExpressionColor) => {
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+
+ const updatedLayer: LayerItem = {
+ ...target,
+ expressionColor: mode,
+ monoThreshold: target.monoThreshold ?? 128,
+ monoExpressBlack: target.monoExpressBlack ?? true,
+ monoExpressWhite: target.monoExpressWhite ?? true,
+ };
+ activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? updatedLayer : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Update Monochrome Color threshold (1 - 255)
+ const setLayerMonoThreshold = useCallback((id: string, threshold: number) => {
+ const clamped = Math.max(1, Math.min(255, Math.round(threshold)));
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+ if (target.expressionColor === 'monochrome') activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) => (l.id === id ? { ...l, monoThreshold: clamped } : l));
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Update Monochrome Express Colors (express black, express white)
+ const setLayerMonoExpressMode = useCallback((id: string, expressBlack: boolean, expressWhite: boolean) => {
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return prev;
+ if (target.expressionColor === 'monochrome') activeTileGridRef.current.notifyChange(true);
+ return prev.map((l) =>
+ l.id === id ? { ...l, monoExpressBlack: expressBlack, monoExpressWhite: expressWhite } : l
+ );
+ });
+ }, [activeTileGridRef, setLayers]);
+
+ // Bake previewed expression color permanently into SparseTileGrid tiles (tile-native, zero full-doc canvas)
+ const applyExpressionColorOfPreview = useCallback(
+ (id: string): { tileDeltas: TileDelta[] } | null => {
+ const target = layers.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return null;
+
+ const exprMode = target.expressionColor || 'color';
+ if (exprMode === 'color') return null;
+
+ const grid = activeTileGridRef.current;
+ const beforeSnapshot = new Map<string, TileSnapshotEntry>();
+ const targetFormat =
+ exprMode === 'monochrome'
+ ? 'monochrome-1bit'
+ : exprMode === 'gray'
+ ? 'grayscale-8bit'
+ : 'color-32bit';
+
+ const modified = grid.transformLayerTiles(
+ id,
+ (rgba) => {
+ const fakeImgData = { data: rgba, width: TILE_SIZE, height: TILE_SIZE } as ImageData;
+ applyExpressionColorToImageData(fakeImgData, exprMode, {
+ threshold: target.monoThreshold ?? 128,
+ expressBlack: target.monoExpressBlack ?? true,
+ expressWhite: target.monoExpressWhite ?? true,
+ });
+ return true;
+ },
+ {
+ targetFormat,
+ monoThreshold: target.monoThreshold ?? 128,
+ snapshotOut: beforeSnapshot,
+ }
+ );
+
+ if (!modified) return null;
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, id);
+ updateLayerThumbnail(id, true);
+ return { tileDeltas };
+ },
+ [activeTileGridRef, layers, updateLayerThumbnail]
+ );
+
+ // Bake layer color tint permanently into SparseTileGrid tiles and disable layerColorEnabled
+ const applyLayerColorPermanently = useCallback(
+ (id: string): { tileDeltas: TileDelta[] } | null => {
+ const target = layers.find((l) => l.id === id);
+ if (!target || target.type === 'folder' || !target.layerColorEnabled) return null;
+
+ const grid = activeTileGridRef.current;
+ const beforeSnapshot = new Map<string, TileSnapshotEntry>();
+
+ const modified = grid.transformLayerTiles(
+ id,
+ (rgba) => {
+ const fakeImgData = { data: rgba, width: TILE_SIZE, height: TILE_SIZE } as ImageData;
+ applyLayerTintToImageData(fakeImgData, target.layerColor, target.layerSubColor);
+ return true;
+ },
+ {
+ targetFormat: 'color-32bit',
+ snapshotOut: beforeSnapshot,
+ }
+ );
+
+ setLayers((prev) =>
+ prev.map((l) => (l.id === id ? { ...l, layerColorEnabled: false } : l))
+ );
+
+ if (!modified) {
+ grid.notifyChange(true);
+ return { tileDeltas: [] };
+ }
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, id);
+ updateLayerThumbnail(id, true);
+ return { tileDeltas };
+ },
+ [activeTileGridRef, layers, setLayers, updateLayerThumbnail]
+ );
+
+ // Direct permanent conversion of any layer to Color, Gray, or Monochrome (tile-native)
+ const convertLayer = useCallback(
+ (
+ id: string,
+ targetMode: ExpressionColor,
+ options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }
+ ): { tileDeltas: TileDelta[] } | null => {
+ const target = layers.find((l) => l.id === id);
+ if (!target || target.type === 'folder') return null;
+
+ const grid = activeTileGridRef.current;
+ const beforeSnapshot = new Map<string, TileSnapshotEntry>();
+ const threshold = options?.threshold ?? target.monoThreshold ?? 128;
+ const expressBlack = options?.expressBlack ?? target.monoExpressBlack ?? true;
+ const expressWhite = options?.expressWhite ?? target.monoExpressWhite ?? true;
+ const targetFormat =
+ targetMode === 'monochrome'
+ ? 'monochrome-1bit'
+ : targetMode === 'gray'
+ ? 'grayscale-8bit'
+ : 'color-32bit';
+
+ const updatedLayer: LayerItem = {
+ ...target,
+ expressionColor: targetMode,
+ monoThreshold: threshold,
+ monoExpressBlack: expressBlack,
+ monoExpressWhite: expressWhite,
+ };
+
+ grid.transformLayerTiles(
+ id,
+ (rgba) => {
+ const fakeImgData = { data: rgba, width: TILE_SIZE, height: TILE_SIZE } as ImageData;
+ if (targetMode !== 'color') {
+ applyExpressionColorToImageData(fakeImgData, targetMode, {
+ threshold,
+ expressBlack,
+ expressWhite,
+ });
+ }
+ return true;
+ },
+ {
+ targetFormat,
+ monoThreshold: threshold,
+ snapshotOut: beforeSnapshot,
+ }
+ );
+
+ grid.setLayerFormat(id, targetFormat);
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, id);
+ setLayers((prev) => prev.map((l) => (l.id === id ? updatedLayer : l)));
+ grid.notifyChange(true);
+ updateLayerThumbnail(id, true);
+ return { tileDeltas };
+ },
+ [activeTileGridRef, layers, setLayers, updateLayerThumbnail]
+ );
+
+ return {
+ toggleTone,
+ setToneFrequency,
+ setToneAngle,
+ setToneDotShape,
+ setToneDensity,
+ setToneDensityType,
+ toggleLayerColor,
+ setLayerColor,
+ setLayerSubColor,
+ setLayerExpressionColor,
+ setLayerMonoThreshold,
+ setLayerMonoExpressMode,
+ applyExpressionColorOfPreview,
+ applyLayerColorPermanently,
+ convertLayer,
+ };
+}
diff --git a/src/hooks/layerManager/useLayerPropertiesAndMasks.ts b/src/hooks/layerManager/useLayerPropertiesAndMasks.ts
new file mode 100644
index 0000000..dc721c2
--- /dev/null
+++ b/src/hooks/layerManager/useLayerPropertiesAndMasks.ts
@@ -0,0 +1,326 @@
+import { useCallback } from 'react';
+import {
+ AdjustmentLayerData,
+ BlendMode,
+ LayerItem,
+ LayerStyles,
+ isFolderLikeLayer,
+} from '../../types/editor';
+import { createCanvasThumbnail, get2DContext } from '../../utils/canvasUtils';
+import { multiplayerService } from '../../services/multiplayerService';
+import { releaseTemporaryCanvas } from '../../utils/tileEngine';
+import {
+ computeBatchLock,
+ computeBatchVisibility,
+ isBackgroundLayerId,
+} from './layerTreeOps';
+import { LayerCanvasRegistryApi, LayerManagerContext } from './types';
+
+export function useLayerPropertiesAndMasks(
+ ctx: LayerManagerContext,
+ canvasRegistry: Pick<LayerCanvasRegistryApi, 'updateLayerThumbnail'>
+) {
+ const {
+ dimensions,
+ activeTileGridRef,
+ setLayers,
+ layersRef,
+ activeLayerId,
+ setActiveLayerId,
+ selectedLayerIdsRef,
+ } = ctx;
+ const { updateLayerThumbnail } = canvasRegistry;
+
+ // Toggle visibility of a layer or folder (batch toggle if part of multi-selection)
+ const toggleVisibility = useCallback((id: string) => {
+ setLayers((prev) => computeBatchVisibility(prev, selectedLayerIdsRef.current, id));
+ }, [selectedLayerIdsRef, setLayers]);
+
+ // Set layer opacity (0.0 to 1.0)
+ const setOpacity = useCallback((id: string, opacity: number) => {
+ const clamped = Math.max(0, Math.min(1, opacity));
+ setLayers((prev) =>
+ prev.map((l) => (l.id === id ? { ...l, opacity: clamped } : l))
+ );
+ }, [setLayers]);
+
+ // Set layer blend mode
+ const setBlendMode = useCallback((id: string, blendMode: BlendMode) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === id ? { ...l, blendMode } : l))
+ );
+ }, [setLayers]);
+
+ // Toggle locked state (batch toggle if part of multi-selection)
+ const toggleLock = useCallback((id: string) => {
+ setLayers((prev) => computeBatchLock(prev, selectedLayerIdsRef.current, id));
+ }, [selectedLayerIdsRef, setLayers]);
+
+ // Toggle folder collapse state
+ const toggleCollapse = useCallback((id: string) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === id ? { ...l, collapsed: !l.collapsed } : l))
+ );
+ }, [setLayers]);
+
+ // Toggle clipping mask state (Clip to Layer Below)
+ const toggleClipping = useCallback((id: string) => {
+ setLayers((prev) => {
+ const idx = prev.findIndex((l) => l.id === id);
+ if (idx === -1 || idx === prev.length - 1 || isBackgroundLayerId(id)) {
+ return prev;
+ }
+ return prev.map((l) => (l.id === id ? { ...l, clipped: !l.clipped } : l));
+ });
+ }, [setLayers]);
+
+ // Toggle alpha locked state (Lock Transparent Pixels)
+ const toggleAlphaLock = useCallback((id: string) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === id ? { ...l, alphaLocked: !l.alphaLocked } : l))
+ );
+ }, [setLayers]);
+
+ // Add a non-destructive grayscale Layer Mask
+ const addLayerMask = useCallback((layerId: string) => {
+ setLayers((prev) =>
+ prev.map((l) => {
+ if (l.id !== layerId) return l;
+ if (l.maskCanvas) return l; // Already has mask
+
+ const mask = document.createElement('canvas');
+ mask.width = dimensions.width;
+ mask.height = dimensions.height;
+ const mCtx = get2DContext(mask);
+ if (mCtx) {
+ mCtx.fillStyle = '#ffffff';
+ mCtx.fillRect(0, 0, mask.width, mask.height);
+ }
+ const thumb = createCanvasThumbnail(mask, false);
+ return {
+ ...l,
+ maskCanvas: mask,
+ maskEnabled: true,
+ maskLinked: true,
+ maskThumbnailUrl: thumb,
+ maskVersion: 1,
+ };
+ })
+ );
+ activeTileGridRef.current.notifyChange(true);
+ }, [activeTileGridRef, dimensions, setLayers]);
+
+ // Remove or apply layer mask (directly onto SparseTileGrid tiles, zero full-doc layer canvas)
+ const removeLayerMask = useCallback(
+ (layerId: string, apply: boolean = false) => {
+ const grid = activeTileGridRef.current;
+ setLayers((prev) =>
+ prev.map((l) => {
+ if (l.id !== layerId || !l.maskCanvas) return l;
+
+ if (apply) {
+ const beforeSnap = multiplayerService.isConnected()
+ ? grid.snapshotLayerTiles(layerId)
+ : null;
+ grid.applyMaskCanvasToLayer(layerId, l.maskCanvas, dimensions);
+ if (beforeSnap && multiplayerService.isConnected()) {
+ const deltas = grid.computeDeltasFromSnapshot(beforeSnap, layerId);
+ if (deltas.length > 0) {
+ multiplayerService.sendTileDeltas(deltas, grid, { force: true });
+ }
+ }
+ updateLayerThumbnail(layerId, true);
+ }
+
+ releaseTemporaryCanvas(l.maskCanvas);
+
+ return {
+ ...l,
+ maskCanvas: undefined,
+ maskEnabled: undefined,
+ maskLinked: undefined,
+ maskThumbnailUrl: undefined,
+ maskVersion: undefined,
+ };
+ })
+ );
+ grid.notifyChange(true);
+ },
+ [activeTileGridRef, dimensions, setLayers, updateLayerThumbnail]
+ );
+
+ // Toggle layer mask enabled state
+ const toggleLayerMask = useCallback((layerId: string) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === layerId ? { ...l, maskEnabled: !l.maskEnabled } : l))
+ );
+ activeTileGridRef.current.notifyChange(true);
+ }, [activeTileGridRef, setLayers]);
+
+ // Toggle mask linked state
+ const toggleMaskLinked = useCallback((layerId: string) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === layerId ? { ...l, maskLinked: !l.maskLinked } : l))
+ );
+ }, [setLayers]);
+
+ // Update mask thumbnail
+ const updateMaskThumbnail = useCallback((layerId: string, immediate: boolean = false) => {
+ const run = () => {
+ const target = layersRef.current.find((l) => l.id === layerId);
+ if (!target?.maskCanvas) return;
+ const thumb = createCanvasThumbnail(target.maskCanvas, false);
+ setLayers((prev) =>
+ prev.map((l) =>
+ l.id === layerId
+ ? { ...l, maskThumbnailUrl: thumb, maskVersion: (l.maskVersion || 0) + 1 }
+ : l
+ )
+ );
+ activeTileGridRef.current.notifyChange(true);
+ };
+
+ if (immediate) {
+ run();
+ } else {
+ setTimeout(run, 150);
+ }
+ }, [activeTileGridRef, layersRef, setLayers]);
+
+ // Add non-destructive adjustment layer
+ const addAdjustmentLayer = useCallback(
+ (
+ type: 'curves' | 'gradient-map' | 'levels' | 'color-balance',
+ customData?: AdjustmentLayerData
+ ): LayerItem => {
+ let createdLayer: LayerItem | null = null;
+ const id = `adjustment-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+
+ let defaultData: AdjustmentLayerData;
+ let layerName: string;
+
+ switch (type) {
+ case 'curves':
+ layerName = 'Curves 1';
+ defaultData = customData || {
+ type: 'curves',
+ curves: {
+ rgb: [[0, 0], [255, 255]],
+ r: [[0, 0], [255, 255]],
+ g: [[0, 0], [255, 255]],
+ b: [[0, 0], [255, 255]],
+ },
+ };
+ break;
+ case 'gradient-map':
+ layerName = 'Gradient Map 1';
+ defaultData = customData || {
+ type: 'gradient-map',
+ stops: [
+ { position: 0, color: '#000000' },
+ { position: 1, color: '#ffffff' },
+ ],
+ interpolation: 'smooth',
+ };
+ break;
+ case 'levels':
+ layerName = 'Levels 1';
+ defaultData = customData || {
+ type: 'levels',
+ blackPoint: 0,
+ gamma: 1.0,
+ whitePoint: 255,
+ outputMin: 0,
+ outputMax: 255,
+ channel: 'rgb',
+ };
+ break;
+ case 'color-balance':
+ layerName = 'Color Balance 1';
+ defaultData = customData || {
+ type: 'color-balance',
+ shadows: [0, 0, 0],
+ midtones: [0, 0, 0],
+ highlights: [0, 0, 0],
+ preserveLuminosity: true,
+ };
+ break;
+ }
+
+ setLayers((prev) => {
+ const activeIdx = prev.findIndex((l) => l.id === activeLayerId);
+ const activeLayer = prev[activeIdx];
+ const parentId = activeLayer ? (activeLayer.type === 'folder' ? activeLayer.id : activeLayer.parentId) : null;
+
+ let count = 1;
+ const base = layerName.replace(/ \d+$/, '');
+ prev.forEach((l) => {
+ if (l.name.startsWith(base)) {
+ const num = parseInt(l.name.replace(`${base} `, ''), 10);
+ if (!isNaN(num) && num >= count) count = num + 1;
+ }
+ });
+ const name = `${base} ${count}`;
+
+ const newLayer: LayerItem = {
+ id,
+ name,
+ type: 'adjustment',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ collapsed: false,
+ parentId,
+ adjustmentData: defaultData,
+ };
+ createdLayer = newLayer;
+
+ const insertIndex = activeIdx >= 0 ? activeIdx : 0;
+ const next = [...prev];
+ next.splice(insertIndex, 0, newLayer);
+ return next;
+ });
+
+ setActiveLayerId(id);
+ activeTileGridRef.current.notifyChange(true);
+ return createdLayer!;
+ },
+ [activeLayerId, activeTileGridRef, setActiveLayerId, setLayers]
+ );
+
+ // Update adjustment layer data
+ const updateAdjustmentData = useCallback((layerId: string, data: AdjustmentLayerData) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === layerId ? { ...l, adjustmentData: data } : l))
+ );
+ activeTileGridRef.current.notifyChange(true);
+ }, [activeTileGridRef, setLayers]);
+
+ // Update Layer Styles (Stroke, Drop Shadow, Outer Glow)
+ const updateLayerStyles = useCallback((id: string, styles: LayerStyles) => {
+ setLayers((prev) => {
+ const target = prev.find((l) => l.id === id);
+ if (!target || isFolderLikeLayer(target)) return prev;
+ return prev.map((l) => (l.id === id ? { ...l, styles } : l));
+ });
+ }, [setLayers]);
+
+ return {
+ toggleVisibility,
+ setOpacity,
+ setBlendMode,
+ toggleLock,
+ toggleCollapse,
+ toggleClipping,
+ toggleAlphaLock,
+ addLayerMask,
+ removeLayerMask,
+ toggleLayerMask,
+ toggleMaskLinked,
+ updateMaskThumbnail,
+ addAdjustmentLayer,
+ updateAdjustmentData,
+ updateLayerStyles,
+ };
+}
diff --git a/src/hooks/layerManager/useLayerResize.ts b/src/hooks/layerManager/useLayerResize.ts
new file mode 100644
index 0000000..c270d00
--- /dev/null
+++ b/src/hooks/layerManager/useLayerResize.ts
@@ -0,0 +1,148 @@
+import { useCallback } from 'react';
+import { CanvasDimensions, hasTileBackedLayer } from '../../types/editor';
+import { ResizeCanvasOptions } from '../../types/settings';
+import { createCanvasThumbnail, get2DContext } from '../../utils/canvasUtils';
+import { releaseTemporaryCanvas } from '../../utils/tileEngine';
+import { isBackgroundLayerId } from './layerTreeOps';
+import { LayerManagerContext } from './types';
+
+export function useLayerResize(ctx: LayerManagerContext) {
+ const {
+ dimensions,
+ activeTileGridRef,
+ layers,
+ setLayers,
+ } = ctx;
+
+ // Resize canvas dimensions tile-by-tile directly inside SparseTileGrid (zero full-doc layer canvas)
+ const resizeCanvas = useCallback(
+ (
+ newDims: CanvasDimensions,
+ options: ResizeCanvasOptions = { width: newDims.width, height: newDims.height }
+ ) => {
+ const {
+ scaleContent = false,
+ anchor = 'center',
+ backgroundColor = '#ffffff',
+ } = options;
+
+ const currentW = dimensions.width;
+ const currentH = dimensions.height;
+ const newW = newDims.width;
+ const newH = newDims.height;
+
+ let offsetX = 0;
+ let offsetY = 0;
+
+ if (!scaleContent) {
+ if (anchor === 'top-left' || anchor === 'left' || anchor === 'bottom-left') {
+ offsetX = 0;
+ } else if (anchor === 'top-right' || anchor === 'right' || anchor === 'bottom-right') {
+ offsetX = newW - currentW;
+ } else {
+ offsetX = Math.round((newW - currentW) / 2);
+ }
+
+ if (anchor === 'top-left' || anchor === 'top' || anchor === 'top-right') {
+ offsetY = 0;
+ } else if (anchor === 'bottom-left' || anchor === 'bottom' || anchor === 'bottom-right') {
+ offsetY = newH - currentH;
+ } else {
+ offsetY = Math.round((newH - currentH) / 2);
+ }
+ }
+
+ const updatedThumbnails = new Map<string, string>();
+ const grid = activeTileGridRef.current;
+
+ for (const layer of layers) {
+ if (!hasTileBackedLayer(layer)) continue;
+ const layerId = layer.id;
+ const isBg = isBackgroundLayerId(layerId);
+ const targetFormat =
+ !isBg && layer.expressionColor === 'monochrome'
+ ? 'monochrome-1bit'
+ : !isBg && layer.expressionColor === 'gray'
+ ? 'grayscale-8bit'
+ : 'color-32bit';
+
+ if (!grid.hasLayerTiles(layerId)) {
+ if (isBg && backgroundColor !== 'transparent') {
+ grid.fillLayerSolidColor(layerId, newW, newH, backgroundColor, 'color-32bit');
+ updatedThumbnails.set(layerId, createCanvasThumbnail({ grid, layerId, dimensions: newDims }, false));
+ } else {
+ grid.setLayerFormat(layerId, targetFormat);
+ grid.markLayerIngested(layerId);
+ }
+ continue;
+ }
+
+ grid.resizeLayerInGrid(layerId, dimensions, newDims, {
+ scaleContent,
+ offsetX,
+ offsetY,
+ isBackground: isBg,
+ backgroundColor,
+ targetFormat,
+ });
+
+ updatedThumbnails.set(layerId, createCanvasThumbnail({ grid, layerId, dimensions: newDims }, !isBg));
+ }
+
+ // Resize layer masks if present
+ const updatedMasks = new Map<string, { maskCanvas: HTMLCanvasElement; maskThumb: string }>();
+ layers.forEach((l) => {
+ if (l.maskCanvas) {
+ const tempMask = document.createElement('canvas');
+ tempMask.width = l.maskCanvas.width;
+ tempMask.height = l.maskCanvas.height;
+ get2DContext(tempMask)?.drawImage(l.maskCanvas, 0, 0);
+
+ l.maskCanvas.width = newW;
+ l.maskCanvas.height = newH;
+ const mCtx = get2DContext(l.maskCanvas);
+ if (mCtx) {
+ mCtx.fillStyle = '#ffffff';
+ mCtx.fillRect(0, 0, newW, newH);
+ if (scaleContent) {
+ mCtx.drawImage(tempMask, 0, 0, tempMask.width, tempMask.height, 0, 0, newW, newH);
+ } else {
+ mCtx.drawImage(tempMask, offsetX, offsetY);
+ }
+ }
+ releaseTemporaryCanvas(tempMask);
+ updatedMasks.set(l.id, {
+ maskCanvas: l.maskCanvas,
+ maskThumb: createCanvasThumbnail(l.maskCanvas, false),
+ });
+ }
+ });
+
+ grid.notifyChange(true);
+
+ setLayers((prev) =>
+ prev.map((l) => {
+ const newThumb = updatedThumbnails.get(l.id);
+ const maskInfo = updatedMasks.get(l.id);
+ if (!newThumb && !maskInfo) return l;
+ return {
+ ...l,
+ ...(newThumb ? { thumbnailUrl: newThumb } : {}),
+ ...(maskInfo
+ ? {
+ maskCanvas: maskInfo.maskCanvas,
+ maskThumbnailUrl: maskInfo.maskThumb,
+ maskVersion: (l.maskVersion || 0) + 1,
+ }
+ : {}),
+ };
+ })
+ );
+ },
+ [activeTileGridRef, dimensions, layers, setLayers]
+ );
+
+ return {
+ resizeCanvas,
+ };
+}
diff --git a/src/hooks/layerManager/useLayerSpecialLayers.ts b/src/hooks/layerManager/useLayerSpecialLayers.ts
new file mode 100644
index 0000000..69da01b
--- /dev/null
+++ b/src/hooks/layerManager/useLayerSpecialLayers.ts
@@ -0,0 +1,279 @@
+import { useCallback } from 'react';
+import {
+ ComicFrame,
+ FrameDivideMode,
+ LayerItem,
+ LayerType,
+ SpeechBalloon,
+ TextLayerData,
+ hasTileBackedLayer,
+} from '../../types/editor';
+import { divideFramesInFolder, Point2D } from '../../utils/frameEngine';
+import { syncVectorObjectLayerToGrid } from '../../utils/vectorLayerRenderer';
+import { LayerManagerContext } from './types';
+
+export function useLayerSpecialLayers(
+ ctx: LayerManagerContext,
+ addLayer: (
+ type?: LayerType,
+ explicitParentId?: string | null,
+ customName?: string,
+ customId?: string,
+ selectNewLayer?: boolean
+ ) => LayerItem,
+ updateLayerThumbnail: (id: string, immediate?: boolean) => void
+) {
+ const {
+ activeTileGridRef,
+ dimensionsRef,
+ setLayers,
+ layersRef,
+ } = ctx;
+
+ // Create or update a non-destructive Vector Text Layer (re-renders crisply into tileGrid)
+ const upsertTextLayer = useCallback(
+ (textData: TextLayerData, editingLayerId?: string | null): LayerItem => {
+ const grid = activeTileGridRef.current;
+ const dims = dimensionsRef.current;
+ const snippet = textData.text.trim().replace(/\s+/g, ' ').slice(0, 22) || 'Text';
+
+ if (editingLayerId) {
+ const existing = layersRef.current.find((l) => l.id === editingLayerId);
+ if (existing && existing.type === 'text') {
+ const updated: LayerItem = {
+ ...existing,
+ name: snippet,
+ textData: { ...textData },
+ };
+ setLayers((prev) => {
+ const next = prev.map((l) => (l.id === editingLayerId ? updated : l));
+ layersRef.current = next;
+ return next;
+ });
+ syncVectorObjectLayerToGrid(updated, dims, grid);
+ updateLayerThumbnail(editingLayerId, true);
+ return updated;
+ }
+ }
+
+ const created = addLayer('text', undefined, snippet, undefined, true);
+ const withData: LayerItem = {
+ ...created,
+ textData: { ...textData },
+ };
+ setLayers((prev) => {
+ const next = prev.map((l) => (l.id === created.id ? { ...l, textData: { ...textData } } : l));
+ layersRef.current = next;
+ return next;
+ });
+ syncVectorObjectLayerToGrid(withData, dims, grid);
+ updateLayerThumbnail(created.id, true);
+ return withData;
+ },
+ [activeTileGridRef, addLayer, dimensionsRef, layersRef, setLayers, updateLayerThumbnail]
+ );
+
+ // Create or update a non-destructive Speech Balloon Layer (re-renders crisply into tileGrid)
+ const upsertBalloonLayer = useCallback(
+ (balloonData: SpeechBalloon, editingLayerId?: string | null): LayerItem => {
+ const grid = activeTileGridRef.current;
+ const dims = dimensionsRef.current;
+ const clonedBalloon: SpeechBalloon = JSON.parse(JSON.stringify(balloonData));
+ const snippet = clonedBalloon.text.trim().replace(/\s+/g, ' ').slice(0, 18);
+ const label = snippet ? `Balloon: ${snippet}` : undefined;
+
+ if (editingLayerId) {
+ const existing = layersRef.current.find((l) => l.id === editingLayerId);
+ if (existing && existing.type === 'balloon') {
+ const updated: LayerItem = {
+ ...existing,
+ name: label || existing.name,
+ balloonData: clonedBalloon,
+ };
+ setLayers((prev) => {
+ const next = prev.map((l) => (l.id === editingLayerId ? updated : l));
+ layersRef.current = next;
+ return next;
+ });
+ syncVectorObjectLayerToGrid(updated, dims, grid);
+ updateLayerThumbnail(editingLayerId, true);
+ return updated;
+ }
+ }
+
+ const created = addLayer('balloon', undefined, label, undefined, true);
+ const withData: LayerItem = {
+ ...created,
+ balloonData: clonedBalloon,
+ };
+ setLayers((prev) => {
+ const next = prev.map((l) => (l.id === created.id ? { ...l, balloonData: clonedBalloon } : l));
+ layersRef.current = next;
+ return next;
+ });
+ syncVectorObjectLayerToGrid(withData, dims, grid);
+ updateLayerThumbnail(created.id, true);
+ return withData;
+ },
+ [activeTileGridRef, addLayer, dimensionsRef, layersRef, setLayers, updateLayerThumbnail]
+ );
+
+ // Create a true Manga Frame Border Folder with auto-clipping & initial child raster layer
+ const createFrameFolder = useCallback(
+ (
+ frames: ComicFrame[],
+ customName?: string,
+ addInitialChildLayer = true
+ ): { folder: LayerItem; childLayer: LayerItem | null } => {
+ const folder = addLayer('frame-folder', null, customName, undefined, !addInitialChildLayer);
+ const normalizedFrames = frames.map((f) => ({
+ ...f,
+ layerId: folder.id,
+ clipChildren: f.clipChildren !== false,
+ }));
+ const updatedFolder: LayerItem = {
+ ...folder,
+ comicFrames: normalizedFrames,
+ };
+ setLayers((prev) => {
+ const next = prev.map((l) =>
+ l.id === folder.id ? { ...l, comicFrames: normalizedFrames } : l
+ );
+ layersRef.current = next;
+ return next;
+ });
+
+ let childLayer: LayerItem | null = null;
+ if (addInitialChildLayer) {
+ childLayer = addLayer('raster', folder.id, 'Panel Layer', undefined, true);
+ }
+
+ activeTileGridRef.current.notifyChange(true);
+ return { folder: updatedFolder, childLayer };
+ },
+ [activeTileGridRef, addLayer, layersRef, setLayers]
+ );
+
+ // Divide a Frame Border Folder along a cut line (single folder split polygons or 2 independent folders)
+ const divideFrameFolder = useCallback(
+ (
+ folderId: string,
+ cutStart: Point2D,
+ cutEnd: Point2D,
+ dpi = 600,
+ mode: FrameDivideMode = 'same-folder'
+ ): boolean => {
+ const current = layersRef.current;
+ const folderIdx = current.findIndex((l) => l.id === folderId && l.type === 'frame-folder');
+ if (folderIdx < 0) return false;
+ const folder = current[folderIdx];
+ const frames = folder.comicFrames || [];
+ if (frames.length === 0) return false;
+
+ const result = divideFramesInFolder(frames, cutStart, cutEnd, dpi, mode);
+ if (!result.divided) return false;
+
+ const grid = activeTileGridRef.current;
+
+ if (mode === 'same-folder' || result.folderGroups.length < 2) {
+ const nextFrames = result.frames.map((f) => ({ ...f, layerId: folder.id }));
+ setLayers((prev) => {
+ const next = prev.map((l) =>
+ l.id === folder.id ? { ...l, comicFrames: nextFrames } : l
+ );
+ layersRef.current = next;
+ return next;
+ });
+ grid.notifyChange(true);
+ return true;
+ }
+
+ // Split into 2 independent frame folders, cloning child layers into the 2nd folder so artwork stays intact
+ const [group1, group2] = result.folderGroups;
+ const newFolderId = `frame-folder-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ const updatedFolder1: LayerItem = {
+ ...folder,
+ comicFrames: group1.map((f) => ({ ...f, layerId: folder.id })),
+ };
+ const newFolder2: LayerItem = {
+ ...folder,
+ id: newFolderId,
+ name: `${folder.name} B`,
+ comicFrames: group2.map((f) => ({ ...f, layerId: newFolderId })),
+ };
+
+ const directChildren = current.filter((l) => l.parentId === folder.id);
+ const clonedChildren: LayerItem[] = directChildren.map((child) => {
+ const cloneId = `${child.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ if (hasTileBackedLayer(child)) {
+ grid.cloneLayer(child.id, cloneId);
+ }
+ return {
+ ...child,
+ id: cloneId,
+ parentId: newFolderId,
+ textData: child.textData ? JSON.parse(JSON.stringify(child.textData)) : undefined,
+ balloonData: child.balloonData ? JSON.parse(JSON.stringify(child.balloonData)) : undefined,
+ vectorStrokes: child.vectorStrokes ? JSON.parse(JSON.stringify(child.vectorStrokes)) : undefined,
+ };
+ });
+
+ setLayers((prev) => {
+ const idx = prev.findIndex((l) => l.id === folder.id);
+ if (idx < 0) return prev;
+ const next = prev.map((l) => (l.id === folder.id ? updatedFolder1 : l));
+ next.splice(idx, 0, newFolder2, ...clonedChildren);
+ layersRef.current = next;
+ return next;
+ });
+
+ grid.notifyChange(true);
+ return true;
+ },
+ [activeTileGridRef, layersRef, setLayers]
+ );
+
+ // Rasterize a non-destructive text, balloon, or vector layer into a standard raster layer
+ const rasterizeLayer = useCallback(
+ (id: string): boolean => {
+ const target = layersRef.current.find((l) => l.id === id);
+ if (!target) return false;
+ if (target.type !== 'text' && target.type !== 'balloon' && target.type !== 'vector') {
+ return false;
+ }
+
+ const grid = activeTileGridRef.current;
+ const dims = dimensionsRef.current;
+
+ if (target.type === 'text' || target.type === 'balloon') {
+ syncVectorObjectLayerToGrid(target, dims, grid);
+ }
+
+ setLayers((prev) => {
+ const next = prev.map((l) => {
+ if (l.id !== id) return l;
+ const { textData: _td, balloonData: _bd, vectorStrokes: _vs, ...rest } = l;
+ return {
+ ...rest,
+ type: 'raster' as const,
+ };
+ });
+ layersRef.current = next;
+ return next;
+ });
+
+ updateLayerThumbnail(id, true);
+ grid.notifyChange(true);
+ return true;
+ },
+ [activeTileGridRef, dimensionsRef, layersRef, setLayers, updateLayerThumbnail]
+ );
+
+ return {
+ upsertTextLayer,
+ upsertBalloonLayer,
+ createFrameFolder,
+ divideFrameFolder,
+ rasterizeLayer,
+ };
+}
diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.ts
index e5cf9cd..6c6fc37 100644
--- a/src/hooks/useCanvasDrawing.ts
+++ b/src/hooks/useCanvasDrawing.ts
@@ -29,8 +29,6 @@ export function useCanvasDrawing({
activeLayerId,
activeLayerLocked = false,
activeLayerVisible = true,
- layerCanvasesRef,
- layerSourceCanvasesRef,
layers,
onUpdateLayerThumbnail,
isMaskMode = false,
@@ -47,7 +45,6 @@ export function useCanvasDrawing({
onActiveConstraintAxisChange,
activeSessionId = null,
tileGrid,
- materializeLayerCanvas,
}: UseCanvasDrawingProps) {
const effectiveDraftCanvasRef = draftCanvasRef ?? strokeCanvasRef;
@@ -139,40 +136,16 @@ export function useCanvasDrawing({
onActiveConstraintAxisChange,
]);
- const getCachedLayerCanvas = useCallback(
+ const getActiveMaskCanvas = useCallback(
(layerId?: string): HTMLCanvasElement | null => {
+ if (!isMaskModeRef.current) return null;
const targetId = layerId || activeLayerIdRef.current || activeLayerId;
- if (isMaskModeRef.current && (!layerId || layerId === activeLayerIdRef.current)) {
- const activeLayer = layersRef.current?.find((l) => l.id === targetId);
- if (activeLayer?.maskCanvas) {
- return activeLayer.maskCanvas;
- }
- }
- return layerCanvasesRef.current.get(targetId) || null;
+ const activeLayer = layersRef.current?.find((l) => l.id === targetId);
+ return activeLayer?.maskCanvas || null;
},
- [activeLayerId, layerCanvasesRef]
+ [activeLayerId]
);
- const getActiveCanvas = useCallback(() => {
- const targetId = activeLayerIdRef.current || activeLayerId;
- if (isMaskModeRef.current) {
- const activeLayer = layersRef.current?.find((l) => l.id === targetId);
- if (activeLayer?.maskCanvas) {
- return activeLayer.maskCanvas;
- }
- }
- const existing = layerCanvasesRef.current.get(targetId);
- if (existing) return existing;
- if (targetId && materializeLayerCanvas) {
- return materializeLayerCanvas(targetId);
- }
- return (
- layerCanvasesRef.current.get('layer-1') ||
- layerCanvasesRef.current.values().next().value ||
- null
- );
- }, [activeLayerId, layerCanvasesRef, materializeLayerCanvas]);
-
const history = useDrawingHistory({
activeSessionId,
tileGrid,
@@ -183,8 +156,6 @@ export function useCanvasDrawing({
activeLayerIdRef,
colorModeRef,
layersRef,
- layerCanvasesRef,
- layerSourceCanvasesRef,
onUpdateLayerThumbnail,
onUpdateMaskThumbnailRef,
isDrawingRef,
@@ -214,7 +185,6 @@ export function useCanvasDrawing({
selectionRef,
isMaskModeRef,
layersRef,
- layerSourceCanvasesRef,
effectiveDraftCanvasRef,
predictedCanvasRef,
activeTileGridRef: history.activeTileGridRef,
@@ -227,7 +197,7 @@ export function useCanvasDrawing({
onCollabStrokeChunkRef,
onCollabStrokeFinishRef,
onCollabCursorMoveRef,
- getCachedLayerCanvas,
+ getActiveMaskCanvas,
pushHistoryStep: history.pushHistoryStep,
flushPendingHistoryTasks: history.flushPendingHistoryTasks,
enqueueHistoryTask: history.enqueueHistoryTask,
@@ -238,7 +208,6 @@ export function useCanvasDrawing({
return {
interactionRef,
isDrawingRef,
- getActiveCanvas,
pushHistoryStep: history.pushHistoryStep,
flushPendingHistoryTasks: history.flushPendingHistoryTasks,
handlePointerDown: brushSession.handlePointerDown,
diff --git a/src/hooks/useCollabSync.ts b/src/hooks/useCollabSync.ts
index a08a1f8..4d9e812 100644
--- a/src/hooks/useCollabSync.ts
+++ b/src/hooks/useCollabSync.ts
@@ -1,46 +1,64 @@
import React, { useRef, useEffect, useCallback } from 'react';
import {
- BrushSettings,
+ AnimationTimeline,
CanvasColorMode,
CanvasDimensions,
DocumentTab,
LayerItem,
- Point,
- ToolType,
+ hasTileBackedLayer,
} from '../types/editor';
import {
CollabPeer,
+ LayerActionMessage,
+ LayerClearableField,
+ LayerMaskDataMessage,
+ LayerTreeSyncMessage,
+ LayerUpdateMessage,
MultiplayerMessage,
StrokeChunkMessage,
StrokeFinishMessage,
StrokeStartMessage,
+ WireLayerItem,
} from '../types/multiplayer';
+import { PerspectiveRuler, StraightRuler } from '../types/perspective';
+import { ResizeCanvasOptions } from '../types/settings';
import { useMultiplayer } from './useMultiplayer';
import { getNextCollabLayerName } from './useLayerManager';
import { multiplayerService } from '../services/multiplayerService';
-import { enforceColorMode } from '../utils/colorUtils';
+import { get2DContext } from '../utils/canvasUtils';
import {
- drawDot,
- drawSmoothBezierSegment,
- get2DContext,
- getMidPoint,
- getReusableBakeCanvas,
- renderCompleteStroke,
-} from '../utils/canvasUtils';
-import { drawPencilBezierSegment, drawPencilDot, PencilGrade } from '../utils/pencilEngine';
+ deepEqualWireValue,
+ diffWireLayerTrees,
+ serializeLayerForWire,
+} from '../utils/collabSyncUtils';
+import {
+ canDeleteLayer,
+ canEditLayer,
+ canMutateCanvas,
+ canToggleLayerOwnerLock,
+ filterDeletableLayerIds,
+ peerIdEquals,
+} from '../utils/collabPermissions';
+import { RemoteStrokeSession } from '../engine/RemoteStrokeRenderer';
import { renderVectorStroke } from '../utils/vectorEngine';
import { documentStore } from '../utils/documentStore';
-import { documentStoreActions, uiStoreActions } from '../stores';
+import { TileFormat, releaseTemporaryCanvas } from '../utils/tileEngine';
+import { documentStoreActions, uiStoreActions, useDocumentStore } from '../stores';
import { PushHistoryStepFn } from './drawing/types';
-interface LayerActionMessageBase {
- type: string;
- layerItem?: LayerItem;
- imageDataUrl?: string;
- layerId?: string;
- newName?: string;
- visible?: boolean;
- opacity?: number;
+function normalizeAnimForSync(
+ tl: AnimationTimeline | null,
+ prevSynced: AnimationTimeline | null
+): AnimationTimeline | null {
+ if (!tl) return null;
+ // Suppress per-tick currentFrame broadcasts during local playback preview
+ const effectiveFrame =
+ tl.isPlaying && prevSynced ? prevSynced.currentFrame : tl.currentFrame;
+ return {
+ ...tl,
+ currentFrame: effectiveFrame,
+ isPlaying: false,
+ };
}
export interface UseCollabSyncParams {
@@ -50,14 +68,18 @@ export interface UseCollabSyncParams {
layers: LayerItem[];
activeLayerId: string;
selectedLayerIds: string[];
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- materializeLayerCanvas: (id: string) => HTMLCanvasElement | null;
+ perspectiveRuler?: PerspectiveRuler | null;
+ straightRuler?: StraightRuler | null;
+ animationTimeline?: AnimationTimeline | null;
pushHistoryStepRef: React.MutableRefObject<PushHistoryStepFn | null>;
selectiveUndoRef: React.MutableRefObject<
(peerId?: string | number, strokeId?: string) => unknown
>;
resetZoomAndCenter: (dims?: CanvasDimensions) => void;
+ resetHistory?: (targetDocumentId?: string) => void;
+ setLayers: React.Dispatch<React.SetStateAction<LayerItem[]>>;
setActiveLayerId: (id: string) => void;
+ toggleLock: (id: string) => void;
addLayer: (
type?: 'raster' | 'folder' | 'vector',
parentId?: string | null,
@@ -65,18 +87,38 @@ export interface UseCollabSyncParams {
customId?: string,
selectNew?: boolean
) => LayerItem;
- addRemoteLayer: (layerItem: LayerItem, imageDataUrl?: string) => void;
+ addRemoteLayer: (
+ layerItem: LayerItem | WireLayerItem,
+ insertIndex?: number,
+ onCommitted?: (nextLayers: LayerItem[]) => void
+ ) => void;
deleteLayer: (id: string) => void;
- deleteRemoteLayer: (id: string) => void;
+ deleteRemoteLayer: (id: string, onCommitted?: (nextLayers: LayerItem[]) => void) => void;
+ applyRemoteLayerUpdate: (
+ layerId: string,
+ patch: Partial<WireLayerItem>,
+ clearedFields?: LayerClearableField[],
+ onCommitted?: (nextLayers: LayerItem[]) => void
+ ) => void;
+ applyRemoteLayerTree: (
+ wireLayers: WireLayerItem[],
+ removedLayerIds?: string[],
+ onCommitted?: (nextLayers: LayerItem[]) => void
+ ) => void;
+ applyRemoteMaskData: (
+ msg: LayerMaskDataMessage,
+ onCommitted?: (nextLayers: LayerItem[]) => void
+ ) => void;
deleteSelectedLayers: () => void;
groupSelectedLayers: () => void;
syncRemoteDocument: (
- layers: LayerItem[],
- dataUrls: Record<string, string>,
+ layers: Array<LayerItem | WireLayerItem>,
assignedLayerId?: string,
targetDocumentId?: string,
- syncDims?: CanvasDimensions
+ syncDims?: CanvasDimensions,
+ onCommitted?: (nextLayers: LayerItem[]) => void
) => void;
+ resizeCanvas?: (newDims: CanvasDimensions, options: ResizeCanvasOptions) => void;
renameLayer: (id: string, newName: string) => void;
toggleVisibility: (id: string) => void;
setOpacity: (id: string, opacity: number) => void;
@@ -92,19 +134,27 @@ export function useCollabSync({
layers,
activeLayerId,
selectedLayerIds,
- layerCanvasesRef,
- materializeLayerCanvas,
+ perspectiveRuler = null,
+ straightRuler = null,
+ animationTimeline = null,
pushHistoryStepRef,
selectiveUndoRef,
resetZoomAndCenter,
+ resetHistory,
+ setLayers,
setActiveLayerId,
+ toggleLock,
addLayer,
addRemoteLayer,
deleteLayer,
deleteRemoteLayer,
+ applyRemoteLayerUpdate,
+ applyRemoteLayerTree,
+ applyRemoteMaskData,
deleteSelectedLayers,
groupSelectedLayers,
syncRemoteDocument,
+ resizeCanvas,
renameLayer,
toggleVisibility,
setOpacity,
@@ -114,246 +164,150 @@ export function useCollabSync({
}: UseCollabSyncParams) {
const remoteDraftCanvasesRef = useRef<Map<string | number, HTMLCanvasElement>>(new Map());
const pendingAssignedLayerIdRef = useRef<string | undefined>(undefined);
- const remoteStrokeStatesRef = useRef<
- Map<
- string,
- {
- brushSettings: BrushSettings;
- tool: ToolType;
- points: Point[];
- layerId: string;
- peerId: string | number;
- }
- >
- >(new Map());
+ const remoteStrokeSessionsRef = useRef<Map<string, RemoteStrokeSession>>(new Map());
+
+ const dimensionsRef = useRef(dimensions);
+ dimensionsRef.current = dimensions;
const layersRef = useRef(layers);
+ layersRef.current = layers;
+
+ // Canonical last-synced snapshots to compute minimal diffs and prevent echo loops
+ const lastSyncedWireLayersRef = useRef<WireLayerItem[]>([]);
+ const wasConnectedRef = useRef(false);
+ const lastSyncedPerspectiveRef = useRef<PerspectiveRuler | null>(perspectiveRuler);
+ const lastSyncedStraightRef = useRef<StraightRuler | null>(straightRuler);
+ const lastSyncedAnimationRef = useRef<AnimationTimeline | null>(
+ normalizeAnimForSync(animationTimeline, null)
+ );
+
+ const markRemoteLayersSynced = useCallback((committedLayers: LayerItem[]) => {
+ lastSyncedWireLayersRef.current = committedLayers.map(serializeLayerForWire);
+ }, []);
+
+ // Dispose any active remote preview sessions on unmount
useEffect(() => {
- layersRef.current = layers;
- }, [layers]);
+ return () => {
+ for (const session of remoteStrokeSessionsRef.current.values()) {
+ session.dispose(remoteDraftCanvasesRef.current.get(session.peerId));
+ }
+ remoteStrokeSessionsRef.current.clear();
+ };
+ }, []);
+
+ const disposePeerSessions = useCallback((peerId: string | number) => {
+ const peerKey = String(peerId);
+ for (const [strokeId, session] of remoteStrokeSessionsRef.current.entries()) {
+ if (String(session.peerId) === peerKey) {
+ session.dispose(remoteDraftCanvasesRef.current.get(session.peerId));
+ remoteStrokeSessionsRef.current.delete(strokeId);
+ }
+ }
+ }, []);
const handleRemoteStrokeStart = useCallback(
(msg: StrokeStartMessage) => {
- remoteStrokeStatesRef.current.set(msg.strokeId, {
- brushSettings: msg.brushSettings,
- tool: msg.tool,
- points: [msg.startPoint],
- layerId: msg.layerId,
+ // Clean up any stale unfinished live preview from the same peer
+ disposePeerSessions(msg.peerId);
+
+ const targetLayer = layersRef.current.find((l) => l.id === msg.layerId);
+ const session = new RemoteStrokeSession({
+ strokeId: msg.strokeId,
peerId: msg.peerId,
+ layerId: msg.layerId,
+ tool: msg.tool,
+ brushSettings: msg.brushSettings,
+ brushAssetRefs: msg.brushAssetRefs,
+ startPoint: msg.startPoint,
+ colorMode,
+ targetLayer,
+ onRequestAsset: (hash) => {
+ multiplayerService.sendBrushAssetRequest(hash, msg.peerId);
+ },
});
+ remoteStrokeSessionsRef.current.set(msg.strokeId, session);
const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
- if (!draftCanvas) return;
- const ctx = get2DContext(draftCanvas);
- if (!ctx) return;
-
- ctx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
- const bs = msg.brushSettings;
- const isEraser = msg.tool === 'eraser';
- const isBgEraser =
- isEraser && (msg.layerId === 'layer-bg' || msg.layerId.startsWith('layer-bg'));
- const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
-
- if (isPencil) {
- drawPencilDot(
- ctx,
- msg.startPoint,
- strokeColor,
- (bs.preset as PencilGrade) || 'pencil-2b',
- bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- bs.hardness
- );
- } else {
- drawDot(
- ctx,
- msg.startPoint,
- strokeColor,
- isEraser && !isBgEraser,
- colorMode === 'monochrome' ? 1.0 : bs.hardness ?? 1.0,
- bs.flow ?? 1.0
- );
- }
+ session.start(draftCanvas, () => remoteDraftCanvasesRef.current.get(msg.peerId));
},
- [colorMode]
+ [colorMode, disposePeerSessions]
);
- const handleRemoteStrokeChunk = useCallback(
- (msg: StrokeChunkMessage) => {
- const strokeState = remoteStrokeStatesRef.current.get(msg.strokeId);
- if (!strokeState) return;
+ const handleRemoteStrokeChunk = useCallback((msg: StrokeChunkMessage) => {
+ const session = remoteStrokeSessionsRef.current.get(msg.strokeId);
+ if (!session) return;
- const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
- if (!draftCanvas) return;
- const ctx = get2DContext(draftCanvas);
- if (!ctx) return;
-
- const bs = strokeState.brushSettings;
- const isEraser = strokeState.tool === 'eraser';
- const isBgEraser =
- isEraser &&
- (strokeState.layerId === 'layer-bg' || strokeState.layerId.startsWith('layer-bg'));
- const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
- const pts = strokeState.points;
-
- for (let i = 0; i < msg.points.length; i++) {
- const pt = msg.points[i];
- pts.push(pt);
-
- if (isPencil) {
- if (pts.length >= 3) {
- const p0 = pts[pts.length - 3];
- const p1 = pts[pts.length - 2];
- const p2 = pts[pts.length - 1];
- drawPencilBezierSegment(
- ctx,
- getMidPoint(p0, p1),
- p1,
- getMidPoint(p1, p2),
- strokeColor,
- (bs.preset as PencilGrade) || 'pencil-2b',
- bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- bs.hardness
- );
- } else if (pts.length === 2) {
- drawPencilBezierSegment(
- ctx,
- pts[0],
- pts[0],
- getMidPoint(pts[0], pts[1]),
- strokeColor,
- (bs.preset as PencilGrade) || 'pencil-2b',
- bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- bs.hardness
- );
- }
- } else if (bs.smoothing) {
- if (pts.length >= 3) {
- const p0 = pts[pts.length - 3];
- const p1 = pts[pts.length - 2];
- const p2 = pts[pts.length - 1];
- drawSmoothBezierSegment(
- ctx,
- getMidPoint(p0, p1),
- p1,
- getMidPoint(p1, p2),
- strokeColor,
- isEraser && !isBgEraser,
- colorMode === 'monochrome' ? 1.0 : bs.hardness ?? 1.0,
- bs.flow ?? 1.0,
- bs.spacing ?? 0.1
- );
- } else if (pts.length === 2) {
- drawSmoothBezierSegment(
- ctx,
- pts[0],
- pts[0],
- getMidPoint(pts[0], pts[1]),
- strokeColor,
- isEraser && !isBgEraser,
- colorMode === 'monochrome' ? 1.0 : bs.hardness ?? 1.0,
- bs.flow ?? 1.0,
- bs.spacing ?? 0.1
- );
- }
- } else if (pts.length >= 2) {
- const pPrev = pts[pts.length - 2];
- const pCurr = pts[pts.length - 1];
- ctx.save();
- ctx.lineCap = 'round';
- ctx.lineJoin = 'round';
- if ((bs.flow ?? 1.0) < 0.999) {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.flow ?? 1.0));
- }
- if (isBgEraser) {
- ctx.globalCompositeOperation = 'source-over';
- ctx.strokeStyle = '#ffffff';
- } else if (isEraser) {
- ctx.globalCompositeOperation = 'destination-out';
- ctx.strokeStyle = 'rgba(0, 0, 0, 1)';
- } else {
- ctx.globalCompositeOperation = 'source-over';
- ctx.strokeStyle = strokeColor;
- }
- ctx.lineWidth = (pPrev.width + pCurr.width) / 2;
- ctx.beginPath();
- ctx.moveTo(pPrev.x, pPrev.y);
- ctx.lineTo(pCurr.x, pCurr.y);
- ctx.stroke();
- ctx.restore();
- }
- }
- },
- [colorMode]
- );
+ const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
+ session.appendChunk(msg.points, draftCanvas);
+ }, []);
const handleRemoteStrokeFinish = useCallback(
(msg: StrokeFinishMessage) => {
- const strokeState = remoteStrokeStatesRef.current.get(msg.strokeId);
- if (!strokeState) return;
-
- if (msg.endPoint) {
- strokeState.points.push(msg.endPoint);
- }
-
- let targetLayerId = msg.layerId;
- let targetCanvas =
- layerCanvasesRef.current.get(targetLayerId) ??
- (layersRef.current.some((l) => l.id === targetLayerId)
- ? materializeLayerCanvas(targetLayerId)
- : null);
-
- if (!targetCanvas) {
- const byPeerId = layersRef.current.find(
- (l) => l.type === 'raster' && l.id.includes(String(msg.peerId))
- );
- if (byPeerId) {
- targetLayerId = byPeerId.id;
- targetCanvas =
- layerCanvasesRef.current.get(byPeerId.id) ?? materializeLayerCanvas(byPeerId.id);
- }
- }
+ const session = remoteStrokeSessionsRef.current.get(msg.strokeId);
+ const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
- if (!targetCanvas) {
- const fallback =
- layersRef.current.find(
- (l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg')
- ) || layersRef.current.find((l) => l.type === 'raster');
- if (fallback) {
- targetLayerId = fallback.id;
- targetCanvas =
- layerCanvasesRef.current.get(fallback.id) ?? materializeLayerCanvas(fallback.id);
+ // Vector strokes still commit vector geometry; raster strokes commit strictly via LZ4 BINARY_TILE
+ if (msg.vectorStroke) {
+ let targetLayer = layersRef.current.find((l) => l.id === msg.layerId);
+ if (!targetLayer) {
+ targetLayer = layersRef.current.find(
+ (l) => l.type === 'vector' && l.id.includes(String(msg.peerId))
+ );
}
- }
+ const dims = dimensionsRef.current;
+ if (targetLayer && targetLayer.type === 'vector' && dims.width > 0 && dims.height > 0) {
+ const targetLayerId = targetLayer.id;
+ const activeGrid = documentStore.getActiveTileGrid();
+ const isMono =
+ !targetLayerId.startsWith('layer-bg') &&
+ (colorMode === 'monochrome' || targetLayer.expressionColor === 'monochrome');
+ const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
- if (targetCanvas && strokeState.points.length > 0) {
- const activeGrid = documentStore.getActiveTileGrid();
- const targetLayer = layersRef.current.find((l) => l.id === targetLayerId);
- const isMono =
- colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
-
- if (msg.vectorStroke && targetLayer?.type === 'vector') {
const beforeStrokes = [...(targetLayer.vectorStrokes || [])];
const afterStrokes = [...beforeStrokes, msg.vectorStroke];
targetLayer.vectorStrokes = afterStrokes;
- const ctx = get2DContext(targetCanvas);
- if (ctx) {
- renderVectorStroke(ctx, msg.vectorStroke);
- const fullData = ctx.getImageData(0, 0, targetCanvas.width, targetCanvas.height);
- activeGrid.writeImageData(targetLayerId, fullData, 0, 0, targetFormat);
+ // Keep wire snapshot aligned with in-place vector stroke append
+ lastSyncedWireLayersRef.current = lastSyncedWireLayersRef.current.map((wl) =>
+ wl.id === targetLayerId ? { ...wl, vectorStrokes: afterStrokes } : wl
+ );
+
+ const b = msg.vectorStroke.bounds;
+ const vPad = Math.ceil(Math.max(16, msg.vectorStroke.baseWidth || 10));
+ const vx = b ? Math.max(0, Math.floor(b.minX - vPad)) : 0;
+ const vy = b ? Math.max(0, Math.floor(b.minY - vPad)) : 0;
+ const vw = b
+ ? Math.max(0, Math.min(dims.width, Math.ceil(b.maxX + vPad)) - vx)
+ : dims.width;
+ const vh = b
+ ? Math.max(0, Math.min(dims.height, Math.ceil(b.maxY + vPad)) - vy)
+ : dims.height;
+
+ if (vw > 0 && vh > 0) {
+ const tempVec = activeGrid.createRegionCanvas(targetLayerId, {
+ x: vx,
+ y: vy,
+ width: vw,
+ height: vh,
+ });
+ const vCtx = tempVec ? get2DContext(tempVec) : null;
+ if (tempVec && vCtx) {
+ vCtx.save();
+ vCtx.translate(-vx, -vy);
+ renderVectorStroke(vCtx, msg.vectorStroke);
+ vCtx.restore();
+ const subData = vCtx.getImageData(0, 0, vw, vh);
+ activeGrid.writeImageData(targetLayerId, subData, vx, vy, targetFormat);
+ }
+ if (tempVec) releaseTemporaryCanvas(tempVec);
}
+
pushHistoryStepRef.current?.(
'brush',
'Remote Vector Stroke',
null,
null,
targetLayerId,
- undefined,
+ vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : undefined,
undefined,
{ before: beforeStrokes, after: afterStrokes },
msg.peerId,
@@ -361,170 +315,71 @@ export function useCollabSync({
);
activeGrid.notifyChange(true);
updateLayerThumbnail(targetLayerId, true);
- } else {
- const ctx = get2DContext(targetCanvas);
- if (ctx) {
- const isEraser = strokeState.tool === 'eraser';
- const isBgEraser =
- isEraser && (targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg'));
- const bs = strokeState.brushSettings;
- const isTranslucentBrush = !isEraser && (bs.opacity ?? 1.0) < 0.999;
- const isAlphaLocked = Boolean(targetLayer?.alphaLocked);
- const isTransparentInk = Boolean(bs.isTransparentInk);
-
- const pad = Math.ceil(Math.max(32, (bs.size || 10) * 1.5));
- let dirtyX = 0;
- let dirtyY = 0;
- let dirtyW = targetCanvas.width;
- let dirtyH = targetCanvas.height;
-
- if (msg.dirtyRect) {
- dirtyX = Math.max(0, Math.floor(msg.dirtyRect.x));
- dirtyY = Math.max(0, Math.floor(msg.dirtyRect.y));
- dirtyW = Math.min(targetCanvas.width - dirtyX, Math.ceil(msg.dirtyRect.width));
- dirtyH = Math.min(targetCanvas.height - dirtyY, Math.ceil(msg.dirtyRect.height));
- } else if (strokeState.points.length > 0) {
- let minX = Infinity;
- let minY = Infinity;
- let maxX = -Infinity;
- let maxY = -Infinity;
- for (const pt of strokeState.points) {
- if (pt.x < minX) minX = pt.x;
- if (pt.y < minY) minY = pt.y;
- if (pt.x > maxX) maxX = pt.x;
- if (pt.y > maxY) maxY = pt.y;
- }
- dirtyX = Math.max(0, Math.floor(minX - pad));
- dirtyY = Math.max(0, Math.floor(minY - pad));
- dirtyW = Math.min(targetCanvas.width - dirtyX, Math.ceil(maxX + pad) - dirtyX);
- dirtyH = Math.min(targetCanvas.height - dirtyY, Math.ceil(maxY + pad) - dirtyY);
- }
-
- const dirtyRect =
- dirtyW > 0 && dirtyH > 0
- ? { x: dirtyX, y: dirtyY, width: dirtyW, height: dirtyH }
- : undefined;
-
- // Keep display canvas synced with authoritative grid before baking remote stroke
- if (dirtyRect && activeGrid.hasLayerTiles(targetLayerId)) {
- activeGrid.renderLayerToCanvas(targetLayerId, targetCanvas, dirtyRect);
- }
-
- const beforeSnapshot = dirtyRect
- ? activeGrid.snapshotTilesInRect(targetLayerId, dirtyRect)
- : null;
-
- if (isTranslucentBrush || isTransparentInk || isAlphaLocked) {
- const bakeCanvas = getReusableBakeCanvas(targetCanvas.width, targetCanvas.height);
- const bCtx = get2DContext(bakeCanvas);
- if (bCtx) {
- bCtx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
- renderCompleteStroke(
- bCtx,
- strokeState.points,
- { ...bs, opacity: 1.0, isTransparentInk: false },
- strokeState.tool,
- colorMode,
- isBgEraser,
- targetCanvas,
- false
- );
- ctx.save();
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if (isTransparentInk) {
- ctx.globalCompositeOperation = 'destination-out';
- } else if (isAlphaLocked) {
- ctx.globalCompositeOperation = 'source-atop';
- } else {
- ctx.globalCompositeOperation = 'source-over';
- }
- ctx.drawImage(bakeCanvas, 0, 0);
- ctx.restore();
- }
- } else {
- renderCompleteStroke(
- ctx,
- strokeState.points,
- bs,
- strokeState.tool,
- colorMode,
- isBgEraser,
- targetCanvas,
- isAlphaLocked
- );
- }
-
- if (dirtyRect) {
- const afterData = ctx.getImageData(dirtyX, dirtyY, dirtyW, dirtyH);
- activeGrid.writeImageData(targetLayerId, afterData, dirtyX, dirtyY, targetFormat);
- if (beforeSnapshot) {
- const tileDeltas = activeGrid.computeDeltasFromSnapshot(
- beforeSnapshot,
- targetLayerId,
- dirtyRect
- );
- if (tileDeltas.length > 0) {
- pushHistoryStepRef.current?.(
- isEraser ? 'eraser' : 'brush',
- isEraser ? 'Remote Eraser' : 'Remote Brush',
- null,
- null,
- targetLayerId,
- dirtyRect,
- tileDeltas,
- undefined,
- msg.peerId,
- msg.strokeId
- );
- }
- }
- }
-
- activeGrid.notifyChange(true);
- updateLayerThumbnail(targetLayerId, true);
- }
}
}
- const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
- if (draftCanvas) {
+ if (session) {
+ session.dispose(draftCanvas);
+ remoteStrokeSessionsRef.current.delete(msg.strokeId);
+ } else if (draftCanvas) {
const ctx = get2DContext(draftCanvas);
if (ctx) {
+ ctx.resetTransform();
ctx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
}
+ draftCanvas.style.opacity = '';
}
-
- remoteStrokeStatesRef.current.delete(msg.strokeId);
},
- [colorMode, layerCanvasesRef, materializeLayerCanvas, pushHistoryStepRef, updateLayerThumbnail]
+ [colorMode, pushHistoryStepRef, updateLayerThumbnail]
);
const handleRemoteDocSync = useCallback(
(
syncDims: CanvasDimensions,
syncMode: CanvasColorMode,
- syncLayers: LayerItem[],
- syncDataUrls: Record<string, string>,
+ syncLayers: WireLayerItem[],
assignedLayerId?: string,
- roomName?: string
+ roomName?: string,
+ syncPerspectiveRuler: PerspectiveRuler | null = null,
+ syncStraightRuler: StraightRuler | null = null,
+ syncAnimationTimeline: AnimationTimeline | null = null,
+ isReconnect: boolean = false
) => {
- const newDocId = `doc-collab-${Date.now()}`;
+ const existingActiveDocId = useDocumentStore.getState().activeDocumentId;
+ const newDocId =
+ isReconnect && existingActiveDocId && existingActiveDocId.startsWith('doc-collab-')
+ ? existingActiveDocId
+ : `doc-collab-${Date.now()}`;
const effectiveAssignedId = assignedLayerId || pendingAssignedLayerIdRef.current;
pendingAssignedLayerIdRef.current = undefined;
const resolvedActiveLayerId =
- effectiveAssignedId && syncLayers.some((l) => l.id === effectiveAssignedId)
- ? effectiveAssignedId
- : syncLayers.find(
- (l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg')
- )?.id ||
- syncLayers[0]?.id ||
- 'layer-1';
+ isReconnect && activeLayerId && syncLayers.some((l) => l.id === activeLayerId)
+ ? activeLayerId
+ : effectiveAssignedId && syncLayers.some((l) => l.id === effectiveAssignedId)
+ ? effectiveAssignedId
+ : syncLayers.find(
+ (l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg')
+ )?.id ||
+ syncLayers[0]?.id ||
+ 'layer-1';
const tabName = (roomName || '').trim() || 'Collab Session';
- // Bind new documentStore session BEFORE any BINARY_TILE packets arrive
- syncRemoteDocument(syncLayers, syncDataUrls, resolvedActiveLayerId, newDocId, syncDims);
+ // Bind documentStore session BEFORE LZ4 BINARY_TILE / BINARY_MASK packets arrive
+ syncRemoteDocument(
+ syncLayers,
+ resolvedActiveLayerId,
+ newDocId,
+ syncDims,
+ markRemoteLayersSynced
+ );
+
+ // Prime document-state refs before updating store so subscribers do not echo back
+ const normalizedAnim = normalizeAnimForSync(syncAnimationTimeline, null);
+ lastSyncedPerspectiveRef.current = syncPerspectiveRuler;
+ lastSyncedStraightRef.current = syncStraightRuler;
+ lastSyncedAnimationRef.current = normalizedAnim;
documentStoreActions.setDimensions(syncDims);
documentStoreActions.setColorMode(syncMode);
@@ -533,21 +388,27 @@ export function useCollabSync({
name: tabName,
dimensions: syncDims,
colorMode: syncMode,
- layers: syncLayers,
+ layers: layersRef.current,
activeLayerId: resolvedActiveLayerId,
- perspectiveRuler: null,
+ perspectiveRuler: syncPerspectiveRuler,
+ straightRuler: syncStraightRuler,
+ animation: normalizedAnim,
};
- documentStoreActions.setPerspectiveRuler(null);
documentStoreActions.setDocuments([newDoc]);
documentStoreActions.setActiveDocumentId(newDocId);
documentStoreActions.setDocumentName(tabName);
+ documentStoreActions.setPerspectiveRuler(syncPerspectiveRuler);
+ documentStoreActions.setStraightRuler(syncStraightRuler);
+ documentStoreActions.setAnimationTimeline(normalizedAnim);
uiStoreActions.setAppView('workspace');
- requestAnimationFrame(() => {
- resetZoomAndCenter(syncDims);
- });
+ if (!isReconnect) {
+ requestAnimationFrame(() => {
+ resetZoomAndCenter(syncDims);
+ });
+ }
},
- [resetZoomAndCenter, syncRemoteDocument]
+ [activeLayerId, markRemoteLayersSynced, resetZoomAndCenter, syncRemoteDocument]
);
const handleRemoteAssignedLayer = useCallback(
@@ -563,81 +424,178 @@ export function useCollabSync({
const layerName = getNextCollabLayerName(peer.name, layersRef.current);
const layerId = `layer-${peer.id}-1`;
const newLayer = addLayer('raster', null, layerName, layerId, false);
- multiplayerService.sendLayerAdd(newLayer);
- const updated = layersRef.current.some((l) => l.id === newLayer.id)
- ? layersRef.current
- : [newLayer, ...layersRef.current];
+ const ownedLayer: LayerItem = {
+ ...newLayer,
+ ownerPeerId: peer.id,
+ ownerPeerName: peer.name,
+ };
+ setLayers((prev) => {
+ const next = prev.map((l) =>
+ l.id === ownedLayer.id
+ ? { ...l, ownerPeerId: peer.id, ownerPeerName: peer.name }
+ : l
+ );
+ layersRef.current = next;
+ return next;
+ });
+ const updated = layersRef.current.some((l) => l.id === ownedLayer.id)
+ ? layersRef.current.map((l) =>
+ l.id === ownedLayer.id ? { ...l, ownerPeerId: peer.id, ownerPeerName: peer.name } : l
+ )
+ : [ownedLayer, ...layersRef.current];
+ const insertIndex = updated.findIndex((l) => l.id === ownedLayer.id);
+ lastSyncedWireLayersRef.current = updated.map(serializeLayerForWire);
+ multiplayerService.sendLayerAdd(ownedLayer, insertIndex >= 0 ? insertIndex : 0);
return {
assignedLayerId: layerId,
updatedLayers: updated,
};
},
- [addLayer]
+ [addLayer, setLayers]
);
const handleRemoteLayerAction = useCallback(
(msg: MultiplayerMessage) => {
- const action = msg as unknown as LayerActionMessageBase;
+ if (msg.type === 'LAYER_TREE_SYNC') {
+ const treeMsg = msg as LayerTreeSyncMessage;
+ applyRemoteLayerTree(treeMsg.layers, treeMsg.removedLayerIds, markRemoteLayersSynced);
+ return;
+ }
+
+ if (msg.type === 'LAYER_UPDATE') {
+ const updMsg = msg as LayerUpdateMessage;
+ applyRemoteLayerUpdate(
+ updMsg.layerId,
+ updMsg.patch,
+ updMsg.clearedFields,
+ markRemoteLayersSynced
+ );
+ return;
+ }
+
+ const action = msg as LayerActionMessage;
if (action.type === 'LAYER_ADD') {
if (action.layerItem) {
- addRemoteLayer(action.layerItem, action.imageDataUrl);
+ addRemoteLayer(action.layerItem, action.insertIndex, markRemoteLayersSynced);
}
} else if (action.type === 'LAYER_DELETE') {
if (action.layerId) {
- deleteRemoteLayer(action.layerId);
+ deleteRemoteLayer(action.layerId, markRemoteLayersSynced);
}
} else if (action.type === 'LAYER_CLEAR' && action.layerId) {
const layerId = action.layerId;
- const targetCanvas = layerCanvasesRef.current.get(layerId);
- if (targetCanvas) {
- const ctx = get2DContext(targetCanvas);
- if (ctx) {
- const isBg = layerId === 'layer-bg' || layerId.startsWith('layer-bg');
- if (isBg) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, targetCanvas.width, targetCanvas.height);
- documentStore.getActiveTileGrid().ingestCanvas(layerId, targetCanvas, 'color-32bit');
- } else {
- ctx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
- documentStore.getActiveTileGrid().clearLayer(layerId);
- }
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(layerId, true);
- }
+ const activeGrid = documentStore.getActiveTileGrid();
+ const dims = dimensionsRef.current;
+ const target = layersRef.current.find((l) => l.id === layerId);
+ if (target?.type === 'vector') {
+ target.vectorStrokes = [];
+ lastSyncedWireLayersRef.current = lastSyncedWireLayersRef.current.map((wl) =>
+ wl.id === layerId ? { ...wl, vectorStrokes: [] } : wl
+ );
}
+ const isBg = layerId === 'layer-bg' || layerId.startsWith('layer-bg');
+ if (isBg) {
+ activeGrid.fillLayerSolidWhite(layerId, dims.width, dims.height, 'color-32bit');
+ } else {
+ activeGrid.clearLayer(layerId);
+ activeGrid.markLayerIngested(layerId);
+ }
+ activeGrid.notifyChange(true);
+ updateLayerThumbnail(layerId, true);
} else if (action.type === 'LAYER_RENAME') {
if (action.layerId && action.newName) {
- renameLayer(action.layerId, action.newName);
+ applyRemoteLayerUpdate(
+ action.layerId,
+ { name: action.newName },
+ undefined,
+ markRemoteLayersSynced
+ );
}
} else if (action.type === 'LAYER_VISIBILITY') {
if (action.layerId && action.visible !== undefined) {
- const l = layersRef.current.find((item) => item.id === action.layerId);
- if (l && l.visible !== action.visible) {
- toggleVisibility(action.layerId);
- }
+ applyRemoteLayerUpdate(
+ action.layerId,
+ { visible: action.visible },
+ undefined,
+ markRemoteLayersSynced
+ );
}
} else if (action.type === 'LAYER_OPACITY') {
if (action.layerId && action.opacity !== undefined) {
- setOpacity(action.layerId, action.opacity);
+ applyRemoteLayerUpdate(
+ action.layerId,
+ { opacity: action.opacity },
+ undefined,
+ markRemoteLayersSynced
+ );
}
}
},
[
addRemoteLayer,
deleteRemoteLayer,
- layerCanvasesRef,
+ applyRemoteLayerUpdate,
+ applyRemoteLayerTree,
+ markRemoteLayersSynced,
updateLayerThumbnail,
- renameLayer,
- toggleVisibility,
- setOpacity,
]
);
+ const handleRemoteMaskData = useCallback(
+ (msg: LayerMaskDataMessage) => {
+ applyRemoteMaskData(msg, markRemoteLayersSynced);
+ },
+ [applyRemoteMaskData, markRemoteLayersSynced]
+ );
+
+ const handleRemotePerspectiveRuler = useCallback((ruler: PerspectiveRuler | null) => {
+ lastSyncedPerspectiveRef.current = ruler;
+ documentStoreActions.setPerspectiveRuler(ruler);
+ }, []);
+
+ const handleRemoteStraightRuler = useCallback((ruler: StraightRuler | null) => {
+ lastSyncedStraightRef.current = ruler;
+ documentStoreActions.setStraightRuler(ruler);
+ }, []);
+
+ const handleRemoteAnimationSync = useCallback((timeline: AnimationTimeline | null) => {
+ const normalized = normalizeAnimForSync(timeline, null);
+ lastSyncedAnimationRef.current = normalized;
+ documentStoreActions.setAnimationTimeline(normalized);
+ const activeDocId = useDocumentStore.getState().activeDocumentId;
+ if (activeDocId) {
+ documentStoreActions.setDocuments((docs) =>
+ docs.map((d) => (d.id === activeDocId ? { ...d, animation: normalized } : d))
+ );
+ }
+ }, []);
+
+ const handleRemoteCanvasResize = useCallback(
+ (newDims: CanvasDimensions, options: ResizeCanvasOptions) => {
+ resizeCanvas?.(newDims, options);
+ documentStoreActions.setDimensions(newDims);
+ resetZoomAndCenter(newDims);
+ resetHistory?.();
+ lastSyncedWireLayersRef.current = layersRef.current.map(serializeLayerForWire);
+ showToast(`Canvas resized remotely to ${newDims.width} × ${newDims.height} px`);
+ },
+ [resizeCanvas, resetZoomAndCenter, resetHistory, showToast]
+ );
+
+ const handleRemoteTileApplied = useCallback(
+ (layerId: string) => {
+ updateLayerThumbnail(layerId, false);
+ },
+ [updateLayerThumbnail]
+ );
+
const mp = useMultiplayer({
dimensions,
colorMode,
layers,
- layerCanvasesRef,
+ perspectiveRuler,
+ straightRuler,
+ animationTimeline,
onRemoteStrokeStart: handleRemoteStrokeStart,
onRemoteStrokeChunk: handleRemoteStrokeChunk,
onRemoteStrokeFinish: handleRemoteStrokeFinish,
@@ -645,12 +603,173 @@ export function useCollabSync({
onRemoteJoinRequest: handleRemoteJoinRequest,
onRemoteAssignedLayer: handleRemoteAssignedLayer,
onRemoteLayerAction: handleRemoteLayerAction,
+ onRemoteMaskData: handleRemoteMaskData,
+ onRemotePerspectiveRuler: handleRemotePerspectiveRuler,
+ onRemoteStraightRuler: handleRemoteStraightRuler,
+ onRemoteAnimationSync: handleRemoteAnimationSync,
+ onRemoteCanvasResize: handleRemoteCanvasResize,
onRemoteSelectiveUndo: (strokeId, peerId) => {
selectiveUndoRef.current(peerId, strokeId);
},
+ onRemoteTileApplied: handleRemoteTileApplied,
+ onRemotePeerLeft: disposePeerSessions,
showToast,
});
+ // Reactive full layer-tree & property diff broadcaster (catches every UI/menu/shortcut/auto-action mutation)
+ useEffect(() => {
+ if (!mp.isConnected) {
+ wasConnectedRef.current = false;
+ lastSyncedWireLayersRef.current = layers.map(serializeLayerForWire);
+ return;
+ }
+
+ const nextWire = layers.map(serializeLayerForWire);
+ if (!wasConnectedRef.current) {
+ wasConnectedRef.current = true;
+ lastSyncedWireLayersRef.current = nextWire;
+ return;
+ }
+
+ if (!canMutateCanvas(mp.myRole)) {
+ lastSyncedWireLayersRef.current = nextWire;
+ return;
+ }
+
+ const diff = diffWireLayerTrees(lastSyncedWireLayersRef.current, nextWire);
+ lastSyncedWireLayersRef.current = nextWire;
+ if (diff.kind === 'none') return;
+
+ const activeGrid = documentStore.getActiveTileGrid();
+
+ if (diff.kind === 'single-update') {
+ const patchKeys = Object.keys(diff.patch);
+ if (diff.clearedFields.length === 0 && patchKeys.length === 1) {
+ const onlyKey = patchKeys[0];
+ if (onlyKey === 'name' && typeof diff.patch.name === 'string') {
+ multiplayerService.sendLayerRename(diff.layerId, diff.patch.name);
+ } else if (onlyKey === 'visible' && typeof diff.patch.visible === 'boolean') {
+ multiplayerService.sendLayerVisibility(diff.layerId, diff.patch.visible);
+ } else if (onlyKey === 'opacity' && typeof diff.patch.opacity === 'number') {
+ multiplayerService.sendLayerOpacity(diff.layerId, diff.patch.opacity);
+ } else {
+ multiplayerService.sendLayerUpdate(diff.layerId, diff.patch);
+ }
+ } else {
+ multiplayerService.sendLayerUpdate(diff.layerId, diff.patch, diff.clearedFields);
+ }
+
+ if (diff.maskCreated) {
+ const target = layers.find((l) => l.id === diff.layerId);
+ if (target?.maskCanvas) {
+ multiplayerService.sendLayerMaskData(target.id, target.maskCanvas);
+ }
+ }
+ if (diff.rasterized) {
+ multiplayerService.streamLayerTiles(diff.layerId, activeGrid, { force: true });
+ }
+ return;
+ }
+
+ // Structural mutation: reorder, group, multi-delete, duplicate, merge, split frame folder, paste/import, batch toggle
+ const dirtyTileLayerIds: string[] = [];
+ for (const addedId of diff.addedLayerIds) {
+ const addedLayer = layers.find((l) => l.id === addedId);
+ if (
+ addedLayer &&
+ hasTileBackedLayer(addedLayer) &&
+ addedLayer.type !== 'text' &&
+ addedLayer.type !== 'balloon' &&
+ activeGrid.hasLayerTiles(addedId)
+ ) {
+ dirtyTileLayerIds.push(addedId);
+ }
+ }
+
+ multiplayerService.sendLayerTreeSync(nextWire, {
+ dirtyTileLayerIds,
+ removedLayerIds: diff.removedLayerIds,
+ });
+
+ for (const tileLayerId of dirtyTileLayerIds) {
+ multiplayerService.streamLayerTiles(tileLayerId, activeGrid);
+ }
+
+ for (const maskLayerId of diff.maskCreatedIds) {
+ const maskLayer = layers.find((l) => l.id === maskLayerId);
+ if (maskLayer?.maskCanvas) {
+ multiplayerService.sendLayerMaskData(maskLayer.id, maskLayer.maskCanvas);
+ }
+ }
+ }, [layers, mp.isConnected, mp.myRole]);
+
+ // Reactive document-level state broadcaster: Perspective Ruler, Straight Ruler, Animation Timeline
+ useEffect(() => {
+ const state = useDocumentStore.getState();
+ lastSyncedPerspectiveRef.current = state.perspectiveRuler;
+ lastSyncedStraightRef.current = state.straightRuler;
+ lastSyncedAnimationRef.current = normalizeAnimForSync(state.animationTimeline, null);
+
+ if (!mp.isConnected || !canMutateCanvas(mp.myRole)) return;
+
+ return useDocumentStore.subscribe(() => {
+ if (!multiplayerService.isConnected()) return;
+ const nextState = useDocumentStore.getState();
+
+ if (!deepEqualWireValue(nextState.perspectiveRuler, lastSyncedPerspectiveRef.current)) {
+ lastSyncedPerspectiveRef.current = nextState.perspectiveRuler;
+ multiplayerService.sendPerspectiveRulerSync(nextState.perspectiveRuler);
+ }
+
+ if (!deepEqualWireValue(nextState.straightRuler, lastSyncedStraightRef.current)) {
+ lastSyncedStraightRef.current = nextState.straightRuler;
+ multiplayerService.sendStraightRulerSync(nextState.straightRuler);
+ }
+
+ const normalizedAnim = normalizeAnimForSync(
+ nextState.animationTimeline,
+ lastSyncedAnimationRef.current
+ );
+ if (!deepEqualWireValue(normalizedAnim, lastSyncedAnimationRef.current)) {
+ lastSyncedAnimationRef.current = normalizedAnim;
+ multiplayerService.sendAnimationSync(normalizedAnim);
+ }
+ });
+ }, [mp.isConnected, mp.myRole]);
+
+ const isSessionActive = mp.isConnected || mp.isReconnecting;
+
+ const canEditLayerById = useCallback(
+ (layerId: string) => {
+ if (!isSessionActive) return { allowed: true };
+ const target = layersRef.current.find((l) => l.id === layerId);
+ return canEditLayer(target, mp.myPeer.id, mp.myRole);
+ },
+ [isSessionActive, mp.myPeer.id, mp.myRole]
+ );
+
+ const canDeleteLayerById = useCallback(
+ (layerId: string) => {
+ if (!isSessionActive) return { allowed: true };
+ return canDeleteLayer(layerId, layersRef.current, mp.myPeer.id, mp.myRole);
+ },
+ [isSessionActive, mp.myPeer.id, mp.myRole]
+ );
+
+ const canToggleOwnerLockById = useCallback(
+ (layerId: string) => {
+ if (!isSessionActive) return { allowed: true };
+ const target = layersRef.current.find((l) => l.id === layerId);
+ return canToggleLayerOwnerLock(target, mp.myPeer.id, mp.myRole);
+ },
+ [isSessionActive, mp.myPeer.id, mp.myRole]
+ );
+
+ const activeLayerObj = layers.find((l) => l.id === activeLayerId);
+ const canEditActiveLayer = !isSessionActive
+ ? true
+ : canEditLayer(activeLayerObj, mp.myPeer.id, mp.myRole).allowed;
+
const handleStartHosting = useCallback(
async (
roomName: string,
@@ -664,6 +783,19 @@ export function useCollabSync({
return false;
}
const finalHostName = (hostNickname || mp.myPeer.name || 'Artist').trim();
+ const hostPeerId = mp.myPeer.id;
+
+ // Stamp ownership on host's existing non-background layers to protect them from accidental guest deletion
+ setLayers((prev) => {
+ const next = prev.map((l) => {
+ if (l.id === 'layer-bg' || l.id.startsWith('layer-bg')) return l;
+ if (l.ownerPeerId !== undefined) return l;
+ return { ...l, ownerPeerId: hostPeerId, ownerPeerName: finalHostName };
+ });
+ layersRef.current = next;
+ return next;
+ });
+
const defaultLayer =
layersRef.current.find((l) => l.id === activeLayerId) ||
layersRef.current.find(
@@ -682,89 +814,243 @@ export function useCollabSync({
}
return await mp.startHosting(roomName, port, finalHostName, isGlobal, onStatus);
},
- [hasOpenDocument, showToast, mp.myPeer.name, activeLayerId, renameLayer, mp.startHosting]
+ [
+ hasOpenDocument,
+ showToast,
+ mp.myPeer.id,
+ mp.myPeer.name,
+ activeLayerId,
+ renameLayer,
+ setLayers,
+ mp.startHosting,
+ ]
);
const handleAddLayer = useCallback(
- (type: 'raster' | 'folder' = 'raster') => {
- if (mp.isConnected && type === 'raster') {
- const name = getNextCollabLayerName(mp.myPeer.name, layersRef.current);
- const newLayer = addLayer('raster', null, name);
- if (newLayer) {
- multiplayerService.sendLayerAdd(newLayer);
- }
- } else {
- addLayer(type);
+ (type: 'raster' | 'folder' | 'vector' = 'raster') => {
+ if (isSessionActive && !canMutateCanvas(mp.myRole)) {
+ showToast('Viewers have read-only access');
+ return;
+ }
+ const created =
+ isSessionActive && type === 'raster'
+ ? addLayer('raster', null, getNextCollabLayerName(mp.myPeer.name, layersRef.current))
+ : addLayer(type);
+ if (isSessionActive && created) {
+ const ownerId = mp.myPeer.id;
+ const ownerName = mp.myPeer.name;
+ setLayers((prev) => {
+ const next = prev.map((l) =>
+ l.id === created.id ? { ...l, ownerPeerId: ownerId, ownerPeerName: ownerName } : l
+ );
+ layersRef.current = next;
+ return next;
+ });
}
},
- [mp.isConnected, mp.myPeer.name, addLayer]
+ [isSessionActive, mp.myRole, mp.myPeer.id, mp.myPeer.name, addLayer, setLayers, showToast]
);
const handleDeleteLayer = useCallback(
(id: string) => {
- deleteLayer(id);
- if (mp.isConnected) {
- multiplayerService.sendLayerDelete(id);
+ if (isSessionActive) {
+ const perm = canDeleteLayer(id, layersRef.current, mp.myPeer.id, mp.myRole);
+ if (!perm.allowed) {
+ showToast(perm.reason || 'You do not have permission to delete this layer');
+ return;
+ }
}
+ deleteLayer(id);
},
- [deleteLayer, mp.isConnected]
+ [isSessionActive, mp.myPeer.id, mp.myRole, deleteLayer, showToast]
);
const handleDeleteSelectedLayers = useCallback(() => {
if (selectedLayerIds && selectedLayerIds.length > 1) {
+ if (isSessionActive) {
+ const { allowedIds, blockedReasons } = filterDeletableLayerIds(
+ selectedLayerIds,
+ layersRef.current,
+ mp.myPeer.id,
+ mp.myRole
+ );
+ if (allowedIds.length === 0) {
+ showToast(blockedReasons[0] || 'Selected layers cannot be deleted');
+ return;
+ }
+ if (blockedReasons.length > 0) {
+ for (const allowedId of allowedIds) {
+ deleteLayer(allowedId);
+ }
+ showToast(
+ `Deleted ${allowedIds.length} layer(s); protected ${blockedReasons.length} other user layer(s)`
+ );
+ return;
+ }
+ }
deleteSelectedLayers();
showToast(`Deleted ${selectedLayerIds.length} layers`);
} else {
handleDeleteLayer(activeLayerId);
}
- }, [selectedLayerIds, deleteSelectedLayers, handleDeleteLayer, activeLayerId, showToast]);
+ }, [
+ selectedLayerIds,
+ isSessionActive,
+ mp.myPeer.id,
+ mp.myRole,
+ deleteLayer,
+ deleteSelectedLayers,
+ handleDeleteLayer,
+ activeLayerId,
+ showToast,
+ ]);
const handleGroupSelectedLayers = useCallback(() => {
+ if (isSessionActive && !canMutateCanvas(mp.myRole)) {
+ showToast('Viewers have read-only access');
+ return;
+ }
groupSelectedLayers();
showToast('Grouped layers into folder');
- }, [groupSelectedLayers, showToast]);
+ }, [isSessionActive, mp.myRole, groupSelectedLayers, showToast]);
const handleToggleVisibility = useCallback(
(id: string) => {
- const l = layersRef.current.find((item) => item.id === id);
- toggleVisibility(id);
- if (mp.isConnected && l) {
- multiplayerService.sendLayerVisibility(id, !l.visible);
+ if (isSessionActive) {
+ const perm = canEditLayerById(id);
+ if (!perm.allowed) {
+ showToast(perm.reason || 'Cannot modify this layer');
+ return;
+ }
}
+ toggleVisibility(id);
},
- [toggleVisibility, mp.isConnected]
+ [isSessionActive, canEditLayerById, toggleVisibility, showToast]
);
const handleSetOpacity = useCallback(
(id: string, opacity: number) => {
- setOpacity(id, opacity);
- if (mp.isConnected) {
- multiplayerService.sendLayerOpacity(id, opacity);
+ if (isSessionActive) {
+ const perm = canEditLayerById(id);
+ if (!perm.allowed) {
+ showToast(perm.reason || 'Cannot modify this layer');
+ return;
+ }
}
+ setOpacity(id, opacity);
},
- [setOpacity, mp.isConnected]
+ [isSessionActive, canEditLayerById, setOpacity, showToast]
);
const handleRenameLayer = useCallback(
(id: string, newName: string) => {
+ if (isSessionActive) {
+ const perm = canEditLayerById(id);
+ if (!perm.allowed) {
+ showToast(perm.reason || 'Cannot rename this layer');
+ return;
+ }
+ }
renameLayer(id, newName);
- if (mp.isConnected) {
- multiplayerService.sendLayerRename(id, newName);
+ },
+ [isSessionActive, canEditLayerById, renameLayer, showToast]
+ );
+
+ const handleToggleLock = useCallback(
+ (id: string) => {
+ if (isSessionActive) {
+ const perm = canEditLayerById(id);
+ if (!perm.allowed) {
+ showToast(perm.reason || 'Cannot modify lock on this layer');
+ return;
+ }
+ }
+ toggleLock(id);
+ },
+ [isSessionActive, canEditLayerById, toggleLock, showToast]
+ );
+
+ const handleToggleOwnerLock = useCallback(
+ (id: string) => {
+ const target = layersRef.current.find((l) => l.id === id);
+ if (!target) return;
+ if (isSessionActive) {
+ const perm = canToggleLayerOwnerLock(target, mp.myPeer.id, mp.myRole);
+ if (!perm.allowed) {
+ showToast(perm.reason || 'Cannot toggle owner lock on this layer');
+ return;
+ }
+ }
+
+ const isCurrentlyReserved =
+ target.reservedByPeerId !== undefined && target.reservedByPeerId !== '';
+ if (isCurrentlyReserved) {
+ setLayers((prev) =>
+ prev.map((l) => {
+ if (l.id !== id) return l;
+ const { reservedByPeerId: _id, reservedByPeerName: _name, ...rest } = l;
+ return rest;
+ })
+ );
+ showToast(`Unlocked "${target.name}" for collaboration`);
+ } else {
+ const lockPeerId =
+ mp.myRole === 'host' && target.ownerPeerId && !peerIdEquals(target.ownerPeerId, mp.myPeer.id)
+ ? target.ownerPeerId
+ : mp.myPeer.id;
+ const lockPeerName =
+ mp.myRole === 'host' && target.ownerPeerId && !peerIdEquals(target.ownerPeerId, mp.myPeer.id)
+ ? target.ownerPeerName || 'Owner'
+ : mp.myPeer.name;
+ setLayers((prev) =>
+ prev.map((l) =>
+ l.id === id
+ ? {
+ ...l,
+ ownerPeerId: l.ownerPeerId ?? lockPeerId,
+ ownerPeerName: l.ownerPeerName ?? lockPeerName,
+ reservedByPeerId: lockPeerId,
+ reservedByPeerName: lockPeerName,
+ }
+ : l
+ )
+ );
+ showToast(`Locked "${target.name}" to ${lockPeerName}`);
}
},
- [renameLayer, mp.isConnected]
+ [isSessionActive, mp.myPeer.id, mp.myPeer.name, mp.myRole, setLayers, showToast]
);
const handleClearActiveLayer = useCallback(() => {
+ if (isSessionActive) {
+ const perm = canEditLayerById(activeLayerId);
+ if (!perm.allowed) {
+ showToast(perm.reason || 'Cannot clear this layer');
+ return;
+ }
+ }
+ const active = layersRef.current.find((l) => l.id === activeLayerId);
+ if (active?.type === 'vector') {
+ active.vectorStrokes = [];
+ }
clearActiveLayer();
if (mp.isConnected) {
multiplayerService.sendLayerClear(activeLayerId);
+ if (activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg')) {
+ multiplayerService.streamLayerTiles(activeLayerId, documentStore.getActiveTileGrid(), {
+ force: true,
+ });
+ }
}
- }, [clearActiveLayer, mp.isConnected, activeLayerId]);
+ }, [isSessionActive, canEditLayerById, clearActiveLayer, mp.isConnected, activeLayerId, showToast]);
return {
...mp,
remoteDraftCanvasesRef,
+ canEditActiveLayer,
+ canEditLayerById,
+ canDeleteLayerById,
+ canToggleOwnerLockById,
handleStartHosting,
handleAddLayer,
handleDeleteLayer,
@@ -773,6 +1059,8 @@ export function useCollabSync({
handleToggleVisibility,
handleSetOpacity,
handleRenameLayer,
+ handleToggleLock,
+ handleToggleOwnerLock,
handleClearActiveLayer,
};
}
diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.ts
index baabaf4..4cbcd39 100644
--- a/src/hooks/useLayerManager.ts
+++ b/src/hooks/useLayerManager.ts
@@ -1,370 +1,30 @@
import { useState, useRef, useCallback, useEffect } from 'react';
-import {
- LayerItem,
- LayerType,
- BlendMode,
- CanvasDimensions,
- CanvasColorMode,
- LoadedDocument,
- ExpressionColor,
- CanvasSelection,
- DirtyRect,
- AdjustmentLayerData,
- LayerStyles,
- TextLayerData,
- SpeechBalloon,
- ComicFrame,
- FrameDivideMode,
- isFolderLikeLayer,
- hasTileBackedLayer,
-} from '../types/editor';
-import { ResizeCanvasOptions } from '../types/settings';
-import { createCanvasThumbnail, get2DContext, getCanvasCompositeOperation } from '../utils/canvasUtils';
-import { applyLayerEffects, applyExpressionColorToImageData } from '../utils/layerEffectsEngine';
-import { HalftoneDotShape } from '../utils/screentoneEngine';
-import { SparseTileGrid, globalTileGrid, releaseTemporaryCanvas } from '../utils/tileEngine';
+import { CanvasDimensions, LayerItem } from '../types/editor';
+import { SparseTileGrid, globalTileGrid } from '../utils/tileEngine';
import { documentStore } from '../utils/documentStore';
import { recoveryService } from '../services/recoveryService';
-import { divideFramesInFolder, Point2D } from '../utils/frameEngine';
-import { syncVectorObjectLayerToGrid } from '../utils/vectorLayerRenderer';
-import { LayerInsertTarget, sanitizeImportedLayerName } from '../utils/fileDropImport';
-
-interface UseLayerManagerProps {
- dimensions: CanvasDimensions;
- activeSessionId?: string | null;
- tileGrid?: SparseTileGrid;
-}
-
-export function isBackgroundLayerId(id: string): boolean {
- return id === 'layer-bg' || id.startsWith('layer-bg');
-}
-
-// Helper to generate the next collaborative layer name (e.g. "Sora 1", "Sora 2", "Alex 1")
-export function getNextCollabLayerName(username: string, layers: LayerItem[]): string {
- const cleanName = (username || 'User').trim();
- let maxNum = 0;
- const escaped = cleanName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const regex = new RegExp(`^${escaped}\\s*(\\d*)$`, 'i');
-
- layers.forEach((l) => {
- const match = l.name.match(regex);
- if (match) {
- const num = match[1] ? parseInt(match[1], 10) : 1;
- if (!isNaN(num) && num > maxNum) {
- maxNum = num;
- }
- }
- });
-
- return `${cleanName} ${maxNum + 1}`;
-}
-
-// Pure selection computation for single, Shift (range), and Ctrl/Cmd (toggle) clicks
-export function computeLayerSelection(
- layers: LayerItem[],
- currentSelectedIds: string[],
- activeId: string,
- pivotId: string | null,
- targetId: string,
- isShift: boolean,
- isCtrl: boolean
-): { nextSelectedIds: string[]; nextActiveId: string; nextPivotId: string } {
- const targetIndex = layers.findIndex((l) => l.id === targetId);
- if (targetIndex === -1) {
- return {
- nextSelectedIds: currentSelectedIds,
- nextActiveId: activeId,
- nextPivotId: pivotId || activeId,
- };
- }
-
- if (isShift) {
- const effectivePivot = pivotId || activeId || targetId;
- const pivotIndex = layers.findIndex((l) => l.id === effectivePivot);
- const safePivotIdx = pivotIndex >= 0 ? pivotIndex : targetIndex;
- const start = Math.min(safePivotIdx, targetIndex);
- const end = Math.max(safePivotIdx, targetIndex);
- const rangeIds = layers.slice(start, end + 1).map((l) => l.id);
-
- if (isCtrl) {
- return {
- nextSelectedIds: Array.from(new Set([...currentSelectedIds, ...rangeIds])),
- nextActiveId: targetId,
- nextPivotId: effectivePivot,
- };
- } else {
- return {
- nextSelectedIds: rangeIds,
- nextActiveId: targetId,
- nextPivotId: effectivePivot,
- };
- }
- } else if (isCtrl) {
- const exists = currentSelectedIds.includes(targetId);
- if (exists) {
- const next = currentSelectedIds.filter((item) => item !== targetId);
- const nextActive = activeId === targetId && next.length > 0 ? next[next.length - 1] : activeId;
- return {
- nextSelectedIds: next,
- nextActiveId: nextActive,
- nextPivotId: targetId,
- };
- } else {
- return {
- nextSelectedIds: [...currentSelectedIds, targetId],
- nextActiveId: targetId,
- nextPivotId: targetId,
- };
- }
- } else {
- return {
- nextSelectedIds: [targetId],
- nextActiveId: targetId,
- nextPivotId: targetId,
- };
- }
-}
-
-// Pure batch deletion helper
-export function computeBatchDeleteLayers(
- layers: LayerItem[],
- selectedIds: string[],
- activeId: string
-): { nextLayers: LayerItem[]; deletedIds: string[]; nextActiveId: string } {
- let targets = [...selectedIds];
- if (targets.length === 0 && activeId) {
- targets = [activeId];
- }
- if (targets.length === 0) {
- return { nextLayers: layers, deletedIds: [], nextActiveId: activeId };
- }
-
- const targetSet = new Set(targets);
- const allToDelete = new Set<string>();
-
- const collectDescendants = (parentId: string) => {
- for (const l of layers) {
- if (l.parentId === parentId) {
- allToDelete.add(l.id);
- if (isFolderLikeLayer(l)) collectDescendants(l.id);
- }
- }
- };
-
- for (const id of targetSet) {
- allToDelete.add(id);
- const item = layers.find((l) => l.id === id);
- if (isFolderLikeLayer(item)) {
- collectDescendants(id);
- }
- }
-
- // Ensure we don't delete all raster layers if user tries to delete everything
- const remainingRaster = layers.filter((l) => l.type === 'raster' && !allToDelete.has(l.id));
- if (remainingRaster.length === 0) {
- const preserved = layers.find((l) => l.id === 'layer-bg' || l.id.startsWith('layer-bg')) || layers.find((l) => l.type === 'raster');
- if (preserved) {
- allToDelete.delete(preserved.id);
- }
- }
-
- const nextLayers = layers.filter((l) => !allToDelete.has(l.id));
- const nextActive = nextLayers.find((l) => l.type === 'raster') || nextLayers[0];
- const nextActiveId = nextActive ? nextActive.id : '';
-
- return {
- nextLayers,
- deletedIds: Array.from(allToDelete),
- nextActiveId,
- };
-}
-
-// Pure group selected layers helper
-export function computeGroupLayers(
- layers: LayerItem[],
- selectedIds: string[],
- activeId: string,
- customFolderId?: string
-): { nextLayers: LayerItem[]; newFolder: LayerItem } | null {
- let targets = [...selectedIds];
- if (targets.length === 0 && activeId) {
- targets = [activeId];
- }
- if (targets.length === 0) return null;
-
- const targetSet = new Set(targets);
- const selectedItems = layers.filter((l) => targetSet.has(l.id));
- if (selectedItems.length === 0) return null;
-
- const indices = selectedItems.map((l) => layers.indexOf(l)).filter((idx) => idx >= 0);
- const minIdx = Math.min(...indices);
-
- const firstParent = selectedItems[0].parentId;
- const allSameParent = selectedItems.every((l) => l.parentId === firstParent);
- const folderParentId = allSameParent ? firstParent : null;
-
- const folderId = customFolderId || `folder-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
- let count = 1;
- layers.forEach((l) => {
- if (l.type === 'folder' && l.name.startsWith('Folder ')) {
- const num = parseInt(l.name.replace('Folder ', ''), 10);
- if (!isNaN(num) && num >= count) count = num + 1;
- }
- });
-
- const newFolder: LayerItem = {
- id: folderId,
- name: `Folder ${count}`,
- type: 'folder',
- visible: true,
- opacity: 1,
- blendMode: 'pass-through',
- locked: false,
- collapsed: false,
- parentId: folderParentId,
- thumbnailUrl: '',
- };
-
- const movingIds = new Set<string>();
- const getDescendants = (parentId: string) => {
- for (const l of layers) {
- if (l.parentId === parentId) {
- movingIds.add(l.id);
- if (isFolderLikeLayer(l)) getDescendants(l.id);
- }
- }
- };
- for (const item of selectedItems) {
- movingIds.add(item.id);
- if (isFolderLikeLayer(item)) getDescendants(item.id);
- }
-
- const movingItems = layers
- .filter((l) => movingIds.has(l.id))
- .map((l) => {
- if (!l.parentId || !movingIds.has(l.parentId)) {
- return { ...l, parentId: folderId };
- }
- return l;
- });
-
- const remaining = layers.filter((l) => !movingIds.has(l.id));
- const targetInsertIdx = Math.min(minIdx, remaining.length);
-
- const nextLayers = [
- ...remaining.slice(0, targetInsertIdx),
- newFolder,
- ...movingItems,
- ...remaining.slice(targetInsertIdx),
- ];
-
- return { nextLayers, newFolder };
-}
-
-// Pure drag-and-drop / reordering helper
-export function computeBatchReorderLayers(
- layers: LayerItem[],
- selectedIds: string[],
- draggedId: string,
- targetId: string,
- position: 'above' | 'below' | 'inside'
-): LayerItem[] {
- if (draggedId === targetId) return layers;
-
- const isMultiDrag = selectedIds.length > 1 && selectedIds.includes(draggedId);
- const rootIds = isMultiDrag ? selectedIds : [draggedId];
-
- const targetIdx = layers.findIndex((l) => l.id === targetId);
- if (targetIdx < 0) return layers;
- const targetItem = layers[targetIdx];
-
- const getDescendantIds = (parentId: string): string[] => {
- const ids: string[] = [];
- for (const item of layers) {
- if (item.parentId === parentId) {
- ids.push(item.id);
- ids.push(...getDescendantIds(item.id));
- }
- }
- return ids;
- };
-
- const movingIds = new Set<string>();
- for (const id of rootIds) {
- movingIds.add(id);
- const item = layers.find((l) => l.id === id);
- if (isFolderLikeLayer(item)) {
- getDescendantIds(id).forEach((descId) => movingIds.add(descId));
- }
- }
-
- if (movingIds.has(targetId)) return layers;
-
- let currCheck: LayerItem | undefined = targetItem;
- while (currCheck) {
- if (movingIds.has(currCheck.id)) return layers;
- currCheck = layers.find((l) => l.id === currCheck?.parentId);
- }
-
- const newParentId = (position === 'inside' && isFolderLikeLayer(targetItem))
- ? targetItem.id
- : targetItem.parentId;
-
- const movingItems = layers
- .filter((l) => movingIds.has(l.id))
- .map((l) => {
- if (!l.parentId || !movingIds.has(l.parentId)) {
- return { ...l, parentId: newParentId };
- }
- return l;
- });
-
- const remaining = layers.filter((l) => !movingIds.has(l.id));
- const newTargetIdx = remaining.findIndex((l) => l.id === targetId);
- if (newTargetIdx < 0) return layers;
-
- let insertIdx = newTargetIdx;
- if (position === 'above') {
- insertIdx = newTargetIdx;
- } else if (position === 'below' || position === 'inside') {
- insertIdx = newTargetIdx + 1;
- }
-
- remaining.splice(insertIdx, 0, ...movingItems);
- return remaining;
-}
-
-// Pure batch visibility toggle
-export function computeBatchVisibility(
- layers: LayerItem[],
- selectedIds: string[],
- targetId: string
-): LayerItem[] {
- const isMulti = selectedIds.length > 1 && selectedIds.includes(targetId);
- if (!isMulti) {
- return layers.map((l) => (l.id === targetId ? { ...l, visible: !l.visible } : l));
- }
- const target = layers.find((l) => l.id === targetId);
- const newVisible = target ? !target.visible : true;
- const selectedSet = new Set(selectedIds);
- return layers.map((l) => (selectedSet.has(l.id) ? { ...l, visible: newVisible } : l));
-}
-
-// Pure batch lock toggle
-export function computeBatchLock(
- layers: LayerItem[],
- selectedIds: string[],
- targetId: string
-): LayerItem[] {
- const isMulti = selectedIds.length > 1 && selectedIds.includes(targetId);
- if (!isMulti) {
- return layers.map((l) => (l.id === targetId ? { ...l, locked: !l.locked } : l));
- }
- const target = layers.find((l) => l.id === targetId);
- const newLocked = target ? !target.locked : true;
- const selectedSet = new Set(selectedIds);
- return layers.map((l) => (selectedSet.has(l.id) ? { ...l, locked: newLocked } : l));
-}
+import { computeLayerSelection } from './layerManager/layerTreeOps';
+import { LayerManagerContext, UseLayerManagerProps } from './layerManager/types';
+import { useLayerCanvasRegistry } from './layerManager/useLayerCanvasRegistry';
+import { useLayerCrud } from './layerManager/useLayerCrud';
+import { useLayerCollabSync } from './layerManager/useLayerCollabSync';
+import { useLayerPropertiesAndMasks } from './layerManager/useLayerPropertiesAndMasks';
+import { useLayerEffects } from './layerManager/useLayerEffects';
+import { useLayerDocumentOps } from './layerManager/useLayerDocumentOps';
+import { useLayerResize } from './layerManager/useLayerResize';
+import { useLayerClipboard } from './layerManager/useLayerClipboard';
+import { useLayerSpecialLayers } from './layerManager/useLayerSpecialLayers';
+
+export {
+ isBackgroundLayerId,
+ getNextCollabLayerName,
+ computeLayerSelection,
+ computeBatchDeleteLayers,
+ computeGroupLayers,
+ computeBatchReorderLayers,
+ computeBatchVisibility,
+ computeBatchLock,
+} from './layerManager/layerTreeOps';
export function useLayerManager({ dimensions: _dimensions, activeSessionId, tileGrid }: UseLayerManagerProps) {
// Active document's SparseTileGrid (isolated per document tab)
@@ -377,17 +37,6 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
activeTileGridRef.current = documentStore.getOrCreateSession(activeSessionId).tileGrid;
}
- // Lazy canvas map: ONLY holds canvases explicitly materialized by legacy tools / effects.
- // Empty and unmodified layers NEVER allocate full-size HTMLCanvasElements here.
- const layerCanvasesRef = useRef<Map<string, HTMLCanvasElement>>(
- activeSessionId ? documentStore.getOrCreateSession(activeSessionId).layerCanvases : new Map()
- );
-
- // Store original offscreen raster source canvases strictly for layers with non-destructive effects
- const layerSourceCanvasesRef = useRef<Map<string, HTMLCanvasElement>>(
- activeSessionId ? documentStore.getOrCreateSession(activeSessionId).layerSourceCanvases : new Map()
- );
-
const dimensionsRef = useRef<CanvasDimensions>(_dimensions);
dimensionsRef.current = _dimensions;
@@ -397,23 +46,16 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
if (activeSessionId) {
const sess = documentStore.getOrCreateSession(activeSessionId);
activeTileGridRef.current = tileGrid ?? sess.tileGrid;
- layerCanvasesRef.current = sess.layerCanvases;
- layerSourceCanvasesRef.current = sess.layerSourceCanvases;
} else {
activeTileGridRef.current = tileGrid ?? globalTileGrid;
- layerCanvasesRef.current = new Map();
- layerSourceCanvasesRef.current = new Map();
}
}
// Default canvas tone frequency (20 to 85 LPI, default: 60)
const defaultToneFrequencyRef = useRef<number>(60);
- // Pending copy queue: targetId -> sourceId (used only when legacy caller mounts a DOM canvas)
- const pendingCanvasCopiesRef = useRef<Map<string, string>>(new Map());
-
- // Pending initial canvas or fill color queue
- const pendingInitialDataRef = useRef<Map<string, HTMLCanvasElement | HTMLImageElement | string>>(new Map());
+ // Debounce timers for thumbnail refreshes
+ const thumbDebounceTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
// Default initial layers: starts empty until a document is created or opened
const [layers, setLayers] = useState<LayerItem[]>([]);
@@ -482,2735 +124,37 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
setSelectedLayerIds(res.nextSelectedIds);
}, [setSelectedLayerIds]);
- // Materialize a full-layer canvas on demand from SparseTileGrid (strictly for legacy tools/effects)
- const materializeLayerCanvas = useCallback((id: string): HTMLCanvasElement | null => {
- const existing = layerCanvasesRef.current.get(id);
- if (existing) return existing;
- if (typeof document === 'undefined') return null;
- const dims = dimensionsRef.current;
- if (dims.width <= 0 || dims.height <= 0) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = dims.width;
- canvas.height = dims.height;
- const grid = activeTileGridRef.current;
- if (grid.hasLayerTiles(id)) {
- grid.renderLayerToCanvas(id, canvas);
- }
- layerCanvasesRef.current.set(id, canvas);
- return canvas;
- }, []);
-
- // Release a transiently materialized display canvas (SparseTileGrid remains authoritative)
- const releaseLayerCanvas = useCallback((id: string) => {
- if (layerSourceCanvasesRef.current.has(id)) return;
- const existing = layerCanvasesRef.current.get(id);
- if (existing) {
- releaseTemporaryCanvas(existing);
- layerCanvasesRef.current.delete(id);
- }
- }, []);
-
- // Register or unregister canvas element for a layer (on-demand only; empty layers do not call this)
- const registerLayerCanvas = useCallback((id: string, canvas: HTMLCanvasElement | null) => {
- const grid = activeTileGridRef.current;
- if (canvas) {
- if (layerCanvasesRef.current.get(id) === canvas) {
- return; // Already registered with same canvas element
- }
-
- layerCanvasesRef.current.set(id, canvas);
-
- const sourceId = pendingCanvasCopiesRef.current.get(id);
- if (sourceId) {
- grid.cloneLayer(sourceId, id);
- grid.renderLayerToCanvas(id, canvas);
- pendingCanvasCopiesRef.current.delete(id);
- }
-
- const initialData = pendingInitialDataRef.current.get(id);
- if (initialData) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- if (typeof initialData === 'string') {
- if (initialData !== 'transparent') {
- ctx.fillStyle = initialData;
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- if (initialData.toLowerCase() === '#ffffff' || initialData.toLowerCase() === '#fff' || initialData.toLowerCase() === 'white') {
- (canvas as any).__isSolidWhite = true;
- }
- } else {
- (canvas as any).__isBlank = true;
- }
- } else {
- ctx.drawImage(initialData, 0, 0);
- }
- }
- pendingInitialDataRef.current.delete(id);
- } else if (!sourceId) {
- if (grid.hasLayerTiles(id)) {
- grid.renderLayerToCanvas(id, canvas);
- } else if (isBackgroundLayerId(id)) {
- grid.fillLayerSolidWhite(id, canvas.width, canvas.height, 'color-32bit');
- grid.renderLayerToCanvas(id, canvas);
- } else {
- (canvas as any).__isBlank = true;
- }
- }
-
- if (!grid.isLayerIngested(id) || sourceId || initialData) {
- const layer = layersRef.current.find((l) => l.id === id);
- const isMono = layer?.expressionColor === 'monochrome';
- grid.ingestCanvas(id, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
-
- requestAnimationFrame(() => {
- const dims = dimensionsRef.current;
- const thumb = createCanvasThumbnail(
- { grid: activeTileGridRef.current, layerId: id, dimensions: dims },
- !isBackgroundLayerId(id)
- );
- if (thumb) {
- setLayers((prev) =>
- prev.map((l) => (l.id === id && !l.thumbnailUrl ? { ...l, thumbnailUrl: thumb } : l))
- );
- }
- });
- } else {
- const existing = layerCanvasesRef.current.get(id);
- if (existing) releaseTemporaryCanvas(existing);
- layerCanvasesRef.current.delete(id);
- grid.clearLayer(id);
- }
- }, []);
-
- const thumbDebounceTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
-
- // Cleanup debounce timers on unmount
- useEffect(() => {
- return () => {
- for (const timer of thumbDebounceTimersRef.current.values()) {
- clearTimeout(timer);
- }
- thumbDebounceTimersRef.current.clear();
- };
- }, []);
-
- // Update a single layer's thumbnail directly from SparseTileGrid LOD 3 (zero full-canvas read)
- const updateLayerThumbnail = useCallback((id: string, immediate: boolean = false) => {
- const capturedGrid = activeTileGridRef.current;
- const capturedDocId = activeSessionIdRef.current;
- const run = () => {
- if (capturedDocId !== activeSessionIdRef.current) return;
- const dims = dimensionsRef.current;
- const thumb = createCanvasThumbnail(
- { grid: capturedGrid, layerId: id, dimensions: dims },
- !isBackgroundLayerId(id)
- );
-
- if (!thumb) return;
-
- setLayers((prev) => {
- const existingLayer = prev.find((l) => l.id === id);
- if (!existingLayer || existingLayer.thumbnailUrl === thumb) return prev;
- return prev.map((l) => (l.id === id ? { ...l, thumbnailUrl: thumb } : l));
- });
- };
-
- const existing = thumbDebounceTimersRef.current.get(id);
- if (existing) clearTimeout(existing);
-
- if (immediate) {
- thumbDebounceTimersRef.current.delete(id);
- run();
- } else {
- const isLargeDoc = _dimensions.width * _dimensions.height > 1024 * 1024;
- const delayMs = isLargeDoc ? 900 : 350;
- const timer = setTimeout(() => {
- thumbDebounceTimersRef.current.delete(id);
- run();
- }, delayMs);
- thumbDebounceTimersRef.current.set(id, timer);
- }
- }, [_dimensions]);
-
- // Add a new raster layer, folder, frame-folder, text, balloon, or adjustment layer
- const addLayer = useCallback(
- (
- type: LayerType = 'raster',
- explicitParentId?: string | null,
- customName?: string,
- customId?: string,
- selectNewLayer: boolean = true
- ): LayerItem => {
- const id = customId || `${type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
- const currentLayers = layersRef.current;
- const currentActiveIdx = currentLayers.findIndex((l) => l.id === activeLayerIdRef.current);
- const currentActiveLayer = currentLayers[currentActiveIdx];
-
- let initialParentId: string | null = null;
- if (explicitParentId !== undefined) {
- initialParentId = explicitParentId;
- } else if (currentActiveLayer) {
- initialParentId = isFolderLikeLayer(currentActiveLayer) ? currentActiveLayer.id : currentActiveLayer.parentId;
- }
-
- const resolveLayerName = (list: LayerItem[]) => {
- if (customName) return customName;
- let count = 1;
- const prefix =
- type === 'folder' ? 'Folder ' :
- type === 'frame-folder' ? 'Frame ' :
- type === 'vector' ? 'Vector ' :
- type === 'frame' ? 'Frame ' :
- type === 'text' ? 'Text ' :
- type === 'balloon' ? 'Balloon ' :
- type === 'adjustment' ? 'Adjustment ' : 'Layer ';
- list.forEach((l) => {
- if (l.type === type && l.name.startsWith(prefix)) {
- const num = parseInt(l.name.replace(prefix, ''), 10);
- if (!isNaN(num) && num >= count) {
- count = num + 1;
- }
- }
- });
- return `${prefix}${count}`;
- };
-
- const createdLayer: LayerItem = {
- id,
- name: resolveLayerName(currentLayers),
- type,
- visible: true,
- opacity: 1,
- blendMode: type === 'folder' ? 'pass-through' : 'normal',
- locked: false,
- collapsed: false,
- parentId: initialParentId,
- thumbnailUrl: '',
- expressionColor:
- currentActiveLayer?.expressionColor === 'monochrome'
- ? 'monochrome'
- : currentActiveLayer?.expressionColor === 'gray'
- ? 'gray'
- : 'color',
- monoThreshold: currentActiveLayer?.monoThreshold ?? 128,
- monoExpressBlack: currentActiveLayer?.monoExpressBlack ?? true,
- monoExpressWhite: currentActiveLayer?.monoExpressWhite ?? true,
- };
-
- setLayers((prev) => {
- if (prev.some((l) => l.id === id)) return prev;
- const activeIdx = prev.findIndex((l) => l.id === activeLayerIdRef.current);
- const activeLayer = prev[activeIdx];
-
- let parentId: string | null = null;
- if (explicitParentId !== undefined) {
- parentId = explicitParentId;
- } else if (activeLayer) {
- parentId = isFolderLikeLayer(activeLayer) ? activeLayer.id : activeLayer.parentId;
- }
-
- const newLayer: LayerItem = {
- ...createdLayer,
- name: resolveLayerName(prev),
- parentId,
- };
-
- const insertIndex = activeIdx >= 0 ? activeIdx : 0;
- const nextLayers = [...prev];
- nextLayers.splice(insertIndex, 0, newLayer);
- layersRef.current = nextLayers;
- return nextLayers;
- });
-
- if (hasTileBackedLayer({ type })) {
- const grid = activeTileGridRef.current;
- const isMono = createdLayer.expressionColor === 'monochrome';
- grid.setLayerFormat(id, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.markLayerIngested(id);
- }
-
- if (selectNewLayer) {
- setActiveLayerId(id);
- }
- return createdLayer;
- },
- [setActiveLayerId]
- );
-
- // Add a layer that originated from a remote peer
- const addRemoteLayer = useCallback(
- (layerItem: LayerItem, initialDataUrl?: string) => {
- const grid = activeTileGridRef.current;
- const isMono = layerItem.expressionColor === 'monochrome';
- grid.setLayerFormat(layerItem.id, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.markLayerIngested(layerItem.id);
-
- if (initialDataUrl) {
- const img = new Image();
- img.onload = () => {
- const dims = dimensionsRef.current;
- const temp = document.createElement('canvas');
- temp.width = dims.width || img.naturalWidth || img.width;
- temp.height = dims.height || img.naturalHeight || img.height;
- const ctx = get2DContext(temp);
- if (ctx) {
- ctx.drawImage(img, 0, 0);
- grid.ingestCanvas(layerItem.id, temp, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
- const existing = layerCanvasesRef.current.get(layerItem.id);
- if (existing) {
- grid.renderLayerToCanvas(layerItem.id, existing);
- }
- updateLayerThumbnail(layerItem.id, true);
- }
- releaseTemporaryCanvas(temp);
- };
- img.src = initialDataUrl;
- }
-
- setLayers((prev) => {
- if (prev.some((l) => l.id === layerItem.id)) return prev;
- const next = [...prev];
- const bgIdx = next.findIndex((l) => isBackgroundLayerId(l.id));
- if (bgIdx >= 0) {
- next.splice(bgIdx, 0, layerItem);
- } else {
- next.push(layerItem);
- }
- return next;
- });
- },
- [updateLayerThumbnail]
- );
-
- // Delete a layer triggered remotely
- const deleteRemoteLayer = useCallback((layerId: string) => {
- setLayers((prev) => prev.filter((l) => l.id !== layerId));
- const timer = thumbDebounceTimersRef.current.get(layerId);
- if (timer) {
- clearTimeout(timer);
- thumbDebounceTimersRef.current.delete(layerId);
- }
- const display = layerCanvasesRef.current.get(layerId);
- if (display) releaseTemporaryCanvas(display);
- layerCanvasesRef.current.delete(layerId);
- const source = layerSourceCanvasesRef.current.get(layerId);
- if (source) releaseTemporaryCanvas(source);
- layerSourceCanvasesRef.current.delete(layerId);
- activeTileGridRef.current.clearLayer(layerId);
- }, []);
-
- // Sync entire document state from remote host
- const syncRemoteDocument = useCallback(
- (
- syncedLayers: LayerItem[],
- layerDataUrls: Record<string, string>,
- assignedLayerId?: string,
- targetDocumentId?: string,
- syncDims?: CanvasDimensions
- ) => {
- for (const timer of thumbDebounceTimersRef.current.values()) {
- clearTimeout(timer);
- }
- thumbDebounceTimersRef.current.clear();
-
- let grid = activeTileGridRef.current;
- if (targetDocumentId) {
- const session =
- documentStore.setActiveDocument(targetDocumentId) ??
- documentStore.getOrCreateSession(targetDocumentId);
- activeSessionIdRef.current = targetDocumentId;
- activeTileGridRef.current = session.tileGrid;
- layerCanvasesRef.current = session.layerCanvases;
- layerSourceCanvasesRef.current = session.layerSourceCanvases;
- grid = session.tileGrid;
- }
- if (syncDims) {
- dimensionsRef.current = syncDims;
- }
-
- grid.clearAll();
- pendingCanvasCopiesRef.current.clear();
- pendingInitialDataRef.current.clear();
- for (const c of layerCanvasesRef.current.values()) releaseTemporaryCanvas(c);
- layerCanvasesRef.current.clear();
- for (const c of layerSourceCanvasesRef.current.values()) releaseTemporaryCanvas(c);
- layerSourceCanvasesRef.current.clear();
-
- setLayers(syncedLayers);
- layersRef.current = syncedLayers;
-
- if (assignedLayerId && syncedLayers.some((l) => l.id === assignedLayerId)) {
- setActiveLayerId(assignedLayerId);
- } else {
- const topRaster = syncedLayers.find((l) => l.type === 'raster' && !isBackgroundLayerId(l.id));
- if (topRaster) {
- setActiveLayerId(topRaster.id);
- } else if (syncedLayers[0]) {
- setActiveLayerId(syncedLayers[0].id);
- }
- }
-
- // Load snapshot images directly into SparseTileGrid without holding duplicate full canvases
- syncedLayers.forEach((layer) => {
- const isMono = layer.expressionColor === 'monochrome';
- grid.setLayerFormat(layer.id, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.markLayerIngested(layer.id);
- const dataUrl = layerDataUrls[layer.id];
- if (dataUrl) {
- const img = new Image();
- img.onload = () => {
- const dims = dimensionsRef.current;
- const temp = document.createElement('canvas');
- temp.width = dims.width || img.naturalWidth || img.width;
- temp.height = dims.height || img.naturalHeight || img.height;
- const ctx = get2DContext(temp);
- if (ctx) {
- ctx.drawImage(img, 0, 0);
- grid.ingestCanvas(layer.id, temp, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
- const existing = layerCanvasesRef.current.get(layer.id);
- if (existing) {
- grid.renderLayerToCanvas(layer.id, existing);
- }
- updateLayerThumbnail(layer.id, true);
- }
- releaseTemporaryCanvas(temp);
- };
- img.src = dataUrl;
- }
- });
-
- grid.notifyChange(true);
- },
- [setActiveLayerId, updateLayerThumbnail]
- );
-
- // Duplicate an existing layer or folder hierarchy with a single click
- const duplicateLayer = useCallback((id: string) => {
- setLayers((prev) => {
- const sourceIdx = prev.findIndex((l) => l.id === id);
- if (sourceIdx < 0) return prev;
- const grid = activeTileGridRef.current;
-
- const cloneSingleLayer = (source: LayerItem, newParentId: string | null, nameSuffix: string = ' Copy'): LayerItem => {
- const newId = `${source.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
-
- if (hasTileBackedLayer(source)) {
- grid.cloneLayer(source.id, newId);
-
- const srcSource = layerSourceCanvasesRef.current.get(source.id);
- if (srcSource) {
- const newSource = document.createElement('canvas');
- newSource.width = srcSource.width;
- newSource.height = srcSource.height;
- get2DContext(newSource)?.drawImage(srcSource, 0, 0);
- layerSourceCanvasesRef.current.set(newId, newSource);
- }
- }
-
- let newMaskCanvas: HTMLCanvasElement | undefined;
- let newMaskThumb: string | undefined;
- if (source.maskCanvas) {
- newMaskCanvas = document.createElement('canvas');
- newMaskCanvas.width = source.maskCanvas.width;
- newMaskCanvas.height = source.maskCanvas.height;
- const mCtx = get2DContext(newMaskCanvas);
- if (mCtx) mCtx.drawImage(source.maskCanvas, 0, 0);
- newMaskThumb = source.maskThumbnailUrl;
- }
-
- return {
- ...source,
- id: newId,
- name: `${source.name}${nameSuffix}`,
- parentId: newParentId,
- thumbnailUrl: source.thumbnailUrl,
- maskCanvas: newMaskCanvas,
- maskThumbnailUrl: newMaskThumb,
- maskVersion: source.maskCanvas ? 1 : undefined,
- vectorStrokes: source.vectorStrokes ? JSON.parse(JSON.stringify(source.vectorStrokes)) : undefined,
- comicFrames: source.comicFrames ? JSON.parse(JSON.stringify(source.comicFrames)) : undefined,
- textData: source.textData ? JSON.parse(JSON.stringify(source.textData)) : undefined,
- balloonData: source.balloonData ? JSON.parse(JSON.stringify(source.balloonData)) : undefined,
- balloons: source.balloons ? JSON.parse(JSON.stringify(source.balloons)) : undefined,
- adjustmentData: source.adjustmentData ? JSON.parse(JSON.stringify(source.adjustmentData)) : undefined,
- styles: source.styles ? JSON.parse(JSON.stringify(source.styles)) : undefined,
- };
- };
-
- const source = prev[sourceIdx];
- if (!isFolderLikeLayer(source)) {
- const newLayer = cloneSingleLayer(source, source.parentId, ' Copy');
- const nextLayers = [...prev];
- nextLayers.splice(sourceIdx, 0, newLayer);
- setActiveLayerId(newLayer.id);
- return nextLayers;
- }
-
- // Recursively duplicate folder or frame-folder and all nested descendants in stack order
- const clonedItems: LayerItem[] = [];
- const cloneFolderSubtree = (folder: LayerItem, targetParentId: string | null, isRootFolder: boolean) => {
- const folderCopy = cloneSingleLayer(folder, targetParentId, isRootFolder ? ' Copy' : '');
- clonedItems.push(folderCopy);
- const directChildren = prev.filter((l) => l.parentId === folder.id);
- for (const child of directChildren) {
- if (isFolderLikeLayer(child)) {
- cloneFolderSubtree(child, folderCopy.id, false);
- } else {
- clonedItems.push(cloneSingleLayer(child, folderCopy.id, ' Copy'));
- }
- }
- };
-
- cloneFolderSubtree(source, source.parentId, true);
- const nextLayers = [...prev];
- nextLayers.splice(sourceIdx, 0, ...clonedItems);
- if (clonedItems[0]) {
- setActiveLayerId(clonedItems[0].id);
- }
- return nextLayers;
- });
- }, [setActiveLayerId]);
-
- // Delete a layer or folder (including nested folder hierarchies)
- const deleteLayer = useCallback((id: string) => {
- setLayers((prev) => {
- const res = computeBatchDeleteLayers(prev, [id], activeLayerIdRef.current);
- if (res.deletedIds.length === 0) return prev;
- const grid = activeTileGridRef.current;
-
- for (const delId of res.deletedIds) {
- const timer = thumbDebounceTimersRef.current.get(delId);
- if (timer) {
- clearTimeout(timer);
- thumbDebounceTimersRef.current.delete(delId);
- }
- const display = layerCanvasesRef.current.get(delId);
- if (display) releaseTemporaryCanvas(display);
- layerCanvasesRef.current.delete(delId);
-
- const source = layerSourceCanvasesRef.current.get(delId);
- if (source) releaseTemporaryCanvas(source);
- layerSourceCanvasesRef.current.delete(delId);
-
- const deletedLayer = prev.find((l) => l.id === delId);
- if (deletedLayer?.maskCanvas) {
- releaseTemporaryCanvas(deletedLayer.maskCanvas);
- }
-
- grid.clearLayer(delId);
- }
-
- if (res.deletedIds.includes(activeLayerIdRef.current)) {
- setActiveLayerId(res.nextActiveId);
- } else {
- setSelectedLayerIds((prevSelected) => prevSelected.filter((sid) => !res.deletedIds.includes(sid)));
- }
- return res.nextLayers;
- });
- }, [setActiveLayerId, setSelectedLayerIds]);
-
- // Delete all selected layers or folders
- const deleteSelectedLayers = useCallback(() => {
- setLayers((prev) => {
- const res = computeBatchDeleteLayers(prev, selectedLayerIdsRef.current, activeLayerIdRef.current);
- if (res.deletedIds.length === 0) return prev;
- const grid = activeTileGridRef.current;
-
- for (const delId of res.deletedIds) {
- const timer = thumbDebounceTimersRef.current.get(delId);
- if (timer) {
- clearTimeout(timer);
- thumbDebounceTimersRef.current.delete(delId);
- }
- const display = layerCanvasesRef.current.get(delId);
- if (display) releaseTemporaryCanvas(display);
- layerCanvasesRef.current.delete(delId);
-
- const source = layerSourceCanvasesRef.current.get(delId);
- if (source) releaseTemporaryCanvas(source);
- layerSourceCanvasesRef.current.delete(delId);
-
- const deletedLayer = prev.find((l) => l.id === delId);
- if (deletedLayer?.maskCanvas) {
- releaseTemporaryCanvas(deletedLayer.maskCanvas);
- }
-
- grid.clearLayer(delId);
- }
-
- setActiveLayerId(res.nextActiveId);
- return res.nextLayers;
- });
- }, [setActiveLayerId]);
-
- // Group all currently selected layers into a new folder
- const groupSelectedLayers = useCallback(() => {
- setLayers((prev) => {
- const res = computeGroupLayers(prev, selectedLayerIdsRef.current, activeLayerIdRef.current);
- if (!res) return prev;
-
- setActiveLayerId(res.newFolder.id);
- return res.nextLayers;
- });
- }, [setActiveLayerId]);
-
- // Toggle visibility of a layer or folder (batch toggle if part of multi-selection)
- const toggleVisibility = useCallback((id: string) => {
- setLayers((prev) => computeBatchVisibility(prev, selectedLayerIdsRef.current, id));
- }, []);
-
- // Set layer opacity (0.0 to 1.0)
- const setOpacity = useCallback((id: string, opacity: number) => {
- const clamped = Math.max(0, Math.min(1, opacity));
- setLayers((prev) =>
- prev.map((l) => (l.id === id ? { ...l, opacity: clamped } : l))
- );
- }, []);
-
- // Set layer blend mode
- const setBlendMode = useCallback((id: string, blendMode: BlendMode) => {
- setLayers((prev) =>
- prev.map((l) => (l.id === id ? { ...l, blendMode } : l))
- );
- }, []);
-
- // Toggle locked state (batch toggle if part of multi-selection)
- const toggleLock = useCallback((id: string) => {
- setLayers((prev) => computeBatchLock(prev, selectedLayerIdsRef.current, id));
- }, []);
-
- // Toggle folder collapse state
- const toggleCollapse = useCallback((id: string) => {
- setLayers((prev) =>
- prev.map((l) => (l.id === id ? { ...l, collapsed: !l.collapsed } : l))
- );
- }, []);
-
- // Toggle clipping mask state (Clip to Layer Below)
- const toggleClipping = useCallback((id: string) => {
- setLayers((prev) => {
- const idx = prev.findIndex((l) => l.id === id);
- if (idx === -1 || idx === prev.length - 1 || isBackgroundLayerId(id)) {
- return prev;
- }
- return prev.map((l) => (l.id === id ? { ...l, clipped: !l.clipped } : l));
- });
- }, []);
-
- // Toggle alpha locked state (Lock Transparent Pixels)
- const toggleAlphaLock = useCallback((id: string) => {
- setLayers((prev) =>
- prev.map((l) => (l.id === id ? { ...l, alphaLocked: !l.alphaLocked } : l))
- );
- }, []);
-
- // Add a non-destructive grayscale Layer Mask
- const addLayerMask = useCallback((layerId: string) => {
- setLayers((prev) =>
- prev.map((l) => {
- if (l.id !== layerId) return l;
- if (l.maskCanvas) return l; // Already has mask
-
- const mask = document.createElement('canvas');
- mask.width = _dimensions.width;
- mask.height = _dimensions.height;
- const mCtx = get2DContext(mask);
- if (mCtx) {
- mCtx.fillStyle = '#ffffff';
- mCtx.fillRect(0, 0, mask.width, mask.height);
- }
- const thumb = createCanvasThumbnail(mask, false);
- return {
- ...l,
- maskCanvas: mask,
- maskEnabled: true,
- maskLinked: true,
- maskThumbnailUrl: thumb,
- maskVersion: 1,
- };
- })
- );
- activeTileGridRef.current.notifyChange(true);
- }, [_dimensions]);
-
- // Remove or apply layer mask
- const removeLayerMask = useCallback(
- (layerId: string, apply: boolean = false) => {
- const grid = activeTileGridRef.current;
- setLayers((prev) =>
- prev.map((l) => {
- if (l.id !== layerId || !l.maskCanvas) return l;
-
- if (apply) {
- const hadCanvas = layerCanvasesRef.current.has(layerId);
- const c = hadCanvas ? layerCanvasesRef.current.get(layerId)! : materializeLayerCanvas(layerId);
- if (c) {
- const ctx = get2DContext(c);
- const mCtx = get2DContext(l.maskCanvas);
- if (ctx && mCtx) {
- const imgData = ctx.getImageData(0, 0, c.width, c.height);
- const maskData = mCtx.getImageData(0, 0, c.width, c.height).data;
- const d = imgData.data;
- for (let i = 0; i < d.length; i += 4) {
- if (d[i + 3] === 0) continue;
- const maskLum =
- ((0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255) *
- (maskData[i + 3] / 255);
- d[i + 3] = Math.round(d[i + 3] * maskLum);
- }
- ctx.putImageData(imgData, 0, 0);
-
- const sCanvas = layerSourceCanvasesRef.current.get(layerId);
- if (sCanvas) {
- const sCtx = get2DContext(sCanvas);
- if (sCtx) {
- const sData = sCtx.getImageData(0, 0, sCanvas.width, sCanvas.height);
- const sd = sData.data;
- for (let i = 0; i < sd.length; i += 4) {
- if (sd[i + 3] === 0) continue;
- const maskLum =
- ((0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255) *
- (maskData[i + 3] / 255);
- sd[i + 3] = Math.round(sd[i + 3] * maskLum);
- }
- sCtx.putImageData(sData, 0, 0);
- }
- }
-
- const isMono = l.expressionColor === 'monochrome';
- grid.ingestCanvas(layerId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
- updateLayerThumbnail(layerId, true);
- }
- if (!hadCanvas) {
- releaseLayerCanvas(layerId);
- }
- }
- }
-
- releaseTemporaryCanvas(l.maskCanvas);
-
- return {
- ...l,
- maskCanvas: undefined,
- maskEnabled: undefined,
- maskLinked: undefined,
- maskThumbnailUrl: undefined,
- maskVersion: undefined,
- };
- })
- );
- grid.notifyChange(true);
- },
- [materializeLayerCanvas, releaseLayerCanvas, updateLayerThumbnail]
- );
-
- // Toggle layer mask enabled state
- const toggleLayerMask = useCallback((layerId: string) => {
- setLayers((prev) =>
- prev.map((l) => (l.id === layerId ? { ...l, maskEnabled: !l.maskEnabled } : l))
- );
- activeTileGridRef.current.notifyChange(true);
- }, []);
-
- // Toggle mask linked state
- const toggleMaskLinked = useCallback((layerId: string) => {
- setLayers((prev) =>
- prev.map((l) => (l.id === layerId ? { ...l, maskLinked: !l.maskLinked } : l))
- );
- }, []);
-
- // Update mask thumbnail
- const updateMaskThumbnail = useCallback((layerId: string, immediate: boolean = false) => {
- const run = () => {
- const target = layersRef.current.find((l) => l.id === layerId);
- if (!target?.maskCanvas) return;
- const thumb = createCanvasThumbnail(target.maskCanvas, false);
- setLayers((prev) =>
- prev.map((l) =>
- l.id === layerId
- ? { ...l, maskThumbnailUrl: thumb, maskVersion: (l.maskVersion || 0) + 1 }
- : l
- )
- );
- activeTileGridRef.current.notifyChange(true);
- };
-
- if (immediate) {
- run();
- } else {
- setTimeout(run, 150);
- }
- }, []);
-
- // Add non-destructive adjustment layer
- const addAdjustmentLayer = useCallback(
- (
- type: 'curves' | 'gradient-map' | 'levels' | 'color-balance',
- customData?: AdjustmentLayerData
- ): LayerItem => {
- let createdLayer: LayerItem | null = null;
- const id = `adjustment-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
-
- let defaultData: AdjustmentLayerData;
- let layerName: string;
-
- switch (type) {
- case 'curves':
- layerName = 'Curves 1';
- defaultData = customData || {
- type: 'curves',
- curves: {
- rgb: [[0, 0], [255, 255]],
- r: [[0, 0], [255, 255]],
- g: [[0, 0], [255, 255]],
- b: [[0, 0], [255, 255]],
- },
- };
- break;
- case 'gradient-map':
- layerName = 'Gradient Map 1';
- defaultData = customData || {
- type: 'gradient-map',
- stops: [
- { position: 0, color: '#000000' },
- { position: 1, color: '#ffffff' },
- ],
- interpolation: 'smooth',
- };
- break;
- case 'levels':
- layerName = 'Levels 1';
- defaultData = customData || {
- type: 'levels',
- blackPoint: 0,
- gamma: 1.0,
- whitePoint: 255,
- outputMin: 0,
- outputMax: 255,
- channel: 'rgb',
- };
- break;
- case 'color-balance':
- layerName = 'Color Balance 1';
- defaultData = customData || {
- type: 'color-balance',
- shadows: [0, 0, 0],
- midtones: [0, 0, 0],
- highlights: [0, 0, 0],
- preserveLuminosity: true,
- };
- break;
- }
-
- setLayers((prev) => {
- const activeIdx = prev.findIndex((l) => l.id === activeLayerId);
- const activeLayer = prev[activeIdx];
- const parentId = activeLayer ? (activeLayer.type === 'folder' ? activeLayer.id : activeLayer.parentId) : null;
-
- let count = 1;
- const base = layerName.replace(/ \d+$/, '');
- prev.forEach((l) => {
- if (l.name.startsWith(base)) {
- const num = parseInt(l.name.replace(`${base} `, ''), 10);
- if (!isNaN(num) && num >= count) count = num + 1;
- }
- });
- const name = `${base} ${count}`;
-
- const newLayer: LayerItem = {
- id,
- name,
- type: 'adjustment',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: false,
- collapsed: false,
- parentId,
- adjustmentData: defaultData,
- };
- createdLayer = newLayer;
-
- const insertIndex = activeIdx >= 0 ? activeIdx : 0;
- const next = [...prev];
- next.splice(insertIndex, 0, newLayer);
- return next;
- });
-
- setActiveLayerId(id);
- activeTileGridRef.current.notifyChange(true);
- return createdLayer!;
- },
- [activeLayerId, setActiveLayerId]
- );
-
- // Update adjustment layer data
- const updateAdjustmentData = useCallback((layerId: string, data: AdjustmentLayerData) => {
- setLayers((prev) =>
- prev.map((l) => (l.id === layerId ? { ...l, adjustmentData: data } : l))
- );
- activeTileGridRef.current.notifyChange(true);
- }, []);
-
- // Ensure offscreen source canvas exists for non-destructive operations
- const ensureSourceCanvas = useCallback(
- (id: string, copyFromDisplay = true, forceCopy = false) => {
- let sourceCanvas = layerSourceCanvasesRef.current.get(id);
- const displayCanvas = layerCanvasesRef.current.get(id);
- const targetW = displayCanvas?.width || dimensionsRef.current.width;
- const targetH = displayCanvas?.height || dimensionsRef.current.height;
- const grid = activeTileGridRef.current;
-
- if (!sourceCanvas) {
- sourceCanvas = document.createElement('canvas');
- sourceCanvas.width = targetW;
- sourceCanvas.height = targetH;
- if (copyFromDisplay) {
- if (displayCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.drawImage(displayCanvas, 0, 0);
- } else if (grid.hasLayerTiles(id)) {
- grid.renderLayerToCanvas(id, sourceCanvas);
- }
- }
- layerSourceCanvasesRef.current.set(id, sourceCanvas);
- } else {
- const sizeMismatch = sourceCanvas.width !== targetW || sourceCanvas.height !== targetH;
- if (sizeMismatch) {
- sourceCanvas.width = targetW;
- sourceCanvas.height = targetH;
- }
- if (forceCopy || (copyFromDisplay && sizeMismatch)) {
- if (displayCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- sCtx.clearRect(0, 0, targetW, targetH);
- sCtx.drawImage(displayCanvas, 0, 0);
- }
- } else if (grid.hasLayerTiles(id)) {
- grid.renderLayerToCanvas(id, sourceCanvas);
- }
- }
- }
- return sourceCanvas;
- },
- []
- );
-
- const pendingEffectRendersRef = useRef<Map<string, { layer: LayerItem; dirtyRect?: DirtyRect }>>(new Map());
- const effectRafIdRef = useRef<number | null>(null);
-
- const scheduleLayerEffectRender = useCallback((layer: LayerItem, dirtyRect?: DirtyRect) => {
- pendingEffectRendersRef.current.set(layer.id, { layer, dirtyRect });
- if (effectRafIdRef.current === null) {
- effectRafIdRef.current = requestAnimationFrame(() => {
- effectRafIdRef.current = null;
- const queue = new Map(pendingEffectRendersRef.current);
- pendingEffectRendersRef.current.clear();
- const grid = activeTileGridRef.current;
-
- queue.forEach(({ layer: l, dirtyRect: rect }, id) => {
- const sourceCanvas = ensureSourceCanvas(id, true, false);
- const displayCanvas = materializeLayerCanvas(id);
- if (sourceCanvas && displayCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, l, dimensionsRef.current.dpi ?? 600, rect);
- const isMono = l.expressionColor === 'monochrome';
- grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
- updateLayerThumbnail(id, false);
- }
- });
- });
- }
- }, [ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]);
-
- useEffect(() => {
- return () => {
- if (effectRafIdRef.current !== null) {
- cancelAnimationFrame(effectRafIdRef.current);
- effectRafIdRef.current = null;
- }
- };
- }, []);
-
- // Toggle non-destructive Clip Studio Paint style screentone effect on a layer
- // Toggle non-destructive Clip Studio Paint style screentone effect on a layer
- const toggleTone = useCallback((id: string) => {
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const newEnabled = !target.toneEnabled;
- const freq = target.toneFrequency ?? defaultToneFrequencyRef.current ?? 60;
- const angle = target.toneAngle ?? 45;
- const shape = target.toneDotShape ?? 'circle';
- const density = target.toneDensity ?? 40;
- const densityType = target.toneDensityType ?? 'specified';
-
- const updatedLayer: LayerItem = {
- ...target,
- toneEnabled: newEnabled,
- toneFrequency: freq,
- toneAngle: angle,
- toneDotShape: shape,
- toneDensity: density,
- toneDensityType: densityType,
- };
-
- const displayCanvas = materializeLayerCanvas(id);
- const grid = activeTileGridRef.current;
- if (displayCanvas) {
- if (newEnabled) {
- // Initialize sourceCanvas only if not already present; never force-overwrite existing continuous-tone source
- const sourceCanvas = ensureSourceCanvas(id, true, false);
- if (sourceCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
- }
- } else {
- // Turning off tone: restore continuous raster from sourceCanvas
- let sourceCanvas = layerSourceCanvasesRef.current.get(id);
- if (!sourceCanvas) {
- sourceCanvas = ensureSourceCanvas(id, true, false);
- }
- if (sourceCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
- }
- }
- const isMono = updatedLayer.expressionColor === 'monochrome';
- grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
- updateLayerThumbnail(id, true);
- }
-
- let nextLayers = prev.map((l) => (l.id === id ? updatedLayer : l));
-
- // If turning ON and there is no background layer in the document, create one
- // so screentone transparent holes render against clean white paper instead of dark checkerboard
- const hasBg = prev.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');
- if (newEnabled && !hasBg) {
- const bgId = `layer-bg-${Date.now()}`;
- const dims = dimensionsRef.current;
- grid.fillLayerSolidWhite(bgId, dims.width, dims.height, 'color-32bit');
- const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: dims }, false);
- const bgLayer: LayerItem = {
- id: bgId,
- name: 'Background',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: true,
- parentId: null,
- thumbnailUrl: bgThumb,
- };
- nextLayers = [...nextLayers, bgLayer];
- }
-
- return nextLayers;
- });
- }, [ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]);
-
- // Update screentone frequency (Lines / LPI, 20 to 85)
- const setToneFrequency = useCallback((id: string, frequency: number) => {
- const clampedFreq = Math.max(20, Math.min(85, Math.round(frequency)));
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = { ...target, toneFrequency: clampedFreq };
- if (target.toneEnabled) {
- scheduleLayerEffectRender(updatedLayer);
- }
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [scheduleLayerEffectRender]);
-
- // Update screentone angle (0 to 90 degrees)
- const setToneAngle = useCallback((id: string, angle: number) => {
- const clampedAngle = Math.max(0, Math.min(90, Math.round(angle)));
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = { ...target, toneAngle: clampedAngle };
- if (target.toneEnabled) {
- scheduleLayerEffectRender(updatedLayer);
- }
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [scheduleLayerEffectRender]);
-
- // Update screentone dot shape (default: circle)
- const setToneDotShape = useCallback((id: string, dotShape: HalftoneDotShape) => {
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = { ...target, toneDotShape: dotShape };
- if (target.toneEnabled) {
- scheduleLayerEffectRender(updatedLayer);
- }
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [scheduleLayerEffectRender]);
-
- // Update screentone density (1 to 100%)
- const setToneDensity = useCallback((id: string, density: number) => {
- const clampedDensity = Math.max(1, Math.min(100, Math.round(density)));
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = { ...target, toneDensity: clampedDensity };
- if (target.toneEnabled) {
- scheduleLayerEffectRender(updatedLayer);
- }
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [scheduleLayerEffectRender]);
-
- // Update screentone density mode ('specified' vs 'image')
- const setToneDensityType = useCallback((id: string, densityType: 'specified' | 'image') => {
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = { ...target, toneDensityType: densityType };
- if (target.toneEnabled) {
- scheduleLayerEffectRender(updatedLayer);
- }
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [scheduleLayerEffectRender]);
-
- // Toggle Clip Studio Paint style Layer Color (Tint) effect on a layer
- const toggleLayerColor = useCallback((id: string) => {
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const newEnabled = !target.layerColorEnabled;
- const layerColor = target.layerColor || '#1c73c2';
- const layerSubColor = target.layerSubColor || '#ffffff';
-
- const updatedLayer: LayerItem = {
- ...target,
- layerColorEnabled: newEnabled,
- layerColor,
- layerSubColor,
- };
-
- const displayCanvas = materializeLayerCanvas(id);
- if (displayCanvas) {
- const sourceCanvas = ensureSourceCanvas(id, true, false);
- if (sourceCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
- }
- const grid = activeTileGridRef.current;
- const isMono = updatedLayer.expressionColor === 'monochrome';
- grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
- updateLayerThumbnail(id, true);
- }
-
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]);
-
- // Update Layer Color (Tint primary color)
- const setLayerColor = useCallback((id: string, color: string) => {
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = {
- ...target,
- layerColor: color,
- };
- if (target.layerColorEnabled) {
- scheduleLayerEffectRender(updatedLayer);
- }
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [scheduleLayerEffectRender]);
-
- // Update Layer Sub Color (Tint secondary color)
- const setLayerSubColor = useCallback((id: string, color: string) => {
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = {
- ...target,
- layerSubColor: color,
- };
- if (target.layerColorEnabled) {
- scheduleLayerEffectRender(updatedLayer);
- }
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [scheduleLayerEffectRender]);
-
- // Update Expression Color ('color' | 'gray' | 'monochrome')
- const setLayerExpressionColor = useCallback((id: string, mode: ExpressionColor) => {
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = {
- ...target,
- expressionColor: mode,
- monoThreshold: target.monoThreshold ?? 128,
- monoExpressBlack: target.monoExpressBlack ?? true,
- monoExpressWhite: target.monoExpressWhite ?? true,
- };
-
- const displayCanvas = materializeLayerCanvas(id);
- if (displayCanvas) {
- const sourceCanvas = ensureSourceCanvas(id, true, false);
- if (sourceCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
- }
- const grid = activeTileGridRef.current;
- const isMono = updatedLayer.expressionColor === 'monochrome';
- grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
- updateLayerThumbnail(id, true);
- }
-
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]);
-
- // Update Monochrome Color threshold (1 - 255)
- const setLayerMonoThreshold = useCallback((id: string, threshold: number) => {
- const clamped = Math.max(1, Math.min(255, Math.round(threshold)));
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = {
- ...target,
- monoThreshold: clamped,
- };
- if (target.expressionColor === 'monochrome') {
- scheduleLayerEffectRender(updatedLayer);
- }
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [scheduleLayerEffectRender]);
-
- // Update Monochrome Express Colors (express black, express white)
- const setLayerMonoExpressMode = useCallback((id: string, expressBlack: boolean, expressWhite: boolean) => {
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || target.type === 'folder') return prev;
-
- const updatedLayer: LayerItem = {
- ...target,
- monoExpressBlack: expressBlack,
- monoExpressWhite: expressWhite,
- };
- if (target.expressionColor === 'monochrome') {
- scheduleLayerEffectRender(updatedLayer);
- }
- return prev.map((l) => (l.id === id ? updatedLayer : l));
- });
- }, [scheduleLayerEffectRender]);
-
- // Apply previewed expression color permanently into layer pixel buffer
- const applyExpressionColorOfPreview = useCallback(
- (id: string): { beforeImageData: ImageData | null; afterImageData: ImageData | null } | null => {
- const target = layers.find((l) => l.id === id);
- if (!target || target.type === 'folder') return null;
-
- const displayCanvas = materializeLayerCanvas(id);
- let sourceCanvas = layerSourceCanvasesRef.current.get(id);
- if (!displayCanvas) return null;
-
- if (!sourceCanvas) {
- sourceCanvas = ensureSourceCanvas(id, true, true);
- }
-
- const sCtx = sourceCanvas ? get2DContext(sourceCanvas) : null;
- const dCtx = get2DContext(displayCanvas);
- if (!sCtx || !dCtx) return null;
-
- const beforeImageData = sCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
- const afterImageData = dCtx.getImageData(0, 0, displayCanvas.width, displayCanvas.height);
-
- // Bake displayCanvas into sourceCanvas permanently
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- sCtx.drawImage(displayCanvas, 0, 0);
-
- const grid = activeTileGridRef.current;
- const isMono = target.expressionColor === 'monochrome';
- grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
- updateLayerThumbnail(id, true);
-
- return { beforeImageData, afterImageData };
- },
- [layers, ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]
- );
-
- // Apply layer color tint permanently into layer pixel buffer
- const applyLayerColorPermanently = useCallback(
- (id: string): { beforeImageData: ImageData | null; afterImageData: ImageData | null } | null => {
- const target = layers.find((l) => l.id === id);
- if (!target || target.type === 'folder' || !target.layerColorEnabled) return null;
-
- const displayCanvas = materializeLayerCanvas(id);
- let sourceCanvas = layerSourceCanvasesRef.current.get(id);
- if (!displayCanvas) return null;
-
- if (!sourceCanvas) {
- sourceCanvas = ensureSourceCanvas(id, true, true);
- }
-
- const sCtx = sourceCanvas ? get2DContext(sourceCanvas) : null;
- const dCtx = get2DContext(displayCanvas);
- if (!sCtx || !dCtx) return null;
-
- const beforeImageData = sCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
- const afterImageData = dCtx.getImageData(0, 0, displayCanvas.width, displayCanvas.height);
-
- // Bake displayCanvas into sourceCanvas permanently and turn off layerColorEnabled
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- sCtx.drawImage(displayCanvas, 0, 0);
-
- setLayers((prev) =>
- prev.map((l) => (l.id === id ? { ...l, layerColorEnabled: false } : l))
- );
-
- const grid = activeTileGridRef.current;
- const isMono = target.expressionColor === 'monochrome';
- grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
- updateLayerThumbnail(id, true);
-
- return { beforeImageData, afterImageData };
- },
- [layers, ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]
- );
-
- // Direct permanent conversion of any layer (including imported image) to Color, Gray, or Monochrome
- const convertLayer = useCallback(
- (
- id: string,
- targetMode: ExpressionColor,
- options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }
- ): { beforeImageData: ImageData | null; afterImageData: ImageData | null } | null => {
- const target = layers.find((l) => l.id === id);
- if (!target || target.type === 'folder') return null;
-
- const displayCanvas = materializeLayerCanvas(id);
- if (!displayCanvas) return null;
-
- const sourceCanvas = ensureSourceCanvas(id, true, false);
- if (!sourceCanvas) return null;
-
- const sCtx = get2DContext(sourceCanvas);
- const dCtx = get2DContext(displayCanvas);
- if (!sCtx || !dCtx) return null;
-
- const beforeImageData = sCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
-
- const updatedLayer: LayerItem = {
- ...target,
- expressionColor: targetMode,
- monoThreshold: options?.threshold ?? target.monoThreshold ?? 128,
- monoExpressBlack: options?.expressBlack ?? target.monoExpressBlack ?? true,
- monoExpressWhite: options?.expressWhite ?? target.monoExpressWhite ?? true,
- };
-
- if (updatedLayer.toneEnabled) {
- // If tone is enabled, apply expression color to sourceCanvas directly, then update displayCanvas
- const sData = sCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
- applyExpressionColorToImageData(sData, targetMode, options);
- sCtx.putImageData(sData, 0, 0);
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
- } else {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- sCtx.drawImage(displayCanvas, 0, 0);
- }
-
- const afterImageData = dCtx.getImageData(0, 0, displayCanvas.width, displayCanvas.height);
-
- const grid = activeTileGridRef.current;
- const isMono = targetMode === 'monochrome';
- grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
- setLayers((prev) => prev.map((l) => (l.id === id ? updatedLayer : l)));
- updateLayerThumbnail(id, true);
-
- return { beforeImageData, afterImageData };
- },
- [layers, ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]
- );
-
- // Rename a layer
- const renameLayer = useCallback((id: string, newName: string) => {
- if (!newName.trim()) return;
- setLayers((prev) =>
- prev.map((l) => (l.id === id ? { ...l, name: newName.trim() } : l))
- );
- }, []);
-
- // Move layer up or down in visual stack
- const moveLayer = useCallback((id: string, direction: 'up' | 'down') => {
- setLayers((prev) => {
- const idx = prev.findIndex((l) => l.id === id);
- if (idx < 0) return prev;
-
- const targetIdx = direction === 'up' ? idx - 1 : idx + 1;
- if (targetIdx < 0 || targetIdx >= prev.length) return prev;
-
- const next = [...prev];
- const [item] = next.splice(idx, 1);
- next.splice(targetIdx, 0, item);
- return next;
- });
- }, []);
-
- // Move layer into a specific folder or to root
- const moveLayerToFolder = useCallback((id: string, targetFolderId: string | null) => {
- setLayers((prev) => {
- const item = prev.find((l) => l.id === id);
- if (!item || item.id === targetFolderId) return prev;
-
- // If moving a folder into itself, ignore
- if (isFolderLikeLayer(item) && targetFolderId) {
- let curr: LayerItem | undefined = prev.find((l) => l.id === targetFolderId);
- while (curr) {
- if (curr.id === id) return prev;
- curr = prev.find((l) => l.id === curr?.parentId);
- }
- }
-
- return prev.map((l) => (l.id === id ? { ...l, parentId: targetFolderId } : l));
- });
- }, []);
-
- // Reorder layer via drag-and-drop (supports multi-layer selection)
- const reorderLayers = useCallback((draggedId: string, targetId: string, position: 'above' | 'below' | 'inside') => {
- setLayers((prev) => computeBatchReorderLayers(prev, selectedLayerIdsRef.current, draggedId, targetId, position));
- }, []);
-
- // Move selected layers into a target parent folder or index
- const moveSelectedLayers = useCallback((targetParentId: string | null, targetIndex?: number) => {
- setLayers((prev) => {
- const selectedIds = selectedLayerIdsRef.current.length > 0
- ? selectedLayerIdsRef.current
- : activeLayerIdRef.current ? [activeLayerIdRef.current] : [];
- if (selectedIds.length === 0) return prev;
-
- const getDescendantIds = (parentId: string): string[] => {
- const ids: string[] = [];
- for (const item of prev) {
- if (item.parentId === parentId) {
- ids.push(item.id);
- ids.push(...getDescendantIds(item.id));
- }
- }
- return ids;
- };
-
- const movingIds = new Set<string>();
- for (const id of selectedIds) {
- movingIds.add(id);
- const item = prev.find((l) => l.id === id);
- if (isFolderLikeLayer(item)) {
- getDescendantIds(id).forEach((descId) => movingIds.add(descId));
- }
- }
-
- if (targetParentId && movingIds.has(targetParentId)) return prev;
-
- const movingItems = prev
- .filter((l) => movingIds.has(l.id))
- .map((l) => {
- if (!l.parentId || !movingIds.has(l.parentId)) {
- return { ...l, parentId: targetParentId };
- }
- return l;
- });
-
- const remaining = prev.filter((l) => !movingIds.has(l.id));
-
- let insertIdx = remaining.length;
- if (typeof targetIndex === 'number') {
- insertIdx = Math.max(0, Math.min(remaining.length, targetIndex));
- } else if (targetParentId) {
- const parentIdx = remaining.findIndex((l) => l.id === targetParentId);
- insertIdx = parentIdx >= 0 ? parentIdx + 1 : remaining.length;
- }
-
- remaining.splice(insertIdx, 0, ...movingItems);
- return remaining;
- });
- }, []);
-
- // Calculate effective opacity accounting for parent folders
- const getEffectiveOpacity = useCallback((layer: LayerItem): number => {
- if (!layer.parentId) return layer.opacity;
- const parent = layers.find((l) => l.id === layer.parentId);
- if (!parent) return layer.opacity;
- return layer.opacity * getEffectiveOpacity(parent);
- }, [layers]);
-
- // Check if layer is visible accounting for parent folders
- const isLayerEffectivelyVisible = useCallback((layer: LayerItem): boolean => {
- if (!layer.visible) return false;
- if (!layer.parentId) return true;
- const parent = layers.find((l) => l.id === layer.parentId);
- if (!parent) return true;
- return isLayerEffectivelyVisible(parent);
- }, [layers]);
-
- // Clear active layer content directly in SparseTileGrid (zero forced full canvas allocation)
- const clearActiveLayer = useCallback(() => {
- const grid = activeTileGridRef.current;
- const dims = dimensionsRef.current;
- const isBg = isBackgroundLayerId(activeLayerId);
-
- if (isBg) {
- grid.fillLayerSolidWhite(activeLayerId, dims.width, dims.height, 'color-32bit');
- } else {
- grid.clearLayer(activeLayerId);
- grid.markLayerIngested(activeLayerId);
- }
-
- const canvas = layerCanvasesRef.current.get(activeLayerId);
- if (canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- if (isBg) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- (canvas as any).__isSolidWhite = true;
- } else {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- (canvas as any).__isBlank = true;
- }
- }
- }
-
- const sCanvas = layerSourceCanvasesRef.current.get(activeLayerId);
- if (sCanvas) {
- const sCtx = get2DContext(sCanvas);
- if (sCtx) {
- if (isBg) {
- sCtx.fillStyle = '#ffffff';
- sCtx.fillRect(0, 0, sCanvas.width, sCanvas.height);
- } else {
- sCtx.clearRect(0, 0, sCanvas.width, sCanvas.height);
- }
- }
- }
-
- grid.notifyChange(true);
- updateLayerThumbnail(activeLayerId);
- }, [activeLayerId, updateLayerThumbnail]);
-
- // Merge active raster layer down onto the raster layer directly below it
- const mergeDown = useCallback(
- (targetLayerId?: string): { targetId: string; removedId: string } | null => {
- const currentLayers = layersRef.current;
- const srcId = targetLayerId || activeLayerId;
- const srcIdx = currentLayers.findIndex((l) => l.id === srcId);
- if (srcIdx < 0) return null;
-
- const srcLayer = currentLayers[srcIdx];
- if (!srcLayer || srcLayer.type !== 'raster' || srcLayer.locked) return null;
-
- // Find the next raster layer below (higher index in top-to-bottom stack)
- let dstIdx = -1;
- for (let i = srcIdx + 1; i < currentLayers.length; i++) {
- if (currentLayers[i].type === 'raster') {
- dstIdx = i;
- break;
- }
- }
- if (dstIdx < 0) return null;
- const dstLayer = currentLayers[dstIdx];
- if (dstLayer.locked) return null;
-
- const srcCanvas = materializeLayerCanvas(srcLayer.id);
- const dstCanvas = materializeLayerCanvas(dstLayer.id);
- if (!srcCanvas || !dstCanvas) return null;
-
- const dstCtx = get2DContext(dstCanvas);
- if (!dstCtx) return null;
-
- // Composite upper layer (respecting mask if present and enabled)
- let drawSource: HTMLCanvasElement = srcCanvas;
- let tempMasked: HTMLCanvasElement | null = null;
- if (srcLayer.maskCanvas && srcLayer.maskEnabled !== false) {
- tempMasked = document.createElement('canvas');
- tempMasked.width = srcCanvas.width;
- tempMasked.height = srcCanvas.height;
- const tCtx = get2DContext(tempMasked);
- if (tCtx) {
- tCtx.drawImage(srcCanvas, 0, 0);
- tCtx.globalCompositeOperation = 'destination-in';
- tCtx.drawImage(srcLayer.maskCanvas, 0, 0);
- drawSource = tempMasked;
- }
- }
-
- dstCtx.save();
- dstCtx.globalAlpha = srcLayer.visible ? Math.max(0, Math.min(1, srcLayer.opacity)) : 0;
- dstCtx.globalCompositeOperation = getCanvasCompositeOperation(srcLayer.blendMode);
- dstCtx.drawImage(drawSource, 0, 0);
- dstCtx.restore();
-
- if (tempMasked) {
- releaseTemporaryCanvas(tempMasked);
- }
-
- // Sync destination canvas back into SparseTileGrid & remove source layer
- const grid = activeTileGridRef.current;
- const dstData = dstCtx.getImageData(0, 0, dstCanvas.width, dstCanvas.height);
- grid.writeImageData(dstLayer.id, dstData, 0, 0, 'color-32bit');
- grid.clearLayer(srcLayer.id);
- layerCanvasesRef.current.delete(srcLayer.id);
- layerSourceCanvasesRef.current.delete(srcLayer.id);
- layerSourceCanvasesRef.current.delete(dstLayer.id);
- (dstCanvas as unknown as { __isBlank?: boolean }).__isBlank = false;
-
- const nextLayers = currentLayers.filter((l) => l.id !== srcLayer.id);
- layersRef.current = nextLayers;
- setLayers(nextLayers);
- setActiveLayerId(dstLayer.id);
- setSelectedLayerIds([dstLayer.id]);
-
- grid.notifyChange(true);
- updateLayerThumbnail(dstLayer.id);
- return { targetId: dstLayer.id, removedId: srcLayer.id };
- },
- [activeLayerId, materializeLayerCanvas, setActiveLayerId, updateLayerThumbnail]
- );
-
- // Switch active document tab in O(1): binds session's SparseTileGrid without clearing or re-slicing
- const switchDocumentSession = useCallback(
- (documentId: string, nextLayers: LayerItem[], nextActiveLayerId: string, nextDims?: CanvasDimensions) => {
- for (const timer of thumbDebounceTimersRef.current.values()) {
- clearTimeout(timer);
- }
- thumbDebounceTimersRef.current.clear();
-
- const session = documentStore.setActiveDocument(documentId) ?? documentStore.getOrCreateSession(documentId);
- activeSessionIdRef.current = documentId;
- activeTileGridRef.current = session.tileGrid;
- layerCanvasesRef.current = session.layerCanvases;
- layerSourceCanvasesRef.current = session.layerSourceCanvases;
- if (nextDims) {
- dimensionsRef.current = nextDims;
- }
-
- pendingCanvasCopiesRef.current.clear();
- pendingInitialDataRef.current.clear();
-
- setLayers(nextLayers);
- layersRef.current = nextLayers;
- const resolvedActiveId =
- nextActiveLayerId && nextLayers.some((l) => l.id === nextActiveLayerId)
- ? nextActiveLayerId
- : (nextLayers.find((l) => l.type === 'raster')?.id || nextLayers[0]?.id || '');
- setActiveLayerId(resolvedActiveId);
- session.tileGrid.notifyChange(true);
- },
- [setActiveLayerId]
- );
-
- // Reset layers to a fresh canvas with specified background color (allocated directly in SparseTileGrid)
- const resetToNewCanvas = useCallback(
- (
- _dims: CanvasDimensions,
- backgroundColor: string = '#ffffff',
- _mode: CanvasColorMode = 'color',
- defaultToneFrequency: number = 60,
- targetDocumentId?: string
- ) => {
- defaultToneFrequencyRef.current = Math.max(20, Math.min(85, Math.round(defaultToneFrequency || 60)));
- dimensionsRef.current = _dims;
-
- for (const timer of thumbDebounceTimersRef.current.values()) {
- clearTimeout(timer);
- }
- thumbDebounceTimersRef.current.clear();
-
- let grid = activeTileGridRef.current;
- if (targetDocumentId) {
- const session = documentStore.setActiveDocument(targetDocumentId) ?? documentStore.getOrCreateSession(targetDocumentId);
- activeSessionIdRef.current = targetDocumentId;
- activeTileGridRef.current = session.tileGrid;
- layerCanvasesRef.current = session.layerCanvases;
- layerSourceCanvasesRef.current = session.layerSourceCanvases;
- grid = session.tileGrid;
- }
-
- grid.clearAll();
- pendingCanvasCopiesRef.current.clear();
- pendingInitialDataRef.current.clear();
- for (const c of layerCanvasesRef.current.values()) releaseTemporaryCanvas(c);
- layerCanvasesRef.current.clear();
- for (const c of layerSourceCanvasesRef.current.values()) releaseTemporaryCanvas(c);
- layerSourceCanvasesRef.current.clear();
-
- const now = Date.now();
- const bgId = `layer-bg-${now}`;
- const topId = `layer-1-${now}`;
-
- // Initialize background directly in SparseTileGrid without creating full-size HTMLCanvasElement
- if (backgroundColor !== 'transparent') {
- grid.fillLayerSolidColor(bgId, _dims.width, _dims.height, backgroundColor, 'color-32bit');
- } else {
- grid.setLayerFormat(bgId, 'color-32bit');
- grid.markLayerIngested(bgId);
- }
-
- // Empty top layer: 0 tiles, 0 HTMLCanvasElement allocated
- const topFormat = _mode === 'monochrome' ? 'monochrome-1bit' : 'color-32bit';
- grid.setLayerFormat(topId, topFormat);
- grid.markLayerIngested(topId);
-
- const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: _dims }, false);
-
- const initialLayers: LayerItem[] = [
- {
- id: topId,
- name: 'Layer 1',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: false,
- parentId: null,
- thumbnailUrl: '',
- toneFrequency: defaultToneFrequencyRef.current,
- expressionColor: _mode === 'monochrome' ? 'monochrome' : _mode === 'grayscale' ? 'gray' : 'color',
- monoThreshold: 128,
- monoExpressBlack: true,
- monoExpressWhite: true,
- },
- {
- id: bgId,
- name: 'Background',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: true,
- parentId: null,
- thumbnailUrl: bgThumb,
- },
- ];
-
- setLayers(initialLayers);
- layersRef.current = initialLayers;
- setActiveLayerId(topId);
- grid.notifyChange(true);
- return { layers: initialLayers, activeLayerId: topId };
- },
- [setActiveLayerId]
- );
-
- // Clear all layers and canvas references when no document is active
- const clearDocument = useCallback(() => {
- for (const timer of thumbDebounceTimersRef.current.values()) {
- clearTimeout(timer);
- }
- thumbDebounceTimersRef.current.clear();
- pendingCanvasCopiesRef.current.clear();
- pendingInitialDataRef.current.clear();
- setLayers([]);
- layersRef.current = [];
- setActiveLayerId('');
- }, [setActiveLayerId]);
-
- // Import an external document (from PSD, CSP, Image, or Crash Recovery) into its own isolated session.
- // Temporary import canvases are immediately released after ingestion into SparseTileGrid.
- const loadDocument = useCallback(
- (doc: LoadedDocument, targetDocumentId?: string, skipIngest: boolean = false) => {
- for (const timer of thumbDebounceTimersRef.current.values()) {
- clearTimeout(timer);
- }
- thumbDebounceTimersRef.current.clear();
-
- dimensionsRef.current = doc.dimensions;
- let grid = activeTileGridRef.current;
- if (targetDocumentId) {
- const session = documentStore.setActiveDocument(targetDocumentId) ?? documentStore.getOrCreateSession(targetDocumentId);
- activeSessionIdRef.current = targetDocumentId;
- activeTileGridRef.current = session.tileGrid;
- layerCanvasesRef.current = session.layerCanvases;
- layerSourceCanvasesRef.current = session.layerSourceCanvases;
- grid = session.tileGrid;
- }
-
- const restoredFormats = doc.tileGrid ? doc.tileGrid.getAllLayerFormats() : null;
- if (!skipIngest) {
- if (doc.tileGrid && doc.tileGrid !== grid) {
- grid.restoreFromSnapshot(doc.tileGrid.getAllTiles(), restoredFormats || undefined);
- doc.tileGrid.clearAll();
- } else if (!doc.tileGrid) {
- grid.clearAll();
- }
- }
- pendingCanvasCopiesRef.current.clear();
- pendingInitialDataRef.current.clear();
- for (const c of layerCanvasesRef.current.values()) releaseTemporaryCanvas(c);
- layerCanvasesRef.current.clear();
- for (const c of layerSourceCanvasesRef.current.values()) releaseTemporaryCanvas(c);
- layerSourceCanvasesRef.current.clear();
-
- for (const l of doc.layers) {
- if (hasTileBackedLayer(l)) {
- const existingFormat = restoredFormats?.get(l.id);
- const inferredFormat =
- existingFormat ??
- (l.expressionColor === 'monochrome'
- ? 'monochrome-1bit'
- : l.expressionColor === 'gray'
- ? 'grayscale-8bit'
- : 'color-32bit');
- grid.setLayerFormat(l.id, inferredFormat);
- grid.markLayerIngested(l.id);
- }
- }
-
- if (!skipIngest && doc.layerCanvases) {
- doc.layerCanvases.forEach((c, id) => {
- const layerMeta = doc.layers.find((l) => l.id === id);
- const isMono = layerMeta?.expressionColor === 'monochrome';
- grid.ingestCanvas(id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
- const needsEffectBacking = Boolean(
- layerMeta &&
- (layerMeta.toneEnabled ||
- layerMeta.layerColorEnabled ||
- (layerMeta.expressionColor && layerMeta.expressionColor !== 'color'))
- );
- if (needsEffectBacking) {
- const sClone = document.createElement('canvas');
- sClone.width = c.width;
- sClone.height = c.height;
- get2DContext(sClone)?.drawImage(c, 0, 0);
- layerSourceCanvasesRef.current.set(id, sClone);
- layerCanvasesRef.current.set(id, c);
- } else {
- // Release temporary import canvas immediately — SparseTileGrid is authoritative
- releaseTemporaryCanvas(c);
- }
- });
- }
-
- setLayers(doc.layers);
- layersRef.current = doc.layers;
- const topRaster = doc.layers.find((l) => l.type === 'raster');
- setActiveLayerId(topRaster ? topRaster.id : doc.layers[0]?.id || '');
- grid.notifyChange(true);
- },
- [setActiveLayerId]
- );
-
- // Internal Layer Clipboard
- const layerClipboardRef = useRef<{
- name: string;
- type: LayerItem['type'];
- blendMode: BlendMode;
- opacity: number;
- canvas: HTMLCanvasElement;
- } | null>(null);
-
- // Paste a canvas directly into SparseTileGrid as a new raster layer (no duplicate full canvas retained)
- const pasteLayerFromCanvas = useCallback(
- (
- sourceCanvas: HTMLCanvasElement,
- layerName: string = 'Pasted Layer',
- blendMode: BlendMode = 'normal',
- opacity: number = 1,
- customId?: string,
- layerOverrides?: Partial<LayerItem>,
- insertTarget?: LayerInsertTarget
- ) => {
- const newId = customId || `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
- const grid = activeTileGridRef.current;
- const isMono = layerOverrides?.expressionColor === 'monochrome';
- grid.ingestCanvas(newId, sourceCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- grid.notifyChange(true);
-
- const dims = dimensionsRef.current;
- const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dims }, true);
-
- setLayers((prev) => {
- const getSubtreeEndIndex = (list: LayerItem[], folderIndex: number): number => {
- const folderId = list[folderIndex].id;
- const subtreeIds = new Set<string>([folderId]);
- let endIdx = folderIndex + 1;
- while (endIdx < list.length) {
- const item = list[endIdx];
- if (item.parentId && subtreeIds.has(item.parentId)) {
- subtreeIds.add(item.id);
- endIdx++;
- } else {
- break;
- }
- }
- return endIdx;
- };
-
- let insertIdx = 0;
- let resolvedParentId: string | null = null;
- let expandFolderId: string | null = null;
-
- const targetIdx = insertTarget?.targetLayerId
- ? prev.findIndex((l) => l.id === insertTarget.targetLayerId)
- : -1;
-
- if (targetIdx >= 0) {
- const targetItem = prev[targetIdx];
- const pos = insertTarget?.position || (isFolderLikeLayer(targetItem) ? 'inside' : 'above');
- if (pos === 'inside' && isFolderLikeLayer(targetItem)) {
- resolvedParentId = targetItem.id;
- insertIdx = targetIdx + 1;
- if (targetItem.collapsed) expandFolderId = targetItem.id;
- } else if (pos === 'below') {
- resolvedParentId = targetItem.parentId;
- insertIdx = isFolderLikeLayer(targetItem)
- ? getSubtreeEndIndex(prev, targetIdx)
- : targetIdx + 1;
- } else {
- resolvedParentId = targetItem.parentId;
- insertIdx = targetIdx;
- }
- } else {
- const activeIdx = prev.findIndex((l) => l.id === activeLayerIdRef.current);
- const activeItem = activeIdx >= 0 ? prev[activeIdx] : undefined;
- if (activeItem && isFolderLikeLayer(activeItem)) {
- resolvedParentId = activeItem.id;
- insertIdx = activeIdx + 1;
- if (activeItem.collapsed) expandFolderId = activeItem.id;
- } else {
- resolvedParentId = activeItem?.parentId || null;
- insertIdx = activeIdx >= 0 ? activeIdx : 0;
- }
- }
-
- const newLayer: LayerItem = {
- id: newId,
- name: layerName,
- type: layerOverrides?.type || 'raster',
- visible: true,
- opacity,
- blendMode,
- locked: false,
- collapsed: false,
- parentId: layerOverrides?.parentId !== undefined ? layerOverrides.parentId : resolvedParentId,
- thumbnailUrl: thumb,
- ...layerOverrides,
- };
-
- const nextLayers = expandFolderId
- ? prev.map((l) => (l.id === expandFolderId ? { ...l, collapsed: false } : l))
- : [...prev];
- nextLayers.splice(insertIdx, 0, newLayer);
- layersRef.current = nextLayers;
- return nextLayers;
- });
-
- setActiveLayerId(newId);
- return newId;
- },
- [setActiveLayerId]
- );
-
- // Fill selection with non-destructive Clip Studio Paint screentone layer
- const fillScreentoneSelection = useCallback(
- (
- selection: CanvasSelection | null,
- density: number = 40,
- frequency: number = defaultToneFrequencyRef.current ?? 60,
- angle: number = 45,
- dotShape: HalftoneDotShape = 'circle',
- densityType: 'specified' | 'image' = 'specified'
- ): { id: string; canvas: HTMLCanvasElement; sourceCanvas: HTMLCanvasElement } => {
- const resolvedFreq = frequency || defaultToneFrequencyRef.current || 60;
- const resolvedDensity = Math.max(1, Math.min(100, Math.round(density <= 1.0 && density > 0 ? density * 100 : density)));
- const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
- const targetW = _dimensions.width;
- const targetH = _dimensions.height;
-
- // 1. Offscreen source canvas with continuous mask/tone
- const sourceCanvas = document.createElement('canvas');
- sourceCanvas.width = targetW;
- sourceCanvas.height = targetH;
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- sCtx.save();
- // In "specified" mode, solid black ink acts as the mask
- // In "image" mode, grayscale value corresponds to density
- const grayVal = densityType === 'specified' ? 0 : Math.round(255 * (1 - resolvedDensity / 100));
- sCtx.fillStyle = `rgb(${grayVal},${grayVal},${grayVal})`;
-
- if (selection) {
- if (selection.mask) {
- const imgData = sCtx.createImageData(targetW, targetH);
- const d = imgData.data;
- const m = selection.mask;
- const len = Math.min(m.length, targetW * targetH);
- for (let i = 0; i < len; i++) {
- const a = m[i];
- if (a > 0) {
- const p = i * 4;
- d[p] = grayVal;
- d[p + 1] = grayVal;
- d[p + 2] = grayVal;
- d[p + 3] = a;
- }
- }
- sCtx.putImageData(imgData, 0, 0);
- } else if (selection.type === 'rect') {
- sCtx.fillRect(
- selection.bounds.x,
- selection.bounds.y,
- selection.bounds.width,
- selection.bounds.height
- );
- } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
- sCtx.beginPath();
- sCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);
- for (let i = 1; i < selection.polygon.length; i++) {
- sCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);
- }
- sCtx.closePath();
- sCtx.fill();
- }
- } else {
- // If no active selection, fill full canvas
- sCtx.fillRect(0, 0, targetW, targetH);
- }
- sCtx.restore();
- }
-
- // 2. Offscreen display canvas with rendered screentone dots
- const displayCanvas = document.createElement('canvas');
- displayCanvas.width = targetW;
- displayCanvas.height = targetH;
-
- const newLayer: LayerItem = {
- id: newId,
- name: 'Screen Tone',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: false,
- collapsed: false,
- parentId: null,
- thumbnailUrl: '',
- toneEnabled: true,
- toneFrequency: resolvedFreq,
- toneAngle: angle,
- toneDotShape: dotShape,
- toneDensity: resolvedDensity,
- toneDensityType: densityType,
- };
-
- const grid = activeTileGridRef.current;
- applyLayerEffects(sourceCanvas, displayCanvas, newLayer, _dimensions.dpi ?? 600, selection ? selection.bounds : undefined);
- grid.ingestCanvas(newId, displayCanvas, 'color-32bit');
- grid.notifyChange(true);
-
- const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: _dimensions }, true);
- newLayer.thumbnailUrl = thumb;
-
- // Register both offscreen canvases synchronously for non-destructive tone updates
- layerSourceCanvasesRef.current.set(newId, sourceCanvas);
- layerCanvasesRef.current.set(newId, displayCanvas);
-
- setLayers((prev) => {
- const activeIdx = prev.findIndex((l) => l.id === activeLayerId);
- const activeItem = prev[activeIdx];
- const parentId = activeItem?.type === 'folder' ? activeItem.id : (activeItem?.parentId || null);
- newLayer.parentId = parentId;
-
- let name = 'Screen Tone';
- let count = 1;
- prev.forEach((l) => {
- if (l.name.startsWith('Screen Tone')) {
- const num = parseInt(l.name.replace('Screen Tone', '').trim(), 10);
- if (!isNaN(num) && num >= count) {
- count = num + 1;
- } else if (num === 1 || count === 1) {
- count = Math.max(count, 2);
- }
- }
- });
- if (count > 1) {
- name = `Screen Tone ${count}`;
- }
- newLayer.name = name;
-
- const insertIdx = activeIdx >= 0 ? activeIdx : 0;
- let nextLayers = [...prev];
- nextLayers.splice(insertIdx, 0, newLayer);
-
- const hasBg = prev.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');
- if (!hasBg) {
- const bgId = `layer-bg-${Date.now()}`;
- grid.fillLayerSolidWhite(bgId, _dimensions.width, _dimensions.height, 'color-32bit');
- const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: _dimensions }, false);
- const bgLayer: LayerItem = {
- id: bgId,
- name: 'Background',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: true,
- parentId: null,
- thumbnailUrl: bgThumb,
- };
- nextLayers = [...nextLayers, bgLayer];
- }
-
- return nextLayers;
- });
-
- setActiveLayerId(newId);
- return { id: newId, canvas: displayCanvas, sourceCanvas };
- },
- [_dimensions, activeLayerId, setActiveLayerId]
- );
-
- // Copy selected layer (internal clipboard & system clipboard) directly from SparseTileGrid
- const copyLayer = useCallback(
- (targetId?: string): LayerItem | null => {
- const id = targetId || activeLayerId;
- const targetLayer = layers.find((l) => l.id === id);
- if (!targetLayer) return null;
-
- const dims = dimensionsRef.current;
- const existingCanvas = layerCanvasesRef.current.get(id);
- const clone = document.createElement('canvas');
- clone.width = existingCanvas?.width || dims.width;
- clone.height = existingCanvas?.height || dims.height;
- if (existingCanvas) {
- get2DContext(clone)?.drawImage(existingCanvas, 0, 0);
- } else {
- activeTileGridRef.current.renderLayerToCanvas(id, clone);
- }
-
- if (layerClipboardRef.current?.canvas) {
- releaseTemporaryCanvas(layerClipboardRef.current.canvas);
- }
- layerClipboardRef.current = {
- name: targetLayer.name,
- type: targetLayer.type,
- blendMode: targetLayer.blendMode,
- opacity: targetLayer.opacity,
- canvas: clone,
- };
-
- // Try copying to system clipboard
- try {
- clone.toBlob((blob) => {
- if (blob && navigator.clipboard && window.isSecureContext) {
- navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]).catch(() => {});
- }
- });
- } catch (err) {
- // Ignore clipboard write restrictions
- }
-
- return targetLayer;
- },
- [activeLayerId, layers]
- );
-
- // Paste layer from internal or system clipboard
- const pasteLayer = useCallback(async (): Promise<{ success: boolean; layerName?: string }> => {
- // 1. Check internal clipboard
- if (layerClipboardRef.current) {
- const data = layerClipboardRef.current;
- const newName = `${data.name} Copy`;
- pasteLayerFromCanvas(data.canvas, newName, data.blendMode, data.opacity);
- return { success: true, layerName: newName };
- }
-
- // 2. Check system clipboard
- try {
- if (navigator.clipboard && navigator.clipboard.read) {
- const items = await navigator.clipboard.read();
- for (const item of items) {
- const imageType = item.types.find((t) => t.startsWith('image/'));
- if (imageType) {
- const blob = await item.getType(imageType);
- const img = new Image();
- const url = URL.createObjectURL(blob);
- await new Promise<void>((resolve, reject) => {
- img.onload = () => resolve();
- img.onerror = reject;
- img.src = url;
- });
-
- const offscreen = document.createElement('canvas');
- offscreen.width = _dimensions.width;
- offscreen.height = _dimensions.height;
- const ctx = offscreen.getContext('2d');
- if (ctx) {
- const scale = Math.min(1, Math.min(_dimensions.width / img.naturalWidth, _dimensions.height / img.naturalHeight));
- const dw = Math.round(img.naturalWidth * scale);
- const dh = Math.round(img.naturalHeight * scale);
- const dx = Math.round((_dimensions.width - dw) / 2);
- const dy = Math.round((_dimensions.height - dh) / 2);
- ctx.drawImage(img, dx, dy, dw, dh);
- }
- URL.revokeObjectURL(url);
-
- const newName = 'Pasted Image';
- pasteLayerFromCanvas(offscreen, newName);
- releaseTemporaryCanvas(offscreen);
- return { success: true, layerName: newName };
- }
- }
- }
- } catch (err) {
- console.warn('System clipboard read failed:', err);
- }
-
- return { success: false };
- }, [_dimensions, pasteLayerFromCanvas]);
-
- // Import an image file directly as a centered/fitted raster layer
- const importImageFileAsLayer = useCallback(
- async (file: File, insertTarget?: LayerInsertTarget): Promise<{ id: string; name: string }> => {
- const decodeImage = (): Promise<HTMLImageElement> =>
- new Promise((resolve, reject) => {
- const canUseObjectUrl = typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function';
- if (canUseObjectUrl) {
- const url = URL.createObjectURL(file);
- const img = new Image();
- img.onload = () => {
- URL.revokeObjectURL(url);
- resolve(img);
- };
- img.onerror = () => {
- URL.revokeObjectURL(url);
- reject(new Error(`Failed to decode image "${file.name}".`));
- };
- img.src = url;
- return;
- }
-
- const reader = new FileReader();
- reader.onload = (e) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error(`Failed to decode image "${file.name}".`));
- img.src = e.target?.result as string;
- };
- reader.onerror = () => reject(new Error(`Failed to read file "${file.name}".`));
- reader.readAsDataURL(file);
- });
-
- const img = await decodeImage();
- const natW = img.naturalWidth || img.width;
- const natH = img.naturalHeight || img.height;
- if (natW <= 0 || natH <= 0) {
- throw new Error(`Image "${file.name}" has invalid dimensions.`);
- }
-
- const dims = dimensionsRef.current;
- const offscreen = document.createElement('canvas');
- offscreen.width = dims.width;
- offscreen.height = dims.height;
- const ctx = offscreen.getContext('2d');
- if (ctx) {
- const scale = Math.min(1, dims.width / natW, dims.height / natH);
- const dw = Math.max(1, Math.round(natW * scale));
- const dh = Math.max(1, Math.round(natH * scale));
- const dx = Math.round((dims.width - dw) / 2);
- const dy = Math.round((dims.height - dh) / 2);
- ctx.imageSmoothingEnabled = true;
- ctx.imageSmoothingQuality = 'high';
- ctx.drawImage(img, dx, dy, dw, dh);
- }
-
- const layerName = sanitizeImportedLayerName(file.name);
- const id = pasteLayerFromCanvas(
- offscreen,
- layerName,
- 'normal',
- 1,
- undefined,
- undefined,
- insertTarget
- );
- releaseTemporaryCanvas(offscreen);
- return { id, name: layerName };
- },
- [pasteLayerFromCanvas]
- );
-
- // Paste a photo from file
- const pasteLayerFromFile = useCallback(
- async (file: File, insertTarget?: LayerInsertTarget): Promise<string> => {
- const { name } = await importImageFileAsLayer(file, insertTarget);
- return name;
- },
- [importImageFileAsLayer]
- );
-
- // Resize canvas dimensions (content scaling or anchor expansion/crop)
- const resizeCanvas = useCallback(
- (
- newDims: CanvasDimensions,
- options: ResizeCanvasOptions = { width: newDims.width, height: newDims.height }
- ) => {
- const {
- scaleContent = false,
- anchor = 'center',
- backgroundColor = '#ffffff',
- } = options;
-
- const currentW = _dimensions.width;
- const currentH = _dimensions.height;
- const newW = newDims.width;
- const newH = newDims.height;
-
- // Calculate anchor offsets
- let offsetX = 0;
- let offsetY = 0;
-
- if (!scaleContent) {
- if (anchor === 'top-left' || anchor === 'left' || anchor === 'bottom-left') {
- offsetX = 0;
- } else if (anchor === 'top-right' || anchor === 'right' || anchor === 'bottom-right') {
- offsetX = newW - currentW;
- } else {
- offsetX = Math.round((newW - currentW) / 2);
- }
-
- if (anchor === 'top-left' || anchor === 'top' || anchor === 'top-right') {
- offsetY = 0;
- } else if (anchor === 'bottom-left' || anchor === 'bottom' || anchor === 'bottom-right') {
- offsetY = newH - currentH;
- } else {
- offsetY = Math.round((newH - currentH) / 2);
- }
- }
-
- const updatedThumbnails = new Map<string, string>();
- const grid = activeTileGridRef.current;
-
- // Resize every raster/vector/frame layer directly through SparseTileGrid,
- // skipping empty layers completely (zero canvas allocation) and releasing temp canvases immediately.
- for (const layer of layers) {
- if (layer.type !== 'raster' && layer.type !== 'vector' && layer.type !== 'frame') continue;
- const layerId = layer.id;
- const isBg = isBackgroundLayerId(layerId);
- const isMono = !isBg && layer.expressionColor === 'monochrome';
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
- const existingCanvas = layerCanvasesRef.current.get(layerId);
- const hasContent = Boolean(existingCanvas) || grid.hasLayerTiles(layerId);
-
- if (!hasContent) {
- if (isBg && backgroundColor !== 'transparent') {
- grid.fillLayerSolidColor(layerId, newW, newH, backgroundColor, 'color-32bit');
- updatedThumbnails.set(layerId, createCanvasThumbnail({ grid, layerId, dimensions: newDims }, false));
- } else {
- grid.setLayerFormat(layerId, targetFormat);
- grid.markLayerIngested(layerId);
- }
- continue;
- }
-
- const oldTemp = document.createElement('canvas');
- oldTemp.width = currentW;
- oldTemp.height = currentH;
- if (existingCanvas) {
- get2DContext(oldTemp)?.drawImage(existingCanvas, 0, 0);
- } else {
- grid.renderLayerToCanvas(layerId, oldTemp);
- }
-
- const resizedCanvas = existingCanvas || document.createElement('canvas');
- resizedCanvas.width = newW;
- resizedCanvas.height = newH;
- const ctx = get2DContext(resizedCanvas);
- if (ctx) {
- ctx.clearRect(0, 0, newW, newH);
- if (isBg && backgroundColor !== 'transparent') {
- ctx.fillStyle = backgroundColor;
- ctx.fillRect(0, 0, newW, newH);
- }
- if (scaleContent) {
- ctx.drawImage(oldTemp, 0, 0, oldTemp.width, oldTemp.height, 0, 0, newW, newH);
- } else {
- ctx.drawImage(oldTemp, offsetX, offsetY);
- }
- grid.clearLayer(layerId);
- grid.ingestCanvas(layerId, resizedCanvas, targetFormat);
- }
-
- releaseTemporaryCanvas(oldTemp);
- if (!existingCanvas) {
- releaseTemporaryCanvas(resizedCanvas);
- }
- updatedThumbnails.set(layerId, createCanvasThumbnail({ grid, layerId, dimensions: newDims }, !isBg));
- }
-
- // Resize offscreen source canvases (strictly for layers with active non-destructive effects)
- layerSourceCanvasesRef.current.forEach((sCanvas, layerId) => {
- const temp = document.createElement('canvas');
- temp.width = sCanvas.width;
- temp.height = sCanvas.height;
- get2DContext(temp)?.drawImage(sCanvas, 0, 0);
-
- sCanvas.width = newW;
- sCanvas.height = newH;
- const sCtx = get2DContext(sCanvas);
- if (sCtx) {
- sCtx.clearRect(0, 0, newW, newH);
- const isBg = isBackgroundLayerId(layerId);
- if (isBg && backgroundColor !== 'transparent') {
- sCtx.fillStyle = backgroundColor;
- sCtx.fillRect(0, 0, newW, newH);
- }
- if (scaleContent) {
- sCtx.drawImage(temp, 0, 0, temp.width, temp.height, 0, 0, newW, newH);
- } else {
- sCtx.drawImage(temp, offsetX, offsetY);
- }
- }
- releaseTemporaryCanvas(temp);
- });
-
- // Re-apply screentone and layer effects for layers that have them enabled, and resize mask canvases
- const updatedMasks = new Map<string, { maskCanvas: HTMLCanvasElement; maskThumb: string }>();
- layers.forEach((l) => {
- if (l.maskCanvas) {
- const tempMask = document.createElement('canvas');
- tempMask.width = l.maskCanvas.width;
- tempMask.height = l.maskCanvas.height;
- get2DContext(tempMask)?.drawImage(l.maskCanvas, 0, 0);
-
- l.maskCanvas.width = newW;
- l.maskCanvas.height = newH;
- const mCtx = get2DContext(l.maskCanvas);
- if (mCtx) {
- mCtx.fillStyle = '#ffffff';
- mCtx.fillRect(0, 0, newW, newH);
- if (scaleContent) {
- mCtx.drawImage(tempMask, 0, 0, tempMask.width, tempMask.height, 0, 0, newW, newH);
- } else {
- mCtx.drawImage(tempMask, offsetX, offsetY);
- }
- }
- releaseTemporaryCanvas(tempMask);
- updatedMasks.set(l.id, {
- maskCanvas: l.maskCanvas,
- maskThumb: createCanvasThumbnail(l.maskCanvas, false),
- });
- }
-
- if (l.toneEnabled || l.layerColorEnabled || (l.expressionColor && l.expressionColor !== 'color')) {
- const sCanvas = layerSourceCanvasesRef.current.get(l.id);
- const dCanvas = layerCanvasesRef.current.get(l.id);
- if (sCanvas && dCanvas) {
- applyLayerEffects(sCanvas, dCanvas, l, newDims.dpi ?? _dimensions.dpi ?? 600);
- const isMono = l.expressionColor === 'monochrome';
- grid.clearLayer(l.id);
- grid.ingestCanvas(l.id, dCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- updatedThumbnails.set(l.id, createCanvasThumbnail({ grid, layerId: l.id, dimensions: newDims }, true));
- }
- }
- });
-
- grid.notifyChange(true);
+ const ctx: LayerManagerContext = {
+ dimensions: _dimensions,
+ activeTileGridRef,
+ dimensionsRef,
+ activeSessionIdRef,
+ defaultToneFrequencyRef,
+ thumbDebounceTimersRef,
+ layers,
+ setLayers,
+ layersRef,
+ activeLayerId,
+ setActiveLayerId,
+ activeLayerIdRef,
+ selectedLayerIds,
+ setSelectedLayerIds,
+ selectedLayerIdsRef,
+ };
- setLayers((prev) =>
- prev.map((l) => {
- const newThumb = updatedThumbnails.get(l.id);
- const maskInfo = updatedMasks.get(l.id);
- if (!newThumb && !maskInfo) return l;
- return {
- ...l,
- ...(newThumb ? { thumbnailUrl: newThumb } : {}),
- ...(maskInfo
- ? {
- maskCanvas: maskInfo.maskCanvas,
- maskThumbnailUrl: maskInfo.maskThumb,
- maskVersion: (l.maskVersion || 0) + 1,
- }
- : {}),
- };
- })
- );
- },
- [_dimensions, layers]
- );
+ const canvasRegistry = useLayerCanvasRegistry(ctx);
+ const crud = useLayerCrud(ctx);
+ const collabSync = useLayerCollabSync(ctx, canvasRegistry.updateLayerThumbnail);
+ const propertiesAndMasks = useLayerPropertiesAndMasks(ctx, canvasRegistry);
+ const effects = useLayerEffects(ctx, canvasRegistry);
+ const documentOps = useLayerDocumentOps(ctx, canvasRegistry);
+ const resize = useLayerResize(ctx);
+ const clipboard = useLayerClipboard(ctx);
+ const specialLayers = useLayerSpecialLayers(ctx, crud.addLayer, canvasRegistry.updateLayerThumbnail);
// Get active layer object
const activeLayer = layers.find((l) => l.id === activeLayerId) || layers[0];
- // Update Layer Styles (Stroke, Drop Shadow, Outer Glow)
- const updateLayerStyles = useCallback((id: string, styles: LayerStyles) => {
- setLayers((prev) => {
- const target = prev.find((l) => l.id === id);
- if (!target || isFolderLikeLayer(target)) return prev;
- return prev.map((l) => (l.id === id ? { ...l, styles } : l));
- });
- }, []);
-
- // Create or update a non-destructive Vector Text Layer (re-renders crisply into tileGrid)
- const upsertTextLayer = useCallback(
- (textData: TextLayerData, editingLayerId?: string | null): LayerItem => {
- const grid = activeTileGridRef.current;
- const dims = dimensionsRef.current;
- const snippet = textData.text.trim().replace(/\s+/g, ' ').slice(0, 22) || 'Text';
-
- if (editingLayerId) {
- const existing = layersRef.current.find((l) => l.id === editingLayerId);
- if (existing && existing.type === 'text') {
- const updated: LayerItem = {
- ...existing,
- name: snippet,
- textData: { ...textData },
- };
- setLayers((prev) => {
- const next = prev.map((l) => (l.id === editingLayerId ? updated : l));
- layersRef.current = next;
- return next;
- });
- syncVectorObjectLayerToGrid(updated, dims, grid, layerCanvasesRef.current);
- updateLayerThumbnail(editingLayerId, true);
- return updated;
- }
- }
-
- const created = addLayer('text', undefined, snippet, undefined, true);
- const withData: LayerItem = {
- ...created,
- textData: { ...textData },
- };
- setLayers((prev) => {
- const next = prev.map((l) => (l.id === created.id ? { ...l, textData: { ...textData } } : l));
- layersRef.current = next;
- return next;
- });
- syncVectorObjectLayerToGrid(withData, dims, grid, layerCanvasesRef.current);
- updateLayerThumbnail(created.id, true);
- return withData;
- },
- [addLayer, updateLayerThumbnail]
- );
-
- // Create or update a non-destructive Speech Balloon Layer (re-renders crisply into tileGrid)
- const upsertBalloonLayer = useCallback(
- (balloonData: SpeechBalloon, editingLayerId?: string | null): LayerItem => {
- const grid = activeTileGridRef.current;
- const dims = dimensionsRef.current;
- const clonedBalloon: SpeechBalloon = JSON.parse(JSON.stringify(balloonData));
- const snippet = clonedBalloon.text.trim().replace(/\s+/g, ' ').slice(0, 18);
- const label = snippet ? `Balloon: ${snippet}` : undefined;
-
- if (editingLayerId) {
- const existing = layersRef.current.find((l) => l.id === editingLayerId);
- if (existing && existing.type === 'balloon') {
- const updated: LayerItem = {
- ...existing,
- name: label || existing.name,
- balloonData: clonedBalloon,
- };
- setLayers((prev) => {
- const next = prev.map((l) => (l.id === editingLayerId ? updated : l));
- layersRef.current = next;
- return next;
- });
- syncVectorObjectLayerToGrid(updated, dims, grid, layerCanvasesRef.current);
- updateLayerThumbnail(editingLayerId, true);
- return updated;
- }
- }
-
- const created = addLayer('balloon', undefined, label, undefined, true);
- const withData: LayerItem = {
- ...created,
- balloonData: clonedBalloon,
- };
- setLayers((prev) => {
- const next = prev.map((l) => (l.id === created.id ? { ...l, balloonData: clonedBalloon } : l));
- layersRef.current = next;
- return next;
- });
- syncVectorObjectLayerToGrid(withData, dims, grid, layerCanvasesRef.current);
- updateLayerThumbnail(created.id, true);
- return withData;
- },
- [addLayer, updateLayerThumbnail]
- );
-
- // Create a true Manga Frame Border Folder with auto-clipping & initial child raster layer
- const createFrameFolder = useCallback(
- (
- frames: ComicFrame[],
- customName?: string,
- addInitialChildLayer = true
- ): { folder: LayerItem; childLayer: LayerItem | null } => {
- const folder = addLayer('frame-folder', null, customName, undefined, !addInitialChildLayer);
- const normalizedFrames = frames.map((f) => ({
- ...f,
- layerId: folder.id,
- clipChildren: f.clipChildren !== false,
- }));
- const updatedFolder: LayerItem = {
- ...folder,
- comicFrames: normalizedFrames,
- };
- setLayers((prev) => {
- const next = prev.map((l) =>
- l.id === folder.id ? { ...l, comicFrames: normalizedFrames } : l
- );
- layersRef.current = next;
- return next;
- });
-
- let childLayer: LayerItem | null = null;
- if (addInitialChildLayer) {
- childLayer = addLayer('raster', folder.id, 'Panel Layer', undefined, true);
- }
-
- activeTileGridRef.current.notifyChange(true);
- return { folder: updatedFolder, childLayer };
- },
- [addLayer]
- );
-
- // Divide a Frame Border Folder along a cut line (single folder split polygons or 2 independent folders)
- const divideFrameFolder = useCallback(
- (
- folderId: string,
- cutStart: Point2D,
- cutEnd: Point2D,
- dpi = 600,
- mode: FrameDivideMode = 'same-folder'
- ): boolean => {
- const current = layersRef.current;
- const folderIdx = current.findIndex((l) => l.id === folderId && l.type === 'frame-folder');
- if (folderIdx < 0) return false;
- const folder = current[folderIdx];
- const frames = folder.comicFrames || [];
- if (frames.length === 0) return false;
-
- const result = divideFramesInFolder(frames, cutStart, cutEnd, dpi, mode);
- if (!result.divided) return false;
-
- const grid = activeTileGridRef.current;
-
- if (mode === 'same-folder' || result.folderGroups.length < 2) {
- const nextFrames = result.frames.map((f) => ({ ...f, layerId: folder.id }));
- setLayers((prev) => {
- const next = prev.map((l) =>
- l.id === folder.id ? { ...l, comicFrames: nextFrames } : l
- );
- layersRef.current = next;
- return next;
- });
- grid.notifyChange(true);
- return true;
- }
-
- // Split into 2 independent frame folders, cloning child layers into the 2nd folder so artwork stays intact
- const [group1, group2] = result.folderGroups;
- const newFolderId = `frame-folder-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
- const updatedFolder1: LayerItem = {
- ...folder,
- comicFrames: group1.map((f) => ({ ...f, layerId: folder.id })),
- };
- const newFolder2: LayerItem = {
- ...folder,
- id: newFolderId,
- name: `${folder.name} B`,
- comicFrames: group2.map((f) => ({ ...f, layerId: newFolderId })),
- };
-
- const directChildren = current.filter((l) => l.parentId === folder.id);
- const clonedChildren: LayerItem[] = directChildren.map((child) => {
- const cloneId = `${child.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
- if (hasTileBackedLayer(child)) {
- grid.cloneLayer(child.id, cloneId);
- }
- return {
- ...child,
- id: cloneId,
- parentId: newFolderId,
- textData: child.textData ? JSON.parse(JSON.stringify(child.textData)) : undefined,
- balloonData: child.balloonData ? JSON.parse(JSON.stringify(child.balloonData)) : undefined,
- vectorStrokes: child.vectorStrokes ? JSON.parse(JSON.stringify(child.vectorStrokes)) : undefined,
- };
- });
-
- setLayers((prev) => {
- const idx = prev.findIndex((l) => l.id === folder.id);
- if (idx < 0) return prev;
- const next = prev.map((l) => (l.id === folder.id ? updatedFolder1 : l));
- next.splice(idx, 0, newFolder2, ...clonedChildren);
- layersRef.current = next;
- return next;
- });
-
- grid.notifyChange(true);
- return true;
- },
- []
- );
-
- // Rasterize a non-destructive text, balloon, or vector layer into a standard raster layer
- const rasterizeLayer = useCallback(
- (id: string): boolean => {
- const target = layersRef.current.find((l) => l.id === id);
- if (!target) return false;
- if (target.type !== 'text' && target.type !== 'balloon' && target.type !== 'vector') {
- return false;
- }
-
- const grid = activeTileGridRef.current;
- const dims = dimensionsRef.current;
-
- if (target.type === 'text' || target.type === 'balloon') {
- syncVectorObjectLayerToGrid(target, dims, grid, layerCanvasesRef.current);
- }
-
- setLayers((prev) => {
- const next = prev.map((l) => {
- if (l.id !== id) return l;
- const { textData: _td, balloonData: _bd, vectorStrokes: _vs, ...rest } = l;
- return {
- ...rest,
- type: 'raster' as const,
- };
- });
- layersRef.current = next;
- return next;
- });
-
- updateLayerThumbnail(id, true);
- grid.notifyChange(true);
- return true;
- },
- [updateLayerThumbnail]
- );
-
return {
layers,
setLayers,
@@ -3219,80 +163,76 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
selectedLayerIds,
setSelectedLayerIds,
toggleLayerSelection,
- deleteSelectedLayers,
- groupSelectedLayers,
- moveSelectedLayers,
+ deleteSelectedLayers: crud.deleteSelectedLayers,
+ groupSelectedLayers: crud.groupSelectedLayers,
+ moveSelectedLayers: crud.moveSelectedLayers,
activeLayer,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- materializeLayerCanvas,
- releaseLayerCanvas,
- ensureSourceCanvas,
- toggleTone,
- setToneFrequency,
- setToneAngle,
- setToneDotShape,
- setToneDensity,
- setToneDensityType,
- toggleLayerColor,
- setLayerColor,
- setLayerSubColor,
- setLayerExpressionColor,
- setLayerMonoThreshold,
- setLayerMonoExpressMode,
- applyExpressionColorOfPreview,
- applyLayerColorPermanently,
- convertLayer,
- registerLayerCanvas,
- updateLayerThumbnail,
- addLayer,
- addRemoteLayer,
- deleteRemoteLayer,
- syncRemoteDocument,
- duplicateLayer,
- deleteLayer,
- copyLayer,
- pasteLayer,
- pasteLayerFromCanvas,
- fillScreentoneSelection,
- importImageFileAsLayer,
- pasteLayerFromFile,
- resizeCanvas,
- toggleVisibility,
- setOpacity,
- setBlendMode,
- toggleLock,
- toggleAlphaLock,
- toggleClipping,
- toggleCollapse,
- renameLayer,
- moveLayer,
- moveLayerToFolder,
- reorderLayers,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- clearActiveLayer,
- mergeDown,
- resetToNewCanvas,
+ toggleTone: effects.toggleTone,
+ setToneFrequency: effects.setToneFrequency,
+ setToneAngle: effects.setToneAngle,
+ setToneDotShape: effects.setToneDotShape,
+ setToneDensity: effects.setToneDensity,
+ setToneDensityType: effects.setToneDensityType,
+ toggleLayerColor: effects.toggleLayerColor,
+ setLayerColor: effects.setLayerColor,
+ setLayerSubColor: effects.setLayerSubColor,
+ setLayerExpressionColor: effects.setLayerExpressionColor,
+ setLayerMonoThreshold: effects.setLayerMonoThreshold,
+ setLayerMonoExpressMode: effects.setLayerMonoExpressMode,
+ applyExpressionColorOfPreview: effects.applyExpressionColorOfPreview,
+ applyLayerColorPermanently: effects.applyLayerColorPermanently,
+ convertLayer: effects.convertLayer,
+ updateLayerThumbnail: canvasRegistry.updateLayerThumbnail,
+ addLayer: crud.addLayer,
+ addRemoteLayer: collabSync.addRemoteLayer,
+ deleteRemoteLayer: collabSync.deleteRemoteLayer,
+ applyRemoteLayerUpdate: collabSync.applyRemoteLayerUpdate,
+ applyRemoteLayerTree: collabSync.applyRemoteLayerTree,
+ applyRemoteMaskData: collabSync.applyRemoteMaskData,
+ syncRemoteDocument: collabSync.syncRemoteDocument,
+ duplicateLayer: crud.duplicateLayer,
+ deleteLayer: crud.deleteLayer,
+ copyLayer: clipboard.copyLayer,
+ pasteLayer: clipboard.pasteLayer,
+ pasteLayerFromCanvas: clipboard.pasteLayerFromCanvas,
+ fillScreentoneSelection: clipboard.fillScreentoneSelection,
+ importImageFileAsLayer: clipboard.importImageFileAsLayer,
+ pasteLayerFromFile: clipboard.pasteLayerFromFile,
+ resizeCanvas: resize.resizeCanvas,
+ toggleVisibility: propertiesAndMasks.toggleVisibility,
+ setOpacity: propertiesAndMasks.setOpacity,
+ setBlendMode: propertiesAndMasks.setBlendMode,
+ toggleLock: propertiesAndMasks.toggleLock,
+ toggleAlphaLock: propertiesAndMasks.toggleAlphaLock,
+ toggleClipping: propertiesAndMasks.toggleClipping,
+ toggleCollapse: propertiesAndMasks.toggleCollapse,
+ renameLayer: crud.renameLayer,
+ moveLayer: crud.moveLayer,
+ moveLayerToFolder: crud.moveLayerToFolder,
+ reorderLayers: crud.reorderLayers,
+ getEffectiveOpacity: crud.getEffectiveOpacity,
+ isLayerEffectivelyVisible: crud.isLayerEffectivelyVisible,
+ clearActiveLayer: documentOps.clearActiveLayer,
+ mergeDown: documentOps.mergeDown,
+ resetToNewCanvas: documentOps.resetToNewCanvas,
setDefaultToneFrequency: (freq: number) => {
defaultToneFrequencyRef.current = Math.max(20, Math.min(85, Math.round(freq || 60)));
},
- clearDocument,
- loadDocument,
- switchDocumentSession,
- addLayerMask,
- removeLayerMask,
- toggleLayerMask,
- toggleMaskLinked,
- updateMaskThumbnail,
- addAdjustmentLayer,
- updateAdjustmentData,
- updateLayerStyles,
- upsertTextLayer,
- upsertBalloonLayer,
- createFrameFolder,
- divideFrameFolder,
- rasterizeLayer,
+ clearDocument: documentOps.clearDocument,
+ loadDocument: documentOps.loadDocument,
+ switchDocumentSession: documentOps.switchDocumentSession,
+ addLayerMask: propertiesAndMasks.addLayerMask,
+ removeLayerMask: propertiesAndMasks.removeLayerMask,
+ toggleLayerMask: propertiesAndMasks.toggleLayerMask,
+ toggleMaskLinked: propertiesAndMasks.toggleMaskLinked,
+ updateMaskThumbnail: propertiesAndMasks.updateMaskThumbnail,
+ addAdjustmentLayer: propertiesAndMasks.addAdjustmentLayer,
+ updateAdjustmentData: propertiesAndMasks.updateAdjustmentData,
+ updateLayerStyles: propertiesAndMasks.updateLayerStyles,
+ upsertTextLayer: specialLayers.upsertTextLayer,
+ upsertBalloonLayer: specialLayers.upsertBalloonLayer,
+ createFrameFolder: specialLayers.createFrameFolder,
+ divideFrameFolder: specialLayers.divideFrameFolder,
+ rasterizeLayer: specialLayers.rasterizeLayer,
};
}
-
diff --git a/src/hooks/useMultiplayer.ts b/src/hooks/useMultiplayer.ts
index dd76ce5..7ad3c29 100644
--- a/src/hooks/useMultiplayer.ts
+++ b/src/hooks/useMultiplayer.ts
@@ -1,29 +1,58 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { safeLocalStorageSetItem } from '../utils/safeStorage';
import {
+ AccessDeniedMessage,
CollabPeer,
+ CollabRole,
+ ConnectionStatus,
SessionHostInfo,
MultiplayerMessage,
StrokeStartMessage,
StrokeChunkMessage,
StrokeFinishMessage,
+ BrushAssetDataMessage,
+ BrushAssetRequestMessage,
CursorMoveMessage,
JoinAcceptedMessage,
+ LayerMaskDataMessage,
+ PeerBanMessage,
+ PeerKickMessage,
+ PeerRoleUpdateMessage,
+ PeerUnbanMessage,
TileStreamMessage,
SelectiveUndoMessage,
+ WireLayerItem,
} from '../types/multiplayer';
import {
multiplayerService,
ParsedInviteLink,
parseInviteUrl,
} from '../services/multiplayerService';
-import { LayerItem, CanvasDimensions, CanvasColorMode } from '../types/editor';
-import { TILE_SIZE, TileBuffer } from '../utils/tileEngine';
+import {
+ getBrushAssetRecord,
+ registerRemoteBrushAsset,
+} from '../utils/brushAssetSync';
+import { serializeLayerForWire } from '../utils/collabSyncUtils';
+import {
+ normalizeRole,
+ peerIdEquals,
+ validateIncomingRemoteMutation,
+} from '../utils/collabPermissions';
+import {
+ AnimationTimeline,
+ CanvasColorMode,
+ CanvasDimensions,
+ LayerItem,
+} from '../types/editor';
+import { PerspectiveRuler, StraightRuler } from '../types/perspective';
+import { ResizeCanvasOptions } from '../types/settings';
+import { TileBuffer } from '../utils/tileEngine';
import { documentStore } from '../utils/documentStore';
import { uiStoreActions, useUiStore } from '../stores';
-
-const NICKNAME_KEY = 'sora_paint_nickname';
-const NICKNAME_CUSTOMIZED_KEY = 'ink_nickname_customized';
+import {
+ NICKNAME_CUSTOMIZED_STORAGE_KEY as NICKNAME_CUSTOMIZED_KEY,
+ NICKNAME_STORAGE_KEY as NICKNAME_KEY,
+} from '../types/settings';
const PEER_COLORS = [
'#f43f5e', // Rose
@@ -36,6 +65,25 @@ const PEER_COLORS = [
'#84cc16', // Lime
];
+export const RECONNECT_BASE_DELAY_MS = 1000;
+export const RECONNECT_MAX_DELAY_MS = 30000;
+export const RECONNECT_MAX_ATTEMPTS = 12;
+
+export function computeReconnectDelayMs(
+ attempt: number,
+ rng: () => number = Math.random
+): number {
+ const safeAttempt = Math.max(1, Math.floor(attempt));
+ const exp = Math.min(
+ RECONNECT_MAX_DELAY_MS,
+ RECONNECT_BASE_DELAY_MS * Math.pow(2, safeAttempt - 1)
+ );
+ const raw = rng();
+ const clampedRng = Math.max(0, Math.min(1, Number.isFinite(raw) ? raw : 0.5));
+ const jitterFactor = 0.8 + 0.4 * clampedRng; // +/- 20% jitter
+ return Math.min(RECONNECT_MAX_DELAY_MS, Math.round(exp * jitterFactor));
+}
+
function getRandomColor(): string {
return PEER_COLORS[Math.floor(Math.random() * PEER_COLORS.length)];
}
@@ -58,35 +106,56 @@ function getInitialPeerName(): string {
if (!isTauriEnvironment()) {
return 'Guest';
}
- // Desktop: will be replaced by OS username via get_os_username on mount
return 'Artist';
} catch {
return isTauriEnvironment() ? 'Artist' : 'Guest';
}
}
+interface ActiveSessionParams {
+ wsUrl: string;
+ token?: string;
+ roomName: string;
+ host: string;
+ port: number;
+ isSecure: boolean;
+ isHost: boolean;
+}
+
export interface UseMultiplayerProps {
dimensions: CanvasDimensions;
colorMode: CanvasColorMode;
layers: LayerItem[];
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ perspectiveRuler?: PerspectiveRuler | null;
+ straightRuler?: StraightRuler | null;
+ animationTimeline?: AnimationTimeline | null;
onRemoteStrokeStart?: (msg: StrokeStartMessage) => void;
onRemoteStrokeChunk?: (msg: StrokeChunkMessage) => void;
onRemoteStrokeFinish?: (msg: StrokeFinishMessage) => void;
onRemoteLayerAction?: (msg: MultiplayerMessage) => void;
+ onRemoteMaskData?: (msg: LayerMaskDataMessage) => void;
+ onRemotePerspectiveRuler?: (ruler: PerspectiveRuler | null) => void;
+ onRemoteStraightRuler?: (ruler: StraightRuler | null) => void;
+ onRemoteAnimationSync?: (timeline: AnimationTimeline | null) => void;
+ onRemoteCanvasResize?: (dimensions: CanvasDimensions, options: ResizeCanvasOptions) => void;
onRemoteDocSync?: (
dimensions: CanvasDimensions,
colorMode: CanvasColorMode,
- layers: LayerItem[],
- dataUrls: Record<string, string>,
+ layers: WireLayerItem[],
assignedLayerId?: string,
- roomName?: string
+ roomName?: string,
+ perspectiveRuler?: PerspectiveRuler | null,
+ straightRuler?: StraightRuler | null,
+ animationTimeline?: AnimationTimeline | null,
+ isReconnect?: boolean
) => void;
onRemoteJoinRequest?: (
peer: CollabPeer
) => { assignedLayerId: string; updatedLayers: LayerItem[] } | void;
onRemoteAssignedLayer?: (layerId: string) => void;
onRemoteSelectiveUndo?: (strokeId: string, peerId: string | number) => void;
+ onRemoteTileApplied?: (layerId: string) => void;
+ onRemotePeerLeft?: (peerId: string | number) => void;
showToast: (msg: string) => void;
}
@@ -94,27 +163,45 @@ export function useMultiplayer({
dimensions,
colorMode,
layers,
- layerCanvasesRef,
+ perspectiveRuler = null,
+ straightRuler = null,
+ animationTimeline = null,
onRemoteStrokeStart,
onRemoteStrokeChunk,
onRemoteStrokeFinish,
onRemoteLayerAction,
+ onRemoteMaskData,
+ onRemotePerspectiveRuler,
+ onRemoteStraightRuler,
+ onRemoteAnimationSync,
+ onRemoteCanvasResize,
onRemoteDocSync,
onRemoteJoinRequest,
onRemoteAssignedLayer,
onRemoteSelectiveUndo,
+ onRemoteTileApplied,
+ onRemotePeerLeft,
showToast,
}: UseMultiplayerProps) {
+ const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('disconnected');
const [isConnected, setIsConnected] = useState(false);
+ const [reconnectAttempt, setReconnectAttempt] = useState(0);
const [isHost, setIsHost] = useState(false);
+ const [myRole, setMyRole] = useState<CollabRole>('editor');
const [hostInfo, setHostInfo] = useState<SessionHostInfo | null>(null);
const [peers, setPeers] = useState<CollabPeer[]>([]);
+ const [bannedPeerIds, setBannedPeerIds] = useState<string[]>([]);
+
const peersRef = useRef<CollabPeer[]>([]);
+ const myRoleRef = useRef<CollabRole>('editor');
+ const bannedPeerIdsRef = useRef<Set<string>>(new Set());
+ const peerRolesRef = useRef<Map<string, CollabRole>>(new Map());
const [myPeer, setMyPeer] = useState<CollabPeer>(() => ({
id: `peer-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
name: getInitialPeerName(),
color: getRandomColor(),
+ role: 'editor',
}));
const myPeerRef = useRef(myPeer);
@@ -130,42 +217,137 @@ export function useMultiplayer({
// Web Landing modal for browser guests visiting via ?room=...
const [webLandingInvite, setWebLandingInvite] = useState<ParsedInviteLink | null>(null);
+ // Auto-reconnect & seq/version tracking refs
+ const sessionParamsRef = useRef<ActiveSessionParams | null>(null);
+ const intentionalDisconnectRef = useRef(false);
+ const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const reconnectAttemptRef = useRef(0);
+ const isReconnectingInFlightRef = useRef(false);
+ const pendingReconnectCatchUpRef = useRef(false);
+ const lastAppliedSeqRef = useRef(0);
+ const tileSeqMapRef = useRef<Map<string, number>>(new Map());
+ const tileVersionMapRef = useRef<Map<string, number>>(new Map());
+ const docFieldSeqRef = useRef({
+ layerTree: 0,
+ perspectiveRuler: 0,
+ straightRuler: 0,
+ animationTimeline: 0,
+ canvasResize: 0,
+ });
+
// Synchronous refs for event handlers
const dimensionsRef = useRef(dimensions);
const colorModeRef = useRef(colorMode);
const layersRef = useRef(layers);
+ const perspectiveRulerRef = useRef(perspectiveRuler);
+ const straightRulerRef = useRef(straightRuler);
+ const animationTimelineRef = useRef(animationTimeline);
const isHostRef = useRef(isHost);
const hostInfoRef = useRef(hostInfo);
dimensionsRef.current = dimensions;
colorModeRef.current = colorMode;
layersRef.current = layers;
+ perspectiveRulerRef.current = perspectiveRuler;
+ straightRulerRef.current = straightRuler;
+ animationTimelineRef.current = animationTimeline;
isHostRef.current = isHost;
hostInfoRef.current = hostInfo;
myPeerRef.current = myPeer;
peersRef.current = peers;
+ myRoleRef.current = myRole;
// Keep callback refs
const onRemoteStrokeStartRef = useRef(onRemoteStrokeStart);
const onRemoteStrokeChunkRef = useRef(onRemoteStrokeChunk);
const onRemoteStrokeFinishRef = useRef(onRemoteStrokeFinish);
const onRemoteLayerActionRef = useRef(onRemoteLayerAction);
+ const onRemoteMaskDataRef = useRef(onRemoteMaskData);
+ const onRemotePerspectiveRulerRef = useRef(onRemotePerspectiveRuler);
+ const onRemoteStraightRulerRef = useRef(onRemoteStraightRuler);
+ const onRemoteAnimationSyncRef = useRef(onRemoteAnimationSync);
+ const onRemoteCanvasResizeRef = useRef(onRemoteCanvasResize);
const onRemoteDocSyncRef = useRef(onRemoteDocSync);
const onRemoteJoinRequestRef = useRef(onRemoteJoinRequest);
const onRemoteAssignedLayerRef = useRef(onRemoteAssignedLayer);
const onRemoteSelectiveUndoRef = useRef(onRemoteSelectiveUndo);
+ const onRemoteTileAppliedRef = useRef(onRemoteTileApplied);
+ const onRemotePeerLeftRef = useRef(onRemotePeerLeft);
const showToastRef = useRef(showToast);
onRemoteStrokeStartRef.current = onRemoteStrokeStart;
onRemoteStrokeChunkRef.current = onRemoteStrokeChunk;
onRemoteStrokeFinishRef.current = onRemoteStrokeFinish;
onRemoteLayerActionRef.current = onRemoteLayerAction;
+ onRemoteMaskDataRef.current = onRemoteMaskData;
+ onRemotePerspectiveRulerRef.current = onRemotePerspectiveRuler;
+ onRemoteStraightRulerRef.current = onRemoteStraightRuler;
+ onRemoteAnimationSyncRef.current = onRemoteAnimationSync;
+ onRemoteCanvasResizeRef.current = onRemoteCanvasResize;
onRemoteDocSyncRef.current = onRemoteDocSync;
onRemoteJoinRequestRef.current = onRemoteJoinRequest;
onRemoteAssignedLayerRef.current = onRemoteAssignedLayer;
onRemoteSelectiveUndoRef.current = onRemoteSelectiveUndo;
+ onRemoteTileAppliedRef.current = onRemoteTileApplied;
+ onRemotePeerLeftRef.current = onRemotePeerLeft;
showToastRef.current = showToast;
+ const clearReconnectTimer = useCallback(() => {
+ if (reconnectTimerRef.current !== null) {
+ clearTimeout(reconnectTimerRef.current);
+ reconnectTimerRef.current = null;
+ }
+ }, []);
+
+ const applyLocalRole = useCallback((nextRole: CollabRole) => {
+ myRoleRef.current = nextRole;
+ setMyRole(nextRole);
+ multiplayerService.setLocalRole(nextRole);
+ setMyPeer((prev) => {
+ if (prev.role === nextRole && Boolean(prev.isHost) === (nextRole === 'host')) {
+ return prev;
+ }
+ const next: CollabPeer = {
+ ...prev,
+ role: nextRole,
+ isHost: nextRole === 'host',
+ };
+ myPeerRef.current = next;
+ return next;
+ });
+ }, []);
+
+ const resetSessionState = useCallback(() => {
+ clearReconnectTimer();
+ isReconnectingInFlightRef.current = false;
+ pendingReconnectCatchUpRef.current = false;
+ reconnectAttemptRef.current = 0;
+ setReconnectAttempt(0);
+ sessionParamsRef.current = null;
+ setIsConnected(false);
+ setConnectionStatus('disconnected');
+ setIsHost(false);
+ isHostRef.current = false;
+ setHostInfo(null);
+ hostInfoRef.current = null;
+ setPeers([]);
+ peersRef.current = [];
+ bannedPeerIdsRef.current.clear();
+ setBannedPeerIds([]);
+ peerRolesRef.current.clear();
+ lastAppliedSeqRef.current = 0;
+ tileSeqMapRef.current.clear();
+ tileVersionMapRef.current.clear();
+ docFieldSeqRef.current = {
+ layerTree: 0,
+ perspectiveRuler: 0,
+ straightRuler: 0,
+ animationTimeline: 0,
+ canvasResize: 0,
+ };
+ applyLocalRole('editor');
+ }, [applyLocalRole, clearReconnectTimer]);
+
// Desktop: resolve default peer name from OS account name unless explicitly customized
useEffect(() => {
if (!isTauriEnvironment()) return;
@@ -193,7 +375,7 @@ export function useMultiplayer({
return next;
});
const curSettings = useUiStore.getState().appSettings;
- if (!curSettings.userName || curSettings.userName === 'Sora') {
+ if (!curSettings.userName || curSettings.userName === 'Artist') {
uiStoreActions.updateAppSettings({ ...curSettings, userName: trimmed });
}
}
@@ -259,56 +441,320 @@ export function useMultiplayer({
pump();
}, []);
- // Handle incoming messages
+ // Auto-reconnect scheduler with exponential backoff and missed seq/tile catch-up
+ const scheduleReconnectRef = useRef<(immediate?: boolean) => void>(() => {});
+ const scheduleReconnect = useCallback(
+ (immediate = false) => {
+ if (intentionalDisconnectRef.current) return;
+ const params = sessionParamsRef.current;
+ if (!params) return;
+ if (multiplayerService.isConnected() || isReconnectingInFlightRef.current) return;
+
+ clearReconnectTimer();
+
+ const nextAttempt = reconnectAttemptRef.current + 1;
+ if (nextAttempt > RECONNECT_MAX_ATTEMPTS) {
+ resetSessionState();
+ showToastRef.current('Unable to reconnect to collaborative session');
+ return;
+ }
+
+ reconnectAttemptRef.current = nextAttempt;
+ setReconnectAttempt(nextAttempt);
+ setConnectionStatus('reconnecting');
+ setIsConnected(false);
+
+ const delay = immediate ? 150 : computeReconnectDelayMs(nextAttempt);
+
+ reconnectTimerRef.current = setTimeout(() => {
+ reconnectTimerRef.current = null;
+ if (intentionalDisconnectRef.current || !sessionParamsRef.current) return;
+ if (multiplayerService.isConnected() || isReconnectingInFlightRef.current) return;
+
+ const targetParams = sessionParamsRef.current;
+ const sinceSeq = Math.max(
+ lastAppliedSeqRef.current,
+ multiplayerService.getLastServerSeq()
+ );
+ const reconnectPeer: CollabPeer = {
+ ...myPeerRef.current,
+ isHost: targetParams.isHost,
+ role: myRoleRef.current,
+ };
+
+ isReconnectingInFlightRef.current = true;
+ pendingReconnectCatchUpRef.current = true;
+
+ multiplayerService
+ .connect(targetParams.wsUrl, reconnectPeer, targetParams.token, {
+ isReconnect: true,
+ sinceSeq,
+ })
+ .then(() => {
+ isReconnectingInFlightRef.current = false;
+ if (intentionalDisconnectRef.current || !sessionParamsRef.current) {
+ multiplayerService.disconnect();
+ return;
+ }
+ reconnectAttemptRef.current = 0;
+ setReconnectAttempt(0);
+ setIsConnected(true);
+ setConnectionStatus('connected');
+ multiplayerService.clearSyncDedupeCaches();
+ showToastRef.current('Reconnected to collaborative session');
+ })
+ .catch(() => {
+ isReconnectingInFlightRef.current = false;
+ if (!intentionalDisconnectRef.current && sessionParamsRef.current) {
+ scheduleReconnectRef.current(false);
+ }
+ });
+ }, delay);
+ },
+ [clearReconnectTimer, resetSessionState]
+ );
+ scheduleReconnectRef.current = scheduleReconnect;
+
+ // Retry immediately if the browser reports network connectivity restored while reconnecting
+ useEffect(() => {
+ if (typeof window === 'undefined') return;
+ const handleOnline = () => {
+ if (
+ !intentionalDisconnectRef.current &&
+ sessionParamsRef.current &&
+ !multiplayerService.isConnected() &&
+ !isReconnectingInFlightRef.current
+ ) {
+ reconnectAttemptRef.current = Math.max(0, reconnectAttemptRef.current - 1);
+ scheduleReconnectRef.current(true);
+ }
+ };
+ window.addEventListener('online', handleOnline);
+ return () => window.removeEventListener('online', handleOnline);
+ }, []);
+
+ // Clean up timers on unmount
+ useEffect(() => {
+ return () => {
+ intentionalDisconnectRef.current = true;
+ clearReconnectTimer();
+ };
+ }, [clearReconnectTimer]);
+
+ // Handle incoming messages & unexpected close
useEffect(() => {
const unsubscribe = multiplayerService.onMessage((msg: MultiplayerMessage) => {
+ if (
+ msg.type !== 'CANVAS_PING' &&
+ msg.senderId !== undefined &&
+ peerIdEquals(msg.senderId, myPeerRef.current.id)
+ ) {
+ return;
+ }
+
+ // Track highest applied authoritative seq for reconnect catch-up
+ if (typeof msg.seq === 'number' && Number.isSafeInteger(msg.seq) && msg.seq > lastAppliedSeqRef.current) {
+ lastAppliedSeqRef.current = msg.seq;
+ }
+
+ // Defense-in-depth validation against rogue viewer / unauthorized layer mutations
+ const senderPeer =
+ msg.senderId !== undefined
+ ? peersRef.current.find((p) => peerIdEquals(p.id, msg.senderId))
+ : undefined;
+ const permCheck = validateIncomingRemoteMutation(msg, senderPeer, layersRef.current);
+ if (!permCheck.allowed) {
+ return;
+ }
+
switch (msg.type) {
case 'ROOM_INFO': {
+ // Do not leapfrog lastAppliedSeq before missed reconnect ops arrive
+ if (
+ typeof msg.serverSeq === 'number' &&
+ !pendingReconnectCatchUpRef.current &&
+ lastAppliedSeqRef.current === 0
+ ) {
+ lastAppliedSeqRef.current = msg.serverSeq;
+ multiplayerService.updateServerSeq(msg.serverSeq);
+ }
+ break;
+ }
+
+ case 'ACCESS_DENIED': {
+ const denied = msg as AccessDeniedMessage;
+ if (
+ denied.targetPeerId !== undefined &&
+ !peerIdEquals(denied.targetPeerId, myPeerRef.current.id)
+ ) {
+ return;
+ }
+ if (denied.code === 'BANNED' || denied.code === 'KICKED') {
+ intentionalDisconnectRef.current = true;
+ multiplayerService.disconnect();
+ resetSessionState();
+ }
+ showToastRef.current(denied.reason || 'Access denied');
+ break;
+ }
+
+ case 'PEER_ROLE_UPDATE': {
+ const roleMsg = msg as PeerRoleUpdateMessage;
+ const nextRole = normalizeRole(roleMsg.role, false);
+ if (nextRole === 'host') break; // Guests cannot be promoted to host via this event
+
+ peerRolesRef.current.set(String(roleMsg.targetPeerId), nextRole);
+
+ if (peerIdEquals(roleMsg.targetPeerId, myPeerRef.current.id)) {
+ if (!isHostRef.current) {
+ applyLocalRole(nextRole);
+ showToastRef.current(
+ nextRole === 'viewer'
+ ? 'Your role was changed to Viewer (read-only)'
+ : 'Your role was changed to Editor'
+ );
+ }
+ } else {
+ setPeers((prev) => {
+ const next = prev.map((p) =>
+ peerIdEquals(p.id, roleMsg.targetPeerId) ? { ...p, role: nextRole } : p
+ );
+ peersRef.current = next;
+ return next;
+ });
+ }
+ break;
+ }
+
+ case 'PEER_KICK':
+ case 'PEER_BAN': {
+ const modMsg = msg as PeerKickMessage | PeerBanMessage;
+ const isBan = modMsg.type === 'PEER_BAN';
+
+ if (peerIdEquals(modMsg.targetPeerId, myPeerRef.current.id)) {
+ intentionalDisconnectRef.current = true;
+ multiplayerService.disconnect();
+ resetSessionState();
+ showToastRef.current(
+ modMsg.reason ||
+ (isBan
+ ? 'You have been banned from this room by the host'
+ : 'You were removed from this room by the host')
+ );
+ break;
+ }
+
+ if (isBan && isHostRef.current) {
+ const key = String(modMsg.targetPeerId);
+ if (!bannedPeerIdsRef.current.has(key)) {
+ bannedPeerIdsRef.current.add(key);
+ setBannedPeerIds(Array.from(bannedPeerIdsRef.current));
+ }
+ }
+
+ onRemotePeerLeftRef.current?.(modMsg.targetPeerId);
+ setPeers((prev) => {
+ const target = prev.find((p) => peerIdEquals(p.id, modMsg.targetPeerId));
+ if (target) {
+ showToastRef.current(
+ isBan ? `${target.name} was banned` : `${target.name} was kicked`
+ );
+ }
+ const next = prev.filter((p) => !peerIdEquals(p.id, modMsg.targetPeerId));
+ peersRef.current = next;
+ return next;
+ });
+ break;
+ }
+
+ case 'PEER_UNBAN': {
+ const unbanMsg = msg as PeerUnbanMessage;
+ const key = String(unbanMsg.targetPeerId);
+ if (bannedPeerIdsRef.current.delete(key)) {
+ setBannedPeerIds(Array.from(bannedPeerIdsRef.current));
+ }
break;
}
case 'JOIN_REQUEST': {
- // Only the host processes join requests; other guests will receive PEER_JOINED
+ // Host fallback handler when server is a dumb relay (stateful Rust server handles this directly)
if (msg.peer && isHostRef.current) {
- const guestPeer = msg.peer;
+ const rawGuest = msg.peer;
+ const guestIdKey = String(rawGuest.id);
+
+ if (bannedPeerIdsRef.current.has(guestIdKey)) {
+ multiplayerService.sendAccessDenied(
+ 'BANNED',
+ 'You are banned from this room',
+ rawGuest.id
+ );
+ break;
+ }
+
+ const assignedRole: CollabRole =
+ peerRolesRef.current.get(guestIdKey) === 'viewer' ? 'viewer' : 'editor';
+ peerRolesRef.current.set(guestIdKey, assignedRole);
+
+ const guestPeer: CollabPeer = {
+ ...rawGuest,
+ isHost: false,
+ role: assignedRole,
+ };
setPeers((prev) => {
- const filtered = prev.filter((p) => p.id !== guestPeer.id);
+ const filtered = prev.filter((p) => !peerIdEquals(p.id, guestPeer.id));
const next = [...filtered, guestPeer];
peersRef.current = next;
return next;
});
- showToastRef.current(`${guestPeer.name} joined the canvas`);
+ if (!msg.isReconnect) {
+ showToastRef.current(`${guestPeer.name} joined the canvas`);
+ }
let assignedLayerId: string | undefined;
let effectiveLayers = layersRef.current;
- // Delegate layer creation to the host application
- if (onRemoteJoinRequestRef.current) {
- const res = onRemoteJoinRequestRef.current(guestPeer);
- if (res) {
- assignedLayerId = res.assignedLayerId;
- effectiveLayers = res.updatedLayers;
+ if (assignedRole !== 'viewer' && onRemoteJoinRequestRef.current) {
+ const existingOwned = effectiveLayers.find(
+ (l) => l.id === `layer-${guestPeer.id}-1`
+ );
+ if (existingOwned) {
+ assignedLayerId = existingOwned.id;
+ } else {
+ const res = onRemoteJoinRequestRef.current(guestPeer);
+ if (res) {
+ assignedLayerId = res.assignedLayerId;
+ effectiveLayers = res.updatedLayers;
+ }
}
}
const roomName = hostInfoRef.current?.roomName || 'Studio';
- // Send JOIN_ACCEPTED to the joining guest
const joinAcceptedMsg: JoinAcceptedMessage = {
type: 'JOIN_ACCEPTED',
targetPeerId: guestPeer.id,
roomName,
- peers: [...peersRef.current.filter((p) => p.id !== guestPeer.id), myPeerRef.current],
+ peers: [
+ ...peersRef.current.filter((p) => !peerIdEquals(p.id, guestPeer.id)),
+ { ...myPeerRef.current, isHost: true, role: 'host' },
+ ],
hostId: myPeerRef.current.id,
docDimensions: dimensionsRef.current,
colorMode: colorModeRef.current,
assignedLayerId,
+ assignedRole,
+ isReconnect: Boolean(msg.isReconnect),
};
multiplayerService.sendMessage(joinAcceptedMsg);
- // Send document synchronization (carries assignedLayerId & roomName so there is no race)
+ multiplayerService.clearSyncDedupeCaches();
+
+ const wireLayers = effectiveLayers.map(serializeLayerForWire);
+ const wireAnim = animationTimelineRef.current
+ ? { ...animationTimelineRef.current, isPlaying: false }
+ : null;
multiplayerService.sendMessage({
type: 'DOC_SYNC_RESPONSE',
targetPeerId: guestPeer.id,
@@ -316,14 +762,20 @@ export function useMultiplayer({
assignedLayerId,
dimensions: dimensionsRef.current,
colorMode: colorModeRef.current,
- layers: effectiveLayers,
- layerDataUrls: {},
+ layers: wireLayers,
+ perspectiveRuler: perspectiveRulerRef.current,
+ straightRuler: straightRulerRef.current,
+ animationTimeline: wireAnim,
});
- // Progressive paced tile streaming from active document's sparse tile grid
streamTilesPaced(effectiveLayers);
- // Broadcast PEER_JOINED to other already connected peers
+ for (const layer of effectiveLayers) {
+ if (layer.maskCanvas) {
+ multiplayerService.sendLayerMaskData(layer.id, layer.maskCanvas);
+ }
+ }
+
multiplayerService.sendMessage({
type: 'PEER_JOINED',
peer: guestPeer,
@@ -334,31 +786,55 @@ export function useMultiplayer({
case 'JOIN_ACCEPTED': {
const accMsg = msg as JoinAcceptedMessage;
- if (accMsg.targetPeerId && accMsg.targetPeerId !== myPeerRef.current.id) {
+ if (accMsg.targetPeerId && !peerIdEquals(accMsg.targetPeerId, myPeerRef.current.id)) {
return;
}
- // Store all peers (host + existing guests)
- const allOtherPeers = (accMsg.peers || []).filter((p) => p.id !== myPeerRef.current.id);
+ const wasReconnect = Boolean(accMsg.isReconnect || pendingReconnectCatchUpRef.current);
+ pendingReconnectCatchUpRef.current = false;
+
+ if (accMsg.assignedRole && !isHostRef.current) {
+ applyLocalRole(normalizeRole(accMsg.assignedRole, false));
+ }
+
+ const allOtherPeers = (accMsg.peers || [])
+ .filter((p) => !peerIdEquals(p.id, myPeerRef.current.id))
+ .map((p) => ({
+ ...p,
+ role: normalizeRole(p.role, p.isHost),
+ }));
setPeers(allOtherPeers);
peersRef.current = allOtherPeers;
- if (accMsg.assignedLayerId) {
+ if (accMsg.assignedLayerId && !wasReconnect) {
onRemoteAssignedLayerRef.current?.(accMsg.assignedLayerId);
}
- showToastRef.current(`Connected to room "${accMsg.roomName}"`);
+ if (!wasReconnect) {
+ showToastRef.current(`Connected to room "${accMsg.roomName}"`);
+ }
break;
}
case 'PEER_JOINED': {
- if (msg.peer && msg.peer.id !== myPeerRef.current.id) {
+ if (msg.peer && !peerIdEquals(msg.peer.id, myPeerRef.current.id)) {
+ const normalizedPeer: CollabPeer = {
+ ...msg.peer,
+ role: normalizeRole(msg.peer.role, msg.peer.isHost),
+ };
+ multiplayerService.clearSyncDedupeCaches();
setPeers((prev) => {
- const next = [...prev.filter((p) => p.id !== msg.peer.id), msg.peer];
+ const existed = prev.some((p) => peerIdEquals(p.id, normalizedPeer.id));
+ const next = [
+ ...prev.filter((p) => !peerIdEquals(p.id, normalizedPeer.id)),
+ normalizedPeer,
+ ];
peersRef.current = next;
+ if (!existed) {
+ showToastRef.current(`${normalizedPeer.name} joined the canvas`);
+ }
return next;
});
- showToastRef.current(`${msg.peer.name} joined the canvas`);
}
break;
}
@@ -367,12 +843,13 @@ export function useMultiplayer({
case 'PEER_DISCONNECTED': {
const id = (msg as any).peerId ?? (msg as any).clientId;
if (id === undefined || id === null) break;
+ onRemotePeerLeftRef.current?.(id);
setPeers((prev) => {
- const leaving = prev.find((p) => String(p.id) === String(id));
+ const leaving = prev.find((p) => peerIdEquals(p.id, id));
if (leaving) {
showToastRef.current(`${leaving.name} left the canvas`);
}
- const next = prev.filter((p) => String(p.id) !== String(id));
+ const next = prev.filter((p) => !peerIdEquals(p.id, id));
peersRef.current = next;
return next;
});
@@ -382,12 +859,13 @@ export function useMultiplayer({
case 'CURSOR_MOVE': {
const cMsg = msg as CursorMoveMessage;
setPeers((prev) => {
- const existing = prev.find((p) => p.id === cMsg.peerId);
+ const existing = prev.find((p) => peerIdEquals(p.id, cMsg.peerId));
if (!existing) {
const newPeer: CollabPeer = {
id: cMsg.peerId,
name: cMsg.peerName || 'Guest',
color: cMsg.peerColor || getRandomColor(),
+ role: 'editor',
x: cMsg.x,
y: cMsg.y,
isDrawing: cMsg.isDrawing,
@@ -400,7 +878,7 @@ export function useMultiplayer({
}
const next = prev.map((p) =>
- p.id === cMsg.peerId
+ peerIdEquals(p.id, cMsg.peerId)
? {
...p,
name: cMsg.peerName || p.name,
@@ -422,11 +900,12 @@ export function useMultiplayer({
case 'STROKE_START': {
const sMsg = msg as StrokeStartMessage;
setPeers((prev) => {
- if (prev.some((p) => p.id === sMsg.peerId)) return prev;
+ if (prev.some((p) => peerIdEquals(p.id, sMsg.peerId))) return prev;
const newPeer: CollabPeer = {
id: sMsg.peerId,
name: sMsg.peerName || 'Guest',
color: sMsg.peerColor || getRandomColor(),
+ role: 'editor',
isDrawing: true,
tool: sMsg.tool,
lastActive: Date.now(),
@@ -449,28 +928,115 @@ export function useMultiplayer({
break;
}
+ case 'BRUSH_ASSET_DATA': {
+ const aMsg = msg as BrushAssetDataMessage;
+ registerRemoteBrushAsset(aMsg.hash, aMsg.mime, aMsg.data);
+ break;
+ }
+
+ case 'BRUSH_ASSET_REQUEST': {
+ const rMsg = msg as BrushAssetRequestMessage;
+ if (
+ rMsg.targetPeerId !== undefined &&
+ !peerIdEquals(rMsg.targetPeerId, myPeerRef.current.id)
+ ) {
+ break;
+ }
+ const rec = getBrushAssetRecord(rMsg.hash);
+ if (rec) {
+ multiplayerService.sendBrushAssetData(rec.hash, rec.mime, rec.bytes);
+ }
+ break;
+ }
+
case 'LAYER_ADD':
case 'LAYER_DELETE':
case 'LAYER_CLEAR':
case 'LAYER_RENAME':
case 'LAYER_VISIBILITY':
- case 'LAYER_OPACITY': {
+ case 'LAYER_OPACITY':
+ case 'LAYER_UPDATE':
+ case 'LAYER_TREE_SYNC': {
+ if (msg.type === 'LAYER_TREE_SYNC' && typeof msg.seq === 'number') {
+ if (msg.seq < docFieldSeqRef.current.layerTree) break;
+ docFieldSeqRef.current.layerTree = msg.seq;
+ }
onRemoteLayerActionRef.current?.(msg);
break;
}
+ case 'BINARY_MASK': {
+ onRemoteMaskDataRef.current?.(msg as LayerMaskDataMessage);
+ break;
+ }
+
+ case 'PERSPECTIVE_RULER_SYNC': {
+ if (typeof msg.seq === 'number') {
+ if (msg.seq < docFieldSeqRef.current.perspectiveRuler) break;
+ docFieldSeqRef.current.perspectiveRuler = msg.seq;
+ }
+ onRemotePerspectiveRulerRef.current?.(msg.perspectiveRuler ?? null);
+ break;
+ }
+
+ case 'STRAIGHT_RULER_SYNC': {
+ if (typeof msg.seq === 'number') {
+ if (msg.seq < docFieldSeqRef.current.straightRuler) break;
+ docFieldSeqRef.current.straightRuler = msg.seq;
+ }
+ onRemoteStraightRulerRef.current?.(msg.straightRuler ?? null);
+ break;
+ }
+
+ case 'ANIMATION_SYNC': {
+ if (typeof msg.seq === 'number') {
+ if (msg.seq < docFieldSeqRef.current.animationTimeline) break;
+ docFieldSeqRef.current.animationTimeline = msg.seq;
+ }
+ onRemoteAnimationSyncRef.current?.(msg.animationTimeline ?? null);
+ break;
+ }
+
+ case 'CANVAS_RESIZE': {
+ if (typeof msg.seq === 'number') {
+ if (msg.seq < docFieldSeqRef.current.canvasResize) break;
+ docFieldSeqRef.current.canvasResize = msg.seq;
+ }
+ onRemoteCanvasResizeRef.current?.(msg.dimensions, msg.options);
+ break;
+ }
+
case 'DOC_SYNC_RESPONSE': {
- if (msg.targetPeerId && msg.targetPeerId !== myPeerRef.current.id) {
+ if (msg.targetPeerId && !peerIdEquals(msg.targetPeerId, myPeerRef.current.id)) {
return;
}
+ const isReconnectSync = pendingReconnectCatchUpRef.current;
+ pendingReconnectCatchUpRef.current = false;
+
+ const snapSeq = typeof msg.seq === 'number' ? msg.seq : 0;
+ if (snapSeq > lastAppliedSeqRef.current) {
+ lastAppliedSeqRef.current = snapSeq;
+ }
+ tileSeqMapRef.current.clear();
+ tileVersionMapRef.current.clear();
+ docFieldSeqRef.current = {
+ layerTree: snapSeq,
+ perspectiveRuler: snapSeq,
+ straightRuler: snapSeq,
+ animationTimeline: snapSeq,
+ canvasResize: snapSeq,
+ };
if (onRemoteDocSyncRef.current && msg.layers) {
onRemoteDocSyncRef.current(
msg.dimensions,
msg.colorMode,
msg.layers,
- msg.layerDataUrls || {},
msg.assignedLayerId,
- msg.roomName
+ msg.roomName,
+ msg.perspectiveRuler ?? null,
+ msg.straightRuler ?? null,
+ msg.animationTimeline ?? null,
+ isReconnectSync
);
}
break;
@@ -490,6 +1056,46 @@ export function useMultiplayer({
case 'BINARY_TILE': {
const tMsg = msg as TileStreamMessage;
+ const tileKey = `${tMsg.layerId}:${tMsg.tileX}:${tMsg.tileY}`;
+ if (typeof tMsg.seq === 'number') {
+ const prevSeq = tileSeqMapRef.current.get(tileKey);
+ if (prevSeq !== undefined && tMsg.seq < prevSeq) {
+ break;
+ }
+ if (prevSeq !== undefined && tMsg.seq === prevSeq) {
+ const prevVer = tileVersionMapRef.current.get(tileKey);
+ if (prevVer !== undefined && tMsg.version <= prevVer) {
+ break;
+ }
+ }
+ tileSeqMapRef.current.set(tileKey, tMsg.seq);
+ tileVersionMapRef.current.set(tileKey, tMsg.version);
+ } else {
+ const prevVer = tileVersionMapRef.current.get(tileKey);
+ if (
+ tMsg.data !== null &&
+ prevVer !== undefined &&
+ tMsg.version > 0 &&
+ tMsg.version <= prevVer
+ ) {
+ break;
+ }
+ if (tMsg.data === null) {
+ tileVersionMapRef.current.delete(tileKey);
+ } else if (tMsg.version > 0) {
+ tileVersionMapRef.current.set(tileKey, tMsg.version);
+ }
+ }
+
+ const activeGrid = documentStore.getActiveTileGrid();
+ activeGrid.markLayerIngested(tMsg.layerId);
+ if (tMsg.data === null) {
+ activeGrid.deleteTile(tMsg.layerId, tMsg.tileX, tMsg.tileY, 0);
+ activeGrid.bumpLayerVersion(tMsg.layerId);
+ activeGrid.notifyChange(true);
+ onRemoteTileAppliedRef.current?.(tMsg.layerId);
+ break;
+ }
const tile: TileBuffer = {
layerId: tMsg.layerId,
tileX: tMsg.tileX,
@@ -502,18 +1108,9 @@ export function useMultiplayer({
lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
lod: 0,
};
- const activeGrid = documentStore.getActiveTileGrid();
activeGrid.setTile(tMsg.layerId, tMsg.tileX, tMsg.tileY, tile);
- const canvas = layerCanvasesRef.current.get(tMsg.layerId);
- if (canvas) {
- activeGrid.renderLayerToCanvas(tMsg.layerId, canvas, {
- x: tMsg.tileX * TILE_SIZE,
- y: tMsg.tileY * TILE_SIZE,
- width: TILE_SIZE,
- height: TILE_SIZE,
- });
- }
activeGrid.notifyChange(true);
+ onRemoteTileAppliedRef.current?.(tMsg.layerId);
break;
}
@@ -525,24 +1122,31 @@ export function useMultiplayer({
}
});
+ // Unexpected close: keep session state & seq cursors, reconnect with exponential backoff
const unsubClose = multiplayerService.onClose(() => {
+ if (intentionalDisconnectRef.current || !sessionParamsRef.current) {
+ resetSessionState();
+ return;
+ }
+
setIsConnected(false);
- setIsHost(false);
- setPeers([]);
- peersRef.current = [];
- showToastRef.current('Disconnected from collaborative session');
+ setConnectionStatus('reconnecting');
+ if (reconnectAttemptRef.current === 0) {
+ showToastRef.current('Connection lost. Reconnecting...');
+ }
+ scheduleReconnectRef.current(false);
});
return () => {
unsubscribe();
unsubClose();
};
- }, [layerCanvasesRef, streamTilesPaced]);
+ }, [applyLocalRole, resetSessionState, streamTilesPaced]);
// SMART CLIPBOARD INVITATION DETECTION
useEffect(() => {
const checkClipboardForInvite = async () => {
- if (isConnected) return;
+ if (isConnected || connectionStatus === 'reconnecting') return;
try {
if (!navigator.clipboard || !navigator.clipboard.readText) return;
@@ -561,7 +1165,7 @@ export function useMultiplayer({
window.addEventListener('focus', checkClipboardForInvite);
return () => window.removeEventListener('focus', checkClipboardForInvite);
- }, [isConnected]);
+ }, [isConnected, connectionStatus]);
// Check URL query parameters on initial page load (for Web Browser joins)
useEffect(() => {
@@ -582,6 +1186,12 @@ export function useMultiplayer({
onStatus?: (status: string) => void
) => {
try {
+ clearReconnectTimer();
+ intentionalDisconnectRef.current = false;
+ reconnectAttemptRef.current = 0;
+ setReconnectAttempt(0);
+ setConnectionStatus('connecting');
+
let currentName = myPeerRef.current.name;
if (hostNickname && hostNickname.trim()) {
currentName = hostNickname.trim();
@@ -650,18 +1260,65 @@ export function useMultiplayer({
isHostRef.current = true;
hostInfoRef.current = normalizedServerInfo;
+ bannedPeerIdsRef.current.clear();
+ setBannedPeerIds([]);
+ peerRolesRef.current.clear();
+ lastAppliedSeqRef.current = 0;
+ tileSeqMapRef.current.clear();
+ tileVersionMapRef.current.clear();
+ pendingReconnectCatchUpRef.current = false;
+
const hostPeer: CollabPeer = {
...myPeerRef.current,
name: currentName,
isHost: true,
+ role: 'host',
};
setMyPeer(hostPeer);
myPeerRef.current = hostPeer;
+ myRoleRef.current = 'host';
+ setMyRole('host');
+ multiplayerService.setLocalRole('host');
// Host connects locally via 127.0.0.1 with the room token
const wsUrl = `ws://127.0.0.1:${resolvedPort}/ws`;
+ sessionParamsRef.current = {
+ wsUrl,
+ token: resolvedRoomToken || undefined,
+ roomName: resolvedRoomName,
+ host: '127.0.0.1',
+ port: resolvedPort,
+ isSecure: false,
+ isHost: true,
+ };
+
await multiplayerService.connect(wsUrl, hostPeer, resolvedRoomToken || undefined);
setIsConnected(true);
+ setConnectionStatus('connected');
+
+ // Seed the stateful server immediately so joining peers sync directly from the server
+ const initialLayers = layersRef.current;
+ const wireLayers = initialLayers.map(serializeLayerForWire);
+ const wireAnim = animationTimelineRef.current
+ ? { ...animationTimelineRef.current, isPlaying: false }
+ : null;
+ multiplayerService.sendMessage({
+ type: 'DOC_SYNC_RESPONSE',
+ targetPeerId: '__server__',
+ roomName: resolvedRoomName,
+ dimensions: dimensionsRef.current,
+ colorMode: colorModeRef.current,
+ layers: wireLayers,
+ perspectiveRuler: perspectiveRulerRef.current,
+ straightRuler: straightRulerRef.current,
+ animationTimeline: wireAnim,
+ });
+ streamTilesPaced(initialLayers);
+ for (const layer of initialLayers) {
+ if (layer.maskCanvas) {
+ multiplayerService.sendLayerMaskData(layer.id, layer.maskCanvas);
+ }
+ }
// Auto-copy invite link
try {
@@ -679,34 +1336,31 @@ export function useMultiplayer({
return normalizedServerInfo;
} catch (err: any) {
console.error('Failed to start host session:', err);
+ resetSessionState();
const errMsg = err?.message || (typeof err === 'string' ? err : 'Connection error');
showToast(`Failed to start host: ${errMsg}`);
throw err;
}
},
- [showToast]
+ [clearReconnectTimer, resetSessionState, showToast, streamTilesPaced]
);
// STOP HOSTING
const stopHosting = useCallback(async () => {
try {
+ intentionalDisconnectRef.current = true;
+ clearReconnectTimer();
multiplayerService.disconnect();
if (isTauriEnvironment()) {
const { invoke } = await import('@tauri-apps/api/core');
await invoke('stop_collab_server');
}
- setIsConnected(false);
- setIsHost(false);
- isHostRef.current = false;
- setHostInfo(null);
- hostInfoRef.current = null;
- setPeers([]);
- peersRef.current = [];
+ resetSessionState();
showToast('Collaborative session stopped');
} catch (err) {
console.error('Failed to stop collab server:', err);
}
- }, [showToast]);
+ }, [clearReconnectTimer, resetSessionState, showToast]);
// JOIN ROOM
const joinRoom = useCallback(
@@ -720,6 +1374,12 @@ export function useMultiplayer({
persistName: boolean = false
): Promise<boolean> => {
try {
+ clearReconnectTimer();
+ intentionalDisconnectRef.current = false;
+ reconnectAttemptRef.current = 0;
+ setReconnectAttempt(0);
+ setConnectionStatus('connecting');
+
let currentName = myPeerRef.current.name;
if (guestNickname && guestNickname.trim()) {
currentName = guestNickname.trim();
@@ -742,14 +1402,35 @@ export function useMultiplayer({
...myPeerRef.current,
name: currentName,
isHost: false,
+ role: 'editor',
};
setMyPeer(guestPeer);
myPeerRef.current = guestPeer;
+ myRoleRef.current = 'editor';
+ setMyRole('editor');
+ multiplayerService.setLocalRole('editor');
+
+ lastAppliedSeqRef.current = 0;
+ tileSeqMapRef.current.clear();
+ tileVersionMapRef.current.clear();
+ pendingReconnectCatchUpRef.current = false;
+
+ sessionParamsRef.current = {
+ wsUrl,
+ token,
+ roomName,
+ host,
+ port,
+ isSecure,
+ isHost: false,
+ };
await multiplayerService.connect(wsUrl, guestPeer, token);
setIsConnected(true);
+ setConnectionStatus('connected');
setIsHost(false);
isHostRef.current = false;
+
const inviteProto = isSecure ? 'https' : 'http';
const tokenQuery = token ? `&token=${encodeURIComponent(token)}` : '';
const nextHostInfo: SessionHostInfo = {
@@ -768,11 +1449,12 @@ export function useMultiplayer({
setWebLandingInvite(null);
return true;
} catch (err: any) {
+ resetSessionState();
showToast(`Failed to connect: ${err?.message || err}`);
return false;
}
},
- [showToast]
+ [clearReconnectTimer, resetSessionState, showToast]
);
const joinByInviteUrl = useCallback(
@@ -796,16 +1478,98 @@ export function useMultiplayer({
);
const leaveRoom = useCallback(() => {
+ intentionalDisconnectRef.current = true;
+ clearReconnectTimer();
multiplayerService.disconnect();
- setIsConnected(false);
- setIsHost(false);
- isHostRef.current = false;
- setHostInfo(null);
- hostInfoRef.current = null;
- setPeers([]);
- peersRef.current = [];
+ resetSessionState();
showToast('Left the collaborative session');
- }, [showToast]);
+ }, [clearReconnectTimer, resetSessionState, showToast]);
+
+ // HOST MODERATION: ROLE CHANGE, KICK, BAN, UNBAN
+ const setPeerRole = useCallback(
+ (peerId: string | number, role: Exclude<CollabRole, 'host'>) => {
+ if (!isHostRef.current) {
+ showToast('Only the Host can change participant roles');
+ return;
+ }
+ if (peerIdEquals(peerId, myPeerRef.current.id)) return;
+
+ peerRolesRef.current.set(String(peerId), role);
+ setPeers((prev) => {
+ const next = prev.map((p) => (peerIdEquals(p.id, peerId) ? { ...p, role } : p));
+ peersRef.current = next;
+ return next;
+ });
+ multiplayerService.sendPeerRoleUpdate(peerId, role);
+ },
+ [showToast]
+ );
+
+ const kickPeer = useCallback(
+ (peerId: string | number, reason?: string) => {
+ if (!isHostRef.current) {
+ showToast('Only the Host can kick participants');
+ return;
+ }
+ if (peerIdEquals(peerId, myPeerRef.current.id)) return;
+
+ multiplayerService.sendPeerKick(peerId, reason);
+ onRemotePeerLeftRef.current?.(peerId);
+ setPeers((prev) => {
+ const target = prev.find((p) => peerIdEquals(p.id, peerId));
+ if (target) {
+ showToast(`Kicked ${target.name} from the room`);
+ }
+ const next = prev.filter((p) => !peerIdEquals(p.id, peerId));
+ peersRef.current = next;
+ return next;
+ });
+ },
+ [showToast]
+ );
+
+ const banPeer = useCallback(
+ (peerId: string | number, reason?: string) => {
+ if (!isHostRef.current) {
+ showToast('Only the Host can ban participants');
+ return;
+ }
+ if (peerIdEquals(peerId, myPeerRef.current.id)) return;
+
+ const key = String(peerId);
+ bannedPeerIdsRef.current.add(key);
+ setBannedPeerIds(Array.from(bannedPeerIdsRef.current));
+
+ multiplayerService.sendPeerBan(peerId, reason);
+ onRemotePeerLeftRef.current?.(peerId);
+ setPeers((prev) => {
+ const target = prev.find((p) => peerIdEquals(p.id, peerId));
+ if (target) {
+ showToast(`Banned ${target.name} from the room`);
+ }
+ const next = prev.filter((p) => !peerIdEquals(p.id, peerId));
+ peersRef.current = next;
+ return next;
+ });
+ },
+ [showToast]
+ );
+
+ const unbanPeer = useCallback(
+ (peerId: string | number) => {
+ if (!isHostRef.current) {
+ showToast('Only the Host can unban participants');
+ return;
+ }
+ const key = String(peerId);
+ if (bannedPeerIdsRef.current.delete(key)) {
+ setBannedPeerIds(Array.from(bannedPeerIdsRef.current));
+ multiplayerService.sendPeerUnban(peerId);
+ showToast(`Unbanned ${key}`);
+ }
+ },
+ [showToast]
+ );
const updateMyName = useCallback((name: string, markCustomized: boolean = true) => {
const fallback = isTauriEnvironment() ? 'Artist' : 'Guest';
@@ -839,9 +1603,14 @@ export function useMultiplayer({
return {
isConnected,
+ connectionStatus,
+ isReconnecting: connectionStatus === 'reconnecting',
+ reconnectAttempt,
isHost,
+ myRole,
hostInfo,
peers,
+ bannedPeerIds,
myPeer,
activePings,
clipboardInvite,
@@ -855,6 +1624,10 @@ export function useMultiplayer({
joinRoom,
joinByInviteUrl,
leaveRoom,
+ setPeerRole,
+ kickPeer,
+ banPeer,
+ unbanPeer,
updateMyName,
updateMyColor,
sendPing,
diff --git a/src/hooks/useTonalAndFilterActions.ts b/src/hooks/useTonalAndFilterActions.ts
index 0367312..9f0997a 100644
--- a/src/hooks/useTonalAndFilterActions.ts
+++ b/src/hooks/useTonalAndFilterActions.ts
@@ -8,17 +8,22 @@ import {
FilterType,
LayerItem,
LayerStyles,
+ TileDelta,
} from '../types/editor';
import { documentStore } from '../utils/documentStore';
import {
- applyFilter,
+ TileFormat,
+ TileSnapshotEntry,
+ releaseTemporaryCanvas,
+} from '../utils/tileEngine';
+import {
+ applyFilterToTileGridAsync,
FilmGrainParams,
GaussianBlurParams,
MotionBlurParams,
UnsharpMaskParams,
} from '../utils/filterEngine';
-import { applyScreentone, HalftoneDotShape } from '../utils/screentoneEngine';
-import { applyLayerEffects } from '../utils/layerEffectsEngine';
+import { HalftoneDotShape } from '../utils/screentoneEngine';
import { get2DContext } from '../utils/canvasUtils';
import {
TonalCorrectionType,
@@ -27,8 +32,8 @@ import {
HueSaturationParams,
PosterizationParams,
LevelCorrectionParams,
- applyTonalFilter,
- applyReverseGradient,
+ applyTonalToTileGrid,
+ computeHistogramsFromTileSnapshot,
createSelectionMask,
getProcessingBounds,
} from '../utils/tonalEngine';
@@ -64,12 +69,7 @@ export interface UseTonalAndFilterActionsParams {
activeLayer: LayerItem | undefined;
activeLayerId: string;
selection: CanvasSelection | null;
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- layerSourceCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- materializeLayerCanvas: (layerId: string) => HTMLCanvasElement | null;
- releaseLayerCanvas: (layerId: string) => void;
setActiveLayerId: (id: string) => void;
- getActiveCanvas: () => HTMLCanvasElement | null;
updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
handleCommitFloatingSelection: () => void;
pushHistoryStepRef: React.MutableRefObject<PushHistoryStepFn | null>;
@@ -100,18 +100,18 @@ export interface UseTonalAndFilterActionsParams {
angle: number,
dotShape: HalftoneDotShape,
densityType: 'specified' | 'image'
- ) => { id: string; canvas: HTMLCanvasElement };
+ ) => { id: string; tileDeltas: TileDelta[] };
applyExpressionColorOfPreview: (
layerId: string
- ) => { beforeImageData: ImageData | null; afterImageData: ImageData | null } | null | undefined;
+ ) => { tileDeltas: TileDelta[] } | null | undefined;
applyLayerColorPermanently: (
layerId: string
- ) => { beforeImageData: ImageData | null; afterImageData: ImageData | null } | null | undefined;
+ ) => { tileDeltas: TileDelta[] } | null | undefined;
convertLayer: (
layerId: string,
targetMode: ExpressionColor,
options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }
- ) => { beforeImageData: ImageData | null; afterImageData: ImageData | null } | null | undefined;
+ ) => { tileDeltas: TileDelta[] } | null | undefined;
showToast: (msg: string) => void;
}
@@ -123,12 +123,7 @@ export function useTonalAndFilterActions({
activeLayer,
activeLayerId,
selection,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- materializeLayerCanvas,
- releaseLayerCanvas,
setActiveLayerId,
- getActiveCanvas,
updateLayerThumbnail,
handleCommitFloatingSelection,
pushHistoryStepRef,
@@ -143,6 +138,19 @@ export function useTonalAndFilterActions({
convertLayer,
showToast,
}: UseTonalAndFilterActionsParams) {
+ const resolveTargetFormat = useCallback(
+ (layerId: string, layer?: LayerItem): TileFormat => {
+ const isBg = layerId === 'layer-bg' || layerId.startsWith('layer-bg');
+ if (isBg) return 'color-32bit';
+ const l = layer ?? layers.find((item) => item.id === layerId);
+ if (colorMode === 'monochrome' || l?.expressionColor === 'monochrome') {
+ return 'monochrome-1bit';
+ }
+ return 'color-32bit';
+ },
+ [colorMode, layers]
+ );
+
const handleOpenAdjustmentModal = useCallback(
(
layerId?: string,
@@ -208,111 +216,43 @@ export function useTonalAndFilterActions({
showToast('Select an unlocked raster layer to apply filter');
return;
}
+ if (dimensions.width <= 0 || dimensions.height <= 0) return;
+
const grid = documentStore.getActiveTileGrid();
- const isTone = Boolean(
- activeLayer.toneEnabled && layerSourceCanvasesRef.current?.get(activeLayerId)
- );
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- const displayCanvas = layerCanvasesRef.current.get(activeLayerId);
-
- const width = dimensions.width;
- const height = dimensions.height;
- if (width <= 0 || height <= 0) return;
-
- let beforeImageData: ImageData;
- if (isTone && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (!sCtx) return;
- beforeImageData = sCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- const raw = grid.readImageData(activeLayerId, 0, 0, width, height);
- beforeImageData = new ImageData(new Uint8ClampedArray(raw.data), width, height);
- }
+ const targetFormat = resolveTargetFormat(activeLayerId, activeLayer);
+ const targetLayerId = activeLayerId;
- const rawFiltered = applyFilter(
- new ImageData(
- new Uint8ClampedArray(beforeImageData.data),
- beforeImageData.width,
- beforeImageData.height
- ),
+ void applyFilterToTileGridAsync({
+ grid,
+ layerId: targetLayerId,
+ dimensions,
type,
- params
- );
-
- let finalImageData = rawFiltered;
- if (selection) {
- const selMask = createSelectionMask(selection, width, height);
- if (selMask) {
- finalImageData = new ImageData(new Uint8ClampedArray(beforeImageData.data), width, height);
- const src = beforeImageData.data;
- const flt = rawFiltered.data;
- const dst = finalImageData.data;
- for (let i = 0; i < selMask.length; i++) {
- const m = selMask[i];
- if (m === 0) continue;
- const p = i * 4;
- if (m === 255) {
- dst[p] = flt[p];
- dst[p + 1] = flt[p + 1];
- dst[p + 2] = flt[p + 2];
- dst[p + 3] = flt[p + 3];
- } else {
- const a = m / 255;
- const inv = 1 - a;
- dst[p] = Math.round(src[p] * inv + flt[p] * a);
- dst[p + 1] = Math.round(src[p + 1] * inv + flt[p + 1] * a);
- dst[p + 2] = Math.round(src[p + 2] * inv + flt[p + 2] * a);
- dst[p + 3] = Math.round(src[p + 3] * inv + flt[p + 3] * a);
- }
- }
- }
- }
-
- const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
-
- if (isTone && sourceCanvas) {
- get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
- const effDisplay = displayCanvas || materializeLayerCanvas(activeLayerId);
- if (effDisplay) {
- applyLayerEffects(sourceCanvas, effDisplay, activeLayer, dimensions.dpi ?? 600);
- grid.ingestCanvas(activeLayerId, effDisplay, targetFormat);
- }
- } else {
- grid.writeImageData(activeLayerId, finalImageData, 0, 0, targetFormat);
- if (displayCanvas) {
- get2DContext(displayCanvas)?.putImageData(finalImageData, 0, 0);
- releaseLayerCanvas(activeLayerId);
- }
- if (sourceCanvas) {
- get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
+ filterParams: params,
+ targetFormat,
+ selection,
+ }).then(({ dirtyRect, tileDeltas }) => {
+ if (tileDeltas.length > 0) {
+ pushHistoryStepRef.current?.(
+ 'filter',
+ `Filter: ${type.replace('-', ' ')}`,
+ null,
+ null,
+ targetLayerId,
+ dirtyRect ?? undefined,
+ tileDeltas
+ );
}
- }
-
- pushHistoryStepRef.current?.(
- 'filter',
- `Filter: ${type.replace('-', ' ')}`,
- beforeImageData,
- finalImageData,
- activeLayerId
- );
- grid.notifyChange(true);
- updateLayerThumbnail(activeLayerId, true);
- showToast(`Filter applied: ${type.replace('-', ' ')}`);
+ updateLayerThumbnail(targetLayerId, true);
+ showToast(`Filter applied: ${type.replace('-', ' ')}`);
+ });
},
[
hasOpenDocument,
activeLayer,
activeLayerId,
selection,
- dimensions.width,
- dimensions.height,
- dimensions.dpi,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- materializeLayerCanvas,
- releaseLayerCanvas,
- colorMode,
+ dimensions,
+ resolveTargetFormat,
pushHistoryStepRef,
updateLayerThumbnail,
showToast,
@@ -354,7 +294,6 @@ export function useTonalAndFilterActions({
const grid = documentStore.getActiveTileGrid();
let targetLayerId = activeLayerId;
- let targetLayer = layers.find((l) => l.id === targetLayerId);
const hasPixels = grid.hasLayerTiles(targetLayerId);
if (!hasPixels) {
@@ -367,7 +306,6 @@ export function useTonalAndFilterActions({
);
if (candidate) {
targetLayerId = candidate.id;
- targetLayer = candidate;
setActiveLayerId(candidate.id);
showToast(`Switched to "${candidate.name}" (active layer had no pixels)`);
} else {
@@ -376,29 +314,20 @@ export function useTonalAndFilterActions({
}
}
- const displayCanvas = materializeLayerCanvas(targetLayerId);
- const isTone = Boolean(
- targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
- );
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
-
- if (!canvas) {
- showToast('Canvas not available for active layer.');
- return;
- }
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const selectionMask = createSelectionMask(selection, canvas.width, canvas.height);
- const bounds = getProcessingBounds(selection, canvas.width, canvas.height);
+ const beforeTileSnapshot = grid.snapshotLayerTiles(targetLayerId);
+ const selectionMask = createSelectionMask(selection, dimensions.width, dimensions.height);
+ const bounds = getProcessingBounds(selection, dimensions.width, dimensions.height);
+ const histograms =
+ type === 'level-correction'
+ ? computeHistogramsFromTileSnapshot(beforeTileSnapshot, dimensions, selectionMask)
+ : null;
uiStoreActions.setTonalModalState({
isOpen: true,
type,
targetLayerId,
- beforeImageData,
+ beforeTileSnapshot,
+ histograms,
selectionMask,
bounds,
});
@@ -408,10 +337,9 @@ export function useTonalAndFilterActions({
activeLayer,
activeLayerId,
layers,
+ dimensions,
selection,
handleCommitFloatingSelection,
- materializeLayerCanvas,
- layerSourceCanvasesRef,
setActiveLayerId,
showToast,
]
@@ -420,124 +348,79 @@ export function useTonalAndFilterActions({
const handleTonalPreviewChange = useCallback(
(type: TonalCorrectionType, params: AnyTonalParams, enabled: boolean) => {
const state = useUiStore.getState().tonalModalState;
- if (!state.isOpen || !state.beforeImageData) return;
+ if (!state.isOpen || !state.beforeTileSnapshot) return;
+ const grid = documentStore.getActiveTileGrid();
const targetLayerId = state.targetLayerId;
- const targetLayer = layers.find((l) => l.id === targetLayerId);
- const isTone = Boolean(
- targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
- );
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
- const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
if (enabled) {
- const previewData = ctx.createImageData(canvas.width, canvas.height);
- applyTonalFilter(
- state.beforeImageData,
- previewData,
+ applyTonalToTileGrid({
+ grid,
+ layerId: targetLayerId,
+ dimensions,
+ beforeSnapshot: state.beforeTileSnapshot,
type,
- params,
- state.selectionMask,
- state.bounds
- );
- ctx.putImageData(previewData, 0, 0);
- } else {
- ctx.putImageData(state.beforeImageData, 0, 0);
- }
-
- if (isTone && sourceCanvas && displayCanvas) {
- applyScreentone(sourceCanvas, displayCanvas, {
- frequency: targetLayer?.toneFrequency ?? 60,
- angle: targetLayer?.toneAngle ?? 45,
- dotShape: targetLayer?.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
+ tonalParams: params,
+ targetFormat: resolveTargetFormat(targetLayerId),
+ selectionMask: state.selectionMask,
+ bounds: state.bounds,
});
- }
-
- if (displayCanvas) {
- const isMono =
- colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
- documentStore
- .getActiveTileGrid()
- .ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- documentStore.getActiveTileGrid().notifyChange(true);
+ } else {
+ grid.restoreLayerSnapshot(targetLayerId, state.beforeTileSnapshot, false);
}
},
- [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi]
+ [dimensions, resolveTargetFormat]
);
const handleTonalApply = useCallback(
(type: TonalCorrectionType, params: AnyTonalParams) => {
const state = useUiStore.getState().tonalModalState;
- if (!state.isOpen || !state.beforeImageData) return;
+ if (!state.isOpen || !state.beforeTileSnapshot) return;
+ const grid = documentStore.getActiveTileGrid();
const targetLayerId = state.targetLayerId;
- const targetLayer = layers.find((l) => l.id === targetLayerId);
- const isTone = Boolean(
- targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
- );
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
- const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const finalData = ctx.createImageData(canvas.width, canvas.height);
- applyTonalFilter(
- state.beforeImageData,
- finalData,
+
+ const { tileDeltas } = applyTonalToTileGrid({
+ grid,
+ layerId: targetLayerId,
+ dimensions,
+ beforeSnapshot: state.beforeTileSnapshot,
type,
- params,
- state.selectionMask,
- state.bounds
- );
- ctx.putImageData(finalData, 0, 0);
-
- if (isTone && sourceCanvas && displayCanvas) {
- applyScreentone(sourceCanvas, displayCanvas, {
- frequency: targetLayer?.toneFrequency ?? 60,
- angle: targetLayer?.toneAngle ?? 45,
- dotShape: targetLayer?.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
+ tonalParams: params,
+ targetFormat: resolveTargetFormat(targetLayerId),
+ selectionMask: state.selectionMask,
+ bounds: state.bounds,
+ });
- updateLayerThumbnail(targetLayerId, true);
const label = getTonalLabel(type);
- pushHistoryStepRef.current?.(
- 'tonal-correction',
- label,
- state.beforeImageData,
- finalData,
- targetLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- if (!isTone) {
- releaseLayerCanvas(targetLayerId);
+ if (tileDeltas.length > 0) {
+ pushHistoryStepRef.current?.(
+ 'tonal-correction',
+ label,
+ null,
+ null,
+ targetLayerId,
+ undefined,
+ tileDeltas
+ );
}
+ updateLayerThumbnail(targetLayerId, true);
uiStoreActions.setTonalModalState({
isOpen: false,
type,
targetLayerId: '',
- beforeImageData: null,
+ beforeTileSnapshot: null,
+ histograms: null,
selectionMask: null,
bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
});
showToast(`Applied ${label}`);
},
[
- layers,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- dimensions.dpi,
+ dimensions,
+ resolveTargetFormat,
updateLayerThumbnail,
getTonalLabel,
pushHistoryStepRef,
- releaseLayerCanvas,
showToast,
]
);
@@ -545,55 +428,22 @@ export function useTonalAndFilterActions({
const handleTonalCancel = useCallback(() => {
const state = useUiStore.getState().tonalModalState;
if (!state.isOpen) return;
- if (state.beforeImageData) {
- const targetLayerId = state.targetLayerId;
- const targetLayer = layers.find((l) => l.id === targetLayerId);
- const isTone = Boolean(
- targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
- );
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
- const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
- if (canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- ctx.putImageData(state.beforeImageData, 0, 0);
- if (isTone && sourceCanvas && displayCanvas) {
- applyScreentone(sourceCanvas, displayCanvas, {
- frequency: targetLayer?.toneFrequency ?? 60,
- angle: targetLayer?.toneAngle ?? 45,
- dotShape: targetLayer?.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
- if (displayCanvas) {
- const isMono =
- colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
- documentStore
- .getActiveTileGrid()
- .ingestCanvas(
- targetLayerId,
- displayCanvas,
- isMono ? 'monochrome-1bit' : 'color-32bit'
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- if (!isTone) {
- releaseLayerCanvas(targetLayerId);
- }
- }
- }
- }
+ if (state.beforeTileSnapshot && state.targetLayerId) {
+ documentStore
+ .getActiveTileGrid()
+ .restoreLayerSnapshot(state.targetLayerId, state.beforeTileSnapshot, false);
}
uiStoreActions.setTonalModalState({
isOpen: false,
type: state.type,
targetLayerId: '',
- beforeImageData: null,
+ beforeTileSnapshot: null,
+ histograms: null,
selectionMask: null,
bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
});
- }, [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi, releaseLayerCanvas]);
+ }, []);
const handleApplyReverseGradient = useCallback(() => {
if (
@@ -608,42 +458,19 @@ export function useTonalAndFilterActions({
handleCommitFloatingSelection();
}
+ const grid = documentStore.getActiveTileGrid();
let targetLayerId = activeLayerId;
- let targetLayer = layers.find((l) => l.id === targetLayerId);
- let displayCanvas = layerCanvasesRef.current.get(targetLayerId);
-
- let hasPixels = false;
- if (displayCanvas) {
- const dCtx = get2DContext(displayCanvas);
- if (dCtx) {
- const dData = dCtx.getImageData(0, 0, displayCanvas.width, displayCanvas.height).data;
- for (let i = 3; i < dData.length; i += 4) {
- if (dData[i] > 0) {
- hasPixels = true;
- break;
- }
- }
- }
- }
-
- if (!hasPixels) {
- const candidate = layers.find((l) => {
- if (l.id === targetLayerId || l.type !== 'raster' || !l.visible) return false;
- const c = layerCanvasesRef.current.get(l.id);
- if (!c) return false;
- const cCtx = get2DContext(c);
- if (!cCtx) return false;
- const cData = cCtx.getImageData(0, 0, c.width, c.height).data;
- for (let j = 3; j < cData.length; j += 4) {
- if (cData[j] > 0) return true;
- }
- return false;
- });
+ if (!grid.hasLayerTiles(targetLayerId)) {
+ const candidate = layers.find(
+ (l) =>
+ l.id !== targetLayerId &&
+ l.type === 'raster' &&
+ l.visible &&
+ grid.hasLayerTiles(l.id)
+ );
if (candidate) {
targetLayerId = candidate.id;
- targetLayer = candidate;
- displayCanvas = layerCanvasesRef.current.get(candidate.id);
setActiveLayerId(candidate.id);
showToast(`Switched to "${candidate.name}" (active layer had no pixels)`);
} else {
@@ -652,53 +479,44 @@ export function useTonalAndFilterActions({
}
}
- const isTone = Boolean(
- targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
- );
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const afterImageData = ctx.createImageData(canvas.width, canvas.height);
- afterImageData.data.set(beforeImageData.data);
-
- const mask = createSelectionMask(selection, canvas.width, canvas.height);
- const bounds = getProcessingBounds(selection, canvas.width, canvas.height);
-
- applyReverseGradient(beforeImageData, afterImageData, mask, bounds);
- ctx.putImageData(afterImageData, 0, 0);
-
- if (isTone && sourceCanvas && displayCanvas) {
- applyScreentone(sourceCanvas, displayCanvas, {
- frequency: targetLayer?.toneFrequency ?? 60,
- angle: targetLayer?.toneAngle ?? 45,
- dotShape: targetLayer?.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
+ const beforeSnapshot = grid.snapshotLayerTiles(targetLayerId);
+ const mask = createSelectionMask(selection, dimensions.width, dimensions.height);
+ const bounds = getProcessingBounds(selection, dimensions.width, dimensions.height);
+
+ const { tileDeltas } = applyTonalToTileGrid({
+ grid,
+ layerId: targetLayerId,
+ dimensions,
+ beforeSnapshot,
+ type: 'reverse-gradient',
+ tonalParams: {},
+ targetFormat: resolveTargetFormat(targetLayerId),
+ selectionMask: mask,
+ bounds,
+ });
+ if (tileDeltas.length > 0) {
+ pushHistoryStepRef.current?.(
+ 'tonal-correction',
+ 'Reverse Gradient',
+ null,
+ null,
+ targetLayerId,
+ undefined,
+ tileDeltas
+ );
+ }
updateLayerThumbnail(targetLayerId, true);
- pushHistoryStepRef.current?.(
- 'tonal-correction',
- 'Reverse Gradient',
- beforeImageData,
- afterImageData,
- targetLayerId
- );
showToast('Inverted colors (Reverse Gradient)');
}, [
hasOpenDocument,
activeLayer,
activeLayerId,
layers,
+ dimensions,
selection,
handleCommitFloatingSelection,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- dimensions.dpi,
+ resolveTargetFormat,
updateLayerThumbnail,
pushHistoryStepRef,
setActiveLayerId,
@@ -707,43 +525,92 @@ export function useTonalAndFilterActions({
const handleApplyMangaEffects = useCallback(
(type: 'saturated' | 'stream', options: SaturatedLinesOptions | StreamLinesOptions) => {
- const canvas = getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
-
- const renderOn = (target: HTMLCanvasElement) => {
- const c = get2DContext(target);
- if (!c) return;
- if (type === 'saturated') {
- renderSaturatedLines(c, canvas.width, canvas.height, options as SaturatedLinesOptions);
- } else {
- renderStreamLines(c, canvas.width, canvas.height, options as StreamLinesOptions);
- }
- };
+ if (!activeLayerId || activeLayer?.locked || dimensions.width <= 0 || dimensions.height <= 0) {
+ return;
+ }
- renderOn(canvas);
- if (sourceCanvas) renderOn(sourceCanvas);
+ const grid = documentStore.getActiveTileGrid();
+ const targetFormat = resolveTargetFormat(activeLayerId, activeLayer);
+ const beforeSnapshot = new Map<string, TileSnapshotEntry>();
+ const CHUNK = 1024;
+ const chunkCanvas = document.createElement('canvas');
+ chunkCanvas.width = Math.min(CHUNK, dimensions.width);
+ chunkCanvas.height = Math.min(CHUNK, dimensions.height);
+ const cCtx = get2DContext(chunkCanvas);
+ if (!cCtx) {
+ releaseTemporaryCanvas(chunkCanvas);
+ return;
+ }
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ try {
+ for (let cy = 0; cy < dimensions.height; cy += CHUNK) {
+ const ch = Math.min(CHUNK, dimensions.height - cy);
+ for (let cx = 0; cx < dimensions.width; cx += CHUNK) {
+ const cw = Math.min(CHUNK, dimensions.width - cx);
+ if (chunkCanvas.width !== cw) chunkCanvas.width = cw;
+ if (chunkCanvas.height !== ch) chunkCanvas.height = ch;
+
+ cCtx.setTransform(1, 0, 0, 1, 0, 0);
+ cCtx.clearRect(0, 0, cw, ch);
+ cCtx.save();
+ cCtx.translate(-cx, -cy);
+ if (type === 'saturated') {
+ renderSaturatedLines(
+ cCtx,
+ dimensions.width,
+ dimensions.height,
+ options as SaturatedLinesOptions
+ );
+ } else {
+ renderStreamLines(
+ cCtx,
+ dimensions.width,
+ dimensions.height,
+ options as StreamLinesOptions
+ );
+ }
+ cCtx.restore();
+
+ const img = cCtx.getImageData(0, 0, cw, ch);
+ grid.compositeStrokeToTiles({
+ layerId: activeLayerId,
+ strokeData: img,
+ destX: cx,
+ destY: cy,
+ format: targetFormat,
+ compositeOp: 'source-over',
+ opacity: 1.0,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+ }
+ } finally {
+ releaseTemporaryCanvas(chunkCanvas);
+ }
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, activeLayerId);
+ grid.notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
- pushHistoryStepRef.current?.(
- 'brush',
- `Manga Effect (${type})`,
- beforeImageData,
- afterImageData,
- activeLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
+ if (tileDeltas.length > 0) {
+ pushHistoryStepRef.current?.(
+ 'brush',
+ `Manga Effect (${type})`,
+ null,
+ null,
+ activeLayerId,
+ undefined,
+ tileDeltas
+ );
+ }
showToast(`Applied manga ${type} lines`);
},
[
- getActiveCanvas,
activeLayerId,
- layerSourceCanvasesRef,
+ activeLayer,
+ dimensions.width,
+ dimensions.height,
+ resolveTargetFormat,
updateLayerThumbnail,
pushHistoryStepRef,
showToast,
@@ -769,7 +636,7 @@ export function useTonalAndFilterActions({
const handleConfirmTone = useCallback(
(settings: SimpleToneSettings) => {
uiStoreActions.setToneModalOpen(false);
- const { id, canvas } = fillScreentoneSelection(
+ const { id, tileDeltas } = fillScreentoneSelection(
selection,
settings.density,
settings.frequency,
@@ -777,15 +644,15 @@ export function useTonalAndFilterActions({
settings.dotShape,
settings.densityType
);
- const ctx = get2DContext(canvas);
- if (ctx) {
- const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ if (tileDeltas.length > 0) {
pushHistoryStepRef.current?.(
'screentone',
`Screentone (${settings.density}%)`,
null,
- afterData,
- id
+ null,
+ id,
+ selection?.bounds,
+ tileDeltas
);
}
showToast(`Created Screentone Layer (${settings.density}%)`);
@@ -796,13 +663,15 @@ export function useTonalAndFilterActions({
const handleApplyExpressionColor = useCallback(
(layerId: string) => {
const result = applyExpressionColorOfPreview(layerId);
- if (result && result.beforeImageData && result.afterImageData) {
+ if (result && result.tileDeltas.length > 0) {
pushHistoryStepRef.current?.(
'expression-color',
'Apply Expression Color',
- result.beforeImageData,
- result.afterImageData,
- layerId
+ null,
+ null,
+ layerId,
+ undefined,
+ result.tileDeltas
);
showToast('Applied expression color to layer');
}
@@ -813,13 +682,15 @@ export function useTonalAndFilterActions({
const handleApplyLayerColor = useCallback(
(layerId: string) => {
const result = applyLayerColorPermanently(layerId);
- if (result && result.beforeImageData && result.afterImageData) {
+ if (result && result.tileDeltas.length > 0) {
pushHistoryStepRef.current?.(
'layer-color',
'Apply Layer Color Tint',
- result.beforeImageData,
- result.afterImageData,
- layerId
+ null,
+ null,
+ layerId,
+ undefined,
+ result.tileDeltas
);
showToast('Applied tint to layer permanently');
}
@@ -834,13 +705,15 @@ export function useTonalAndFilterActions({
options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }
) => {
const result = convertLayer(layerId, targetMode, options);
- if (result && result.beforeImageData && result.afterImageData) {
+ if (result && result.tileDeltas.length > 0) {
pushHistoryStepRef.current?.(
'layer-convert',
`Convert to ${targetMode.toUpperCase()}`,
- result.beforeImageData,
- result.afterImageData,
- layerId
+ null,
+ null,
+ layerId,
+ undefined,
+ result.tileDeltas
);
showToast(`Converted layer to ${targetMode}`);
}
diff --git a/src/services/bake3DService.ts b/src/services/bake3DService.ts
index 75b31ad..23d0f39 100644
--- a/src/services/bake3DService.ts
+++ b/src/services/bake3DService.ts
@@ -1,5 +1,6 @@
import * as THREE from 'three';
import { LayerItem, BlendMode } from '../types/editor';
+import { documentStore } from '../utils/documentStore';
import { multiplayerService } from './multiplayerService';
import { applyScreentoneCPU } from '../utils/screentoneEngine';
@@ -326,11 +327,12 @@ export async function bake3DToRasterLayer(options: Bake3DOptions): Promise<Bake3
onInsertLayer(layer, rasterCanvas);
}
- // 5. Multiplayer Broadcast: Send standard 2D raster pixels, zero 3D overhead
+ // 5. Multiplayer Broadcast: Send layer metadata + LZ4 BINARY_TILE raster pixels (no base64 data URLs)
if (onBroadcastLayer) {
onBroadcastLayer(layer, dataUrl);
} else if (multiplayerService.isConnected()) {
- multiplayerService.sendLayerAdd(layer, dataUrl);
+ multiplayerService.sendLayerAdd(layer);
+ multiplayerService.streamLayerTiles(layer.id, documentStore.getActiveTileGrid());
}
return { layer, canvas: rasterCanvas, dataUrl };
@@ -968,9 +970,14 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak
onBroadcastLayer(lineLayer, lineDataUrl);
toneLayersStackOrder.forEach((l, i) => onBroadcastLayer(l, toneCanvasesStackOrder[i].toDataURL('image/png')));
} else if (multiplayerService.isConnected()) {
+ const activeGrid = documentStore.getActiveTileGrid();
multiplayerService.sendLayerAdd(folderLayer);
- multiplayerService.sendLayerAdd(lineLayer, lineDataUrl);
- toneLayersStackOrder.forEach((l, i) => multiplayerService.sendLayerAdd(l, toneCanvasesStackOrder[i].toDataURL('image/png')));
+ multiplayerService.sendLayerAdd(lineLayer);
+ multiplayerService.streamLayerTiles(lineLayer.id, activeGrid);
+ toneLayersStackOrder.forEach((l) => {
+ multiplayerService.sendLayerAdd(l);
+ multiplayerService.streamLayerTiles(l.id, activeGrid);
+ });
}
return {
diff --git a/src/services/multiplayerService.ts b/src/services/multiplayerService.ts
index d414bfb..4bd37d1 100644
--- a/src/services/multiplayerService.ts
+++ b/src/services/multiplayerService.ts
@@ -1,17 +1,75 @@
import {
+ AccessDeniedCode,
+ AccessDeniedMessage,
+ AnimationSyncMessage,
+ BrushAssetDataMessage,
+ BrushAssetRequestMessage,
+ CanvasPingMessage,
+ CanvasResizeMessage,
CollabPeer,
+ CollabRole,
+ CursorMoveMessage,
+ DocSyncResponseMessage,
+ LayerActionMessage,
+ LayerClearableField,
+ LayerMaskDataMessage,
+ LayerTreeSyncMessage,
+ LayerUpdateMessage,
MultiplayerMessage,
- StrokeStartMessage,
+ PeerBanMessage,
+ PeerKickMessage,
+ PeerRoleUpdateMessage,
+ PeerUnbanMessage,
+ PerspectiveRulerSyncMessage,
+ SelectiveUndoMessage,
+ StraightRulerSyncMessage,
StrokeChunkMessage,
StrokeFinishMessage,
- CursorMoveMessage,
- LayerActionMessage,
- CanvasPingMessage,
+ StrokeStartMessage,
TileStreamMessage,
- SelectiveUndoMessage,
+ WireLayerItem,
} from '../types/multiplayer';
-import { Point, BrushSettings, ToolType, DirtyRect, LayerItem, VectorStroke } from '../types/editor';
-import { TileBuffer, serializeTileBuffer, deserializeTileBuffer } from '../utils/tileEngine';
+import {
+ AnimationTimeline,
+ BrushSettings,
+ CanvasDimensions,
+ DirtyRect,
+ LayerItem,
+ Point,
+ TileDelta,
+ ToolType,
+ VectorStroke,
+} from '../types/editor';
+import { PerspectiveRuler, StraightRuler } from '../types/perspective';
+import { ResizeCanvasOptions } from '../types/settings';
+import {
+ SparseTileGrid,
+ TileBuffer,
+ parseTileKey,
+ serializeTileBuffer,
+ deserializeTileBufferStrict,
+} from '../utils/tileEngine';
+import {
+ MAX_BRUSH_ASSET_BYTES,
+ isAllowedBrushAssetMime,
+ isValidBrushAssetHash,
+ prepareBrushSettingsForWire,
+ sanitizeBrushAssetRefs,
+} from '../utils/brushAssetSync';
+import { lz4CompressBlock, lz4DecompressBlock } from '../utils/lz4';
+import {
+ MAX_SYNC_CANVAS_DIM,
+ extractMaskGrayscaleRect,
+ sanitizeAnimationTimeline,
+ sanitizeCanvasResize,
+ sanitizeClearedFields,
+ sanitizePerspectiveRuler,
+ sanitizeStraightRuler,
+ sanitizeWireLayer,
+ sanitizeWireLayerPatch,
+ sanitizeWireLayerTree,
+ serializeLayerForWire,
+} from '../utils/collabSyncUtils';
type MessageHandler = (msg: MultiplayerMessage) => void;
@@ -25,11 +83,45 @@ export const CODE_STROKE_FINISH = 0x03;
export const CODE_TILE_DELTA = 0x04;
export const CODE_CURSOR_MOVE = 0x05;
export const CODE_SELECTIVE_UNDO = 0x06;
+export const CODE_BRUSH_ASSET_DATA = 0x07;
+export const CODE_BRUSH_ASSET_REQUEST = 0x08;
+export const CODE_LAYER_MASK_DATA = 0x09;
+
+const MASK_FLAG_FULL_REPLACE = 0x01;
+const MASK_FLAG_LZ4 = 0x02;
+const MASK_FLAG_SOLID_FILL = 0x04;
+const MAX_MASK_CHUNK_DIM = 1024;
+const MAX_MASK_DECODE_BYTES = 4 * 1024 * 1024; // 4 MB safety ceiling per mask packet
const MAX_BINARY_PACKET_BYTES = 16 * 1024 * 1024;
const MAX_JSON_MESSAGE_CHARS = 8 * 1024 * 1024;
const MAX_STROKE_CHUNK_POINTS = 4096;
+const STROKE_CHUNK_POINT_STRIDE = 20;
+const MAX_TILE_COORD = 4096;
const WS_CONNECT_TIMEOUT_MS = 15000;
+const STATE_SYNC_THROTTLE_MS = 33;
+
+const TOOL_TYPES_LIST: ToolType[] = [
+ 'brush',
+ 'eraser',
+ 'pipette',
+ 'transform',
+ 'select-rect',
+ 'select-lasso',
+ 'select-wand',
+ 'select-pen',
+ 'select-eraser',
+ 'fill',
+ 'text',
+ 'frame',
+ 'balloon',
+ 'vector-edit',
+ 'liquify',
+ 'shape',
+ 'object',
+];
+
+export const DEEP_LINK_SCHEME = 'inkstudio:';
export interface ParsedInviteLink {
roomName: string;
@@ -68,7 +160,7 @@ export function parseInviteUrl(raw: string): ParsedInviteLink | null {
};
}
- if (parsedUrl.protocol === 'forsora:') {
+ if (parsedUrl.protocol === DEEP_LINK_SCHEME) {
const host = parsedUrl.searchParams.get('host');
const portParam = parsedUrl.searchParams.get('port');
if (!host) return null;
@@ -120,8 +212,19 @@ function sanitizeRemoteBrushSettings(raw: unknown): BrushSettings | null {
: 3,
}
: undefined;
+ const {
+ customTipDataUrl: _tipUrl,
+ customTipImage: _tipImg,
+ dualTipDataUrl: _dualUrl,
+ dualTipImage: _dualImg,
+ paperTexture: _paperUrl,
+ paperTextureImage: _paperImg,
+ subTips: _subTips,
+ subTipImages: _subImgs,
+ ...rest
+ } = bs;
return {
- ...bs,
+ ...rest,
size,
opacity,
flow,
@@ -137,21 +240,388 @@ function isValidRemotePoint(pt: unknown): pt is Point {
return Number.isFinite(p.x) && Number.isFinite(p.y);
}
+/**
+ * Strictly validates and sanitizes untrusted remote JSON messages before dispatching.
+ * Returns null to drop malformed or malicious payloads.
+ */
+export function sanitizeIncomingJsonMessage(raw: unknown): MultiplayerMessage | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const msg = raw as Record<string, unknown>;
+ if (typeof msg.type !== 'string') return null;
+
+ const senderId =
+ typeof msg.senderId === 'string' || typeof msg.senderId === 'number'
+ ? msg.senderId
+ : undefined;
+ const seq =
+ typeof msg.seq === 'number' && Number.isSafeInteger(msg.seq) && msg.seq >= 0
+ ? msg.seq
+ : undefined;
+
+ const sanitized = sanitizeIncomingJsonBody(msg, senderId);
+ if (sanitized && seq !== undefined) {
+ sanitized.seq = seq;
+ }
+ return sanitized;
+}
+
+function sanitizeIncomingJsonBody(
+ msg: Record<string, unknown>,
+ senderId: string | number | undefined
+): MultiplayerMessage | null {
+ switch (msg.type) {
+ case 'LAYER_ADD': {
+ const layerItem = sanitizeWireLayer(msg.layerItem);
+ if (!layerItem) return null;
+ const insertIndex =
+ typeof msg.insertIndex === 'number' && Number.isInteger(msg.insertIndex) && msg.insertIndex >= 0
+ ? msg.insertIndex
+ : undefined;
+ return {
+ type: 'LAYER_ADD',
+ senderId,
+ layerId: layerItem.id,
+ layerItem,
+ insertIndex,
+ };
+ }
+
+ case 'LAYER_DELETE':
+ case 'LAYER_CLEAR': {
+ if (typeof msg.layerId !== 'string' || !msg.layerId || msg.layerId.length > 256) return null;
+ return {
+ type: msg.type,
+ senderId,
+ layerId: msg.layerId,
+ };
+ }
+
+ case 'LAYER_RENAME': {
+ if (
+ typeof msg.layerId !== 'string' ||
+ !msg.layerId ||
+ msg.layerId.length > 256 ||
+ typeof msg.newName !== 'string'
+ ) {
+ return null;
+ }
+ return {
+ type: 'LAYER_RENAME',
+ senderId,
+ layerId: msg.layerId,
+ newName: msg.newName.slice(0, 256),
+ };
+ }
+
+ case 'LAYER_VISIBILITY': {
+ if (
+ typeof msg.layerId !== 'string' ||
+ !msg.layerId ||
+ msg.layerId.length > 256 ||
+ typeof msg.visible !== 'boolean'
+ ) {
+ return null;
+ }
+ return {
+ type: 'LAYER_VISIBILITY',
+ senderId,
+ layerId: msg.layerId,
+ visible: msg.visible,
+ };
+ }
+
+ case 'LAYER_OPACITY': {
+ if (
+ typeof msg.layerId !== 'string' ||
+ !msg.layerId ||
+ msg.layerId.length > 256 ||
+ typeof msg.opacity !== 'number' ||
+ !Number.isFinite(msg.opacity)
+ ) {
+ return null;
+ }
+ return {
+ type: 'LAYER_OPACITY',
+ senderId,
+ layerId: msg.layerId,
+ opacity: Math.max(0, Math.min(1, msg.opacity)),
+ };
+ }
+
+ case 'LAYER_UPDATE': {
+ if (typeof msg.layerId !== 'string' || !msg.layerId || msg.layerId.length > 256) return null;
+ const patch = sanitizeWireLayerPatch(msg.patch);
+ const clearedFields = sanitizeClearedFields(msg.clearedFields);
+ if (Object.keys(patch).length === 0 && clearedFields.length === 0) return null;
+ const lamport =
+ typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
+ return {
+ type: 'LAYER_UPDATE',
+ senderId,
+ layerId: msg.layerId,
+ patch,
+ clearedFields: clearedFields.length > 0 ? clearedFields : undefined,
+ lamport,
+ };
+ }
+
+ case 'LAYER_TREE_SYNC': {
+ const layers = sanitizeWireLayerTree(msg.layers);
+ if (!layers) return null;
+ const lamport =
+ typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : 0;
+ const dirtyTileLayerIds = Array.isArray(msg.dirtyTileLayerIds)
+ ? msg.dirtyTileLayerIds
+ .filter((x): x is string => typeof x === 'string' && x.length > 0 && x.length <= 256)
+ .slice(0, 512)
+ : undefined;
+ const removedLayerIds = Array.isArray(msg.removedLayerIds)
+ ? msg.removedLayerIds
+ .filter((x): x is string => typeof x === 'string' && x.length > 0 && x.length <= 256)
+ .slice(0, 512)
+ : undefined;
+ return {
+ type: 'LAYER_TREE_SYNC',
+ senderId,
+ layers,
+ lamport,
+ dirtyTileLayerIds,
+ removedLayerIds,
+ };
+ }
+
+ case 'PERSPECTIVE_RULER_SYNC': {
+ const perspectiveRuler = sanitizePerspectiveRuler(msg.perspectiveRuler);
+ if (perspectiveRuler === undefined) return null;
+ const lamport =
+ typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
+ return {
+ type: 'PERSPECTIVE_RULER_SYNC',
+ senderId,
+ perspectiveRuler,
+ lamport,
+ };
+ }
+
+ case 'STRAIGHT_RULER_SYNC': {
+ const straightRuler = sanitizeStraightRuler(msg.straightRuler);
+ if (straightRuler === undefined) return null;
+ const lamport =
+ typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
+ return {
+ type: 'STRAIGHT_RULER_SYNC',
+ senderId,
+ straightRuler,
+ lamport,
+ };
+ }
+
+ case 'ANIMATION_SYNC': {
+ const animationTimeline = sanitizeAnimationTimeline(msg.animationTimeline);
+ if (animationTimeline === undefined) return null;
+ const lamport =
+ typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
+ return {
+ type: 'ANIMATION_SYNC',
+ senderId,
+ animationTimeline,
+ lamport,
+ };
+ }
+
+ case 'CANVAS_RESIZE': {
+ const safe = sanitizeCanvasResize(msg);
+ if (!safe) return null;
+ const lamport =
+ typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
+ return {
+ type: 'CANVAS_RESIZE',
+ senderId,
+ dimensions: safe.dimensions,
+ options: safe.options,
+ lamport,
+ };
+ }
+
+ case 'DOC_SYNC_RESPONSE': {
+ const layers = sanitizeWireLayerTree(msg.layers);
+ const d = msg.dimensions as Record<string, unknown> | undefined;
+ if (!layers || !d || typeof d !== 'object') return null;
+ if (
+ typeof d.width !== 'number' ||
+ !Number.isFinite(d.width) ||
+ d.width < 1 ||
+ d.width > MAX_SYNC_CANVAS_DIM ||
+ typeof d.height !== 'number' ||
+ !Number.isFinite(d.height) ||
+ d.height < 1 ||
+ d.height > MAX_SYNC_CANVAS_DIM
+ ) {
+ return null;
+ }
+ const width = Math.round(d.width);
+ const height = Math.round(d.height);
+ const dpi =
+ typeof d.dpi === 'number' && Number.isFinite(d.dpi)
+ ? Math.max(36, Math.min(2400, Math.round(d.dpi)))
+ : undefined;
+ const colorMode =
+ msg.colorMode === 'color' || msg.colorMode === 'grayscale' || msg.colorMode === 'monochrome'
+ ? msg.colorMode
+ : 'color';
+
+ const perspectiveRuler =
+ msg.perspectiveRuler !== undefined
+ ? sanitizePerspectiveRuler(msg.perspectiveRuler) ?? null
+ : null;
+ const straightRuler =
+ msg.straightRuler !== undefined ? sanitizeStraightRuler(msg.straightRuler) ?? null : null;
+ const animationTimeline =
+ msg.animationTimeline !== undefined
+ ? sanitizeAnimationTimeline(msg.animationTimeline) ?? null
+ : null;
+
+ return {
+ type: 'DOC_SYNC_RESPONSE',
+ senderId,
+ targetPeerId: (msg.targetPeerId as string | number) ?? '',
+ roomName: typeof msg.roomName === 'string' ? msg.roomName.slice(0, 128) : undefined,
+ assignedLayerId:
+ typeof msg.assignedLayerId === 'string' ? msg.assignedLayerId.slice(0, 256) : undefined,
+ dimensions: { width, height, dpi },
+ colorMode,
+ layers,
+ perspectiveRuler,
+ straightRuler,
+ animationTimeline,
+ } as DocSyncResponseMessage;
+ }
+
+ case 'PEER_ROLE_UPDATE': {
+ const targetPeerId =
+ typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
+ ? String(msg.targetPeerId).trim().slice(0, 128)
+ : '';
+ if (!targetPeerId) return null;
+ if (msg.role !== 'host' && msg.role !== 'editor' && msg.role !== 'viewer') return null;
+ return {
+ type: 'PEER_ROLE_UPDATE',
+ senderId,
+ targetPeerId,
+ role: msg.role,
+ };
+ }
+
+ case 'PEER_KICK':
+ case 'PEER_BAN': {
+ const targetPeerId =
+ typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
+ ? String(msg.targetPeerId).trim().slice(0, 128)
+ : '';
+ if (!targetPeerId) return null;
+ const reason =
+ typeof msg.reason === 'string' && msg.reason.trim()
+ ? msg.reason.trim().slice(0, 256)
+ : undefined;
+ return {
+ type: msg.type,
+ senderId,
+ targetPeerId,
+ ...(reason ? { reason } : {}),
+ };
+ }
+
+ case 'PEER_UNBAN': {
+ const targetPeerId =
+ typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
+ ? String(msg.targetPeerId).trim().slice(0, 128)
+ : '';
+ if (!targetPeerId) return null;
+ return {
+ type: 'PEER_UNBAN',
+ senderId,
+ targetPeerId,
+ };
+ }
+
+ case 'ACCESS_DENIED': {
+ const allowedCodes = new Set<AccessDeniedCode>([
+ 'BANNED',
+ 'KICKED',
+ 'VIEWER_READONLY',
+ 'LAYER_LOCKED',
+ 'NOT_OWNER',
+ 'FORBIDDEN',
+ ]);
+ const code: AccessDeniedCode = allowedCodes.has(msg.code as AccessDeniedCode)
+ ? (msg.code as AccessDeniedCode)
+ : 'FORBIDDEN';
+ const reason =
+ typeof msg.reason === 'string' && msg.reason.trim()
+ ? msg.reason.trim().slice(0, 256)
+ : 'Action not permitted';
+ const targetPeerId =
+ typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
+ ? String(msg.targetPeerId).trim().slice(0, 128)
+ : undefined;
+ return {
+ type: 'ACCESS_DENIED',
+ senderId,
+ ...(targetPeerId ? { targetPeerId } : {}),
+ code,
+ reason,
+ };
+ }
+
+ default:
+ return msg as unknown as MultiplayerMessage;
+ }
+}
+
+export interface ConnectOptions {
+ isReconnect?: boolean;
+ sinceSeq?: number;
+}
+
class MultiplayerService {
private ws: WebSocket | null = null;
private messageHandlers: Set<MessageHandler> = new Set();
private closeHandlers: Set<() => void> = new Set();
private errorHandlers: Set<(err: Event) => void> = new Set();
private currentPeer: CollabPeer | null = null;
+ private localRole: CollabRole = 'editor';
- // Lamport Logical Clock for Vector CRDT and deterministic ordering
+ // Lamport Logical Clock for Vector CRDT + authoritative server sequence tracking
private lamportClock = 0;
+ private lastServerSeq = 0;
+
+ // Track already-broadcast brush asset hashes, tile versions, and tile delta batches
+ private sentAssetHashes: Set<string> = new Set();
+ private sentTileVersions: Map<string, number> = new Map();
+ private sentDeltaBatches: WeakSet<TileDelta[]> = new WeakSet();
// Throttling for cursor movement (max 60fps)
private lastCursorSendTime = 0;
private pendingCursor: { x: number; y: number; isDrawing: boolean; tool: ToolType } | null = null;
private cursorThrottleRaf: number | null = null;
+ // Trailing-edge throttles for high-frequency ruler / animation drag updates (~30Hz)
+ private perspectiveThrottleTimer: ReturnType<typeof setTimeout> | null = null;
+ private pendingPerspectiveRuler: PerspectiveRuler | null | undefined = undefined;
+ private straightThrottleTimer: ReturnType<typeof setTimeout> | null = null;
+ private pendingStraightRuler: StraightRuler | null | undefined = undefined;
+ private animationThrottleTimer: ReturnType<typeof setTimeout> | null = null;
+ private pendingAnimationTimeline: AnimationTimeline | null | undefined = undefined;
+
+ public clearSentAssetHashes(): void {
+ this.sentAssetHashes.clear();
+ }
+
+ public clearSyncDedupeCaches(): void {
+ this.sentAssetHashes.clear();
+ this.sentTileVersions.clear();
+ }
+
public getNextLamport(): number {
return ++this.lamportClock;
}
@@ -160,6 +630,27 @@ class MultiplayerService {
this.lamportClock = Math.max(this.lamportClock, remoteLamport) + 1;
}
+ public getLastServerSeq(): number {
+ return this.lastServerSeq;
+ }
+
+ public updateServerSeq(seq: number): void {
+ if (Number.isSafeInteger(seq) && seq > this.lastServerSeq) {
+ this.lastServerSeq = seq;
+ }
+ }
+
+ public sendDocSyncRequest(sinceSeq?: number): void {
+ if (!this.isConnected() || !this.currentPeer) return;
+ this.sendMessage({
+ type: 'DOC_SYNC_REQUEST',
+ targetPeerId: this.currentPeer.id,
+ ...(sinceSeq !== undefined && Number.isSafeInteger(sinceSeq) && sinceSeq >= 0
+ ? { sinceSeq }
+ : {}),
+ });
+ }
+
public isConnected(): boolean {
return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
}
@@ -168,14 +659,69 @@ class MultiplayerService {
return this.currentPeer;
}
+ public setLocalRole(role: CollabRole): void {
+ this.localRole = role;
+ if (this.currentPeer) {
+ this.currentPeer = {
+ ...this.currentPeer,
+ role,
+ isHost: role === 'host',
+ };
+ }
+ }
+
+ public getLocalRole(): CollabRole {
+ return this.localRole;
+ }
+
+ private canSendMutation(): boolean {
+ return this.localRole !== 'viewer';
+ }
+
public getBufferedAmount(): number {
return this.ws ? this.ws.bufferedAmount : 0;
}
- public connect(url: string, peer: CollabPeer, token?: string): Promise<void> {
+ private closeSocketQuietly(): void {
+ if (!this.ws) return;
+ const closingWs = this.ws;
+ this.ws = null;
+ try {
+ closingWs.onopen = null;
+ closingWs.onmessage = null;
+ closingWs.onclose = null;
+ closingWs.onerror = null;
+ closingWs.close();
+ } catch {
+ // ignore close errors
+ }
+ }
+
+ public connect(
+ url: string,
+ peer: CollabPeer,
+ token?: string,
+ options?: ConnectOptions
+ ): Promise<void> {
return new Promise((resolve, reject) => {
- this.disconnect();
+ const isReconnect = Boolean(options?.isReconnect);
+ if (isReconnect) {
+ this.closeSocketQuietly();
+ } else {
+ this.disconnect();
+ }
this.currentPeer = peer;
+ this.localRole = peer.isHost ? 'host' : peer.role ?? (isReconnect ? this.localRole : 'editor');
+
+ const resumeSeq =
+ isReconnect &&
+ typeof options?.sinceSeq === 'number' &&
+ Number.isSafeInteger(options.sinceSeq) &&
+ options.sinceSeq >= 0
+ ? options.sinceSeq
+ : isReconnect
+ ? this.lastServerSeq
+ : undefined;
let connectUrl = url;
let displayUrl = url;
@@ -232,10 +778,12 @@ class MultiplayerService {
ws.close();
return;
}
- // Send join handshake
+ // Send join handshake (carrying sinceSeq on reconnect for incremental op/tile catch-up)
this.sendMessage({
type: 'JOIN_REQUEST',
peer: this.currentPeer!,
+ ...(isReconnect ? { isReconnect: true } : {}),
+ ...(resumeSeq !== undefined ? { sinceSeq: resumeSeq } : {}),
});
settleResolve();
};
@@ -243,22 +791,35 @@ class MultiplayerService {
ws.onmessage = async (event) => {
if (this.ws !== ws) return;
try {
- if (event.data instanceof ArrayBuffer) {
- const parsed = this.decodeBinaryPacket(event.data);
- if (parsed) {
- this.notifyHandlers(parsed);
- }
- } else if (event.data instanceof Blob) {
- const buf = await event.data.arrayBuffer();
+ if (event.data instanceof ArrayBuffer || event.data instanceof Blob) {
+ const buf =
+ event.data instanceof ArrayBuffer
+ ? event.data
+ : await event.data.arrayBuffer();
const parsed = this.decodeBinaryPacket(buf);
if (parsed) {
+ if (buf.byteLength >= 7) {
+ const serverSeq = new DataView(buf).getUint32(3, true);
+ if (serverSeq > 0) {
+ parsed.seq = serverSeq;
+ this.updateServerSeq(serverSeq);
+ }
+ }
this.notifyHandlers(parsed);
}
} else if (typeof event.data === 'string') {
if (event.data.length > MAX_JSON_MESSAGE_CHARS) return;
- const data = JSON.parse(event.data) as MultiplayerMessage;
- if (data && typeof data === 'object' && typeof data.type === 'string') {
- this.notifyHandlers(data);
+ const raw = JSON.parse(event.data) as unknown;
+ const sanitized = sanitizeIncomingJsonMessage(raw);
+ if (sanitized) {
+ if (typeof sanitized.seq === 'number') {
+ this.updateServerSeq(sanitized.seq);
+ }
+ const remoteLamport = (sanitized as { lamport?: unknown }).lamport;
+ if (typeof remoteLamport === 'number' && Number.isFinite(remoteLamport)) {
+ this.updateLamport(remoteLamport);
+ }
+ this.notifyHandlers(sanitized);
}
}
} catch (err) {
@@ -310,10 +871,29 @@ class MultiplayerService {
}
}
this.currentPeer = null;
+ this.localRole = 'editor';
+ this.lastServerSeq = 0;
+ this.sentAssetHashes.clear();
+ this.sentTileVersions.clear();
if (this.cursorThrottleRaf) {
cancelAnimationFrame(this.cursorThrottleRaf);
this.cursorThrottleRaf = null;
}
+ if (this.perspectiveThrottleTimer) {
+ clearTimeout(this.perspectiveThrottleTimer);
+ this.perspectiveThrottleTimer = null;
+ }
+ this.pendingPerspectiveRuler = undefined;
+ if (this.straightThrottleTimer) {
+ clearTimeout(this.straightThrottleTimer);
+ this.straightThrottleTimer = null;
+ }
+ this.pendingStraightRuler = undefined;
+ if (this.animationThrottleTimer) {
+ clearTimeout(this.animationThrottleTimer);
+ this.animationThrottleTimer = null;
+ }
+ this.pendingAnimationTimeline = undefined;
}
public onMessage(handler: MessageHandler): () => void {
@@ -352,7 +932,7 @@ class MultiplayerService {
// --- Binary Packet Encoding & Decoding ---
- private decodeBinaryPacket(buf: ArrayBuffer): MultiplayerMessage | null {
+ public decodeBinaryPacket(buf: ArrayBuffer): MultiplayerMessage | null {
if (buf.byteLength < 11 || buf.byteLength > MAX_BINARY_PACKET_BYTES) return null;
const view = new DataView(buf);
@@ -370,25 +950,6 @@ class MultiplayerService {
const payloadBytes = new Uint8Array(buf, 11, payloadLen);
const decoder = new TextDecoder();
- const TOOL_TYPES_LIST: ToolType[] = [
- 'brush',
- 'eraser',
- 'pipette',
- 'transform',
- 'select-rect',
- 'select-lasso',
- 'select-wand',
- 'select-pen',
- 'select-eraser',
- 'fill',
- 'text',
- 'frame',
- 'balloon',
- 'vector-edit',
- 'liquify',
- 'shape',
- ];
-
switch (code) {
case CODE_STROKE_START: {
const jsonStr = decoder.decode(payloadBytes);
@@ -397,12 +958,13 @@ class MultiplayerService {
if (!safeSettings || !isValidRemotePoint(data?.startPoint)) return null;
return {
type: 'STROKE_START',
- strokeId: String(data.strokeId || ''),
+ strokeId: String(data.strokeId || '').slice(0, 128),
peerId: data.peerId,
peerName: String(data.peerName || 'Peer').slice(0, 64),
peerColor: String(data.peerColor || '#38bdf8').slice(0, 32),
- layerId: String(data.layerId || ''),
+ layerId: String(data.layerId || '').slice(0, 256),
brushSettings: safeSettings,
+ brushAssetRefs: sanitizeBrushAssetRefs(data.brushAssetRefs),
tool: TOOL_TYPES_LIST.includes(data.tool) ? data.tool : 'brush',
startPoint: {
...data.startPoint,
@@ -417,7 +979,7 @@ class MultiplayerService {
}
case CODE_STROKE_CHUNK: {
- // Format: [strokeIdLen: uint16, strokeIdStr, peerIdLen: uint16, peerIdStr, pointCount: uint16, points...]
+ // Format: [strokeIdLen: u16, strokeId, peerIdLen: u16, peerId, pointCount: u16, points (20B each)...]
let offset = 0;
if (payloadBytes.byteLength < 6) return null;
const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
@@ -436,7 +998,10 @@ class MultiplayerService {
const pointCount = pView.getUint16(offset, true);
offset += 2;
- if (pointCount > MAX_STROKE_CHUNK_POINTS || offset + pointCount * 16 > payloadBytes.byteLength) {
+ if (
+ pointCount > MAX_STROKE_CHUNK_POINTS ||
+ offset + pointCount * STROKE_CHUNK_POINT_STRIDE > payloadBytes.byteLength
+ ) {
return null;
}
@@ -446,13 +1011,21 @@ class MultiplayerService {
const y = pView.getFloat32(offset + 4, true);
const pressure = pView.getFloat32(offset + 8, true);
const width = pView.getFloat32(offset + 12, true);
- offset += 16;
+ const tiltX = pView.getInt8(offset + 16);
+ const tiltY = pView.getInt8(offset + 17);
+ const twist = (pView.getUint8(offset + 18) * 360) / 255;
+ const flags = pView.getUint8(offset + 19);
+ offset += STROKE_CHUNK_POINT_STRIDE;
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
points.push({
x,
y,
pressure: Number.isFinite(pressure) ? Math.max(0, Math.min(1, pressure)) : 0.5,
width: Number.isFinite(width) ? Math.max(0.1, Math.min(2000, width)) : 1,
+ tiltX,
+ tiltY,
+ twist,
+ isCorner: (flags & 1) !== 0,
});
}
@@ -471,9 +1044,9 @@ class MultiplayerService {
const data = JSON.parse(jsonStr);
return {
type: 'STROKE_FINISH',
- strokeId: data.strokeId,
+ strokeId: String(data.strokeId || '').slice(0, 128),
peerId: data.peerId,
- layerId: data.layerId,
+ layerId: String(data.layerId || '').slice(0, 256),
endPoint: data.endPoint,
dirtyRect: data.dirtyRect,
vectorStroke: data.vectorStroke,
@@ -481,18 +1054,29 @@ class MultiplayerService {
}
case CODE_TILE_DELTA: {
- // Format: [layerIdLen: uint16, layerIdStr, serializedTileBuffer...]
+ // Format: [layerIdLen: u16, layerId, lz4SerializedTileBuffer...]
let offset = 0;
if (payloadBytes.byteLength < 2) return null;
const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
const layerIdLen = pView.getUint16(offset, true);
offset += 2;
- if (offset + layerIdLen > payloadBytes.byteLength) return null;
+ if (layerIdLen === 0 || layerIdLen > 256 || offset + layerIdLen > payloadBytes.byteLength) {
+ return null;
+ }
const layerId = decoder.decode(payloadBytes.subarray(offset, offset + layerIdLen));
offset += layerIdLen;
const tilePacket = payloadBytes.subarray(offset);
- const tile = deserializeTileBuffer(layerId, tilePacket);
+ const tile = deserializeTileBufferStrict(layerId, tilePacket);
+ if (
+ !tile ||
+ tile.tileX < 0 ||
+ tile.tileY < 0 ||
+ tile.tileX >= MAX_TILE_COORD ||
+ tile.tileY >= MAX_TILE_COORD
+ ) {
+ return null;
+ }
return {
type: 'BINARY_TILE',
@@ -505,6 +1089,55 @@ class MultiplayerService {
} as TileStreamMessage;
}
+ case CODE_BRUSH_ASSET_DATA: {
+ // Format: [hashLen: u8, hashUtf8, mimeLen: u8, mimeUtf8, rawBytes...]
+ if (payloadBytes.byteLength < 4) return null;
+ let offset = 0;
+ const hashLen = payloadBytes[offset++];
+ if (hashLen === 0 || hashLen > 64 || offset + hashLen + 1 > payloadBytes.byteLength) {
+ return null;
+ }
+ const hash = decoder.decode(payloadBytes.subarray(offset, offset + hashLen));
+ offset += hashLen;
+
+ const mimeLen = payloadBytes[offset++];
+ if (mimeLen === 0 || mimeLen > 64 || offset + mimeLen > payloadBytes.byteLength) {
+ return null;
+ }
+ const mime = decoder.decode(payloadBytes.subarray(offset, offset + mimeLen));
+ offset += mimeLen;
+
+ const rawLen = payloadBytes.byteLength - offset;
+ if (
+ !isValidBrushAssetHash(hash) ||
+ !isAllowedBrushAssetMime(mime) ||
+ rawLen === 0 ||
+ rawLen > MAX_BRUSH_ASSET_BYTES
+ ) {
+ return null;
+ }
+
+ const data = new Uint8Array(rawLen);
+ data.set(payloadBytes.subarray(offset));
+ return {
+ type: 'BRUSH_ASSET_DATA',
+ hash,
+ mime,
+ data,
+ } as BrushAssetDataMessage;
+ }
+
+ case CODE_BRUSH_ASSET_REQUEST: {
+ const jsonStr = decoder.decode(payloadBytes);
+ const data = JSON.parse(jsonStr);
+ if (!isValidBrushAssetHash(data?.hash)) return null;
+ return {
+ type: 'BRUSH_ASSET_REQUEST',
+ hash: data.hash,
+ targetPeerId: data.targetPeerId,
+ } as BrushAssetRequestMessage;
+ }
+
case CODE_CURSOR_MOVE: {
if (payloadBytes.byteLength < 12) return null;
const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
@@ -543,6 +1176,82 @@ class MultiplayerService {
} as SelectiveUndoMessage;
}
+ case CODE_LAYER_MASK_DATA: {
+ // Format: [layerIdLen: u16, layerId, flags: u8, x: u32, y: u32, width: u32, height: u32, body...]
+ if (payloadBytes.byteLength < 19) return null;
+ const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
+ let offset = 0;
+ const layerIdLen = pView.getUint16(offset, true);
+ offset += 2;
+ if (layerIdLen === 0 || layerIdLen > 256 || offset + layerIdLen + 17 > payloadBytes.byteLength) {
+ return null;
+ }
+ const layerId = decoder.decode(payloadBytes.subarray(offset, offset + layerIdLen));
+ offset += layerIdLen;
+
+ const flags = payloadBytes[offset++];
+ const x = pView.getUint32(offset, true);
+ const y = pView.getUint32(offset + 4, true);
+ const width = pView.getUint32(offset + 8, true);
+ const height = pView.getUint32(offset + 12, true);
+ offset += 16;
+
+ if (
+ x > MAX_SYNC_CANVAS_DIM ||
+ y > MAX_SYNC_CANVAS_DIM ||
+ width === 0 ||
+ height === 0 ||
+ width > MAX_SYNC_CANVAS_DIM ||
+ height > MAX_SYNC_CANVAS_DIM
+ ) {
+ return null;
+ }
+
+ const isFullReplace = (flags & MASK_FLAG_FULL_REPLACE) !== 0;
+ const isCompressed = (flags & MASK_FLAG_LZ4) !== 0;
+ const isSolidFill = (flags & MASK_FLAG_SOLID_FILL) !== 0;
+ const body = payloadBytes.subarray(offset);
+
+ if (isSolidFill) {
+ if (body.byteLength !== 1) return null;
+ return {
+ type: 'BINARY_MASK',
+ layerId,
+ x,
+ y,
+ width,
+ height,
+ isFullReplace,
+ solidFill: body[0],
+ data: null,
+ } as LayerMaskDataMessage;
+ }
+
+ const expectedPixels = width * height;
+ if (expectedPixels <= 0 || expectedPixels > MAX_MASK_DECODE_BYTES) return null;
+
+ let data: Uint8Array | null;
+ if (isCompressed) {
+ data = lz4DecompressBlock(body, expectedPixels, MAX_MASK_DECODE_BYTES);
+ if (!data) return null;
+ } else {
+ if (body.byteLength !== expectedPixels) return null;
+ data = new Uint8Array(expectedPixels);
+ data.set(body);
+ }
+
+ return {
+ type: 'BINARY_MASK',
+ layerId,
+ x,
+ y,
+ width,
+ height,
+ isFullReplace,
+ data,
+ } as LayerMaskDataMessage;
+ }
+
default:
return null;
}
@@ -550,6 +1259,53 @@ class MultiplayerService {
// --- Drawing Events via Compact Binary Packets ---
+ public sendBrushAssetData(hash: string, mime: string, bytes: Uint8Array) {
+ if (!this.isConnected()) return;
+ if (!isValidBrushAssetHash(hash) || !isAllowedBrushAssetMime(mime)) return;
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_BRUSH_ASSET_BYTES) return;
+
+ const encoder = new TextEncoder();
+ const hashBytes = encoder.encode(hash);
+ const mimeBytes = encoder.encode(mime);
+ const payloadSize = 1 + hashBytes.length + 1 + mimeBytes.length + bytes.byteLength;
+ const packet = new Uint8Array(11 + payloadSize);
+ const view = new DataView(packet.buffer);
+
+ view.setUint8(0, BINARY_MAGIC_0);
+ view.setUint8(1, BINARY_MAGIC_1);
+ view.setUint8(2, CODE_BRUSH_ASSET_DATA);
+ view.setUint32(3, this.getNextLamport(), true);
+ view.setUint32(7, payloadSize, true);
+
+ let offset = 11;
+ packet[offset++] = hashBytes.length;
+ packet.set(hashBytes, offset);
+ offset += hashBytes.length;
+ packet[offset++] = mimeBytes.length;
+ packet.set(mimeBytes, offset);
+ offset += mimeBytes.length;
+ packet.set(bytes, offset);
+
+ this.sendBinary(packet);
+ }
+
+ public sendBrushAssetRequest(hash: string, targetPeerId?: string | number) {
+ if (!this.isConnected() || !isValidBrushAssetHash(hash)) return;
+
+ const encoder = new TextEncoder();
+ const payloadBytes = encoder.encode(JSON.stringify({ hash, targetPeerId }));
+ const packet = new Uint8Array(11 + payloadBytes.length);
+ const view = new DataView(packet.buffer);
+ view.setUint8(0, BINARY_MAGIC_0);
+ view.setUint8(1, BINARY_MAGIC_1);
+ view.setUint8(2, CODE_BRUSH_ASSET_REQUEST);
+ view.setUint32(3, this.getNextLamport(), true);
+ view.setUint32(7, payloadBytes.length, true);
+ packet.set(payloadBytes, 11);
+
+ this.sendBinary(packet);
+ }
+
public sendStrokeStart(
strokeId: string,
layerId: string,
@@ -557,7 +1313,16 @@ class MultiplayerService {
tool: ToolType,
startPoint: Point
) {
- if (!this.isConnected() || !this.currentPeer) return;
+ if (!this.isConnected() || !this.currentPeer || !this.canSendMutation()) return;
+
+ const { wireSettings, assetRefs, assets } = prepareBrushSettingsForWire(brushSettings);
+ for (let i = 0; i < assets.length; i++) {
+ const asset = assets[i];
+ if (!this.sentAssetHashes.has(asset.hash)) {
+ this.sendBrushAssetData(asset.hash, asset.mime, asset.bytes);
+ this.sentAssetHashes.add(asset.hash);
+ }
+ }
const encoder = new TextEncoder();
const payloadStr = JSON.stringify({
@@ -566,7 +1331,8 @@ class MultiplayerService {
peerName: this.currentPeer.name,
peerColor: this.currentPeer.color,
layerId,
- brushSettings,
+ brushSettings: wireSettings,
+ brushAssetRefs: assetRefs,
tool,
startPoint,
});
@@ -585,7 +1351,7 @@ class MultiplayerService {
}
public sendStrokeChunk(strokeId: string, points: Point[]) {
- if (!this.isConnected() || !this.currentPeer || points.length === 0) return;
+ if (!this.isConnected() || !this.currentPeer || !this.canSendMutation() || points.length === 0) return;
const MAX_POINTS_PER_PACKET = 4096;
if (points.length > MAX_POINTS_PER_PACKET) {
@@ -599,8 +1365,8 @@ class MultiplayerService {
const strokeIdBytes = encoder.encode(strokeId);
const peerIdBytes = encoder.encode(String(this.currentPeer.id));
- // Size: 2 + strokeIdBytes.length + 2 + peerIdBytes.length + 2 + (points.length * 16)
- const payloadSize = 6 + strokeIdBytes.length + peerIdBytes.length + points.length * 16;
+ const payloadSize =
+ 6 + strokeIdBytes.length + peerIdBytes.length + points.length * STROKE_CHUNK_POINT_STRIDE;
const packet = new Uint8Array(11 + payloadSize);
const view = new DataView(packet.buffer);
@@ -630,7 +1396,14 @@ class MultiplayerService {
view.setFloat32(offset + 4, pt.y, true);
view.setFloat32(offset + 8, pt.pressure, true);
view.setFloat32(offset + 12, pt.width, true);
- offset += 16;
+ const tx = Math.max(-90, Math.min(90, Math.round(pt.tiltX ?? 0)));
+ const ty = Math.max(-90, Math.min(90, Math.round(pt.tiltY ?? 0)));
+ const tw = Math.max(0, Math.min(255, Math.round((((pt.twist ?? 0) % 360 + 360) % 360) * (255 / 360))));
+ view.setInt8(offset + 16, tx);
+ view.setInt8(offset + 17, ty);
+ view.setUint8(offset + 18, tw);
+ view.setUint8(offset + 19, pt.isCorner ? 1 : 0);
+ offset += STROKE_CHUNK_POINT_STRIDE;
}
this.sendBinary(packet);
@@ -643,7 +1416,7 @@ class MultiplayerService {
dirtyRect?: DirtyRect,
vectorStroke?: VectorStroke
) {
- if (!this.isConnected() || !this.currentPeer) return;
+ if (!this.isConnected() || !this.currentPeer || !this.canSendMutation()) return;
const encoder = new TextEncoder();
const payloadStr = JSON.stringify({
@@ -669,10 +1442,17 @@ class MultiplayerService {
}
/**
- * Stream a single sparse tile delta (e.g. from flood fill or progressive document sync).
+ * Stream a single LZ4-compressed binary tile (or 14-byte deletion tombstone when tile.data === null).
*/
public sendTileDelta(layerId: string, tile: TileBuffer) {
- if (!this.isConnected()) return;
+ if (!this.isConnected() || !this.canSendMutation()) return;
+
+ const tileKey = `${layerId}:${tile.tileX}:${tile.tileY}`;
+ if (tile.data === null) {
+ this.sentTileVersions.delete(tileKey);
+ } else if (tile.version > 0) {
+ this.sentTileVersions.set(tileKey, tile.version);
+ }
const encoder = new TextEncoder();
const layerIdBytes = encoder.encode(layerId);
@@ -698,11 +1478,118 @@ class MultiplayerService {
this.sendBinary(packet);
}
+ /**
+ * Broadcast authoritative LZ4-compressed BINARY_TILE packets for all tiles touched
+ * by a raster operation (stroke, fill, transform, liquify, filter, tonal, undo/redo).
+ * Idempotent per TileDelta[] reference unless options.force is set.
+ */
+ public sendTileDeltas(
+ deltas: TileDelta[],
+ grid: SparseTileGrid,
+ options?: { force?: boolean }
+ ): void {
+ if (!this.isConnected() || !this.canSendMutation() || !deltas || deltas.length === 0) return;
+ if (!options?.force && this.sentDeltaBatches.has(deltas)) return;
+ this.sentDeltaBatches.add(deltas);
+
+ const seenKeys = new Set<string>();
+ const queue: Array<{ layerId: string; tile: TileBuffer }> = [];
+
+ for (let i = 0; i < deltas.length; i++) {
+ const delta = deltas[i];
+ if (seenKeys.has(delta.key)) continue;
+ seenKeys.add(delta.key);
+
+ const { layerId, tileX, tileY } = parseTileKey(delta.key);
+ const tile = grid.getTile(layerId, tileX, tileY, 0);
+ if (tile && tile.data) {
+ queue.push({ layerId, tile });
+ } else {
+ queue.push({
+ layerId,
+ tile: {
+ layerId,
+ tileX,
+ tileY,
+ format: delta.format,
+ data: null,
+ dirty: true,
+ version: 0,
+ isPagedToDisk: false,
+ lastAccessTimestamp: 0,
+ lod: 0,
+ },
+ });
+ }
+ }
+
+ this.streamTileQueuePaced(queue);
+ }
+
+ /**
+ * Stream all populated LOD 0 tiles of a layer as LZ4-compressed BINARY_TILE packets.
+ * Deduplicates unchanged tile versions unless options.force is true.
+ */
+ public streamLayerTiles(
+ layerId: string,
+ grid: SparseTileGrid,
+ options?: { force?: boolean }
+ ): void {
+ if (!this.isConnected() || !this.canSendMutation()) return;
+ const tiles = grid.getLayerTiles(layerId);
+ if (tiles.length === 0) return;
+
+ const force = Boolean(options?.force);
+ const queue: Array<{ layerId: string; tile: TileBuffer }> = [];
+ for (let i = 0; i < tiles.length; i++) {
+ const t = tiles[i];
+ if (!t.data || t.data.byteLength === 0) continue;
+ if (!force && t.version > 0) {
+ const key = `${layerId}:${t.tileX}:${t.tileY}`;
+ if (this.sentTileVersions.get(key) === t.version) continue;
+ }
+ queue.push({ layerId, tile: t });
+ }
+ this.streamTileQueuePaced(queue);
+ }
+
+ private streamTileQueuePaced(queue: Array<{ layerId: string; tile: TileBuffer }>): void {
+ if (queue.length === 0 || !this.isConnected()) return;
+
+ const MAX_BUFFERED_BYTES = 2 * 1024 * 1024;
+ // Small operations (typical strokes) flush synchronously before STROKE_FINISH for zero flicker
+ if (queue.length <= 32 && this.getBufferedAmount() <= MAX_BUFFERED_BYTES) {
+ for (let i = 0; i < queue.length; i++) {
+ this.sendTileDelta(queue[i].layerId, queue[i].tile);
+ }
+ return;
+ }
+
+ let idx = 0;
+ const BATCH_SIZE = 16;
+ const pump = () => {
+ if (!this.isConnected()) return;
+ if (this.getBufferedAmount() > MAX_BUFFERED_BYTES) {
+ setTimeout(pump, 20);
+ return;
+ }
+ const end = Math.min(idx + BATCH_SIZE, queue.length);
+ for (; idx < end; idx++) {
+ this.sendTileDelta(queue[idx].layerId, queue[idx].tile);
+ }
+ if (idx < queue.length) {
+ setTimeout(pump, 4);
+ }
+ };
+
+ pump();
+ }
+
/**
* Broadcast a selective collaborative undo command (undoing a stroke without reverting peer strokes).
*/
public sendSelectiveUndo(strokeId: string) {
- if (!this.isConnected() || !this.currentPeer) return;
+ if (!this.isConnected() || !this.currentPeer || !this.canSendMutation()) return;
const encoder = new TextEncoder();
const payloadStr = JSON.stringify({
@@ -765,24 +1652,6 @@ class MultiplayerService {
packet.set(peerIdBytes, offset);
offset += peerIdBytes.length;
- const TOOL_TYPES_LIST: ToolType[] = [
- 'brush',
- 'eraser',
- 'pipette',
- 'transform',
- 'select-rect',
- 'select-lasso',
- 'select-wand',
- 'select-pen',
- 'select-eraser',
- 'fill',
- 'text',
- 'frame',
- 'balloon',
- 'vector-edit',
- 'liquify',
- 'shape',
- ];
const toolIdx = Math.max(0, TOOL_TYPES_LIST.indexOf(this.pendingCursor.tool));
view.setFloat32(offset, this.pendingCursor.x, true);
view.setFloat32(offset + 4, this.pendingCursor.y, true);
@@ -793,21 +1662,22 @@ class MultiplayerService {
this.pendingCursor = null;
}
- // --- Layer Synchronization ---
+ // --- Layer & Document State Synchronization ---
- public sendLayerAdd(layerItem: LayerItem, imageDataUrl?: string) {
- if (!this.isConnected()) return;
+ public sendLayerAdd(layerItem: LayerItem | WireLayerItem, insertIndex?: number) {
+ if (!this.isConnected() || !this.canSendMutation()) return;
+ const wireLayer = serializeLayerForWire(layerItem as LayerItem);
const msg: LayerActionMessage = {
type: 'LAYER_ADD',
- layerId: layerItem.id,
- layerItem,
- imageDataUrl,
+ layerId: wireLayer.id,
+ layerItem: wireLayer,
+ ...(insertIndex !== undefined ? { insertIndex } : {}),
};
this.sendMessage(msg);
}
public sendLayerDelete(layerId: string) {
- if (!this.isConnected()) return;
+ if (!this.isConnected() || !this.canSendMutation()) return;
const msg: LayerActionMessage = {
type: 'LAYER_DELETE',
layerId,
@@ -816,7 +1686,7 @@ class MultiplayerService {
}
public sendLayerClear(layerId: string) {
- if (!this.isConnected()) return;
+ if (!this.isConnected() || !this.canSendMutation()) return;
const msg: LayerActionMessage = {
type: 'LAYER_CLEAR',
layerId,
@@ -825,7 +1695,7 @@ class MultiplayerService {
}
public sendLayerRename(layerId: string, newName: string) {
- if (!this.isConnected()) return;
+ if (!this.isConnected() || !this.canSendMutation()) return;
const msg: LayerActionMessage = {
type: 'LAYER_RENAME',
layerId,
@@ -835,7 +1705,7 @@ class MultiplayerService {
}
public sendLayerVisibility(layerId: string, visible: boolean) {
- if (!this.isConnected()) return;
+ if (!this.isConnected() || !this.canSendMutation()) return;
const msg: LayerActionMessage = {
type: 'LAYER_VISIBILITY',
layerId,
@@ -845,7 +1715,7 @@ class MultiplayerService {
}
public sendLayerOpacity(layerId: string, opacity: number) {
- if (!this.isConnected()) return;
+ if (!this.isConnected() || !this.canSendMutation()) return;
const msg: LayerActionMessage = {
type: 'LAYER_OPACITY',
layerId,
@@ -854,6 +1724,361 @@ class MultiplayerService {
this.sendMessage(msg);
}
+ public sendLayerUpdate(
+ layerId: string,
+ patch: Partial<WireLayerItem>,
+ clearedFields?: LayerClearableField[]
+ ) {
+ if (!this.isConnected() || !this.canSendMutation() || !layerId) return;
+ const safePatch = sanitizeWireLayerPatch(patch);
+ const safeCleared = clearedFields && clearedFields.length > 0 ? sanitizeClearedFields(clearedFields) : [];
+ if (Object.keys(safePatch).length === 0 && safeCleared.length === 0) return;
+
+ const msg: LayerUpdateMessage = {
+ type: 'LAYER_UPDATE',
+ layerId,
+ patch: safePatch,
+ ...(safeCleared.length > 0 ? { clearedFields: safeCleared } : {}),
+ lamport: this.getNextLamport(),
+ };
+ this.sendMessage(msg);
+ }
+
+ public sendLayerTreeSync(
+ layers: Array<LayerItem | WireLayerItem>,
+ options?: { dirtyTileLayerIds?: string[]; removedLayerIds?: string[] }
+ ) {
+ if (!this.isConnected() || !this.canSendMutation() || layers.length === 0) return;
+ const wireLayers = layers.map((l) => serializeLayerForWire(l as LayerItem));
+ const msg: LayerTreeSyncMessage = {
+ type: 'LAYER_TREE_SYNC',
+ layers: wireLayers,
+ lamport: this.getNextLamport(),
+ ...(options?.dirtyTileLayerIds && options.dirtyTileLayerIds.length > 0
+ ? { dirtyTileLayerIds: options.dirtyTileLayerIds }
+ : {}),
+ ...(options?.removedLayerIds && options.removedLayerIds.length > 0
+ ? { removedLayerIds: options.removedLayerIds }
+ : {}),
+ };
+ this.sendMessage(msg);
+ }
+
+ // --- Binary Layer Mask Synchronization (LZ4 / 1-byte solid fill, auto-chunked <= 1024x1024) ---
+
+ private sendMaskPacket(
+ layerId: string,
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ isFullReplace: boolean,
+ solidValue: number | null,
+ pixels: Uint8Array | null
+ ) {
+ if (!this.isConnected() || !this.canSendMutation() || !layerId || width <= 0 || height <= 0) return;
+
+ const encoder = new TextEncoder();
+ const layerIdBytes = encoder.encode(layerId);
+ if (layerIdBytes.length === 0 || layerIdBytes.length > 256) return;
+
+ let flags = isFullReplace ? MASK_FLAG_FULL_REPLACE : 0;
+ let body: Uint8Array;
+
+ if (solidValue !== null) {
+ flags |= MASK_FLAG_SOLID_FILL;
+ body = new Uint8Array([Math.max(0, Math.min(255, Math.round(solidValue)))]);
+ } else if (pixels) {
+ const compressed = lz4CompressBlock(pixels);
+ if (compressed.byteLength < pixels.byteLength) {
+ flags |= MASK_FLAG_LZ4;
+ body = compressed;
+ } else {
+ body = pixels;
+ }
+ } else {
+ return;
+ }
+
+ const payloadSize = 2 + layerIdBytes.length + 1 + 16 + body.byteLength;
+ const packet = new Uint8Array(11 + payloadSize);
+ const view = new DataView(packet.buffer);
+
+ view.setUint8(0, BINARY_MAGIC_0);
+ view.setUint8(1, BINARY_MAGIC_1);
+ view.setUint8(2, CODE_LAYER_MASK_DATA);
+ view.setUint32(3, this.getNextLamport(), true);
+ view.setUint32(7, payloadSize, true);
+
+ let offset = 11;
+ view.setUint16(offset, layerIdBytes.length, true);
+ offset += 2;
+ packet.set(layerIdBytes, offset);
+ offset += layerIdBytes.length;
+
+ packet[offset++] = flags;
+ view.setUint32(offset, x, true);
+ view.setUint32(offset + 4, y, true);
+ view.setUint32(offset + 8, width, true);
+ view.setUint32(offset + 12, height, true);
+ offset += 16;
+
+ packet.set(body, offset);
+ this.sendBinary(packet);
+ }
+
+ public sendLayerMaskSolid(
+ layerId: string,
+ width: number,
+ height: number,
+ value: number = 255,
+ isFullReplace: boolean = true
+ ) {
+ if (!this.isConnected() || width <= 0 || height <= 0) return;
+ this.sendMaskPacket(layerId, 0, 0, width, height, isFullReplace, value, null);
+ }
+
+ public sendLayerMaskData(layerId: string, maskCanvas: HTMLCanvasElement, rect?: DirtyRect) {
+ if (!this.isConnected() || !maskCanvas || maskCanvas.width <= 0 || maskCanvas.height <= 0) {
+ return;
+ }
+
+ const isFull = !rect;
+ const x0 = rect ? Math.max(0, Math.min(maskCanvas.width - 1, Math.floor(rect.x))) : 0;
+ const y0 = rect ? Math.max(0, Math.min(maskCanvas.height - 1, Math.floor(rect.y))) : 0;
+ const x1 = rect
+ ? Math.max(x0 + 1, Math.min(maskCanvas.width, Math.ceil(rect.x + rect.width)))
+ : maskCanvas.width;
+ const y1 = rect
+ ? Math.max(y0 + 1, Math.min(maskCanvas.height, Math.ceil(rect.y + rect.height)))
+ : maskCanvas.height;
+ const totalW = x1 - x0;
+ const totalH = y1 - y0;
+ if (totalW <= 0 || totalH <= 0) return;
+
+ // Small rects (<= 1024x1024) send in a single packet
+ if (totalW * totalH <= MAX_MASK_CHUNK_DIM * MAX_MASK_CHUNK_DIM) {
+ const extracted = extractMaskGrayscaleRect(maskCanvas, {
+ x: x0,
+ y: y0,
+ width: totalW,
+ height: totalH,
+ });
+ if (!extracted) return;
+ this.sendMaskPacket(
+ layerId,
+ extracted.x,
+ extracted.y,
+ extracted.width,
+ extracted.height,
+ isFull,
+ extracted.solidValue,
+ extracted.solidValue === null ? extracted.pixels : null
+ );
+ return;
+ }
+
+ // Large masks: chunk into <= 1024x1024 tiles so every packet stays well under the 8MB WS ceiling
+ const chunks: Array<{
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ solidValue: number | null;
+ pixels: Uint8Array | null;
+ }> = [];
+ for (let cy = y0; cy < y1; cy += MAX_MASK_CHUNK_DIM) {
+ const ch = Math.min(MAX_MASK_CHUNK_DIM, y1 - cy);
+ for (let cx = x0; cx < x1; cx += MAX_MASK_CHUNK_DIM) {
+ const cw = Math.min(MAX_MASK_CHUNK_DIM, x1 - cx);
+ const extracted = extractMaskGrayscaleRect(maskCanvas, {
+ x: cx,
+ y: cy,
+ width: cw,
+ height: ch,
+ });
+ if (!extracted) continue;
+ chunks.push({
+ x: extracted.x,
+ y: extracted.y,
+ width: extracted.width,
+ height: extracted.height,
+ solidValue: extracted.solidValue,
+ pixels: extracted.solidValue === null ? extracted.pixels : null,
+ });
+ }
+ }
+
+ if (chunks.length === 0) return;
+
+ // Fast collapse if all chunks share the same uniform solid fill
+ const firstSolid = chunks[0].solidValue;
+ if (firstSolid !== null && chunks.every((c) => c.solidValue === firstSolid)) {
+ this.sendMaskPacket(layerId, x0, y0, totalW, totalH, isFull, firstSolid, null);
+ return;
+ }
+
+ const MAX_BUFFERED_BYTES = 2 * 1024 * 1024;
+ let idx = 0;
+ const pump = () => {
+ if (!this.isConnected()) return;
+ if (this.getBufferedAmount() > MAX_BUFFERED_BYTES) {
+ setTimeout(pump, 20);
+ return;
+ }
+ const end = Math.min(idx + 8, chunks.length);
+ for (; idx < end; idx++) {
+ const c = chunks[idx];
+ this.sendMaskPacket(layerId, c.x, c.y, c.width, c.height, false, c.solidValue, c.pixels);
+ }
+ if (idx < chunks.length) {
+ setTimeout(pump, 4);
+ }
+ };
+ pump();
+ }
+
+ // --- Perspective Ruler, Straight Ruler, Animation & Canvas Resize Sync ---
+
+ public sendPerspectiveRulerSync(perspectiveRuler: PerspectiveRuler | null, immediate = false) {
+ if (!this.isConnected() || !this.canSendMutation()) return;
+ this.pendingPerspectiveRuler = perspectiveRuler;
+ const flush = () => {
+ this.perspectiveThrottleTimer = null;
+ if (!this.isConnected() || !this.canSendMutation() || this.pendingPerspectiveRuler === undefined) return;
+ const value = this.pendingPerspectiveRuler;
+ this.pendingPerspectiveRuler = undefined;
+ const msg: PerspectiveRulerSyncMessage = {
+ type: 'PERSPECTIVE_RULER_SYNC',
+ perspectiveRuler: value,
+ lamport: this.getNextLamport(),
+ };
+ this.sendMessage(msg);
+ };
+ if (immediate) {
+ if (this.perspectiveThrottleTimer) clearTimeout(this.perspectiveThrottleTimer);
+ flush();
+ } else if (!this.perspectiveThrottleTimer) {
+ this.perspectiveThrottleTimer = setTimeout(flush, STATE_SYNC_THROTTLE_MS);
+ }
+ }
+
+ public sendStraightRulerSync(straightRuler: StraightRuler | null, immediate = false) {
+ if (!this.isConnected() || !this.canSendMutation()) return;
+ this.pendingStraightRuler = straightRuler;
+ const flush = () => {
+ this.straightThrottleTimer = null;
+ if (!this.isConnected() || !this.canSendMutation() || this.pendingStraightRuler === undefined) return;
+ const value = this.pendingStraightRuler;
+ this.pendingStraightRuler = undefined;
+ const msg: StraightRulerSyncMessage = {
+ type: 'STRAIGHT_RULER_SYNC',
+ straightRuler: value,
+ lamport: this.getNextLamport(),
+ };
+ this.sendMessage(msg);
+ };
+ if (immediate) {
+ if (this.straightThrottleTimer) clearTimeout(this.straightThrottleTimer);
+ flush();
+ } else if (!this.straightThrottleTimer) {
+ this.straightThrottleTimer = setTimeout(flush, STATE_SYNC_THROTTLE_MS);
+ }
+ }
+
+ public sendAnimationSync(animationTimeline: AnimationTimeline | null, immediate = false) {
+ if (!this.isConnected() || !this.canSendMutation()) return;
+ const wireTimeline: AnimationTimeline | null = animationTimeline
+ ? { ...animationTimeline, isPlaying: false }
+ : null;
+ this.pendingAnimationTimeline = wireTimeline;
+ const flush = () => {
+ this.animationThrottleTimer = null;
+ if (!this.isConnected() || !this.canSendMutation() || this.pendingAnimationTimeline === undefined) return;
+ const value = this.pendingAnimationTimeline;
+ this.pendingAnimationTimeline = undefined;
+ const msg: AnimationSyncMessage = {
+ type: 'ANIMATION_SYNC',
+ animationTimeline: value,
+ lamport: this.getNextLamport(),
+ };
+ this.sendMessage(msg);
+ };
+ if (immediate) {
+ if (this.animationThrottleTimer) clearTimeout(this.animationThrottleTimer);
+ flush();
+ } else if (!this.animationThrottleTimer) {
+ this.animationThrottleTimer = setTimeout(flush, STATE_SYNC_THROTTLE_MS);
+ }
+ }
+
+ public sendCanvasResize(dimensions: CanvasDimensions, options: ResizeCanvasOptions) {
+ if (!this.isConnected() || !this.canSendMutation()) return;
+ const msg: CanvasResizeMessage = {
+ type: 'CANVAS_RESIZE',
+ dimensions,
+ options,
+ lamport: this.getNextLamport(),
+ };
+ this.sendMessage(msg);
+ }
+
+ // --- Room Roles & Moderation (Host-authoritative) ---
+
+ public sendPeerRoleUpdate(targetPeerId: string | number, role: CollabRole) {
+ if (!this.isConnected() || this.localRole !== 'host') return;
+ const msg: PeerRoleUpdateMessage = {
+ type: 'PEER_ROLE_UPDATE',
+ targetPeerId,
+ role,
+ };
+ this.sendMessage(msg);
+ }
+
+ public sendPeerKick(targetPeerId: string | number, reason?: string) {
+ if (!this.isConnected() || this.localRole !== 'host') return;
+ const msg: PeerKickMessage = {
+ type: 'PEER_KICK',
+ targetPeerId,
+ ...(reason ? { reason } : {}),
+ };
+ this.sendMessage(msg);
+ }
+
+ public sendPeerBan(targetPeerId: string | number, reason?: string) {
+ if (!this.isConnected() || this.localRole !== 'host') return;
+ const msg: PeerBanMessage = {
+ type: 'PEER_BAN',
+ targetPeerId,
+ ...(reason ? { reason } : {}),
+ };
+ this.sendMessage(msg);
+ }
+
+ public sendPeerUnban(targetPeerId: string | number) {
+ if (!this.isConnected() || this.localRole !== 'host') return;
+ const msg: PeerUnbanMessage = {
+ type: 'PEER_UNBAN',
+ targetPeerId,
+ };
+ this.sendMessage(msg);
+ }
+
+ public sendAccessDenied(
+ code: AccessDeniedCode,
+ reason: string,
+ targetPeerId?: string | number
+ ) {
+ if (!this.isConnected()) return;
+ const msg: AccessDeniedMessage = {
+ type: 'ACCESS_DENIED',
+ code,
+ reason,
+ ...(targetPeerId !== undefined ? { targetPeerId } : {}),
+ };
+ this.sendMessage(msg);
+ }
+
// --- Radar Ping ---
public sendPing(x: number, y: number) {
diff --git a/src/stores/useToolStore.ts b/src/stores/useToolStore.ts
index a7944f1..bf92a2b 100644
--- a/src/stores/useToolStore.ts
+++ b/src/stores/useToolStore.ts
@@ -98,7 +98,7 @@ function loadInitialLiquifySettings(): LiquifySettings {
};
try {
if (typeof localStorage !== 'undefined') {
- const saved = localStorage.getItem('sora_paint_liquify_settings');
+ const saved = localStorage.getItem('ink_studio_liquify_settings');
if (saved) return { ...defaults, ...(JSON.parse(saved) as Partial<LiquifySettings>) };
}
} catch {
@@ -110,7 +110,7 @@ function loadInitialLiquifySettings(): LiquifySettings {
function loadInitialShapeSettings(): ShapeSettings {
try {
if (typeof localStorage !== 'undefined') {
- const saved = localStorage.getItem('sora_paint_shape_settings');
+ const saved = localStorage.getItem('ink_studio_shape_settings');
if (saved) return { ...DEFAULT_SHAPE_SETTINGS, ...(JSON.parse(saved) as Partial<ShapeSettings>) };
}
} catch {
@@ -528,7 +528,7 @@ export const toolStoreActions = {
updateLiquifySettings(patch: Partial<LiquifySettings>): void {
useToolStore.setState((prev) => {
const next = { ...prev.liquifySettings, ...patch };
- safeLocalStorageSetItem('sora_paint_liquify_settings', JSON.stringify(next), 'liquify settings');
+ safeLocalStorageSetItem('ink_studio_liquify_settings', JSON.stringify(next), 'liquify settings');
return { liquifySettings: next };
});
},
@@ -536,7 +536,7 @@ export const toolStoreActions = {
updateShapeSettings(patch: Partial<ShapeSettings>): void {
useToolStore.setState((prev) => {
const next = { ...prev.shapeSettings, ...patch };
- safeLocalStorageSetItem('sora_paint_shape_settings', JSON.stringify(next), 'shape settings');
+ safeLocalStorageSetItem('ink_studio_shape_settings', JSON.stringify(next), 'shape settings');
return { shapeSettings: next };
});
},
diff --git a/src/stores/useUiStore.ts b/src/stores/useUiStore.ts
index ee5214c..68bf146 100644
--- a/src/stores/useUiStore.ts
+++ b/src/stores/useUiStore.ts
@@ -1,6 +1,7 @@
import { AppSettings, loadAppSettings, saveAppSettings } from '../types/settings';
import { CrashedSessionInfo } from '../services/recoveryService';
-import { TonalCorrectionType, ProcessingBounds } from '../utils/tonalEngine';
+import { TonalCorrectionType, ProcessingBounds, TileHistogramMap } from '../utils/tonalEngine';
+import type { TileSnapshotEntry } from '../utils/tileEngine';
import { safeLocalStorageSetItem, setStorageQuotaNotifier } from '../utils/safeStorage';
import { createStore } from './createStore';
import { useUpdaterStore } from './useUpdaterStore';
@@ -9,7 +10,8 @@ export interface TonalModalState {
isOpen: boolean;
type: TonalCorrectionType;
targetLayerId: string;
- beforeImageData: ImageData | null;
+ beforeTileSnapshot: Map<string, TileSnapshotEntry> | null;
+ histograms: TileHistogramMap | null;
selectionMask: Uint8Array | null;
bounds: ProcessingBounds;
}
@@ -61,7 +63,8 @@ const DEFAULT_TONAL_MODAL_STATE: TonalModalState = {
isOpen: false,
type: 'brightness-contrast',
targetLayerId: '',
- beforeImageData: null,
+ beforeTileSnapshot: null,
+ histograms: null,
selectionMask: null,
bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
};
diff --git a/src/types/editor.ts b/src/types/editor.ts
index 13738e6..53a45dc 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -1,6 +1,6 @@
import type { ReactNode } from 'react';
import { PerspectiveRuler, StraightRuler } from './perspective';
-import type { SparseTileGrid } from '../utils/tileEngine';
+import type { SparseTileGrid, TileSnapshotEntry } from '../utils/tileEngine';
export type {
ShapeKind,
ShapeDrawMode,
@@ -360,7 +360,6 @@ export interface DocumentTab {
} | null;
layers: LayerItem[];
activeLayerId: string;
- layerCanvasesMap?: Map<string, HTMLCanvasElement>;
historyList?: HistoryItemMeta[];
historyIndex?: number;
perspectiveRuler?: PerspectiveRuler | null;
@@ -536,6 +535,7 @@ export interface CanvasSelection {
origY: number;
layerId: string;
beforeImageData?: ImageData;
+ beforeTileSnapshot?: Map<string, TileSnapshotEntry>;
} | null;
}
@@ -543,7 +543,8 @@ export interface TransformSession {
active: boolean;
layerId: string;
sourceCanvas: HTMLCanvasElement;
- beforeImageData: ImageData;
+ beforeImageData?: ImageData;
+ beforeTileSnapshot?: Map<string, TileSnapshotEntry>;
bounds: { x: number; y: number; width: number; height: number };
x: number;
y: number;
@@ -561,26 +562,41 @@ export interface TransformSession {
layerIds?: string[];
layerSourceCanvases?: Map<string, HTMLCanvasElement>;
layerBeforeImages?: Map<string, ImageData>;
-}
-
-export type BlendMode =
- | 'normal'
- | 'multiply'
- | 'screen'
- | 'overlay'
- | 'darken'
- | 'lighten'
- | 'color-dodge'
- | 'color-burn'
- | 'hard-light'
- | 'soft-light'
- | 'difference'
- | 'exclusion'
- | 'pass-through'
- | 'linear-burn'
- | 'add-glow'
- | 'color-dodge-glow'
- | 'divide';
+ layerBeforeSnapshots?: Map<string, Map<string, TileSnapshotEntry>>;
+}
+
+export const ALL_BLEND_MODES = [
+ 'normal',
+ 'multiply',
+ 'screen',
+ 'overlay',
+ 'darken',
+ 'lighten',
+ 'color-dodge',
+ 'color-burn',
+ 'hard-light',
+ 'soft-light',
+ 'difference',
+ 'exclusion',
+ 'pass-through',
+ 'linear-burn',
+ 'add-glow',
+ 'color-dodge-glow',
+ 'divide',
+ 'vivid-light',
+ 'linear-light',
+ 'pin-light',
+ 'hard-mix',
+ 'subtract',
+ 'darker-color',
+ 'lighter-color',
+ 'hue',
+ 'saturation',
+ 'color',
+ 'luminosity',
+] as const;
+
+export type BlendMode = (typeof ALL_BLEND_MODES)[number];
export interface HistoryItemMeta {
id: string;
@@ -800,7 +816,9 @@ export interface LayerItem {
balloonData?: SpeechBalloon;
// Legacy Speech Balloon array
balloons?: SpeechBalloon[];
- // Collaborative Layer Soft-Locking
+ // Collaborative Layer Ownership & Owner-Locking
+ ownerPeerId?: string | number;
+ ownerPeerName?: string;
reservedByPeerId?: string | number;
reservedByPeerName?: string;
}
@@ -874,7 +892,7 @@ export interface NewCanvasOptions {
defaultFrequency?: number;
}
-export interface SoraTimelapseMetadata {
+export interface InkTimelapseMetadata {
enabled: boolean;
frameCount: number;
fps?: number;
@@ -891,7 +909,7 @@ export interface LoadedDocument {
tileGrid?: SparseTileGrid;
perspectiveRuler?: PerspectiveRuler | null;
animationTimeline?: AnimationTimeline | null;
- timelapse?: SoraTimelapseMetadata | null;
+ timelapse?: InkTimelapseMetadata | null;
previewDataUrl?: string;
}
diff --git a/src/types/multiplayer.ts b/src/types/multiplayer.ts
index 7cff5dc..a2c5ab2 100644
--- a/src/types/multiplayer.ts
+++ b/src/types/multiplayer.ts
@@ -1,10 +1,35 @@
-import { Point, BrushSettings, ToolType, DirtyRect, CanvasDimensions, CanvasColorMode, LayerItem, VectorStroke } from './editor';
+import {
+ AnimationTimeline,
+ BrushSettings,
+ CanvasColorMode,
+ CanvasDimensions,
+ DirtyRect,
+ LayerItem,
+ Point,
+ ToolType,
+ VectorStroke,
+} from './editor';
+import { PerspectiveRuler, StraightRuler } from './perspective';
+import { ResizeCanvasOptions } from './settings';
+
+export type CollabRole = 'host' | 'editor' | 'viewer';
+
+export type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
+
+export type AccessDeniedCode =
+ | 'BANNED'
+ | 'KICKED'
+ | 'VIEWER_READONLY'
+ | 'LAYER_LOCKED'
+ | 'NOT_OWNER'
+ | 'FORBIDDEN';
export interface CollabPeer {
id: string | number;
name: string;
color: string;
isHost?: boolean;
+ role?: CollabRole;
isDrawing?: boolean;
x?: number;
y?: number;
@@ -19,36 +44,114 @@ export type MultiplayerMessageType =
| 'PEER_JOINED'
| 'PEER_LEFT'
| 'PEER_DISCONNECTED'
+ | 'PEER_ROLE_UPDATE'
+ | 'PEER_KICK'
+ | 'PEER_BAN'
+ | 'PEER_UNBAN'
+ | 'ACCESS_DENIED'
| 'CURSOR_MOVE'
| 'STROKE_START'
| 'STROKE_CHUNK'
| 'STROKE_FINISH'
+ | 'BRUSH_ASSET_DATA'
+ | 'BRUSH_ASSET_REQUEST'
| 'LAYER_ADD'
| 'LAYER_DELETE'
| 'LAYER_CLEAR'
| 'LAYER_RENAME'
| 'LAYER_VISIBILITY'
| 'LAYER_OPACITY'
+ | 'LAYER_UPDATE'
+ | 'LAYER_TREE_SYNC'
+ | 'BINARY_MASK'
+ | 'PERSPECTIVE_RULER_SYNC'
+ | 'STRAIGHT_RULER_SYNC'
+ | 'ANIMATION_SYNC'
+ | 'CANVAS_RESIZE'
| 'DOC_SYNC_REQUEST'
| 'DOC_SYNC_RESPONSE'
| 'CANVAS_PING'
| 'BINARY_TILE'
| 'SELECTIVE_UNDO';
+/**
+ * JSON-safe wire representation of a LayerItem.
+ * Excludes DOM-only/transient fields (`maskCanvas`, `thumbnailUrl`, `maskThumbnailUrl`).
+ */
+export type WireLayerItem = Omit<
+ LayerItem,
+ 'maskCanvas' | 'thumbnailUrl' | 'maskThumbnailUrl'
+> & {
+ /** Whether the layer owns a non-destructive grayscale mask canvas (pixel bytes stream via BINARY_MASK). */
+ hasMask?: boolean;
+};
+
+export type LayerClearableField =
+ | 'alphaLocked'
+ | 'clipped'
+ | 'isReference'
+ | 'toneEnabled'
+ | 'toneFrequency'
+ | 'toneAngle'
+ | 'toneDotShape'
+ | 'toneDensity'
+ | 'toneDensityType'
+ | 'layerColorEnabled'
+ | 'layerColor'
+ | 'layerSubColor'
+ | 'expressionColor'
+ | 'monoThreshold'
+ | 'monoExpressBlack'
+ | 'monoExpressWhite'
+ | 'maskEnabled'
+ | 'maskLinked'
+ | 'maskVersion'
+ | 'hasMask'
+ | 'adjustmentData'
+ | 'styles'
+ | 'vectorStrokes'
+ | 'comicFrames'
+ | 'textData'
+ | 'balloonData'
+ | 'balloons'
+ | 'ownerPeerId'
+ | 'ownerPeerName'
+ | 'reservedByPeerId'
+ | 'reservedByPeerName';
+
+export interface SubTipAssetRef {
+ hash: string;
+ width: number;
+ height: number;
+ isColor?: boolean;
+}
+
+export interface BrushAssetRefs {
+ tipHash?: string;
+ dualTipHash?: string;
+ paperTextureHash?: string;
+ subTipHashes?: SubTipAssetRef[];
+}
+
export interface BaseMultiplayerMessage {
type: MultiplayerMessageType;
senderId?: string | number;
+ /** Server-assigned monotonic sequence number for deterministic ordering. */
+ seq?: number;
}
export interface RoomInfoMessage extends BaseMultiplayerMessage {
type: 'ROOM_INFO';
clientId: number;
roomName: string;
+ serverSeq?: number;
}
export interface JoinRequestMessage extends BaseMultiplayerMessage {
type: 'JOIN_REQUEST';
peer: CollabPeer;
+ isReconnect?: boolean;
+ sinceSeq?: number;
}
export interface JoinAcceptedMessage extends BaseMultiplayerMessage {
@@ -60,6 +163,9 @@ export interface JoinAcceptedMessage extends BaseMultiplayerMessage {
docDimensions: CanvasDimensions;
colorMode: CanvasColorMode;
assignedLayerId?: string;
+ assignedRole?: CollabRole;
+ isReconnect?: boolean;
+ serverSeq?: number;
}
export interface PeerJoinedMessage extends BaseMultiplayerMessage {
@@ -77,6 +183,36 @@ export interface PeerDisconnectedMessage extends BaseMultiplayerMessage {
peerId: string | number;
}
+export interface PeerRoleUpdateMessage extends BaseMultiplayerMessage {
+ type: 'PEER_ROLE_UPDATE';
+ targetPeerId: string | number;
+ role: CollabRole;
+}
+
+export interface PeerKickMessage extends BaseMultiplayerMessage {
+ type: 'PEER_KICK';
+ targetPeerId: string | number;
+ reason?: string;
+}
+
+export interface PeerBanMessage extends BaseMultiplayerMessage {
+ type: 'PEER_BAN';
+ targetPeerId: string | number;
+ reason?: string;
+}
+
+export interface PeerUnbanMessage extends BaseMultiplayerMessage {
+ type: 'PEER_UNBAN';
+ targetPeerId: string | number;
+}
+
+export interface AccessDeniedMessage extends BaseMultiplayerMessage {
+ type: 'ACCESS_DENIED';
+ targetPeerId?: string | number;
+ code: AccessDeniedCode;
+ reason: string;
+}
+
export interface CursorMoveMessage extends BaseMultiplayerMessage {
type: 'CURSOR_MOVE';
peerId: string | number;
@@ -96,10 +232,24 @@ export interface StrokeStartMessage extends BaseMultiplayerMessage {
peerColor: string;
layerId: string;
brushSettings: BrushSettings;
+ brushAssetRefs?: BrushAssetRefs;
tool: ToolType;
startPoint: Point;
}
+export interface BrushAssetDataMessage extends BaseMultiplayerMessage {
+ type: 'BRUSH_ASSET_DATA';
+ hash: string;
+ mime: string;
+ data: Uint8Array;
+}
+
+export interface BrushAssetRequestMessage extends BaseMultiplayerMessage {
+ type: 'BRUSH_ASSET_REQUEST';
+ hash: string;
+ targetPeerId?: string | number;
+}
+
export interface StrokeChunkMessage extends BaseMultiplayerMessage {
type: 'STROKE_CHUNK';
strokeId: string;
@@ -120,16 +270,73 @@ export interface StrokeFinishMessage extends BaseMultiplayerMessage {
export interface LayerActionMessage extends BaseMultiplayerMessage {
type: 'LAYER_ADD' | 'LAYER_DELETE' | 'LAYER_CLEAR' | 'LAYER_RENAME' | 'LAYER_VISIBILITY' | 'LAYER_OPACITY';
layerId: string;
- layerItem?: LayerItem;
+ layerItem?: WireLayerItem;
+ insertIndex?: number;
newName?: string;
visible?: boolean;
opacity?: number;
- imageDataUrl?: string;
+}
+
+export interface LayerUpdateMessage extends BaseMultiplayerMessage {
+ type: 'LAYER_UPDATE';
+ layerId: string;
+ patch: Partial<WireLayerItem>;
+ clearedFields?: LayerClearableField[];
+ lamport?: number;
+}
+
+export interface LayerTreeSyncMessage extends BaseMultiplayerMessage {
+ type: 'LAYER_TREE_SYNC';
+ layers: WireLayerItem[];
+ lamport: number;
+ dirtyTileLayerIds?: string[];
+ removedLayerIds?: string[];
+}
+
+export interface LayerMaskDataMessage extends BaseMultiplayerMessage {
+ type: 'BINARY_MASK';
+ layerId: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ isFullReplace: boolean;
+ /** Non-undefined when the entire rect is a uniform grayscale value (0..255). */
+ solidFill?: number;
+ /** 1-byte-per-pixel grayscale luminance values (width * height), null when solidFill is used. */
+ data: Uint8Array | null;
+}
+
+export interface PerspectiveRulerSyncMessage extends BaseMultiplayerMessage {
+ type: 'PERSPECTIVE_RULER_SYNC';
+ perspectiveRuler: PerspectiveRuler | null;
+ lamport?: number;
+}
+
+export interface StraightRulerSyncMessage extends BaseMultiplayerMessage {
+ type: 'STRAIGHT_RULER_SYNC';
+ straightRuler: StraightRuler | null;
+ lamport?: number;
+}
+
+export interface AnimationSyncMessage extends BaseMultiplayerMessage {
+ type: 'ANIMATION_SYNC';
+ animationTimeline: AnimationTimeline | null;
+ lamport?: number;
+}
+
+export interface CanvasResizeMessage extends BaseMultiplayerMessage {
+ type: 'CANVAS_RESIZE';
+ dimensions: CanvasDimensions;
+ options: ResizeCanvasOptions;
+ lamport?: number;
}
export interface DocSyncRequestMessage extends BaseMultiplayerMessage {
type: 'DOC_SYNC_REQUEST';
targetPeerId: string | number;
+ /** Optional last applied server sequence number for incremental op-log catch-up. */
+ sinceSeq?: number;
}
export interface DocSyncResponseMessage extends BaseMultiplayerMessage {
@@ -139,8 +346,10 @@ export interface DocSyncResponseMessage extends BaseMultiplayerMessage {
assignedLayerId?: string;
dimensions: CanvasDimensions;
colorMode: CanvasColorMode;
- layers: LayerItem[];
- layerDataUrls: Record<string, string>; // base64 layer thumbnails / images
+ layers: WireLayerItem[];
+ perspectiveRuler?: PerspectiveRuler | null;
+ straightRuler?: StraightRuler | null;
+ animationTimeline?: AnimationTimeline | null;
}
export interface CanvasPingMessage extends BaseMultiplayerMessage {
@@ -158,7 +367,8 @@ export interface TileStreamMessage extends BaseMultiplayerMessage {
tileY: number;
format: 'monochrome-1bit' | 'grayscale-8bit' | 'color-32bit';
version: number;
- data: Uint8Array;
+ /** Raw tile bytes (decompressed from LZ4 on wire) or null to delete/clear the tile. */
+ data: Uint8Array | null;
}
export interface SelectiveUndoMessage extends BaseMultiplayerMessage {
@@ -175,11 +385,25 @@ export type MultiplayerMessage =
| PeerJoinedMessage
| PeerLeftMessage
| PeerDisconnectedMessage
+ | PeerRoleUpdateMessage
+ | PeerKickMessage
+ | PeerBanMessage
+ | PeerUnbanMessage
+ | AccessDeniedMessage
| CursorMoveMessage
| StrokeStartMessage
| StrokeChunkMessage
| StrokeFinishMessage
+ | BrushAssetDataMessage
+ | BrushAssetRequestMessage
| LayerActionMessage
+ | LayerUpdateMessage
+ | LayerTreeSyncMessage
+ | LayerMaskDataMessage
+ | PerspectiveRulerSyncMessage
+ | StraightRulerSyncMessage
+ | AnimationSyncMessage
+ | CanvasResizeMessage
| DocSyncRequestMessage
| DocSyncResponseMessage
| CanvasPingMessage
diff --git a/src/types/settings.ts b/src/types/settings.ts
index f2cf278..f5450d4 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -366,6 +366,8 @@ function sanitizePressureCurve(raw: unknown): PressureCurveSettings {
}
const SETTINGS_KEY = 'ink_studio_app_settings';
+export const NICKNAME_STORAGE_KEY = 'ink_studio_nickname';
+export const NICKNAME_CUSTOMIZED_STORAGE_KEY = 'ink_nickname_customized';
export function loadAppSettings(): AppSettings {
try {
@@ -381,7 +383,7 @@ export function loadAppSettings(): AppSettings {
};
}
const raw = localStorage.getItem(SETTINGS_KEY);
- const legacyName = localStorage.getItem('sora_paint_nickname') || '';
+ const storedNickname = localStorage.getItem(NICKNAME_STORAGE_KEY) || '';
if (raw) {
const parsed = JSON.parse(raw);
const validTheme: ThemePreset = 'modern';
@@ -418,7 +420,7 @@ export function loadAppSettings(): AppSettings {
return {
...DEFAULT_APP_SETTINGS,
...parsed,
- userName: parsed.userName !== undefined ? parsed.userName : legacyName,
+ userName: parsed.userName !== undefined ? parsed.userName : storedNickname,
hasPromptedName: parsed.hasPromptedName !== undefined ? parsed.hasPromptedName : true,
themePreset: validTheme,
modernAccent: validAccent,
@@ -431,10 +433,10 @@ export function loadAppSettings(): AppSettings {
modifierKeys: sanitizeModifierKeys(parsed.modifierKeys),
pressureCurve: sanitizePressureCurve(parsed.pressureCurve),
};
- } else if (legacyName) {
+ } else if (storedNickname) {
return {
...DEFAULT_APP_SETTINGS,
- userName: legacyName,
+ userName: storedNickname,
hasPromptedName: true,
shortcuts: {},
modifierKeys: { ...DEFAULT_MODIFIER_KEY_SETTINGS },
diff --git a/src/utils/__tests__/brushDynamics.test.ts b/src/utils/__tests__/brushDynamics.test.ts
index d6bed28..f94468e 100644
--- a/src/utils/__tests__/brushDynamics.test.ts
+++ b/src/utils/__tests__/brushDynamics.test.ts
@@ -3,12 +3,13 @@ import {
rgbToHsv,
hsvToRgb,
applyColorDynamics,
- drawRadialCubicBezierSegment,
- drawRadialDot,
- drawTexturedDot,
- TexturedBrushOptions,
-} from '../stampEngine';
-import { WebGlBrushEngine } from '../webglBrushEngine';
+ drawBrushCubicBezierSegment,
+ drawBrushQuadraticBezierSegment,
+ drawBrushDot,
+ buildBrushRenderOptions,
+ BrushRenderOptions,
+} from '../../engine/BrushEngine';
+import { GpuDab } from '../../engine/WebGlBrushEngine';
import { BrushSettings, BrushDynamics, Point } from '../../types/editor';
function createMockCanvas(width: number = 200, height: number = 200) {
@@ -138,12 +139,18 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
});
});
- describe('WebGL Brush Engine generateArcLengthDabs Jitter Matrix', () => {
- const gpuEngine = WebGlBrushEngine.getInstance();
+ describe('Unified BrushEngine GPU Batch Dab Jitter Matrix', () => {
const p0: Point = { x: 10, y: 10, pressure: 1.0, width: 20 };
const control: Point = { x: 50, y: 10, pressure: 1.0, width: 20 };
const p2: Point = { x: 90, y: 10, pressure: 1.0, width: 20 };
+ const emitGpuDabs = (settings: BrushSettings, color: string): GpuDab[] => {
+ const { ctx } = createMockCanvas();
+ const dabs: GpuDab[] = [];
+ drawBrushQuadraticBezierSegment(ctx, p0, control, p2, color, buildBrushRenderOptions(settings), 0, { count: 0 }, dabs);
+ return dabs;
+ };
+
const baseSettings: BrushSettings = {
size: 20,
minSizeFactor: 0.2,
@@ -185,10 +192,10 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
},
};
- const res1 = gpuEngine.generateArcLengthDabs(p0, control, p2, settings1, '#ff0000');
- const res3 = gpuEngine.generateArcLengthDabs(p0, control, p2, settings3, '#ff0000');
+ const dabs1 = emitGpuDabs(settings1, '#ff0000');
+ const dabs3 = emitGpuDabs(settings3, '#ff0000');
- expect(res3.dabs.length).toBe(res1.dabs.length * 3);
+ expect(dabs3.length).toBe(dabs1.length * 3);
});
it('applies size jitter variance', () => {
@@ -210,8 +217,8 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
},
};
- const res = gpuEngine.generateArcLengthDabs(p0, control, p2, settings, '#ff0000');
- const widths = res.dabs.map((d) => d.width);
+ const dabs = emitGpuDabs(settings, '#ff0000');
+ const widths = dabs.map((d) => d.width);
const minW = Math.min(...widths);
const maxW = Math.max(...widths);
@@ -239,8 +246,8 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
},
};
- const res = gpuEngine.generateArcLengthDabs(p0, control, p2, settings, '#ff0000');
- const angles = res.dabs.map((d) => d.angle);
+ const dabs = emitGpuDabs(settings, '#ff0000');
+ const angles = dabs.map((d) => d.angle);
const minA = Math.min(...angles);
const maxA = Math.max(...angles);
@@ -248,7 +255,6 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
});
it('applies scatter offset along normal', () => {
- // Stroke is horizontal (y = 10), so perpendicular normal is along Y
const settings: BrushSettings = {
...baseSettings,
dynamics: {
@@ -267,8 +273,8 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
},
};
- const res = gpuEngine.generateArcLengthDabs(p0, control, p2, settings, '#ff0000');
- const yCoords = res.dabs.map((d) => d.y);
+ const dabs = emitGpuDabs(settings, '#ff0000');
+ const yCoords = dabs.map((d) => d.y);
const minY = Math.min(...yCoords);
const maxY = Math.max(...yCoords);
@@ -294,8 +300,8 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
},
};
- const res = gpuEngine.generateArcLengthDabs(p0, control, p2, settings, '#ff0000');
- const alphas = res.dabs.map((d) => d.alpha);
+ const dabs = emitGpuDabs(settings, '#ff0000');
+ const alphas = dabs.map((d) => d.alpha);
const minA = Math.min(...alphas);
const maxA = Math.max(...alphas);
@@ -322,16 +328,15 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
},
};
- const res = gpuEngine.generateArcLengthDabs(p0, control, p2, settings, '#ff0000');
- const colors = res.dabs.map((d) => [d.r, d.g, d.b]);
- // Check that not all dabs are identical pure red
+ const dabs = emitGpuDabs(settings, '#ff0000');
+ const colors = dabs.map((d) => [d.r, d.g, d.b]);
const nonPureRed = colors.some(([r, g, b]) => g > 0.05 || b > 0.05 || r < 0.95);
expect(nonPureRed).toBe(true);
});
});
- describe('Stamp Engine 2D Jitter Matrix Execution', () => {
- it('executes drawRadialCubicBezierSegment with dynamics count and scatter', () => {
+ describe('Unified BrushEngine CPU Fallback Jitter Matrix Execution', () => {
+ it('executes drawBrushCubicBezierSegment with dynamics count and scatter', () => {
const { ctx, drawnDabs } = createMockCanvas();
const p0: Point = { x: 10, y: 20, pressure: 1.0, width: 10 };
const c1: Point = { x: 30, y: 20, pressure: 1.0, width: 10 };
@@ -353,28 +358,18 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
foregroundBackgroundJitter: 0.3,
};
- drawRadialCubicBezierSegment(
- ctx,
- p0,
- c1,
- c2,
- p3,
- '#ff0000',
- 1.0,
- 1.0,
- 0.1,
- false,
- false,
- 0,
- 1.0,
- 0,
- { dynamics, secondaryColor: '#0000ff' }
- );
+ drawBrushCubicBezierSegment(ctx, p0, c1, c2, p3, '#ff0000', {
+ hardness: 1.0,
+ flow: 1.0,
+ spacing: 0.1,
+ dynamics,
+ secondaryColor: '#0000ff',
+ });
expect(drawnDabs.length).toBeGreaterThan(0);
});
- it('executes drawRadialDot with dynamics jitter', () => {
+ it('executes drawBrushDot (radial) with dynamics jitter', () => {
const { ctx, drawnDabs } = createMockCanvas();
const point: Point = { x: 50, y: 50, pressure: 1.0, width: 15 };
@@ -393,7 +388,9 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
foregroundBackgroundJitter: 0.2,
};
- drawRadialDot(ctx, point, '#336699', 0.9, 0.8, false, false, {
+ drawBrushDot(ctx, point, '#336699', {
+ hardness: 0.9,
+ flow: 0.8,
dynamics,
secondaryColor: '#ffffff',
});
@@ -401,13 +398,14 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
expect(drawnDabs.length).toBe(3);
});
- it('executes drawTexturedDot with dynamics count and jitter', () => {
+ it('executes drawBrushDot (textured) with dynamics count and jitter', () => {
const { ctx, drawnDabs } = createMockCanvas();
const point: Point = { x: 40, y: 40, pressure: 1.0, width: 20 };
const tipImg: any = { naturalWidth: 64, naturalHeight: 64, width: 64, height: 64, src: 'tip.png' };
- const options: TexturedBrushOptions = {
+ const options: BrushRenderOptions = {
size: 20,
+ tipImage: tipImg,
dynamics: {
sizeJitter: 0.5,
angleJitter: 0.5,
@@ -425,7 +423,7 @@ describe('Brush Dynamics & Multi-Axis Jitter Matrix', () => {
secondaryColor: '#ffffff',
};
- drawTexturedDot(ctx, point, '#ff5500', tipImg, options);
+ drawBrushDot(ctx, point, '#ff5500', options);
expect(drawnDabs.length).toBe(4);
});
});
diff --git a/src/utils/__tests__/brushEngine.test.ts b/src/utils/__tests__/brushEngine.test.ts
index b447e10..08986a6 100644
--- a/src/utils/__tests__/brushEngine.test.ts
+++ b/src/utils/__tests__/brushEngine.test.ts
@@ -4,24 +4,21 @@ import {
buildCubicArcLengthTable,
getCubicPointAtArcLength,
getRadialDabMaster,
- drawRadialCubicBezierSegment,
+ drawBrushCubicBezierSegment,
+ drawBrushDot,
drawSingleStamp,
- RadialMixingOptions,
-} from '../stampEngine';
-import {
renderCompleteStroke,
- applyParametricTaper,
-} from '../canvasUtils';
+ getPaperGrain,
+ LEGACY_PENCIL_PRESETS,
+ LegacyPencilGrade,
+ BrushRenderOptions,
+ buildBrushRenderOptions,
+} from '../../engine/BrushEngine';
+import { applyParametricTaper } from '../canvasUtils';
import {
PaintReservoir,
LayerPixelSampler,
} from '../colorMixingEngine';
-import {
- getPaperGrain,
- PENCIL_CONFIGS,
- PencilGrade,
- drawPencilDot,
-} from '../pencilEngine';
import { calculatePreviewWidth } from '../brushPreview';
import { Point, BrushSettings } from '../../types/editor';
@@ -238,13 +235,13 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
expect(Math.abs(h1 - h2)).toBeLessThan(15);
});
- it('preserves hardness and density ordering across pencil grades', () => {
- const grades: PencilGrade[] = ['pencil-f', 'pencil-hb', 'pencil-2b', 'pencil-4b'];
+ it('preserves hardness and flow ordering across legacy pencil presets', () => {
+ const grades: LegacyPencilGrade[] = ['pencil-f', 'pencil-hb', 'pencil-2b', 'pencil-4b'];
for (let i = 0; i < grades.length - 1; i++) {
- const harder = PENCIL_CONFIGS[grades[i]];
- const softer = PENCIL_CONFIGS[grades[i + 1]];
- expect(harder.hardness).toBeGreaterThanOrEqual(softer.hardness);
- expect(softer.particleDensity).toBeGreaterThanOrEqual(harder.particleDensity);
+ const harder = LEGACY_PENCIL_PRESETS[grades[i]];
+ const softer = LEGACY_PENCIL_PRESETS[grades[i + 1]];
+ expect(harder.hardness!).toBeGreaterThanOrEqual(softer.hardness!);
+ expect(softer.flow!).toBeGreaterThanOrEqual(harder.flow!);
}
});
});
@@ -262,18 +259,14 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
const seg2 = centripetalCatmullRomToBezier(p0, p1, p2, p2);
const spacing = 0.05; // required step = 10 * 0.05 = 0.5px
- const remainder1 = drawRadialCubicBezierSegment(
+ const remainder1 = drawBrushCubicBezierSegment(
ctx,
p0,
seg1.c1,
seg1.c2,
p1,
'#000000',
- 1.0,
- 1.0,
- spacing,
- false,
- false,
+ { hardness: 1.0, flow: 1.0, spacing },
0
);
@@ -284,18 +277,14 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
expect(dabCountBefore).toBeGreaterThan(150);
// Thread remainder1 into segment 2
- const remainder2 = drawRadialCubicBezierSegment(
+ const remainder2 = drawBrushCubicBezierSegment(
ctx,
p1,
seg2.c1,
seg2.c2,
p2,
'#000000',
- 1.0,
- 1.0,
- spacing,
- false,
- false,
+ { hardness: 1.0, flow: 1.0, spacing },
remainder1
);
@@ -319,18 +308,14 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
const p1: Point = { x: 0.2, y: 0, pressure: 1.0, width: 20 }; // Very short move (0.2px)
const spacing = 0.1; // required step = 2.0px
- const remainder = drawRadialCubicBezierSegment(
+ const remainder = drawBrushCubicBezierSegment(
ctx,
p0,
p0,
p1,
p1,
'#000000',
- 1.0,
- 1.0,
- spacing,
- false,
- false,
+ { hardness: 1.0, flow: 1.0, spacing },
1.0
);
@@ -394,7 +379,10 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
const p2: Point = { x: 80, y: 100, pressure: 1.0, width: 10 };
const p3: Point = { x: 120, y: 100, pressure: 1.0, width: 10 };
- const mixingOptions: RadialMixingOptions = {
+ const mixingOptions: BrushRenderOptions = {
+ hardness: 1.0,
+ flow: 1.0,
+ spacing: 0.05,
colorMixing: true,
amountOfPaint: 0.5,
densityOfPaint: 1.0,
@@ -410,23 +398,7 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
expect(reservoir.b).toBe(0);
// Draw segment crossing from x=30 to x=80 (traversing the black patch at 40..60)
- drawRadialCubicBezierSegment(
- dCtx,
- p0,
- p1,
- p2,
- p3,
- '#ff0000',
- 1.0,
- 1.0,
- 0.05,
- false,
- false,
- 0,
- 1.0,
- 0,
- mixingOptions
- );
+ drawBrushCubicBezierSegment(dCtx, p0, p1, p2, p3, '#ff0000', mixingOptions, 0);
// After crossing black patch: reservoir must have mixed and darkened significantly
expect(reservoir.isLoadedWithCanvasColor).toBe(true);
@@ -615,7 +587,12 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
const c2Upright: Point = { x: 70, y: 50, pressure: 1.0, width: 20, tiltX: 0, tiltY: 0 };
const p3Upright: Point = { x: 90, y: 50, pressure: 1.0, width: 20, tiltX: 0, tiltY: 0 };
- drawRadialCubicBezierSegment(ctxUpright, p0Upright, c1Upright, c2Upright, p3Upright, '#000000', 1.0, 1.0, 0.1);
+ drawBrushCubicBezierSegment(ctxUpright, p0Upright, c1Upright, c2Upright, p3Upright, '#000000', {
+ hardness: 1.0,
+ flow: 1.0,
+ spacing: 0.1,
+ useTilt: true,
+ });
// Tilted flat along X axis (tiltX = 65 degrees)
const p0Tilted: Point = { x: 10, y: 50, pressure: 1.0, width: 20, tiltX: 65, tiltY: 0 };
@@ -623,7 +600,12 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
const c2Tilted: Point = { x: 70, y: 50, pressure: 1.0, width: 20, tiltX: 65, tiltY: 0 };
const p3Tilted: Point = { x: 90, y: 50, pressure: 1.0, width: 20, tiltX: 65, tiltY: 0 };
- drawRadialCubicBezierSegment(ctxTilted, p0Tilted, c1Tilted, c2Tilted, p3Tilted, '#000000', 1.0, 1.0, 0.1);
+ drawBrushCubicBezierSegment(ctxTilted, p0Tilted, c1Tilted, c2Tilted, p3Tilted, '#000000', {
+ hardness: 1.0,
+ flow: 1.0,
+ spacing: 0.1,
+ useTilt: true,
+ });
expect(canvasUpright.drawnDabs.length).toBeGreaterThan(0);
expect(canvasTilted.drawnDabs.length).toBeGreaterThan(0);
@@ -635,17 +617,31 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
expect(avgTiltedW).toBeGreaterThan(avgUprightW * 1.5);
});
- it('widens pencil footprint when stylus is tilted flat', () => {
+ it('widens pencil preset footprint when stylus is tilted flat (via unified BrushEngine)', () => {
const canvasUpright = createMockCanvas(200, 200);
const ctxUpright = canvasUpright.getContext('2d') as unknown as CanvasRenderingContext2D;
const canvasTilted = createMockCanvas(200, 200);
const ctxTilted = canvasTilted.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const pencilOpts = buildBrushRenderOptions({
+ preset: 'pencil-2b',
+ size: 10,
+ minSizeFactor: 0.2,
+ color: '#222326',
+ opacity: 1,
+ flow: 0.74,
+ spacing: 0.06,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ hardness: 0.65,
+ });
+
const pUpright: Point = { x: 50, y: 50, pressure: 0.7, width: 10, tiltX: 0, tiltY: 0 };
- drawPencilDot(ctxUpright, pUpright, '#222326', 'pencil-2b');
+ drawBrushDot(ctxUpright, pUpright, '#222326', pencilOpts);
const pTilted: Point = { x: 50, y: 50, pressure: 0.7, width: 10, tiltX: 70, tiltY: 0 };
- drawPencilDot(ctxTilted, pTilted, '#222326', 'pencil-2b');
+ drawBrushDot(ctxTilted, pTilted, '#222326', pencilOpts);
expect(canvasUpright.drawnDabs.length).toBe(1);
expect(canvasTilted.drawnDabs.length).toBe(1);
diff --git a/src/utils/__tests__/builtinBrushes.test.ts b/src/utils/__tests__/builtinBrushes.test.ts
index 9313ff2..b802ebd 100644
--- a/src/utils/__tests__/builtinBrushes.test.ts
+++ b/src/utils/__tests__/builtinBrushes.test.ts
@@ -5,9 +5,12 @@ import {
getBuiltinBrushConfig,
} from '../presetBrushes';
import { getEffectiveBrushSettings } from '../brushPresetManager';
-import { applyCspPaperTextureAlpha } from '../../engine/CspBrushEngine';
+import {
+ applyCspPaperTextureAlpha,
+ drawBrushCubicBezierSegment,
+ BrushRenderOptions,
+} from '../../engine/BrushEngine';
import { PaintReservoir } from '../colorMixingEngine';
-import { drawTexturedCubicBezierSegment, TexturedBrushOptions } from '../stampEngine';
import { Point } from '../../types/editor';
function createMockCanvas(width: number = 128, height: number = 128) {
@@ -200,17 +203,18 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
const b68 = getBuiltinBrushConfig('pencil-6b-8b')!;
const cUp = createMockCanvas(200, 200);
const cTilt = createMockCanvas(200, 200);
- const b68Opts: TexturedBrushOptions = {
+ const b68Opts: BrushRenderOptions = {
size: b68.size!,
flow: b68.flow,
spacing: 0.2,
useTilt: b68.useTilt,
tiltScale: b68.tiltScale,
thickness: b68.thickness,
+ tipImage: mockTip,
useGpu: false,
};
- drawTexturedCubicBezierSegment(cUp.getContext('2d'), ...uprightPts, '#111111', mockTip, b68Opts);
- drawTexturedCubicBezierSegment(cTilt.getContext('2d'), ...tiltedPts, '#111111', mockTip, b68Opts);
+ drawBrushCubicBezierSegment(cUp.getContext('2d'), ...uprightPts, '#111111', b68Opts);
+ drawBrushCubicBezierSegment(cTilt.getContext('2d'), ...tiltedPts, '#111111', b68Opts);
const avgUpW = cUp.drawnDabs.reduce((s, d) => s + d.width, 0) / cUp.drawnDabs.length;
const avgTiltW = cTilt.drawnDabs.reduce((s, d) => s + d.width, 0) / cTilt.drawnDabs.length;
@@ -223,16 +227,17 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
const mech = getBuiltinBrushConfig('mechanical-pencil')!;
const mUp = createMockCanvas(200, 200);
const mTilt = createMockCanvas(200, 200);
- const mechOpts: TexturedBrushOptions = {
+ const mechOpts: BrushRenderOptions = {
size: mech.size!,
flow: mech.flow,
spacing: 0.2,
useTilt: mech.useTilt,
tiltScale: mech.tiltScale,
+ tipImage: mockTip,
useGpu: false,
};
- drawTexturedCubicBezierSegment(mUp.getContext('2d'), ...uprightPts, '#111111', mockTip, mechOpts);
- drawTexturedCubicBezierSegment(mTilt.getContext('2d'), ...tiltedPts, '#111111', mockTip, mechOpts);
+ drawBrushCubicBezierSegment(mUp.getContext('2d'), ...uprightPts, '#111111', mechOpts);
+ drawBrushCubicBezierSegment(mTilt.getContext('2d'), ...tiltedPts, '#111111', mechOpts);
const mUpW = mUp.drawnDabs.reduce((s, d) => s + d.width, 0) / mUp.drawnDabs.length;
const mTiltW = mTilt.drawnDabs.reduce((s, d) => s + d.width, 0) / mTilt.drawnDabs.length;
diff --git a/src/utils/__tests__/cspBrushEngineV2.test.ts b/src/utils/__tests__/cspBrushEngineV2.test.ts
index 3fde089..13e3b3a 100644
--- a/src/utils/__tests__/cspBrushEngineV2.test.ts
+++ b/src/utils/__tests__/cspBrushEngineV2.test.ts
@@ -13,7 +13,7 @@ import {
applyCspPostCorrection,
applyCspWatercolorEdge,
CSP_PRESSURE_CURVE_PRESETS,
-} from '../../engine/CspBrushEngine';
+} from '../../engine/BrushEngine';
import { stepBrushSizePreset } from '../brushPresetManager';
import { BUILTIN_BRUSHES } from '../presetBrushes';
import { Point } from '../../types/editor';
diff --git a/src/utils/__tests__/cspEngineRefactor.test.ts b/src/utils/__tests__/cspEngineRefactor.test.ts
index c46964c..a2d3688 100644
--- a/src/utils/__tests__/cspEngineRefactor.test.ts
+++ b/src/utils/__tests__/cspEngineRefactor.test.ts
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach } from 'vitest';
import { InputStabilizer } from '../../engine/InputStabilizer';
import { TaperEngine } from '../../engine/TaperEngine';
import { SplineGenerator, SplinePoint } from '../../engine/SplineGenerator';
-import { WebGlBrushEngine } from '../webglBrushEngine';
+import { WebGlBrushEngine } from '../../engine/WebGlBrushEngine';
describe('Clip Studio Paint Drawing Engine Refactor Tests', () => {
describe('Phase 3: Adaptive Corner-Snapping Stabilizer (InputStabilizer)', () => {
diff --git a/src/utils/__tests__/cspKritaOptimizations.test.ts b/src/utils/__tests__/cspKritaOptimizations.test.ts
index 4344ec9..ac9df1b 100644
--- a/src/utils/__tests__/cspKritaOptimizations.test.ts
+++ b/src/utils/__tests__/cspKritaOptimizations.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
BLEND_MODE_MAP,
COMPOSITOR_FRAGMENT_SHADER,
+ COMPOSITOR_INSTANCED_FRAGMENT_SHADER,
FOLDER_BLIT_FRAGMENT_SHADER,
ViewportCompositor,
} from '../compositor';
@@ -35,7 +36,7 @@ import {
MOTION_BLUR_FRAGMENT_SHADER,
WebGlFilterEngine,
} from '../filterEngine';
-import { WebGlBrushEngine } from '../webglBrushEngine';
+import { WebGlBrushEngine } from '../../engine/WebGlBrushEngine';
import { HistoryItem } from '../../types/editor';
describe('CSP & Krita Rendering and Engine Optimizations', () => {
@@ -58,10 +59,30 @@ describe('CSP & Krita Rendering and Engine Optimizations', () => {
expect(BLEND_MODE_MAP['add-glow']).toBe(14);
expect(BLEND_MODE_MAP['color-dodge-glow']).toBe(15);
expect(BLEND_MODE_MAP['divide']).toBe(16);
+ expect(BLEND_MODE_MAP['vivid-light']).toBe(17);
+ expect(BLEND_MODE_MAP['linear-light']).toBe(18);
+ expect(BLEND_MODE_MAP['pin-light']).toBe(19);
+ expect(BLEND_MODE_MAP['hard-mix']).toBe(20);
+ expect(BLEND_MODE_MAP['subtract']).toBe(21);
+ expect(BLEND_MODE_MAP['darker-color']).toBe(22);
+ expect(BLEND_MODE_MAP['lighter-color']).toBe(23);
+ expect(BLEND_MODE_MAP['hue']).toBe(24);
+ expect(BLEND_MODE_MAP['saturation']).toBe(25);
+ expect(BLEND_MODE_MAP['color']).toBe(26);
+ expect(BLEND_MODE_MAP['luminosity']).toBe(27);
expect(COMPOSITOR_FRAGMENT_SHADER).toContain('vec3 evaluateBlendMode(vec3 Cb, vec3 Cs, int mode)');
expect(COMPOSITOR_FRAGMENT_SHADER).toContain('uniform sampler2D u_backdropTexture;');
expect(FOLDER_BLIT_FRAGMENT_SHADER).toContain('vec3 evaluateBlendModeFolder(vec3 Cb, vec3 Cs, int mode)');
+ for (const shader of [
+ COMPOSITOR_FRAGMENT_SHADER,
+ COMPOSITOR_INSTANCED_FRAGMENT_SHADER,
+ FOLDER_BLIT_FRAGMENT_SHADER,
+ ]) {
+ for (let code = 17; code <= 27; code++) {
+ expect(shader).toContain(`mode == ${code}`);
+ }
+ }
});
it('supports mask dirty-version invalidation on ViewportCompositor', () => {
diff --git a/src/utils/__tests__/cspParser.test.ts b/src/utils/__tests__/cspParser.test.ts
index 0e671ff..6693e05 100644
--- a/src/utils/__tests__/cspParser.test.ts
+++ b/src/utils/__tests__/cspParser.test.ts
@@ -1,5 +1,4 @@
import { describe, it, expect, afterEach } from 'vitest';
-import initSqlJs from 'sql.js';
import { zlibSync } from 'fflate';
import {
mapCspBlendMode,
@@ -7,9 +6,13 @@ import {
extractExtaChunks,
parseOffscreenAttribute,
parseBlockDataPayload,
+ decodeCspTileToRgba,
parseCspFile,
} from '../cspParser';
-import { TILE_PIXELS, TILE_SIZE } from '../tileEngine';
+import { hydrateParsedDocumentBinary } from '../nativeBackend';
+import { unpackTabletSampleBatch } from '../nativeTabletInput';
+import { lz4CompressBlock } from '../lz4';
+import { BYTES_32BIT, TILE_PIXELS, TILE_SIZE } from '../tileEngine';
function concatBytes(parts: Uint8Array[]): Uint8Array {
let total = 0;
@@ -88,181 +91,99 @@ function buildOffscreenAttribute(
]);
}
-function buildBlockData(blocks: Array<Uint8Array | Uint8Array[] | null>): Uint8Array {
+function buildBlockData(tileBuffers: Array<Uint8Array | null>): Uint8Array {
+ const beginTag = utf16BeTagged('BlockDataBeginChunk');
+ const endTag = utf16BeTagged('BlockDataEndChunk');
const parts: Uint8Array[] = [];
- for (let idx = 0; idx < blocks.length; idx++) {
- const entry = blocks[idx];
- const beginTag = utf16BeTagged('BlockDataBeginChunk');
- const endTag = utf16BeTagged('BlockDataEndChunk');
- if (entry === null) {
- const inner = concatBytes([
- beginTag,
- u32BE(idx),
- u32BE(0),
- u32BE(256),
- u32BE(256),
- u32BE(0), // empty block
- endTag,
- ]);
- parts.push(u32BE(inner.byteLength), inner);
+
+ for (let idx = 0; idx < tileBuffers.length; idx++) {
+ const raw = tileBuffers[idx];
+ parts.push(beginTag);
+ if (!raw) {
+ parts.push(u32BE(idx), u32BE(0), u32BE(0), u32BE(0), u32BE(0));
} else {
- const planes = Array.isArray(entry) ? entry : [entry];
- const subChunks = planes.map((plane) => {
- const compressed = zlibSync(plane);
- const outerLen = 4 + compressed.byteLength;
- return concatBytes([u32BE(outerLen), u32LE(compressed.byteLength), compressed]);
- });
- const inner = concatBytes([
- beginTag,
- u32BE(idx),
- u32BE(0),
- u32BE(256),
- u32BE(256),
- u32BE(1), // hasData
- ...subChunks,
- endTag,
- ]);
- parts.push(u32BE(inner.byteLength), inner);
+ const z = zlibSync(raw, { level: 1 });
+ const subBlock = concatBytes([u32BE(4 + z.byteLength), u32LE(raw.byteLength), z]);
+ parts.push(u32BE(idx), u32BE(0), u32BE(0), u32BE(0), u32BE(1), subBlock);
}
+ parts.push(endTag);
}
return concatBytes(parts);
}
-function buildChunk(name: string, payload: Uint8Array): Uint8Array {
- return concatBytes([asciiBytes('CHNK'), asciiBytes(name), u64BE(payload.byteLength), payload]);
-}
-
-function buildExtaChunk(externalId: string, payload: Uint8Array, includePayloadLen = true): Uint8Array {
+function buildExtaChunk(externalId: string, payload: Uint8Array, withPayloadLen = true): Uint8Array {
const idBytes = asciiBytes(externalId);
- const body = includePayloadLen
+ const data = withPayloadLen
? concatBytes([u64BE(idBytes.byteLength), idBytes, u64BE(payload.byteLength), payload])
: concatBytes([u64BE(idBytes.byteLength), idBytes, payload]);
- return buildChunk('Exta', body);
+ return concatBytes([asciiBytes('CHNK'), asciiBytes('Exta'), u64BE(data.byteLength), data]);
}
function buildClipFile(chunks: Uint8Array[]): ArrayBuffer {
- const body = concatBytes([...chunks, buildChunk('Foot', new Uint8Array(0))]);
- const totalSize = 24 + body.byteLength;
- const header = concatBytes([asciiBytes('CSFCHUNK'), u64BE(totalSize), u64BE(24)]);
- const full = concatBytes([header, body]);
- const out = new ArrayBuffer(full.byteLength);
- new Uint8Array(out).set(full);
- return out;
+ const header = concatBytes([asciiBytes('CSFCHUNK'), new Uint8Array(16)]);
+ const foot = concatBytes([asciiBytes('CHNK'), asciiBytes('Foot'), u64BE(0)]);
+ const merged = concatBytes([header, ...chunks, foot]);
+ const ab = new ArrayBuffer(merged.byteLength);
+ new Uint8Array(ab).set(merged);
+ return ab;
}
function makeColorTile(r: number, g: number, b: number, a: number): Uint8Array {
const raw = new Uint8Array(TILE_PIXELS * 5);
raw.fill(a, 0, TILE_PIXELS);
for (let p = 0; p < TILE_PIXELS; p++) {
- const off = TILE_PIXELS + p * 4;
- raw[off] = b;
- raw[off + 1] = g;
- raw[off + 2] = r;
- raw[off + 3] = 0;
+ const ci = TILE_PIXELS + p * 4;
+ raw[ci] = b;
+ raw[ci + 1] = g;
+ raw[ci + 2] = r;
+ raw[ci + 3] = 0;
}
return raw;
}
-function createPixelCanvas(width: number, height: number) {
- let w = width;
- let h = height;
- let pixels = new Uint8ClampedArray(w * h * 4);
- const ctx = {
- createImageData(iw: number, ih: number) {
- return { data: new Uint8ClampedArray(iw * ih * 4), width: iw, height: ih };
- },
- putImageData(img: { data: Uint8ClampedArray; width: number; height: number }, dx: number, dy: number) {
- for (let y = 0; y < img.height; y++) {
- const ty = dy + y;
- if (ty < 0 || ty >= h) continue;
- for (let x = 0; x < img.width; x++) {
- const tx = dx + x;
- if (tx < 0 || tx >= w) continue;
- const si = (y * img.width + x) * 4;
- const di = (ty * w + tx) * 4;
- pixels[di] = img.data[si];
- pixels[di + 1] = img.data[si + 1];
- pixels[di + 2] = img.data[si + 2];
- pixels[di + 3] = img.data[si + 3];
- }
- }
- },
- getImageData(sx: number, sy: number, sw: number, sh: number) {
- const out = new Uint8ClampedArray(sw * sh * 4);
- for (let y = 0; y < sh; y++) {
- const py = sy + y;
- if (py < 0 || py >= h) continue;
- for (let x = 0; x < sw; x++) {
- const px = sx + x;
- if (px < 0 || px >= w) continue;
- const si = (py * w + px) * 4;
- const di = (y * sw + x) * 4;
- out[di] = pixels[si];
- out[di + 1] = pixels[si + 1];
- out[di + 2] = pixels[si + 2];
- out[di + 3] = pixels[si + 3];
- }
- }
- return { data: out, width: sw, height: sh };
- },
- clearRect() {
- pixels.fill(0);
- },
- drawImage() {},
- fillRect() {},
- };
- return {
- get width() {
- return w;
- },
- set width(v: number) {
- w = v;
- pixels = new Uint8ClampedArray(Math.max(0, w) * Math.max(0, h) * 4);
- },
- get height() {
- return h;
- },
- set height(v: number) {
- h = v;
- pixels = new Uint8ClampedArray(Math.max(0, w) * Math.max(0, h) * 4);
- },
- getContext: (t: string) => (t === '2d' ? ctx : null),
- toDataURL: () => 'data:image/png;base64,MOCK',
- } as unknown as HTMLCanvasElement;
-}
-
-describe('Clip Studio Paint (.clip) Parser', () => {
- const prevDocument = (globalThis as Record<string, unknown>).document;
+describe('CSP (.clip) binary helpers & Rust INKD wire hydration (zero sql.js)', () => {
+ const originalDocument = (globalThis as Record<string, unknown>).document;
afterEach(() => {
- if (prevDocument === undefined) {
+ if (originalDocument === undefined) {
delete (globalThis as Record<string, unknown>).document;
} else {
- (globalThis as Record<string, unknown>).document = prevDocument;
+ (globalThis as Record<string, unknown>).document = originalDocument;
}
});
- it('maps CSP LayerComposite codes accurately to Ink Studio BlendMode', () => {
+ it('maps CSP composite blend mode integers accurately', () => {
expect(mapCspBlendMode(0)).toBe('normal');
expect(mapCspBlendMode(1)).toBe('darken');
expect(mapCspBlendMode(2)).toBe('multiply');
expect(mapCspBlendMode(3)).toBe('color-burn');
expect(mapCspBlendMode(4)).toBe('linear-burn');
+ expect(mapCspBlendMode(5)).toBe('subtract');
+ expect(mapCspBlendMode(6)).toBe('darker-color');
expect(mapCspBlendMode(7)).toBe('lighten');
expect(mapCspBlendMode(8)).toBe('screen');
expect(mapCspBlendMode(9)).toBe('color-dodge');
expect(mapCspBlendMode(10)).toBe('color-dodge-glow');
expect(mapCspBlendMode(12)).toBe('add-glow');
+ expect(mapCspBlendMode(13)).toBe('lighter-color');
expect(mapCspBlendMode(14)).toBe('overlay');
expect(mapCspBlendMode(15)).toBe('soft-light');
expect(mapCspBlendMode(16)).toBe('hard-light');
+ expect(mapCspBlendMode(17)).toBe('vivid-light');
+ expect(mapCspBlendMode(18)).toBe('linear-light');
+ expect(mapCspBlendMode(19)).toBe('pin-light');
+ expect(mapCspBlendMode(20)).toBe('hard-mix');
expect(mapCspBlendMode(21)).toBe('difference');
expect(mapCspBlendMode(22)).toBe('exclusion');
+ expect(mapCspBlendMode(23)).toBe('hue');
+ expect(mapCspBlendMode(24)).toBe('saturation');
+ expect(mapCspBlendMode(25)).toBe('color');
+ expect(mapCspBlendMode(26)).toBe('luminosity');
expect(mapCspBlendMode(30)).toBe('pass-through');
expect(mapCspBlendMode(36)).toBe('divide');
});
- it('parses CSFCHUNK, CHNKExta (with and without payloadLen), and Offscreen.Attribute', () => {
+ it('parses CSFCHUNK, CHNKExta, Offscreen.Attribute, and BlockData tiles', () => {
const attrBlob = buildOffscreenAttribute(512, 300, 1, 1, 4);
const parsed = parseOffscreenAttribute(attrBlob, 100, 100);
expect(parsed.bitmapWidth).toBe(512);
@@ -270,10 +191,8 @@ describe('Clip Studio Paint (.clip) Parser', () => {
expect(parsed.blockGridWidth).toBe(2);
expect(parsed.blockGridHeight).toBe(2);
expect(parsed.defaultFill).toBe(1);
- expect(parsed.firstPackingChannels).toBe(1);
- expect(parsed.secondPackingChannels).toBe(4);
- const tile = makeColorTile(10, 20, 30, 255);
+ const tile = makeColorTile(240, 20, 10, 200);
const blockData = buildBlockData([null, tile]);
const buf = buildClipFile([
buildExtaChunk('extrnlid_withlen', blockData, true),
@@ -285,311 +204,134 @@ describe('Clip Studio Paint (.clip) Parser', () => {
expect(exta.has('extrnlid_withlen')).toBe(true);
expect(exta.has('extrnlid_nolen')).toBe(true);
- // Sparse tile index 1 must NOT collapse onto index 0!
const decoded = parseBlockDataPayload(exta.get('extrnlid_withlen')!, 2);
expect(decoded.has(0)).toBe(false);
expect(decoded.has(1)).toBe(true);
- expect(decoded.get(1)!.byteLength).toBe(TILE_PIXELS * 5);
- });
-
- it('decodes full editable layer hierarchy, folders, sparse tiles, offsets, masks, grayscale, mono, and paper', async () => {
- (globalThis as Record<string, unknown>).document = {
- createElement: () => createPixelCanvas(512, 256),
- };
-
- const SQL = await initSqlJs();
- const db = new SQL.Database();
-
- db.run(`
- CREATE TABLE Canvas (MainId INTEGER, CanvasWidth INTEGER, CanvasHeight INTEGER, CanvasResolution REAL, CanvasRootFolder INTEGER);
- CREATE TABLE Layer (
- MainId INTEGER, LayerName TEXT, LayerType INTEGER, LayerFolder INTEGER,
- LayerComposite INTEGER, LayerOpacity INTEGER, LayerVisibility INTEGER,
- LayerLock INTEGER, LayerClip INTEGER, LayerSelect INTEGER,
- LayerOffsetX REAL, LayerOffsetY REAL, LayerMaskOffsetX REAL, LayerMaskOffsetY REAL,
- LayerNextIndex INTEGER, LayerFirstChildIndex INTEGER,
- LayerRenderMipmap INTEGER, LayerLayerMaskMipmap INTEGER
- );
- CREATE TABLE Mipmap (MainId INTEGER, BaseMipmapInfo INTEGER);
- CREATE TABLE MipmapInfo (MainId INTEGER, ThisScale REAL, Offscreen INTEGER, NextIndex INTEGER);
- CREATE TABLE Offscreen (MainId INTEGER, LayerId INTEGER, BlockData TEXT, Attribute BLOB);
- `);
-
- // Canvas: 512x256 @ 600 DPI, root folder = 1
- db.run('INSERT INTO Canvas VALUES (1, 512, 256, 600, 1)');
-
- // Root folder (MainId=1): children bottom-to-top: Paper(2) -> Lineart(3) -> PaintFolder(4)
- db.run('INSERT INTO Layer VALUES (1, "", 256, 1, 0, 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0)');
- // Paper (MainId=2, bottom-most, no tiles -> solid white)
- db.run('INSERT INTO Layer VALUES (2, "Paper", 1, 0, 0, 256, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0)');
- // Lineart (MainId=3, 1-bit monochrome, visible, opacity 256, alpha locked)
- db.run('INSERT INTO Layer VALUES (3, "Lineart", 1, 0, 2, 256, 1, 16, 0, 0, 0, 0, 0, 0, 4, 0, 10, 0)');
- // PaintFolder (MainId=4, collapsed=true (17=1|16), pass-through=30, children bottom-to-top: Base(5) -> Shadow(6))
- db.run('INSERT INTO Layer VALUES (4, "Paint", 256, 17, 30, 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0)');
- // Base (MainId=5, color layer with sparse tile at col=1 + layer mask enabled & linked!)
- db.run('INSERT INTO Layer VALUES (5, "Base Color", 1, 0, 0, 256, 3, 0, 0, 256, 0, 0, 0, 0, 6, 0, 20, 21)');
- // Shadow (MainId=6, clipped to Base, Multiply, 50% opacity = 128, grayscale 2-plane)
- db.run('INSERT INTO Layer VALUES (6, "Shadow", 1, 0, 2, 128, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 30, 0)');
-
- // Mipmap -> MipmapInfo -> Offscreen wiring (also include a 0.5x mipmap to verify 1.0x is chosen!)
- db.run('INSERT INTO Mipmap VALUES (10, 100), (20, 200), (21, 210), (30, 300)');
- db.run('INSERT INTO MipmapInfo VALUES (100, 1.0, 1000, 101), (101, 0.5, 1001, 0)');
- db.run('INSERT INTO MipmapInfo VALUES (200, 1.0, 2000, 0)');
- db.run('INSERT INTO MipmapInfo VALUES (210, 1.0, 2100, 0)');
- db.run('INSERT INTO MipmapInfo VALUES (300, 1.0, 3000, 0)');
-
- const attr512 = buildOffscreenAttribute(512, 256, 0, 1, 4);
- const attrMask = buildOffscreenAttribute(512, 256, 0, 0, 1);
-
- db.run('INSERT INTO Offscreen VALUES (1000, 3, "extrnlid_lineart", ?)', [attr512]);
- db.run('INSERT INTO Offscreen VALUES (1001, 3, "extrnlid_lineart_half", ?)', [buildOffscreenAttribute(256, 128, 0, 1, 1)]);
- db.run('INSERT INTO Offscreen VALUES (2000, 5, "extrnlid_base", ?)', [attr512]);
- db.run('INSERT INTO Offscreen VALUES (2100, 5, "extrnlid_mask", ?)', [attrMask]);
- db.run('INSERT INTO Offscreen VALUES (3000, 6, "extrnlid_shadow", ?)', [attr512]);
-
- const sqliteBytes = db.export();
- db.close();
-
- // Lineart: 1-bit monochrome tile at block 0, pixel (0,0) = black ink (MSB bit 7 of byte 0)
- const monoTile = new Uint8Array(8192);
- monoTile[0] = 0x80; // pixel (0, 0) drawn
- const lineartPayload = buildBlockData([monoTile, null]);
-
- // Base Color: sparse — block 0 is EMPTY (null), block 1 (x=256..511) is solid crimson (220, 40, 60, 255) split into 2 planes!
- const alphaPlane = new Uint8Array(TILE_PIXELS).fill(255);
- const bgrxPlane = new Uint8Array(TILE_PIXELS * 4);
- for (let p = 0; p < TILE_PIXELS; p++) {
- bgrxPlane[p * 4] = 60; // B
- bgrxPlane[p * 4 + 1] = 40; // G
- bgrxPlane[p * 4 + 2] = 220; // R
- }
- const basePayload = buildBlockData([null, [alphaPlane, bgrxPlane]]);
-
- // Mask for Base Color: block 0 empty (defaultFill=0 -> masked), block 1 = 200
- const maskTile = new Uint8Array(TILE_PIXELS).fill(200);
- const maskPayload = buildBlockData([null, maskTile]);
-
- // Shadow: grayscale 2-plane (alpha=180, gray=90) on block 0
- const grayTile = new Uint8Array(TILE_PIXELS * 2);
- grayTile.fill(180, 0, TILE_PIXELS);
- grayTile.fill(90, TILE_PIXELS, TILE_PIXELS * 2);
- const shadowPayload = buildBlockData([grayTile, null]);
-
- const clipBuf = buildClipFile([
- buildChunk('SQLi', sqliteBytes),
- buildExtaChunk('extrnlid_lineart', lineartPayload),
- buildExtaChunk('extrnlid_base', basePayload),
- buildExtaChunk('extrnlid_mask', maskPayload),
- buildExtaChunk('extrnlid_shadow', shadowPayload),
- ]);
-
- const doc = await parseCspFile(clipBuf, 'manga_page.clip');
-
- expect(doc.name).toBe('manga_page');
- expect(doc.dimensions).toEqual({ width: 512, height: 256, dpi: 600 });
- expect(doc.tileGrid).toBeDefined();
-
- // Expected top-to-bottom order: Paint (folder) -> Shadow -> Base Color -> Lineart -> Paper
- expect(doc.layers.map((l) => l.name)).toEqual([
- 'Paint',
- 'Shadow',
- 'Base Color',
- 'Lineart',
- 'Paper',
- ]);
-
- const [paintFolder, shadowLayer, baseLayer, lineartLayer, paperLayer] = doc.layers;
-
- expect(paintFolder.type).toBe('folder');
- expect(paintFolder.collapsed).toBe(true);
- expect(paintFolder.blendMode).toBe('pass-through');
- expect(paintFolder.parentId).toBeNull();
-
- expect(shadowLayer.parentId).toBe(paintFolder.id);
- expect(shadowLayer.clipped).toBe(true);
- expect(shadowLayer.blendMode).toBe('multiply');
- expect(shadowLayer.opacity).toBeCloseTo(0.5, 2);
-
- expect(baseLayer.parentId).toBe(paintFolder.id);
- expect(baseLayer.maskEnabled).toBe(true);
- expect(baseLayer.maskLinked).toBe(true);
- expect(baseLayer.maskCanvas).toBeDefined();
- // Verify mask pixel: (10,10) = 0 (defaultFill), (260,10) = 200
- const mCtx = baseLayer.maskCanvas!.getContext('2d')!;
- expect(mCtx.getImageData(10, 10, 1, 1).data[0]).toBe(0);
- expect(mCtx.getImageData(260, 10, 1, 1).data[0]).toBe(200);
-
- expect(lineartLayer.alphaLocked).toBe(true);
- expect(lineartLayer.locked).toBe(false);
- expect(lineartLayer.blendMode).toBe('multiply');
-
- // Verify decoded pixels in SparseTileGrid!
- const grid = doc.tileGrid!;
-
- // Base Color: x=10 (tile 0) must be unallocated (empty); x=260 (tile 1) must be RGBA(220, 40, 60, 255)
- const baseTile0 = grid.getTile(baseLayer.id, 0, 0, 0);
- expect(baseTile0).toBeNull();
- const baseTile1 = grid.getTile(baseLayer.id, 1, 0, 0);
- expect(baseTile1?.data).toBeDefined();
- expect(Array.from(baseTile1!.data!.subarray(0, 4))).toEqual([220, 40, 60, 255]);
- // Lineart 1-bit monochrome: pixel (0,0) = black (0,0,0,255), pixel (1,0) = transparent
- const lineTile0 = grid.getTile(lineartLayer.id, 0, 0, 0);
- expect(Array.from(lineTile0!.data!.subarray(0, 4))).toEqual([0, 0, 0, 255]);
- expect(Array.from(lineTile0!.data!.subarray(4, 8))).toEqual([0, 0, 0, 0]);
-
- // Shadow grayscale: pixel (0,0) = (90, 90, 90, 180)
- const shadowTile0 = grid.getTile(shadowLayer.id, 0, 0, 0);
- expect(Array.from(shadowTile0!.data!.subarray(0, 4))).toEqual([90, 90, 90, 180]);
-
- // Paper: solid white across tiles
- expect(grid.hasLayerTiles(paperLayer.id)).toBe(true);
+ const rgba = new Uint8ClampedArray(BYTES_32BIT);
+ expect(decodeCspTileToRgba(decoded.get(1)!, rgba, parsed)).toBe(true);
+ expect([rgba[0], rgba[1], rgba[2], rgba[3]]).toEqual([240, 20, 10, 200]);
});
- it('respects LayerOffsetX/Y, bitmap boundary clipping, 2-plane monochrome, and disabled masks', async () => {
- (globalThis as Record<string, unknown>).document = {
- createElement: () => createPixelCanvas(300, 300),
+ it('hydrates Rust INKD binary payload into SparseTileGrid with LZ4 tiles, folders, and paper', () => {
+ const rawTile = new Uint8Array(BYTES_32BIT);
+ const px = (5 * TILE_SIZE + 3) * 4;
+ rawTile[px] = 220;
+ rawTile[px + 1] = 30;
+ rawTile[px + 2] = 40;
+ rawTile[px + 3] = 255;
+ const compTile = lz4CompressBlock(rawTile);
+
+ const meta = {
+ width: 512,
+ height: 256,
+ dpi: 600,
+ colorMode: 'color',
+ preview: null,
+ layers: [
+ {
+ id: 'csp-folder-1',
+ name: 'Paint',
+ type: 'folder',
+ visible: true,
+ opacity: 1,
+ blendMode: 'pass-through',
+ locked: false,
+ alphaLocked: false,
+ clipped: false,
+ collapsed: true,
+ parentId: null,
+ solidFillHex: null,
+ tiles: [],
+ mask: null,
+ },
+ {
+ id: 'csp-layer-2',
+ name: 'Ink',
+ type: 'raster',
+ visible: true,
+ opacity: 0.5,
+ blendMode: 'multiply',
+ locked: false,
+ alphaLocked: true,
+ clipped: true,
+ collapsed: false,
+ parentId: 'csp-folder-1',
+ solidFillHex: null,
+ tiles: [{ tx: 1, ty: 0, codec: 2, offset: 0, len: compTile.byteLength }],
+ mask: null,
+ },
+ {
+ id: 'csp-layer-3',
+ name: 'Paper',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ alphaLocked: false,
+ clipped: false,
+ collapsed: false,
+ parentId: null,
+ solidFillHex: '#ffffff',
+ tiles: [],
+ mask: null,
+ },
+ ],
};
- const SQL = await initSqlJs();
- const db = new SQL.Database();
- db.run(`
- CREATE TABLE Canvas (MainId INTEGER, CanvasWidth INTEGER, CanvasHeight INTEGER, CanvasRootFolder INTEGER);
- CREATE TABLE Layer (
- MainId INTEGER, LayerName TEXT, LayerType INTEGER, LayerFolder INTEGER,
- LayerComposite INTEGER, LayerOpacity INTEGER, LayerVisibility INTEGER,
- LayerLock INTEGER, LayerClip INTEGER, LayerSelect INTEGER,
- LayerOffsetX REAL, LayerOffsetY REAL,
- LayerNextIndex INTEGER, LayerFirstChildIndex INTEGER,
- LayerRenderMipmap INTEGER, LayerLayerMaskMipmap INTEGER
- );
- CREATE TABLE Mipmap (MainId INTEGER, BaseMipmapInfo INTEGER);
- CREATE TABLE MipmapInfo (MainId INTEGER, ThisScale REAL, Offscreen INTEGER, NextIndex INTEGER);
- CREATE TABLE Offscreen (MainId INTEGER, LayerId INTEGER, BlockData TEXT, Attribute BLOB);
- `);
-
- db.run('INSERT INTO Canvas VALUES (1, 300, 300, 1)');
- db.run('INSERT INTO Layer VALUES (1, "", 256, 1, 0, 256, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0)');
- // Layer 2: shifted by (+10, +20), LayerVisibility=1 (visible, mask DISABLED), LayerSelect=0 (mask unlinked)
- db.run('INSERT INTO Layer VALUES (2, "Mono2Plane", 1, 0, 0, 256, 1, 1, 0, 0, 10, 20, 0, 0, 10, 11)');
- db.run('INSERT INTO Mipmap VALUES (10, 100), (11, 110)');
- db.run('INSERT INTO MipmapInfo VALUES (100, 1.0, 1000, 0), (110, 1.0, 1100, 0)');
- db.run('INSERT INTO Offscreen VALUES (1000, 2, "extrnlid_mono2", ?)', [buildOffscreenAttribute(100, 100, 0, 1, 1)]);
- db.run('INSERT INTO Offscreen VALUES (1100, 2, "extrnlid_mask2", ?)', [buildOffscreenAttribute(300, 300, 1, 0, 1)]);
-
- const sqliteBytes = db.export();
- db.close();
+ const metaBytes = new TextEncoder().encode(JSON.stringify(meta));
+ const wire = concatBytes([asciiBytes('INKD'), u32LE(1), u32LE(metaBytes.byteLength), metaBytes, compTile]);
- // 2-plane 1-bit mono: pixel (0,0) = opaque white (alpha=1, color=1); pixel (1,0) = opaque black (alpha=1, color=0)
- const mono2 = new Uint8Array(16384);
- mono2[0] = 0xc0; // alpha bits for x=0,1
- mono2[8192] = 0x80; // white bit for x=0 only
-
- const clipBuf = buildClipFile([
- buildChunk('SQLi', sqliteBytes),
- buildExtaChunk('extrnlid_mono2', buildBlockData([mono2])),
- buildExtaChunk('extrnlid_mask2', buildBlockData([null, null, null, null])),
- ]);
+ const doc = hydrateParsedDocumentBinary(wire, 'manga.clip');
+ expect(doc.dimensions).toEqual({ width: 512, height: 256, dpi: 600 });
+ expect(doc.layers).toHaveLength(3);
+ expect(doc.layers[0].type).toBe('folder');
+ expect(doc.layers[0].collapsed).toBe(true);
+ expect(doc.layers[1].parentId).toBe(doc.layers[0].id);
+ expect(doc.layers[1].blendMode).toBe('multiply');
+ expect(doc.layers[1].alphaLocked).toBe(true);
- const doc = await parseCspFile(clipBuf, 'offset_mono.clip');
- expect(doc.layers.length).toBe(1);
- const layer = doc.layers[0];
- expect(layer.locked).toBe(true);
- expect(layer.maskEnabled).toBe(false);
- expect(layer.maskLinked).toBe(false);
+ expect(doc.tileGrid).toBeDefined();
+ const readBack = doc.tileGrid!.readImageData(doc.layers[1].id, 256 + 3, 5, 1, 1);
+ expect(Array.from(readBack.data)).toEqual([220, 30, 40, 255]);
- // Offset (+10, +20): (10,20) must be white (255,255,255,255) and (11,20) must be black (0,0,0,255)
- const tile = doc.tileGrid!.getTile(layer.id, 0, 0, 0)!;
- const idxWhite = (20 * TILE_SIZE + 10) * 4;
- const idxBlack = (20 * TILE_SIZE + 11) * 4;
- expect(Array.from(tile.data!.subarray(idxWhite, idxWhite + 4))).toEqual([255, 255, 255, 255]);
- expect(Array.from(tile.data!.subarray(idxBlack, idxBlack + 4))).toEqual([0, 0, 0, 255]);
+ const paperPx = doc.tileGrid!.readImageData(doc.layers[2].id, 0, 0, 1, 1);
+ expect(Array.from(paperPx.data)).toEqual([255, 255, 255, 255]);
});
- it('accumulates parent folder LayerOffset, child LayerOffset, LayerRenderOffscrOffset, and LayerMaskOffscrOffset', async () => {
- (globalThis as Record<string, unknown>).document = {
- createElement: () => createPixelCanvas(512, 512),
- };
-
- const SQL = await initSqlJs();
- const db = new SQL.Database();
- db.run(`
- CREATE TABLE Canvas (MainId INTEGER, CanvasWidth INTEGER, CanvasHeight INTEGER, CanvasRootFolder INTEGER);
- CREATE TABLE Layer (
- MainId INTEGER, LayerName TEXT, LayerType INTEGER, LayerFolder INTEGER,
- LayerComposite INTEGER, LayerOpacity INTEGER, LayerVisibility INTEGER,
- LayerLock INTEGER, LayerClip INTEGER, LayerSelect INTEGER,
- LayerOffsetX REAL, LayerOffsetY REAL,
- LayerRenderOffscrOffsetX REAL, LayerRenderOffscrOffsetY REAL,
- LayerMaskOffsetX REAL, LayerMaskOffsetY REAL,
- LayerMaskOffscrOffsetX REAL, LayerMaskOffscrOffsetY REAL,
- LayerNextIndex INTEGER, LayerFirstChildIndex INTEGER,
- LayerRenderMipmap INTEGER, LayerLayerMaskMipmap INTEGER
- );
- CREATE TABLE Mipmap (MainId INTEGER, BaseMipmapInfo INTEGER);
- CREATE TABLE MipmapInfo (MainId INTEGER, ThisScale REAL, Offscreen INTEGER, NextIndex INTEGER);
- CREATE TABLE Offscreen (MainId INTEGER, LayerId INTEGER, BlockData TEXT, Attribute BLOB);
- `);
-
- db.run('INSERT INTO Canvas VALUES (1, 512, 512, 1)');
- db.run('INSERT INTO Layer VALUES (1, "", 256, 1, 0, 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0)');
- // Folder moved by (+40, +50)
- db.run('INSERT INTO Layer VALUES (2, "MovedFolder", 256, 1, 30, 256, 1, 0, 0, 0, 40, 50, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0)');
- // Child layer: LayerOffset(+10, +300), LayerRenderOffscrOffset(-30, -320) => effective render offset = (+20, +30)
- // Mask: LayerMaskOffset(+5, +10), LayerMaskOffscrOffset(-15, -300) => effective mask offset = (40+10+5-15, 50+300+10-300) = (+40, +60)
- db.run('INSERT INTO Layer VALUES (3, "Painted", 1, 0, 0, 256, 3, 0, 0, 256, 10, 300, -30, -320, 5, 10, -15, -300, 0, 0, 10, 11)');
-
- db.run('INSERT INTO Mipmap VALUES (10, 100), (11, 110)');
- db.run('INSERT INTO MipmapInfo VALUES (100, 1.0, 1000, 0), (110, 1.0, 1100, 0)');
- db.run('INSERT INTO Offscreen VALUES (1000, 3, "extrnlid_off_paint", ?)', [buildOffscreenAttribute(256, 256, 0, 1, 4)]);
- db.run('INSERT INTO Offscreen VALUES (1100, 3, "extrnlid_off_mask", ?)', [buildOffscreenAttribute(256, 256, 0, 0, 1)]);
-
- const sqliteBytes = db.export();
- db.close();
-
- const paintTile = makeColorTile(10, 200, 30, 255);
- const maskTile = new Uint8Array(TILE_PIXELS).fill(180);
-
- const clipBuf = buildClipFile([
- buildChunk('SQLi', sqliteBytes),
- buildExtaChunk('extrnlid_off_paint', buildBlockData([paintTile])),
- buildExtaChunk('extrnlid_off_mask', buildBlockData([maskTile])),
- ]);
-
- const doc = await parseCspFile(clipBuf, 'offsets.clip');
- const painted = doc.layers.find((l) => l.name === 'Painted')!;
-
- // Tile starts at (+20, +30): pixel (19, 30) must be transparent, pixel (20, 30) must be RGBA(10, 200, 30, 255)
- const tile = doc.tileGrid!.getTile(painted.id, 0, 0, 0)!;
- const beforeIdx = (30 * TILE_SIZE + 19) * 4;
- const startIdx = (30 * TILE_SIZE + 20) * 4;
- expect(Array.from(tile.data!.subarray(beforeIdx, beforeIdx + 4))).toEqual([0, 0, 0, 0]);
- expect(Array.from(tile.data!.subarray(startIdx, startIdx + 4))).toEqual([10, 200, 30, 255]);
-
- // Mask starts at (+40, +60): pixel (39, 60) = 0, pixel (40, 60) = 180
- const mCtx = painted.maskCanvas!.getContext('2d')!;
- expect(mCtx.getImageData(39, 60, 1, 1).data[0]).toBe(0);
- expect(mCtx.getImageData(40, 60, 1, 1).data[0]).toBe(180);
+ it('rejects .clip parsing gracefully outside Tauri (WASM sql.js removed)', async () => {
+ await expect(parseCspFile(new ArrayBuffer(16), 'test.clip')).rejects.toThrow(/Rust backend/);
});
- it('guards against cyclic LayerNextIndex pointers and minimal/missing columns without hanging', async () => {
- const SQL = await initSqlJs();
- const db = new SQL.Database();
- db.run(`
- CREATE TABLE Canvas (CanvasWidth INTEGER, CanvasHeight INTEGER, CanvasRootFolder INTEGER);
- CREATE TABLE Layer (MainId INTEGER, LayerName TEXT, LayerNextIndex INTEGER, LayerFirstChildIndex INTEGER);
- `);
- db.run('INSERT INTO Canvas VALUES (256, 256, 1)');
- db.run('INSERT INTO Layer VALUES (1, "", 0, 2)');
- db.run('INSERT INTO Layer VALUES (2, "CycleA", 3, 0)');
- db.run('INSERT INTO Layer VALUES (3, "CycleB", 2, 0)'); // cycle back to 2!
- const sqliteBytes = db.export();
- db.close();
-
- const clipBuf = buildClipFile([buildChunk('SQLi', sqliteBytes)]);
- const doc = await parseCspFile(clipBuf, 'cyclic.clip');
-
- expect(doc.layers.map((l) => l.name)).toEqual(['CycleB', 'CycleA']);
- expect(doc.layers.every((l) => l.type === 'raster')).toBe(true);
+ it('unpacks binary native tablet sample packets matching Rust layout', () => {
+ const buf = new ArrayBuffer(4 + 36);
+ const v = new DataView(buf);
+ v.setUint32(0, 1, true);
+ v.setFloat32(4, 123.5, true);
+ v.setFloat32(8, 456.25, true);
+ v.setFloat32(12, 0.75, true);
+ v.setFloat32(16, -15.0, true);
+ v.setFloat32(20, 30.0, true);
+ v.setFloat32(24, 90.0, true);
+ v.setFloat64(28, 123456.789, true);
+ v.setUint16(36, 9, true);
+ v.setUint8(38, 2);
+ v.setUint8(39, 1);
+
+ const samples = unpackTabletSampleBatch(buf);
+ expect(samples).toHaveLength(1);
+ expect(samples[0]).toEqual({
+ clientX: 123.5,
+ clientY: 456.25,
+ pressure: 0.75,
+ tiltX: -15.0,
+ tiltY: 30.0,
+ twist: 90.0,
+ timestamp: 123456.789,
+ buttons: 9,
+ phase: 2,
+ backend: 1,
+ });
});
});
diff --git a/src/utils/__tests__/documentIsolation.test.ts b/src/utils/__tests__/documentIsolation.test.ts
index 653fe32..022cba8 100644
--- a/src/utils/__tests__/documentIsolation.test.ts
+++ b/src/utils/__tests__/documentIsolation.test.ts
@@ -213,8 +213,8 @@ describe('Per-Document Isolation, Shared RAM Budgets & Sparse Tile Memory Optimi
});
}
- expect(doc.layerCanvases.size).toBe(0);
- expect(doc.layerSourceCanvases.size).toBe(0);
+ expect('layerCanvases' in doc).toBe(false);
+ expect('layerSourceCanvases' in doc).toBe(false);
const stats = doc.tileGrid.getMemoryStats();
expect(stats.tileCount).toBe(0);
expect(stats.activeBytes).toBe(0);
@@ -224,7 +224,7 @@ describe('Per-Document Isolation, Shared RAM Budgets & Sparse Tile Memory Optimi
const afterStroke = doc.tileGrid.getMemoryStats();
expect(afterStroke.tileCount).toBe(1);
expect(afterStroke.activeBytes).toBe(BYTES_32BIT);
- expect(doc.layerCanvases.size).toBe(0);
+ expect('layerCanvases' in doc).toBe(false);
// Batch-deleting layers cleans up tiles cleanly
const delRes = computeBatchDeleteLayers(layers, ['raster-empty-5', 'raster-empty-6'], 'raster-empty-5');
@@ -246,10 +246,6 @@ describe('Per-Document Isolation, Shared RAM Budgets & Sparse Tile Memory Optimi
doc.historyIndex = 0;
await store.registerUndoStep('doc-closable', item);
- // Attach a mock materialized canvas to verify width/height zeroing on close
- const mockCanvas = { width: 4000, height: 6000 } as HTMLCanvasElement;
- doc.layerCanvases.set('layer-1', mockCanvas);
-
await store.closeSession('doc-closable');
expect(store.hasSession('doc-closable')).toBe(false);
@@ -258,9 +254,7 @@ describe('Per-Document Isolation, Shared RAM Budgets & Sparse Tile Memory Optimi
expect(doc.tileGrid.getMemoryStats().activeBytes).toBe(0);
expect(doc.undoCache.getRamStepCount()).toBe(0);
expect(doc.undoCache.getCompressedRamCount()).toBe(0);
- expect(doc.layerCanvases.size).toBe(0);
- expect(mockCanvas.width).toBe(0);
- expect(mockCanvas.height).toBe(0);
+ expect('layerCanvases' in doc).toBe(false);
});
it('builds and samples layer thumbnails directly from LOD 3 tiles without reading a full-size canvas', () => {
diff --git a/src/utils/__tests__/fileDropImport.test.ts b/src/utils/__tests__/fileDropImport.test.ts
index 6a048eb..a408fe3 100644
--- a/src/utils/__tests__/fileDropImport.test.ts
+++ b/src/utils/__tests__/fileDropImport.test.ts
@@ -93,6 +93,7 @@ describe('fileDropImport utilities', () => {
'malware.exe',
'notes.txt',
'archive.zip',
+ 'project.ink',
'project.sora',
'file.png.exe',
'.png',
diff --git a/src/utils/__tests__/soraV2AndGpuExport.test.ts b/src/utils/__tests__/inkV2AndGpuExport.test.ts
similarity index 79%
rename from src/utils/__tests__/soraV2AndGpuExport.test.ts
rename to src/utils/__tests__/inkV2AndGpuExport.test.ts
index 6955e9e..d2356a2 100644
--- a/src/utils/__tests__/soraV2AndGpuExport.test.ts
+++ b/src/utils/__tests__/inkV2AndGpuExport.test.ts
@@ -21,18 +21,17 @@ import {
import { ViewportCompositor } from '../compositor';
import {
buildGpuExportTilePlan,
- buildSoraProjectPayload,
compositeCanvas,
compositeCanvasAsync,
computeMaxLayerStyleMargin,
createDocumentRegionRenderer,
exportImage,
- extractSoraPreview,
- isSoraV2Bytes,
- parseSoraProject,
+ extractInkPreview,
+ isInkProjectBytes,
+ parseInkProject,
SaveProgress,
serializeDocument,
- serializeSoraV2,
+ serializeInkProject,
} from '../saveManager';
function createMockMaskCanvas(width: number, height: number, fillFn: (x: number, y: number) => number): HTMLCanvasElement {
@@ -59,22 +58,20 @@ function createMockMaskCanvas(width: number, height: number, fillFn: (x: number,
} as unknown as HTMLCanvasElement;
}
-describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
+describe('.ink Binary Format & Round-Trip Serialization', () => {
afterEach(() => {
vi.restoreAllMocks();
});
- it('round-trips 1-bit, 8-bit, 32-bit native SparseTileGrid tiles, masks, vectors, text, balloons, frames, perspective, animation, and timelapse without toDataURL', async () => {
+ it('round-trips 1-bit, 8-bit, 32-bit native SparseTileGrid tiles, masks, vectors, text, balloons, frames, perspective, animation, and timelapse', async () => {
const grid = new SparseTileGrid();
- // 1. 1-bit monochrome ink tile at (2, 3)
const monoTile = grid.getOrCreateTile('layer-mono', 2, 3, 'monochrome-1bit', 0);
setPixel1Bit(monoTile.data!, 5, 7, 1);
setPixel1Bit(monoTile.data!, 200, 123, 1);
monoTile.version = 9;
grid.setLayerFormat('layer-mono', 'monochrome-1bit');
- // 2. 8-bit grayscale tone tile at (0, 1)
const grayTile = grid.getOrCreateTile('layer-gray', 0, 1, 'grayscale-8bit', 0);
grayTile.data![0] = 42;
grayTile.data![256 * 10 + 15] = 199;
@@ -82,7 +79,6 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
grayTile.version = 4;
grid.setLayerFormat('layer-gray', 'grayscale-8bit');
- // 3. 32-bit RGBA color tile at (1, 0) + negative/offset tile at (4, 5)
const colorTile = grid.getOrCreateTile('layer-color', 1, 0, 'color-32bit', 0);
colorTile.data![0] = 220;
colorTile.data![1] = 40;
@@ -112,7 +108,7 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
const textData: TextLayerData = {
x: 300,
y: 220,
- text: 'SORA V2!\nLINE TWO',
+ text: 'INK V2!\nLINE TWO',
fontFamily: 'Anime Ace',
fontSize: 36,
lineSpacing: 1.4,
@@ -197,7 +193,7 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
},
{
id: 'layer-text',
- name: 'SORA V2!',
+ name: 'INK V2!',
type: 'text',
visible: true,
opacity: 1,
@@ -294,7 +290,7 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
];
const progressLog: SaveProgress[] = [];
- const serialized = await serializeSoraV2(
+ const serialized = await serializeInkProject(
{
name: 'Manga Page 01',
dimensions: { width: 7016, height: 9921, dpi: 600 },
@@ -312,12 +308,11 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
grid
);
- // Must be compact ZIP binary starting with PK\x03\x04
- expect(isSoraV2Bytes(serialized.bytes)).toBe(true);
+ expect(serialized.manifest.format).toBe('ink-v2');
+ expect(isInkProjectBytes(serialized.bytes)).toBe(true);
expect(serialized.bytes[0]).toBe(0x50);
expect(serialized.bytes[1]).toBe(0x4b);
- // Inspect ZIP structure directly: manifest + native tile files + mask file
const entries = unzipSync(serialized.bytes);
expect(entries['manifest.json']).toBeDefined();
expect(entries['tiles/layer-mono/2_3.bin']).toBeDefined();
@@ -325,22 +320,19 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
expect(entries['tiles/layer-color/1_0.bin']).toBeDefined();
expect(entries['masks/layer-mono.bin']).toBeDefined();
- // Progress indicator reached 100%
expect(progressLog.length).toBeGreaterThanOrEqual(3);
expect(progressLog[progressLog.length - 1].phase).toBe('done');
expect(progressLog[progressLog.length - 1].percent).toBe(100);
- // Round-trip parse with auto-detection
- const parsed = await parseSoraProject(serialized.bytes);
- expect(parsed.format).toBe('v2');
+ const parsed = await parseInkProject(serialized.bytes);
+ expect(parsed.format).toBe('ink-v2');
expect(parsed.version).toBe('2.0');
expect(parsed.name).toBe('Manga Page 01');
expect(parsed.dimensions).toEqual({ width: 7016, height: 9921, dpi: 600 });
expect(parsed.layers).toHaveLength(8);
expect(parsed.tileGrid).toBeDefined();
- // Verify 1-bit tile exact binary round-trip
- const restoredMono = parsed.tileGrid!.getTile('layer-mono', 2, 3, 0);
+ const restoredMono = parsed.tileGrid.getTile('layer-mono', 2, 3, 0);
expect(restoredMono).toBeDefined();
expect(restoredMono!.format).toBe('monochrome-1bit');
expect(restoredMono!.data!.byteLength).toBe(BYTES_1BIT);
@@ -349,8 +341,7 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
expect(getPixel1Bit(restoredMono!.data!, 0, 0)).toBe(0);
expect(restoredMono!.version).toBe(9);
- // Verify 8-bit tile exact binary round-trip
- const restoredGray = parsed.tileGrid!.getTile('layer-gray', 0, 1, 0);
+ const restoredGray = parsed.tileGrid.getTile('layer-gray', 0, 1, 0);
expect(restoredGray).toBeDefined();
expect(restoredGray!.format).toBe('grayscale-8bit');
expect(restoredGray!.data!.byteLength).toBe(BYTES_8BIT);
@@ -359,8 +350,7 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
expect(restoredGray!.data![BYTES_8BIT - 1]).toBe(255);
expect(restoredGray!.version).toBe(4);
- // Verify 32-bit tile exact binary round-trip
- const restoredColor = parsed.tileGrid!.getTile('layer-color', 1, 0, 0);
+ const restoredColor = parsed.tileGrid.getTile('layer-color', 1, 0, 0);
expect(restoredColor).toBeDefined();
expect(restoredColor!.format).toBe('color-32bit');
expect(restoredColor!.data!.byteLength).toBe(BYTES_32BIT);
@@ -368,8 +358,7 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
expect(Array.from(restoredColor!.data!.subarray(BYTES_32BIT - 4))).toEqual([12, 34, 56, 180]);
expect(restoredColor!.version).toBe(12);
- // Verify binary mask round-trip
- const restoredMask = parsed.masksBinary?.get('layer-mono');
+ const restoredMask = parsed.masksBinary.get('layer-mono');
expect(restoredMask).toBeDefined();
expect(restoredMask!.width).toBe(16);
expect(restoredMask!.height).toBe(8);
@@ -377,7 +366,6 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
expect(restoredMask!.data[17]).toBe(17);
expect(restoredMask!.data[127]).toBe(127);
- // Verify non-destructive vector, text, balloon, frame, styles, screentone, perspective, animation, timelapse
expect(parsed.layers.find((l) => l.id === 'layer-vector')?.vectorStrokes).toEqual([vectorStroke]);
expect(parsed.layers.find((l) => l.id === 'layer-text')?.textData).toEqual(textData);
expect(parsed.layers.find((l) => l.id === 'layer-balloon')?.balloonData?.text).toBe('BOOM!');
@@ -395,7 +383,7 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
});
});
- it('hydrates paged-out scratch disk tiles cleanly during .sora v2 save without data loss', async () => {
+ it('hydrates paged-out scratch disk tiles cleanly during .ink save without data loss', async () => {
const driver = new InMemoryScratchDiskDriver();
const grid = new SparseTileGrid({
sessionId: 'paged-save-test',
@@ -408,7 +396,6 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
tile.data![5000] = 88;
const rawCopy = new Uint8Array(tile.data!);
- // Simulate SSD scratch eviction: write tile to scratch driver and drop RAM pointer
await driver.writeTiles('paged-save-test', [
{ layerId: 'layer-1', tileX: 0, tileY: 0, data: rawCopy },
]);
@@ -429,7 +416,7 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
},
];
- const saved = await serializeSoraV2(
+ const saved = await serializeInkProject(
{
name: 'Paged Doc',
dimensions: { width: 512, height: 512, dpi: 300 },
@@ -443,56 +430,16 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
grid
);
- const parsed = await parseSoraProject(saved.bytes);
- const restored = parsed.tileGrid!.getTile('layer-1', 0, 0, 0);
+ const parsed = await parseInkProject(saved.bytes);
+ const restored = parsed.tileGrid.getTile('layer-1', 0, 0, 0);
expect(restored?.data?.[100]).toBe(177);
expect(restored?.data?.[5000]).toBe(88);
});
- it('auto-detects legacy v1.2 JSON (string & UTF-8 bytes with BOM) and preserves backward compatibility', async () => {
- const layers: LayerItem[] = [
- {
- id: 'layer-bg',
- name: 'Background',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: false,
- parentId: null,
- },
- ];
-
- const v1Payload = buildSoraProjectPayload({
- name: 'Legacy Project',
- dimensions: { width: 1440, height: 900, dpi: 300 },
- colorMode: 'color',
- layers,
- layerCanvasesMap: new Map(),
- getEffectiveOpacity: (l) => l.opacity,
- isLayerEffectivelyVisible: (l) => l.visible,
- });
- const jsonString = JSON.stringify(v1Payload);
-
- // String input
- const parsedStr = await parseSoraProject(jsonString);
- expect(parsedStr.format).toBe('v1');
- expect(parsedStr.version).toBe('1.2');
- expect(parsedStr.name).toBe('Legacy Project');
- expect(parsedStr.layers).toHaveLength(1);
-
- // UTF-8 ArrayBuffer with BOM
- const utf8WithBom = new Uint8Array([0xef, 0xbb, 0xbf, ...new TextEncoder().encode(jsonString)]);
- expect(isSoraV2Bytes(utf8WithBom)).toBe(false);
- const parsedBytes = await parseSoraProject(utf8WithBom.buffer);
- expect(parsedBytes.format).toBe('v1');
- expect(parsedBytes.name).toBe('Legacy Project');
- });
-
- it('extracts preview.png via extractSoraPreview without decompressing tiles, and supports SORA magic wrapper', async () => {
+ it('extracts preview.png via extractInkPreview without decompressing tiles and rejects legacy SORA magic wrapper in primary parser', async () => {
const fakePng = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4]);
const manifest = {
- format: 'sora-v2',
+ format: 'ink-v2',
app: 'Ink Studio',
version: '2.0',
tileSize: 256,
@@ -512,19 +459,14 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
'preview.png': fakePng,
});
- // Direct ZIP
- expect(Array.from(extractSoraPreview(zipBytes)!)).toEqual(Array.from(fakePng));
+ expect(Array.from(extractInkPreview(zipBytes)!)).toEqual(Array.from(fakePng));
- // With optional 8-byte SORA\x00\x02 header prefix
const wrapped = new Uint8Array(8 + zipBytes.byteLength);
wrapped.set([0x53, 0x4f, 0x52, 0x41, 0x00, 0x02, 0x00, 0x00], 0);
wrapped.set(zipBytes, 8);
- expect(isSoraV2Bytes(wrapped)).toBe(true);
- expect(Array.from(extractSoraPreview(wrapped)!)).toEqual(Array.from(fakePng));
-
- const parsed = await parseSoraProject(wrapped);
- expect(parsed.format).toBe('v2');
- expect(parsed.previewDataUrl).toMatch(/^data:image\/png;base64,/);
+ expect(isInkProjectBytes(wrapped)).toBe(false);
+ expect(extractInkPreview(wrapped)).toBeNull();
+ await expect(parseInkProject(wrapped)).rejects.toThrow(/expected binary ZIP container/);
});
it('sanitizes unsafe layer IDs and rejects path traversal and corrupted tile payloads', async () => {
@@ -533,7 +475,7 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
const tile = grid.getOrCreateTile(weirdId, 0, 0, 'monochrome-1bit', 0);
setPixel1Bit(tile.data!, 3, 4, 1);
- const saved = await serializeSoraV2(
+ const saved = await serializeInkProject(
{
name: 'Safe Keys',
dimensions: { width: 256, height: 256, dpi: 300 },
@@ -558,21 +500,19 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
grid
);
- const parsed = await parseSoraProject(saved.bytes);
- const restored = parsed.tileGrid!.getTile(weirdId, 0, 0, 0);
+ const parsed = await parseInkProject(saved.bytes);
+ const restored = parsed.tileGrid.getTile(weirdId, 0, 0, 0);
expect(restored).toBeDefined();
expect(getPixel1Bit(restored!.data!, 3, 4)).toBe(1);
- // Path traversal archive rejected
const evilZip = zipSync({
'manifest.json': new TextEncoder().encode(
JSON.stringify({ dimensions: { width: 256, height: 256 }, layers: [] })
),
'../escape.bin': new Uint8Array([1, 2, 3]),
});
- await expect(parseSoraProject(evilZip)).rejects.toThrow(/Unsafe archive path/);
+ await expect(parseInkProject(evilZip)).rejects.toThrow(/Unsafe archive path/);
- // Truncated / mismatched tile payload rejected
const corruptZip = zipSync({
'manifest.json': new TextEncoder().encode(
JSON.stringify({
@@ -581,47 +521,47 @@ describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
layerTileKeys: { l1: 'l1' },
})
),
- 'tiles/l1/0_0.bin': new Uint8Array([0, 1, 0, 0, 0, 0, 32, 0, 0, 0xff]), // claims 8192 bytes, only 1 byte present
+ 'tiles/l1/0_0.bin': new Uint8Array([0, 1, 0, 0, 0, 0, 32, 0, 0, 0xff]),
});
- await expect(parseSoraProject(corruptZip)).rejects.toThrow(/length mismatch/);
+ await expect(parseInkProject(corruptZip)).rejects.toThrow(/length mismatch/);
});
- it('serializeDocument writes binary .sora v2 Blob instead of legacy JSON', async () => {
+ it('serializeDocument writes binary .ink Blob and refuses read-only .sora writes', async () => {
const grid = new SparseTileGrid();
const t = grid.getOrCreateTile('l1', 0, 0, 'monochrome-1bit', 0);
setPixel1Bit(t.data!, 10, 10, 1);
- const res = await serializeDocument(
- {
- name: 'Doc',
- dimensions: { width: 512, height: 512, dpi: 600 },
- colorMode: 'monochrome',
- layers: [
- {
- id: 'l1',
- name: 'Ink',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: false,
- parentId: null,
- },
- ],
- layerCanvasesMap: new Map(),
- tileGrid: grid,
- getEffectiveOpacity: () => 1,
- isLayerEffectivelyVisible: () => true,
- },
- '.sora'
- );
+ const docData = {
+ name: 'Doc',
+ dimensions: { width: 512, height: 512, dpi: 600 },
+ colorMode: 'monochrome' as const,
+ layers: [
+ {
+ id: 'l1',
+ name: 'Ink',
+ type: 'raster' as const,
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal' as const,
+ locked: false,
+ parentId: null,
+ },
+ ],
+ layerCanvasesMap: new Map(),
+ tileGrid: grid,
+ getEffectiveOpacity: () => 1,
+ isLayerEffectivelyVisible: () => true,
+ };
+ const res = await serializeDocument(docData, '.ink');
expect(res.data).toBeInstanceOf(Blob);
const buf = await (res.data as Blob).arrayBuffer();
- expect(isSoraV2Bytes(buf)).toBe(true);
- const parsed = await parseSoraProject(buf);
- expect(parsed.format).toBe('v2');
- expect(getPixel1Bit(parsed.tileGrid!.getTile('l1', 0, 0, 0)!.data!, 10, 10)).toBe(1);
+ expect(isInkProjectBytes(buf)).toBe(true);
+ const parsed = await parseInkProject(buf);
+ expect(parsed.format).toBe('ink-v2');
+ expect(getPixel1Bit(parsed.tileGrid.getTile('l1', 0, 0, 0)!.data!, 10, 10)).toBe(1);
+
+ await expect(serializeDocument(docData, '.sora')).rejects.toThrow(/read-only/i);
});
});
@@ -663,26 +603,21 @@ describe('Pixel-Accurate GPU Tiled Export & CPU Fallback', () => {
];
const margin = computeMaxLayerStyleMargin(layers);
- // dropShadow extent = ceil(20 + 16 * 1.5) + 2 = 46; hidden layer ignored
expect(margin).toBe(46);
const plan = buildGpuExportTilePlan(4500, 3000, 2048, margin);
- // innerStep = 2048 - 92 = 1956 -> ceil(4500/1956) = 3 cols, ceil(3000/1956) = 2 rows = 6 tiles
expect(plan.tiles).toHaveLength(6);
expect(plan.fboWidth).toBeLessThanOrEqual(2048);
expect(plan.fboHeight).toBeLessThanOrEqual(2048);
- // Top-left tile has 0 left/top pad, positive right/bottom halo pad
expect(plan.tiles[0].padLeft).toBe(0);
expect(plan.tiles[0].padTop).toBe(0);
expect(plan.tiles[0].padRight).toBe(margin);
expect(plan.tiles[0].padBottom).toBe(margin);
- // Interior/second column tile has left halo pad for seamless shadow/stroke stitching
expect(plan.tiles[1].padLeft).toBe(margin);
expect(plan.tiles[1].originX).toBe(plan.tiles[1].tileX - margin);
- // Exact full-canvas coverage with zero gaps or overlaps
const totalArea = plan.tiles.reduce((acc, t) => acc + t.width * t.height, 0);
expect(totalArea).toBe(4500 * 3000);
});
@@ -760,7 +695,6 @@ describe('Pixel-Accurate GPU Tiled Export & CPU Fallback', () => {
},
];
- // 1. Sync compositeCanvas (transparent PNG) on a 3000x1500 doc -> splits horizontally into 2 tiles
const outCanvas = compositeCanvas(
{ width: 3000, height: 1500, dpi: 600 },
layers,
@@ -776,7 +710,6 @@ describe('Pixel-Accurate GPU Tiled Export & CPU Fallback', () => {
expect(drawImageCalls).toHaveLength(2);
expect(disposeSpy).toHaveBeenCalledTimes(1);
- // Verify 1:1 zoom, dpr=1, bypassStackCache, transparentBackground=true
const firstCallArgs = renderSpy.mock.calls[0];
expect(firstCallArgs[1].zoom).toBe(1);
expect(firstCallArgs[1].rotation).toBe(0);
@@ -784,12 +717,10 @@ describe('Pixel-Accurate GPU Tiled Export & CPU Fallback', () => {
expect(firstCallArgs[4]?.bypassStackCache).toBe(true);
expect(firstCallArgs[4]?.devicePixelRatio).toBe(1);
- // Verify stitched regions cover exact [0..3000] x [0..1500]
expect(drawImageCalls[0].dx).toBe(0);
expect(drawImageCalls[0].dw + drawImageCalls[1].dw).toBe(3000);
expect(drawImageCalls[1].dx).toBe(drawImageCalls[0].dw);
- // 2. Async exportImage for JPEG -> transparentBackground=false (white background)
renderSpy.mockClear();
const exported = await exportImage(
{
@@ -810,7 +741,6 @@ describe('Pixel-Accurate GPU Tiled Export & CPU Fallback', () => {
expect(renderSpy).toHaveBeenCalledTimes(1);
expect(renderSpy.mock.calls[0][4]?.transparentBackground).toBe(false);
- // 3. Reusable region renderer for tall Webtoon slices
renderSpy.mockClear();
const renderer = createDocumentRegionRenderer(
{ width: 800, height: 5000, dpi: 300 },
diff --git a/src/utils/__tests__/legacySoraMigrator.test.ts b/src/utils/__tests__/legacySoraMigrator.test.ts
new file mode 100644
index 0000000..e8d17f5
--- /dev/null
+++ b/src/utils/__tests__/legacySoraMigrator.test.ts
@@ -0,0 +1,135 @@
+import { describe, it, expect } from 'vitest';
+import { zipSync } from 'fflate';
+import {
+ extractLegacySoraPreview,
+ hasLegacySoraHeader,
+ isLegacySoraExtension,
+ isLegacySoraV2Bytes,
+ migrateLegacySoraBytes,
+ parseLegacySoraV1Json,
+} from '../legacySoraMigrator';
+import { openFile } from '../imageLoader';
+
+describe('Read-Only Legacy .sora Migrator', () => {
+ it('migrates legacy .sora v1.2 JSON (string & UTF-8 bytes with BOM) and strips prototype keys', async () => {
+ const v1Json = JSON.stringify({
+ app: 'Sora Paint',
+ version: '1.2',
+ name: 'Legacy Project',
+ dimensions: { width: 1440, height: 900, dpi: 300 },
+ colorMode: 'color',
+ layers: [
+ {
+ id: 'layer-bg',
+ name: 'Background',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ],
+ canvases: {},
+ masks: {},
+ });
+
+ const parsedStr = await migrateLegacySoraBytes(v1Json);
+ expect(parsedStr.migratedFrom).toBe('sora-v1');
+ expect(parsedStr.format).toBe('sora-v1');
+ expect(parsedStr.version).toBe('1.2');
+ expect(parsedStr.name).toBe('Legacy Project');
+ expect(parsedStr.layers).toHaveLength(1);
+
+ const utf8WithBom = new Uint8Array([0xef, 0xbb, 0xbf, ...new TextEncoder().encode(v1Json)]);
+ expect(isLegacySoraV2Bytes(utf8WithBom)).toBe(false);
+ const parsedBytes = await migrateLegacySoraBytes(utf8WithBom.buffer);
+ expect(parsedBytes.migratedFrom).toBe('sora-v1');
+ expect(parsedBytes.name).toBe('Legacy Project');
+
+ const polluted = parseLegacySoraV1Json(
+ '{"layers":[{"id":"l1","name":"L1","type":"raster","visible":true,"opacity":1,"blendMode":"normal","locked":false,"parentId":null,"__proto__":{"polluted":true}}]}'
+ );
+ expect((polluted.layers[0] as unknown as Record<string, unknown>).polluted).toBeUndefined();
+ });
+
+ it('migrates legacy .sora v2 ZIP archives with or without 8-byte SORA\\x00\\x02 wrapper prefix and extracts preview.png', async () => {
+ const fakePng = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4]);
+ const manifest = {
+ format: 'sora-v2',
+ app: 'Ink Studio',
+ version: '2.0',
+ tileSize: 256,
+ name: 'Legacy V2 Doc',
+ dimensions: { width: 512, height: 512, dpi: 300 },
+ colorMode: 'color',
+ layers: [],
+ layerFormats: {},
+ layerTileKeys: {},
+ masksMeta: {},
+ preview: { path: 'preview.png', width: 256, height: 256 },
+ savedAt: Date.now(),
+ };
+
+ const zipBytes = zipSync({
+ 'manifest.json': new TextEncoder().encode(JSON.stringify(manifest)),
+ 'preview.png': fakePng,
+ });
+
+ expect(Array.from(extractLegacySoraPreview(zipBytes)!)).toEqual(Array.from(fakePng));
+
+ const wrapped = new Uint8Array(8 + zipBytes.byteLength);
+ wrapped.set([0x53, 0x4f, 0x52, 0x41, 0x00, 0x02, 0x00, 0x00], 0);
+ wrapped.set(zipBytes, 8);
+ expect(hasLegacySoraHeader(wrapped)).toBe(true);
+ expect(isLegacySoraV2Bytes(wrapped)).toBe(true);
+ expect(Array.from(extractLegacySoraPreview(wrapped)!)).toEqual(Array.from(fakePng));
+
+ const migrated = await migrateLegacySoraBytes(wrapped);
+ expect(migrated.migratedFrom).toBe('sora-v2');
+ if (migrated.migratedFrom !== 'sora-v2') throw new Error('Expected sora-v2');
+ expect(migrated.format).toBe('ink-v2');
+ expect(migrated.name).toBe('Legacy V2 Doc');
+ expect(migrated.previewDataUrl).toMatch(/^data:image\/png;base64,/);
+ });
+
+ it('routes .sora files in openFile through the read-only migrator', async () => {
+ const manifest = {
+ format: 'sora-v2',
+ app: 'Ink Studio',
+ version: '2.0',
+ tileSize: 256,
+ name: 'Old Chapter',
+ dimensions: { width: 640, height: 480, dpi: 300 },
+ colorMode: 'color',
+ layers: [],
+ layerFormats: {},
+ layerTileKeys: {},
+ masksMeta: {},
+ preview: null,
+ savedAt: Date.now(),
+ };
+ const zipBytes = zipSync({
+ 'manifest.json': new TextEncoder().encode(JSON.stringify(manifest)),
+ });
+ const file = new File([zipBytes as BlobPart], 'old-chapter.sora', {
+ type: 'application/octet-stream',
+ });
+
+ const loaded = await openFile(file);
+ expect(loaded.name).toBe('Old Chapter');
+ expect(loaded.dimensions).toEqual({ width: 640, height: 480, dpi: 300 });
+ expect(isLegacySoraExtension(file.name)).toBe(true);
+ expect(isLegacySoraExtension('new-chapter.ink')).toBe(false);
+ });
+
+ it('rejects path traversal and corrupted payloads inside legacy .sora archives', async () => {
+ const evilZip = zipSync({
+ 'manifest.json': new TextEncoder().encode(
+ JSON.stringify({ dimensions: { width: 256, height: 256 }, layers: [] })
+ ),
+ '../escape.bin': new Uint8Array([1, 2, 3]),
+ });
+ await expect(migrateLegacySoraBytes(evilZip)).rejects.toThrow(/Unsafe archive path/);
+ });
+});
diff --git a/src/utils/__tests__/multiplayerFixes.test.ts b/src/utils/__tests__/multiplayerFixes.test.ts
index d0f9c46..4c5f624 100644
--- a/src/utils/__tests__/multiplayerFixes.test.ts
+++ b/src/utils/__tests__/multiplayerFixes.test.ts
@@ -1,5 +1,42 @@
-import { describe, it, expect } from 'vitest';
-import { parseInviteUrl } from '../../services/multiplayerService';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import {
+ multiplayerService,
+ parseInviteUrl,
+ BINARY_MAGIC_0,
+ BINARY_MAGIC_1,
+ CODE_TILE_DELTA,
+ CODE_STROKE_START,
+ CODE_STROKE_CHUNK,
+ CODE_BRUSH_ASSET_DATA,
+ CODE_BRUSH_ASSET_REQUEST,
+} from '../../services/multiplayerService';
+import { lz4CompressBlock, lz4DecompressBlock } from '../lz4';
+import {
+ BYTES_32BIT,
+ SparseTileGrid,
+ TILE_CODEC_EMPTY,
+ TILE_CODEC_LZ4,
+ createTileBuffer,
+ deserializeTileBufferStrict,
+ serializeTileBuffer,
+ setPixel1Bit,
+} from '../tileEngine';
+import {
+ computeBrushAssetHash,
+ hydrateBrushSettingsFromHashes,
+ prepareBrushSettingsForWire,
+ registerRemoteBrushAsset,
+ resetBrushAssetCache,
+} from '../brushAssetSync';
+import { StrokePipeline } from '../../engine/StrokePipeline';
+import { RemoteStrokeSession } from '../../engine/RemoteStrokeRenderer';
+import type { BrushSettings, Point } from '../../types/editor';
+import type { CubicBezierSegment } from '../../engine/SplineGenerator';
+
+// Minimal valid 1x1 PNG encoded as base64
+const TINY_PNG_B64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
+const TINY_PNG_DATA_URL = `data:image/png;base64,${TINY_PNG_B64}`;
describe('Multiplayer Invite URL Parsing', () => {
it('parses worldwide Cloudflare HTTPS invite links with secure flag and port 443', () => {
@@ -28,9 +65,9 @@ describe('Multiplayer Invite URL Parsing', () => {
});
});
- it('parses forsora:// deep links and preserves HTTPS protocol flag', () => {
+ it('parses inkstudio:// deep links and rejects legacy forsora:// scheme', () => {
const parsed = parseInviteUrl(
- 'forsora://join?host=cool-cat.trycloudflare.com&port=443&room=Collab&token=xyz&protocol=https'
+ 'inkstudio://join?host=cool-cat.trycloudflare.com&port=443&room=Collab&token=xyz&protocol=https'
);
expect(parsed).toMatchObject({
roomName: 'Collab',
@@ -39,6 +76,12 @@ describe('Multiplayer Invite URL Parsing', () => {
token: 'xyz',
isSecure: true,
});
+
+ expect(
+ parseInviteUrl(
+ 'forsora://join?host=cool-cat.trycloudflare.com&port=443&room=Collab&token=xyz&protocol=https'
+ )
+ ).toBeNull();
});
it('rejects invalid or non-room URLs', () => {
@@ -48,3 +91,358 @@ describe('Multiplayer Invite URL Parsing', () => {
expect(parseInviteUrl('javascript:alert(1)')).toBeNull();
});
});
+
+function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
+ if (a.byteLength !== b.byteLength) return false;
+ for (let i = 0; i < a.byteLength; i++) {
+ if (a[i] !== b[i]) return false;
+ }
+ return true;
+}
+
+describe('LZ4 Block Codec & BINARY_TILE Serialization', () => {
+ it('compresses and decompresses 256KB RGBA solid-fill tiles with high ratio and exact equality', () => {
+ const raw = new Uint8Array(BYTES_32BIT);
+ for (let i = 0; i < raw.length; i += 4) {
+ raw[i] = 0x1a;
+ raw[i + 1] = 0x73;
+ raw[i + 2] = 0xe8;
+ raw[i + 3] = 0xff;
+ }
+
+ const compressed = lz4CompressBlock(raw);
+ expect(compressed.byteLength).toBeLessThan(2048);
+
+ const restored = lz4DecompressBlock(compressed, BYTES_32BIT);
+ expect(restored).not.toBeNull();
+ expect(restored!.byteLength).toBe(BYTES_32BIT);
+ expect(bytesEqual(restored!, raw)).toBe(true);
+ });
+
+ it('handles tiny, empty, patterned, and incompressible random buffers losslessly', () => {
+ expect(lz4DecompressBlock(lz4CompressBlock(new Uint8Array(0)), 0)).toEqual(new Uint8Array(0));
+
+ const tiny = new Uint8Array([1, 2, 3, 4, 5, 6, 7]);
+ expect(lz4DecompressBlock(lz4CompressBlock(tiny), tiny.length)).toEqual(tiny);
+
+ // Pseudo-random incompressible 8KB buffer
+ const noisy = new Uint8Array(8192);
+ let seed = 0x12345678;
+ for (let i = 0; i < noisy.length; i++) {
+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
+ noisy[i] = (seed >>> 24) & 0xff;
+ }
+ expect(lz4DecompressBlock(lz4CompressBlock(noisy), noisy.length)).toEqual(noisy);
+ });
+
+ it('rejects malformed or malicious LZ4 payloads (bounds & offset checks)', () => {
+ // Zero offset attack
+ const zeroOffset = new Uint8Array([0x10, 0xaa, 0x00, 0x00]);
+ expect(lz4DecompressBlock(zeroOffset, 10)).toBeNull();
+
+ // Offset larger than already decoded output
+ const badOffset = new Uint8Array([0x10, 0xaa, 0x05, 0x00]);
+ expect(lz4DecompressBlock(badOffset, 10)).toBeNull();
+
+ // Output overflow / LZ4 bomb beyond declared size
+ const valid = lz4CompressBlock(new Uint8Array(1024));
+ expect(lz4DecompressBlock(valid, 16)).toBeNull();
+ expect(lz4DecompressBlock(valid, 10 * 1024 * 1024, BYTES_32BIT)).toBeNull();
+ });
+
+ it('serializes populated tiles with LZ4 and deleted tiles as 14-byte tombstones', () => {
+ const tile = createTileBuffer('layer-1', 3, 4, 'monochrome-1bit');
+ setPixel1Bit(tile.data!, 12, 18, true);
+ const packet = serializeTileBuffer(tile);
+ expect(packet[13]).toBe(TILE_CODEC_LZ4);
+ expect(packet.byteLength).toBeLessThan(100);
+
+ const decoded = deserializeTileBufferStrict('layer-1', packet);
+ expect(decoded).not.toBeNull();
+ expect(decoded!.tileX).toBe(3);
+ expect(decoded!.tileY).toBe(4);
+ expect(decoded!.data).toEqual(tile.data);
+
+ // Tombstone for deleted/cleared tile
+ const tombstone = serializeTileBuffer({
+ ...tile,
+ data: null,
+ });
+ expect(tombstone.byteLength).toBe(14);
+ expect(tombstone[13]).toBe(TILE_CODEC_EMPTY);
+ const decodedTomb = deserializeTileBufferStrict('layer-1', tombstone);
+ expect(decodedTomb).not.toBeNull();
+ expect(decodedTomb!.data).toBeNull();
+
+ // Corrupt tile packet is dropped strictly
+ const corrupt = packet.slice();
+ corrupt[13] = 0xfe;
+ expect(deserializeTileBufferStrict('layer-1', corrupt)).toBeNull();
+ });
+});
+
+describe('Brush Asset Synchronization via Content Hash', () => {
+ beforeEach(() => {
+ resetBrushAssetCache();
+ });
+
+ it('strips inline base64 data URLs from BrushSettings and emits deterministic hash refs', () => {
+ const bs: BrushSettings = {
+ size: 16,
+ minSizeFactor: 0.1,
+ color: '#112233',
+ opacity: 0.85,
+ flow: 0.9,
+ spacing: 0.08,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 10,
+ hardness: 0.8,
+ customTipDataUrl: TINY_PNG_DATA_URL,
+ paperTexture: TINY_PNG_DATA_URL,
+ };
+
+ const { wireSettings, assetRefs, assets } = prepareBrushSettingsForWire(bs);
+ expect(wireSettings.customTipDataUrl).toBeUndefined();
+ expect(wireSettings.paperTexture).toBeUndefined();
+ expect(wireSettings.customTipImage).toBeUndefined();
+ expect(assetRefs?.tipHash).toMatch(/^[0-9a-f]{32}$/);
+ expect(assetRefs?.paperTextureHash).toBe(assetRefs?.tipHash);
+ // Identical tip and paper texture deduplicate to a single binary asset
+ expect(assets.length).toBe(1);
+ expect(computeBrushAssetHash(assets[0].bytes)).toBe(assetRefs!.tipHash);
+ });
+
+ it('enforces hash integrity and MIME whitelist on remote brush assets', () => {
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3, 4]);
+ const validHash = computeBrushAssetHash(bytes);
+
+ // Reject tampered hash
+ expect(registerRemoteBrushAsset('0'.repeat(32), 'image/png', bytes)).toBe(false);
+ // Reject SVG XSS vector
+ expect(registerRemoteBrushAsset(validHash, 'image/svg+xml', bytes)).toBe(false);
+ // Accept valid hash + allowed MIME
+ expect(registerRemoteBrushAsset(validHash, 'image/png', bytes)).toBe(true);
+
+ // Missing hash is reported for on-demand BRUSH_ASSET_REQUEST
+ const { missingHashes } = hydrateBrushSettingsFromHashes(
+ {
+ size: 10,
+ minSizeFactor: 0.2,
+ color: '#000',
+ opacity: 1,
+ flow: 1,
+ spacing: 0.1,
+ usePressure: true,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 1,
+ },
+ { tipHash: 'f'.repeat(32) }
+ );
+ expect(missingHashes).toEqual(['f'.repeat(32)]);
+ });
+});
+
+describe('Multiplayer Binary Protocol & Deterministic Remote StrokePipeline', () => {
+ beforeEach(() => {
+ resetBrushAssetCache();
+ });
+
+ it('decodes STROKE_START (with asset hashes, zero base64), STROKE_CHUNK (tilt/corner), BRUSH_ASSET_DATA, and BINARY_TILE', () => {
+ const sentPackets: Uint8Array[] = [];
+ const toArrayBuffer = (u8: Uint8Array): ArrayBuffer =>
+ u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) as ArrayBuffer;
+ const sendSpy = vi
+ .spyOn(multiplayerService, 'sendBinary')
+ .mockImplementation((buf) => {
+ sentPackets.push(buf instanceof Uint8Array ? buf : new Uint8Array(buf));
+ });
+ const connSpy = vi.spyOn(multiplayerService, 'isConnected').mockReturnValue(true);
+ (multiplayerService as unknown as { currentPeer: unknown }).currentPeer = {
+ id: 'peer-a',
+ name: 'Alice',
+ color: '#ff0000',
+ };
+ multiplayerService.clearSentAssetHashes();
+
+ const bs: BrushSettings = {
+ size: 12,
+ minSizeFactor: 0.1,
+ color: '#224466',
+ opacity: 0.8,
+ flow: 0.9,
+ spacing: 0.08,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 10,
+ hardness: 0.9,
+ customTipDataUrl: TINY_PNG_DATA_URL,
+ };
+
+ multiplayerService.sendStrokeStart('s-1', 'layer-1', bs, 'brush', {
+ x: 10,
+ y: 20,
+ pressure: 0.7,
+ width: 9,
+ });
+
+ // First packet must be binary BRUSH_ASSET_DATA, second is stripped STROKE_START
+ expect(sentPackets.length).toBe(2);
+ expect(sentPackets[0][0]).toBe(BINARY_MAGIC_0);
+ expect(sentPackets[0][1]).toBe(BINARY_MAGIC_1);
+ expect(sentPackets[0][2]).toBe(CODE_BRUSH_ASSET_DATA);
+ expect(sentPackets[1][2]).toBe(CODE_STROKE_START);
+
+ const decodedAsset = multiplayerService.decodeBinaryPacket(toArrayBuffer(sentPackets[0]));
+ expect(decodedAsset?.type).toBe('BRUSH_ASSET_DATA');
+ const decodedStart = multiplayerService.decodeBinaryPacket(toArrayBuffer(sentPackets[1]));
+ expect(decodedStart?.type).toBe('STROKE_START');
+ if (decodedStart?.type === 'STROKE_START') {
+ expect(decodedStart.brushSettings.customTipDataUrl).toBeUndefined();
+ expect(decodedStart.brushAssetRefs?.tipHash).toMatch(/^[0-9a-f]{32}$/);
+ }
+
+ // Second stroke with same brush does NOT re-send BRUSH_ASSET_DATA
+ sentPackets.length = 0;
+ multiplayerService.sendStrokeStart('s-2', 'layer-1', bs, 'brush', {
+ x: 15,
+ y: 25,
+ pressure: 0.6,
+ width: 8,
+ });
+ expect(sentPackets.length).toBe(1);
+ expect(sentPackets[0][2]).toBe(CODE_STROKE_START);
+
+ // STROKE_CHUNK preserves tilt, twist, and corner flags
+ sentPackets.length = 0;
+ multiplayerService.sendStrokeChunk('s-2', [
+ { x: 20, y: 30, pressure: 0.8, width: 10, tiltX: -25, tiltY: 40, twist: 90, isCorner: true },
+ ]);
+ expect(sentPackets[0][2]).toBe(CODE_STROKE_CHUNK);
+ const decodedChunk = multiplayerService.decodeBinaryPacket(toArrayBuffer(sentPackets[0]));
+ expect(decodedChunk?.type).toBe('STROKE_CHUNK');
+ if (decodedChunk?.type === 'STROKE_CHUNK') {
+ expect(decodedChunk.points[0].tiltX).toBe(-25);
+ expect(decodedChunk.points[0].tiltY).toBe(40);
+ expect(decodedChunk.points[0].isCorner).toBe(true);
+ }
+
+ // BRUSH_ASSET_REQUEST round-trip
+ sentPackets.length = 0;
+ const reqHash = 'a'.repeat(32);
+ multiplayerService.sendBrushAssetRequest(reqHash, 'peer-b');
+ expect(sentPackets[0][2]).toBe(CODE_BRUSH_ASSET_REQUEST);
+ const decodedReq = multiplayerService.decodeBinaryPacket(toArrayBuffer(sentPackets[0]));
+ expect(decodedReq).toMatchObject({
+ type: 'BRUSH_ASSET_REQUEST',
+ hash: reqHash,
+ targetPeerId: 'peer-b',
+ });
+
+ // sendTileDeltas broadcasts LZ4 BINARY_TILEs and deduplicates identical delta batches
+ const grid = new SparseTileGrid();
+ const beforeSnap = grid.snapshotTilesInRect('layer-1', { x: 0, y: 0, width: 32, height: 32 });
+ const img = { data: new Uint8ClampedArray(32 * 32 * 4).fill(200), width: 32, height: 32 };
+ grid.writeImageData('layer-1', img, 0, 0, 'color-32bit');
+ const deltas = grid.computeDeltasFromSnapshot(beforeSnap, 'layer-1');
+
+ sentPackets.length = 0;
+ multiplayerService.sendTileDeltas(deltas, grid);
+ expect(sentPackets.length).toBe(1);
+ expect(sentPackets[0][2]).toBe(CODE_TILE_DELTA);
+
+ // Calling again with same batch is an idempotent no-op
+ multiplayerService.sendTileDeltas(deltas, grid);
+ expect(sentPackets.length).toBe(1);
+
+ // Decoded BINARY_TILE restores exact tile pixels
+ const decodedTile = multiplayerService.decodeBinaryPacket(toArrayBuffer(sentPackets[0]));
+ expect(decodedTile?.type).toBe('BINARY_TILE');
+ if (decodedTile?.type === 'BINARY_TILE') {
+ expect(decodedTile.layerId).toBe('layer-1');
+ expect(decodedTile.tileX).toBe(0);
+ expect(decodedTile.tileY).toBe(0);
+ expect(bytesEqual(decodedTile.data!, grid.getTile('layer-1', 0, 0, 0)!.data!)).toBe(true);
+ }
+
+ sendSpy.mockRestore();
+ connSpy.mockRestore();
+ (multiplayerService as unknown as { currentPeer: unknown }).currentPeer = null;
+ });
+
+ it('produces identical cubic Bezier spline geometry via StrokePipeline.pushStabilizedKnot', () => {
+ const pts: Point[] = [
+ { x: 10, y: 10, pressure: 0.5, width: 5, timestamp: 0 },
+ { x: 30, y: 14, pressure: 0.7, width: 7, timestamp: 16 },
+ { x: 60, y: 35, pressure: 0.9, width: 9, timestamp: 32 },
+ { x: 95, y: 30, pressure: 0.6, width: 6, timestamp: 48, isCorner: true },
+ { x: 110, y: 80, pressure: 0.4, width: 4, timestamp: 64 },
+ ];
+
+ const pipeA = new StrokePipeline();
+ const pipeB = new StrokePipeline();
+ const segsA: CubicBezierSegment[] = [];
+ const segsB: CubicBezierSegment[] = [];
+
+ pipeA.beginStroke({ stabilizerLevel: 0, sharpCorners: true, brushSize: 10, color: '#000' });
+ pipeB.beginStroke({ stabilizerLevel: 0, sharpCorners: true, brushSize: 10, color: '#000' });
+ pipeA.seedKnot(pts[0].x, pts[0].y, pts[0].pressure, pts[0].width, 0, 0, 0, 0, 16);
+ pipeB.seedKnot(pts[0].x, pts[0].y, pts[0].pressure, pts[0].width, 0, 0, 0, 0, 16);
+
+ for (let i = 1; i < pts.length; i++) {
+ const p = pts[i];
+ pipeA.pushStabilizedKnot(p.x, p.y, p.pressure, p.width, 0, 0, 0, p.timestamp!, Boolean(p.isCorner), 16, (s) => {
+ segsA.push({ p0: { ...s.p0 }, c1: { ...s.c1 }, c2: { ...s.c2 }, p3: { ...s.p3 } });
+ });
+ pipeB.pushStabilizedKnot(p.x, p.y, p.pressure, p.width, 0, 0, 0, p.timestamp!, Boolean(p.isCorner), 16, (s) => {
+ segsB.push({ p0: { ...s.p0 }, c1: { ...s.c1 }, c2: { ...s.c2 }, p3: { ...s.p3 } });
+ });
+ }
+
+ expect(segsA.length).toBeGreaterThanOrEqual(3);
+ expect(segsA).toEqual(segsB);
+ });
+
+ it('RemoteStrokeSession requests missing brush asset hashes and keeps preview decoupled from SparseTileGrid', () => {
+ const requested: string[] = [];
+ const missingHash = 'b'.repeat(32);
+
+ const session = new RemoteStrokeSession({
+ strokeId: 'remote-1',
+ peerId: 'peer-2',
+ layerId: 'layer-1',
+ tool: 'brush',
+ brushSettings: {
+ size: 10,
+ minSizeFactor: 0.2,
+ color: '#000000',
+ opacity: 1,
+ flow: 1,
+ spacing: 0.08,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ hardness: 1,
+ useGpu: true,
+ },
+ brushAssetRefs: { tipHash: missingHash },
+ startPoint: { x: 10, y: 10, pressure: 0.8, width: 8 },
+ colorMode: 'color',
+ onRequestAsset: (h) => requested.push(h),
+ });
+
+ expect(requested).toEqual([missingHash]);
+ session.start(undefined);
+ session.appendChunk(
+ [
+ { x: 20, y: 20, pressure: 0.8, width: 8 },
+ { x: 35, y: 25, pressure: 0.7, width: 7 },
+ ],
+ undefined
+ );
+ expect(session.getPoints().length).toBe(3);
+ session.dispose(undefined);
+ expect(session.getPoints().length).toBe(0);
+ });
+});
diff --git a/src/utils/__tests__/multiplayerFullSync.test.ts b/src/utils/__tests__/multiplayerFullSync.test.ts
new file mode 100644
index 0000000..d74db37
--- /dev/null
+++ b/src/utils/__tests__/multiplayerFullSync.test.ts
@@ -0,0 +1,413 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import {
+ multiplayerService,
+ sanitizeIncomingJsonMessage,
+ BINARY_MAGIC_0,
+ BINARY_MAGIC_1,
+ CODE_LAYER_MASK_DATA,
+ CODE_TILE_DELTA,
+} from '../../services/multiplayerService';
+import {
+ applyRemoteLayerPatch,
+ diffWireLayerTrees,
+ mergeRemoteWireLayerIntoLocal,
+ sanitizeAnimationTimeline,
+ sanitizeCanvasResize,
+ sanitizePerspectiveRuler,
+ sanitizeStraightRuler,
+ sanitizeWireLayerTree,
+ serializeLayerForWire,
+} from '../collabSyncUtils';
+import { SparseTileGrid } from '../tileEngine';
+import type { LayerItem } from '../../types/editor';
+import type { WireLayerItem } from '../../types/multiplayer';
+
+function makeLayer(overrides: Partial<LayerItem> = {}): LayerItem {
+ return {
+ id: overrides.id ?? 'layer-1',
+ name: overrides.name ?? 'Layer 1',
+ type: overrides.type ?? 'raster',
+ visible: overrides.visible ?? true,
+ opacity: overrides.opacity ?? 1,
+ blendMode: overrides.blendMode ?? 'normal',
+ locked: overrides.locked ?? false,
+ parentId: overrides.parentId ?? null,
+ ...overrides,
+ };
+}
+
+describe('Full Layer Tree Diff & Patch Engine', () => {
+ it('ignores transient UI fields (thumbnailUrl, maskThumbnailUrl, collapsed, maskVersion)', () => {
+ const a = makeLayer({ id: 'l1', thumbnailUrl: 'data:a', collapsed: false });
+ const b = makeLayer({ id: 'l1', thumbnailUrl: 'data:b', collapsed: true, maskVersion: 9 });
+ const diff = diffWireLayerTrees([serializeLayerForWire(a)], [serializeLayerForWire(b)]);
+ expect(diff.kind).toBe('none');
+ });
+
+ it('emits minimal single-update patches for blendMode, clipping, alphaLock, styles, adjustment, text, balloon, frames', () => {
+ const base = serializeLayerForWire(makeLayer({ id: 'l1' }));
+ const modified = serializeLayerForWire(
+ makeLayer({
+ id: 'l1',
+ blendMode: 'multiply',
+ clipped: true,
+ alphaLocked: true,
+ styles: {
+ stroke: { enabled: true, size: 4, color: '#000000', position: 'outside', opacity: 1 },
+ },
+ toneEnabled: true,
+ toneFrequency: 65,
+ })
+ );
+
+ const diff = diffWireLayerTrees([base], [modified]);
+ expect(diff.kind).toBe('single-update');
+ if (diff.kind === 'single-update') {
+ expect(diff.layerId).toBe('l1');
+ expect(diff.patch).toMatchObject({
+ blendMode: 'multiply',
+ clipped: true,
+ alphaLocked: true,
+ toneEnabled: true,
+ toneFrequency: 65,
+ });
+ expect(diff.patch.styles?.stroke?.size).toBe(4);
+ expect(diff.clearedFields).toEqual([]);
+ }
+ });
+
+ it('tracks clearedFields explicitly when optional properties or masks are removed', () => {
+ const withMaskAndStyles: WireLayerItem = {
+ ...serializeLayerForWire(
+ makeLayer({
+ id: 'l1',
+ styles: { outerGlow: { enabled: true, color: '#fff', opacity: 0.8, blur: 10, spread: 0 } },
+ maskEnabled: true,
+ maskLinked: true,
+ })
+ ),
+ hasMask: true,
+ };
+ const cleared = serializeLayerForWire(makeLayer({ id: 'l1' }));
+
+ const diff = diffWireLayerTrees([withMaskAndStyles], [cleared]);
+ expect(diff.kind).toBe('single-update');
+ if (diff.kind === 'single-update') {
+ expect(diff.maskRemoved).toBe(true);
+ expect(diff.clearedFields).toContain('styles');
+ expect(diff.clearedFields).toContain('hasMask');
+ expect(diff.clearedFields).toContain('maskEnabled');
+ expect(diff.clearedFields).toContain('maskLinked');
+
+ const applied = applyRemoteLayerPatch(
+ makeLayer({
+ id: 'l1',
+ styles: withMaskAndStyles.styles,
+ maskEnabled: true,
+ maskLinked: true,
+ }),
+ diff.patch,
+ diff.clearedFields
+ );
+ expect(applied.styles).toBeUndefined();
+ expect(applied.maskEnabled).toBeUndefined();
+ expect(applied.maskLinked).toBeUndefined();
+ expect(applied.maskCanvas).toBeUndefined();
+ }
+ });
+
+ it('emits tree-sync for layer reorder, grouping, and multi-delete', () => {
+ const l1 = serializeLayerForWire(makeLayer({ id: 'l1' }));
+ const l2 = serializeLayerForWire(makeLayer({ id: 'l2' }));
+ const bg = serializeLayerForWire(makeLayer({ id: 'layer-bg' }));
+
+ // Reorder
+ const reorderDiff = diffWireLayerTrees([l1, l2, bg], [l2, l1, bg]);
+ expect(reorderDiff.kind).toBe('tree-sync');
+
+ // Grouping into folder
+ const folder = serializeLayerForWire(makeLayer({ id: 'folder-1', type: 'folder', blendMode: 'pass-through' }));
+ const groupDiff = diffWireLayerTrees(
+ [l1, l2, bg],
+ [folder, { ...l1, parentId: 'folder-1' }, { ...l2, parentId: 'folder-1' }, bg]
+ );
+ expect(groupDiff.kind).toBe('tree-sync');
+ if (groupDiff.kind === 'tree-sync') {
+ expect(groupDiff.addedLayerIds).toEqual(['folder-1']);
+ expect(groupDiff.removedLayerIds).toEqual([]);
+ }
+
+ // Multi-delete
+ const delDiff = diffWireLayerTrees([l1, l2, bg], [bg]);
+ expect(delDiff.kind).toBe('tree-sync');
+ if (delDiff.kind === 'tree-sync') {
+ expect(delDiff.removedLayerIds).toEqual(['l1', 'l2']);
+ }
+ });
+
+ it('preserves local collapsed UI state when merging remote wire layers', () => {
+ const localFolder = makeLayer({ id: 'f1', type: 'folder', collapsed: true, name: 'Old' });
+ const remoteWire: WireLayerItem = {
+ id: 'f1',
+ name: 'Renamed Folder',
+ type: 'folder',
+ visible: true,
+ opacity: 0.7,
+ blendMode: 'pass-through',
+ locked: false,
+ parentId: null,
+ };
+ const merged = mergeRemoteWireLayerIntoLocal(localFolder, remoteWire, { width: 512, height: 512 });
+ expect(merged.name).toBe('Renamed Folder');
+ expect(merged.opacity).toBe(0.7);
+ expect(merged.collapsed).toBe(true);
+ });
+});
+
+describe('Security Sanitization & Protocol Validation', () => {
+ it('breaks parentId cycles, rejects prototype pollution keys, and clamps numeric ranges', () => {
+ const raw = [
+ {
+ id: 'f1',
+ name: 'F1',
+ type: 'folder',
+ visible: true,
+ opacity: 99,
+ blendMode: 'invalid-mode',
+ locked: false,
+ parentId: 'f2',
+ toneFrequency: 999,
+ styles: JSON.parse('{"__proto__":{"polluted":true},"stroke":{"enabled":true,"size":3,"color":"#000","position":"outside","opacity":1}}'),
+ },
+ {
+ id: 'f2',
+ name: 'F2',
+ type: 'folder',
+ visible: true,
+ opacity: -5,
+ blendMode: 'multiply',
+ locked: false,
+ parentId: 'f1',
+ },
+ ];
+
+ const sanitized = sanitizeWireLayerTree(raw);
+ expect(sanitized).not.toBeNull();
+ expect(sanitized!.length).toBe(2);
+ expect(sanitized![0].opacity).toBe(1);
+ expect(sanitized![1].opacity).toBe(0);
+ expect(sanitized![0].blendMode).toBe('pass-through');
+ expect(sanitized![0].toneFrequency).toBe(85);
+ expect(sanitized![0].parentId === null || sanitized![1].parentId === null).toBe(true);
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ });
+
+ it('sanitizes perspective ruler, straight ruler, animation timeline, and canvas resize messages', () => {
+ expect(sanitizePerspectiveRuler(null)).toBeNull();
+ expect(sanitizePerspectiveRuler({ type: '99-point', vps: [] })).toBeUndefined();
+ const validPersp = sanitizePerspectiveRuler({
+ id: 'p1',
+ type: '2-point',
+ enabled: true,
+ locked: false,
+ snapEnabled: true,
+ vps: [
+ { id: 'vp1', x: 100, y: 200, label: 'VP1', color: '#f00' },
+ { id: 'vp2', x: 900, y: 200, label: 'VP2', color: '#00f' },
+ ],
+ horizonAngle: 0,
+ guideRayCount: 12,
+ grid: { enabled: true, density: 16, plane: 'ground', opacity: 0.4 },
+ });
+ expect(validPersp?.vps.length).toBe(2);
+
+ expect(sanitizeStraightRuler({ x: NaN, y: 0 })).toBeUndefined();
+ expect(sanitizeStraightRuler({ enabled: true, x: 50, y: 60, angle: 45, locked: false, snapEnabled: true })).toMatchObject({
+ x: 50,
+ y: 60,
+ angle: 45,
+ });
+
+ const anim = sanitizeAnimationTimeline({
+ fps: 24,
+ totalFrames: 48,
+ currentFrame: 999,
+ cels: { 0: 'layer-1', 12: 'layer-cel-2', bad: 'x' },
+ onionSkin: { enabled: true, prevFrames: 2, nextFrames: 1, prevTint: '#f00', nextTint: '#00f', opacity: 0.5 },
+ isPlaying: true,
+ loop: true,
+ });
+ expect(anim).not.toBeNull();
+ expect(anim!.currentFrame).toBe(47);
+ expect(anim!.isPlaying).toBe(false);
+ expect(anim!.cels).toEqual({ 0: 'layer-1', 12: 'layer-cel-2' });
+
+ const resize = sanitizeCanvasResize({
+ dimensions: { width: 2000, height: 3000, dpi: 600 },
+ options: { width: 2000, height: 3000, scaleContent: true, anchor: 'top-left', backgroundColor: '#fff' },
+ });
+ expect(resize?.dimensions).toEqual({ width: 2000, height: 3000, dpi: 600 });
+ expect(sanitizeCanvasResize({ dimensions: { width: -10, height: 100 } })).toBeNull();
+ });
+
+ it('sanitizes incoming JSON protocol messages and drops malformed payloads', () => {
+ const validUpdate = sanitizeIncomingJsonMessage({
+ type: 'LAYER_UPDATE',
+ layerId: 'l1',
+ patch: { blendMode: 'overlay', clipped: true, thumbnailUrl: 'javascript:alert(1)' },
+ clearedFields: ['styles', '__proto__'],
+ lamport: 7,
+ });
+ expect(validUpdate?.type).toBe('LAYER_UPDATE');
+ if (validUpdate?.type === 'LAYER_UPDATE') {
+ expect(validUpdate.patch).toEqual({ blendMode: 'overlay', clipped: true });
+ expect(validUpdate.clearedFields).toEqual(['styles']);
+ }
+
+ // Empty / invalid patch is dropped
+ expect(
+ sanitizeIncomingJsonMessage({ type: 'LAYER_UPDATE', layerId: 'l1', patch: {} })
+ ).toBeNull();
+
+ // DOC_SYNC_RESPONSE preserves rulers & animation timeline
+ const docSync = sanitizeIncomingJsonMessage({
+ type: 'DOC_SYNC_RESPONSE',
+ targetPeerId: 'peer-2',
+ dimensions: { width: 1440, height: 900, dpi: 300 },
+ colorMode: 'color',
+ layers: [makeLayer({ id: 'l1', blendMode: 'multiply', alphaLocked: true })],
+ straightRuler: { enabled: true, x: 720, y: 450, angle: 30, locked: false, snapEnabled: true },
+ animationTimeline: {
+ fps: 12,
+ totalFrames: 24,
+ currentFrame: 3,
+ cels: { 0: 'l1' },
+ onionSkin: { enabled: false, prevFrames: 1, nextFrames: 1, prevTint: '#f00', nextTint: '#00f', opacity: 0.3 },
+ },
+ });
+ expect(docSync?.type).toBe('DOC_SYNC_RESPONSE');
+ if (docSync?.type === 'DOC_SYNC_RESPONSE') {
+ expect(docSync.straightRuler?.angle).toBe(30);
+ expect(docSync.animationTimeline?.currentFrame).toBe(3);
+ expect(docSync.layers[0].blendMode).toBe('multiply');
+ expect(docSync.layers[0].alphaLocked).toBe(true);
+ }
+ });
+});
+
+describe('Binary Mask Packet Codec & Tile Version Deduplication', () => {
+ const toArrayBuffer = (u8: Uint8Array): ArrayBuffer =>
+ u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) as ArrayBuffer;
+
+ beforeEach(() => {
+ multiplayerService.clearSyncDedupeCaches();
+ });
+
+ it('encodes and decodes 1-byte solid-fill BINARY_MASK packets losslessly', () => {
+ const sent: Uint8Array[] = [];
+ const sendSpy = vi.spyOn(multiplayerService, 'sendBinary').mockImplementation((buf) => {
+ sent.push(buf instanceof Uint8Array ? buf : new Uint8Array(buf));
+ });
+ const connSpy = vi.spyOn(multiplayerService, 'isConnected').mockReturnValue(true);
+
+ multiplayerService.sendLayerMaskSolid('layer-mask-1', 4096, 4096, 255, true);
+ expect(sent.length).toBe(1);
+ expect(sent[0][0]).toBe(BINARY_MAGIC_0);
+ expect(sent[0][1]).toBe(BINARY_MAGIC_1);
+ expect(sent[0][2]).toBe(CODE_LAYER_MASK_DATA);
+ // Whole 4096x4096 solid white mask fits in < 64 bytes
+ expect(sent[0].byteLength).toBeLessThan(64);
+
+ const decoded = multiplayerService.decodeBinaryPacket(toArrayBuffer(sent[0]));
+ expect(decoded).toEqual({
+ type: 'BINARY_MASK',
+ layerId: 'layer-mask-1',
+ x: 0,
+ y: 0,
+ width: 4096,
+ height: 4096,
+ isFullReplace: true,
+ solidFill: 255,
+ data: null,
+ });
+
+ // Reject oversized / malformed binary mask dimensions
+ const badPacket = sent[0].slice();
+ const badView = new DataView(badPacket.buffer);
+ const layerIdLen = badView.getUint16(11, true);
+ // Overwrite width with 99999 (> MAX_SYNC_CANVAS_DIM)
+ badView.setUint32(11 + 2 + layerIdLen + 1 + 8, 99999, true);
+ expect(multiplayerService.decodeBinaryPacket(toArrayBuffer(badPacket))).toBeNull();
+
+ // Non-solid grayscale mask dirty rect LZ4 round-trip
+ sent.length = 0;
+ const width = 32;
+ const height = 16;
+ const rgba = new Uint8ClampedArray(width * height * 4);
+ for (let i = 0; i < width * height; i++) {
+ const v = i % 256;
+ rgba[i * 4] = v;
+ rgba[i * 4 + 1] = v;
+ rgba[i * 4 + 2] = v;
+ rgba[i * 4 + 3] = 255;
+ }
+ const fakeMaskCanvas = {
+ width,
+ height,
+ getContext: () => ({
+ getImageData: () => ({ data: rgba, width, height }),
+ }),
+ } as unknown as HTMLCanvasElement;
+
+ multiplayerService.sendLayerMaskData('layer-mask-2', fakeMaskCanvas, {
+ x: 0,
+ y: 0,
+ width,
+ height,
+ });
+ expect(sent.length).toBe(1);
+ expect(sent[0][2]).toBe(CODE_LAYER_MASK_DATA);
+ const decodedPatch = multiplayerService.decodeBinaryPacket(toArrayBuffer(sent[0]));
+ expect(decodedPatch?.type).toBe('BINARY_MASK');
+ if (decodedPatch?.type === 'BINARY_MASK') {
+ expect(decodedPatch.layerId).toBe('layer-mask-2');
+ expect(decodedPatch.width).toBe(width);
+ expect(decodedPatch.height).toBe(height);
+ expect(decodedPatch.solidFill).toBeUndefined();
+ expect(decodedPatch.data?.byteLength).toBe(width * height);
+ expect(decodedPatch.data?.[0]).toBe(0);
+ expect(decodedPatch.data?.[127]).toBe(127);
+ expect(decodedPatch.data?.[255]).toBe(255);
+ }
+
+ sendSpy.mockRestore();
+ connSpy.mockRestore();
+ });
+
+ it('deduplicates unchanged tile versions in streamLayerTiles unless force=true', () => {
+ const sent: Uint8Array[] = [];
+ const sendSpy = vi.spyOn(multiplayerService, 'sendBinary').mockImplementation((buf) => {
+ sent.push(buf instanceof Uint8Array ? buf : new Uint8Array(buf));
+ });
+ const connSpy = vi.spyOn(multiplayerService, 'isConnected').mockReturnValue(true);
+
+ const grid = new SparseTileGrid();
+ const img = { data: new Uint8ClampedArray(16 * 16 * 4).fill(180), width: 16, height: 16 };
+ grid.writeImageData('layer-1', img, 0, 0, 'color-32bit');
+
+ multiplayerService.streamLayerTiles('layer-1', grid);
+ expect(sent.length).toBe(1);
+ expect(sent[0][2]).toBe(CODE_TILE_DELTA);
+
+ // Second call with unchanged version is skipped
+ multiplayerService.streamLayerTiles('layer-1', grid);
+ expect(sent.length).toBe(1);
+
+ // Force bypasses dedupe
+ multiplayerService.streamLayerTiles('layer-1', grid, { force: true });
+ expect(sent.length).toBe(2);
+
+ sendSpy.mockRestore();
+ connSpy.mockRestore();
+ });
+});
diff --git a/src/utils/__tests__/multiplayerReconnectAndRoles.test.tsx b/src/utils/__tests__/multiplayerReconnectAndRoles.test.tsx
new file mode 100644
index 0000000..c08a8a0
--- /dev/null
+++ b/src/utils/__tests__/multiplayerReconnectAndRoles.test.tsx
@@ -0,0 +1,538 @@
+import React, { act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import {
+ useMultiplayer,
+ computeReconnectDelayMs,
+ RECONNECT_BASE_DELAY_MS,
+ RECONNECT_MAX_DELAY_MS,
+} from '../../hooks/useMultiplayer';
+import {
+ multiplayerService,
+ sanitizeIncomingJsonMessage,
+} from '../../services/multiplayerService';
+import {
+ canDeleteLayer,
+ canEditLayer,
+ canMutateCanvas,
+ canToggleLayerOwnerLock,
+ filterDeletableLayerIds,
+ validateIncomingRemoteMutation,
+} from '../collabPermissions';
+import { documentStore } from '../documentStore';
+import type { LayerItem } from '../../types/editor';
+import type { CollabPeer, MultiplayerMessage, TileStreamMessage } from '../../types/multiplayer';
+
+// Minimal DOM shim for React 19 createRoot in Vitest Node environment
+class ShimNode extends EventTarget {
+ nodeType = 1;
+ nodeName = 'DIV';
+ tagName = 'DIV';
+ namespaceURI = 'http://www.w3.org/1999/xhtml';
+ ownerDocument: any;
+ parentNode: any = null;
+ childNodes: any[] = [];
+ style: Record<string, string> = {};
+ constructor(tag = 'DIV', doc?: any) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = this.nodeName;
+ this.ownerDocument = doc ?? null;
+ }
+ appendChild(c: any) {
+ c.parentNode = this;
+ this.childNodes.push(c);
+ return c;
+ }
+ removeChild(c: any) {
+ const i = this.childNodes.indexOf(c);
+ if (i >= 0) this.childNodes.splice(i, 1);
+ c.parentNode = null;
+ return c;
+ }
+ insertBefore(c: any, ref: any) {
+ c.parentNode = this;
+ const i = this.childNodes.indexOf(ref);
+ if (i >= 0) this.childNodes.splice(i, 0, c);
+ else this.childNodes.push(c);
+ return c;
+ }
+}
+
+function installDomShim() {
+ const doc: any = new ShimNode('#document');
+ doc.nodeType = 9;
+ doc.activeElement = null;
+ doc.createElement = (tag: string) => new ShimNode(tag, doc);
+ doc.createTextNode = (txt: string) => {
+ const n: any = new ShimNode('#text', doc);
+ n.nodeType = 3;
+ n.nodeValue = txt;
+ return n;
+ };
+ doc.documentElement = new ShimNode('HTML', doc);
+ doc.body = new ShimNode('BODY', doc);
+ const win: any = new EventTarget();
+ win.document = doc;
+ doc.defaultView = win;
+ class HTMLIFrameElementShim extends ShimNode {}
+ win.HTMLElement = ShimNode;
+ win.HTMLIFrameElement = HTMLIFrameElementShim;
+ win.Element = ShimNode;
+ win.Node = ShimNode;
+ win.location = { protocol: 'http:', hostname: '127.0.0.1', href: 'http://127.0.0.1/' };
+ win.requestAnimationFrame = (cb: () => void) => setTimeout(cb, 0);
+ win.cancelAnimationFrame = (id: any) => clearTimeout(id);
+ win.navigator = {};
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ (globalThis as any).window = win;
+ (globalThis as any).document = doc;
+ (globalThis as any).HTMLElement = ShimNode;
+ (globalThis as any).HTMLIFrameElement = HTMLIFrameElementShim;
+ (globalThis as any).Element = ShimNode;
+ (globalThis as any).Node = ShimNode;
+ return { doc, win };
+}
+
+class MockWebSocket {
+ static OPEN = 1;
+ static CLOSED = 3;
+ static instances: MockWebSocket[] = [];
+ static nextFail = false;
+
+ url: string;
+ binaryType = 'arraybuffer';
+ readyState = 0;
+ bufferedAmount = 0;
+ sent: any[] = [];
+ onopen: (() => void) | null = null;
+ onmessage: ((ev: { data: any }) => void) | null = null;
+ onclose: ((ev: { reason?: string }) => void) | null = null;
+ onerror: ((ev: any) => void) | null = null;
+
+ constructor(url: string) {
+ this.url = url;
+ MockWebSocket.instances.push(this);
+ queueMicrotask(() => {
+ if (MockWebSocket.nextFail) {
+ MockWebSocket.nextFail = false;
+ this.readyState = MockWebSocket.CLOSED;
+ this.onerror?.(new Event('error'));
+ this.onclose?.({ reason: 'offline' });
+ } else {
+ this.readyState = MockWebSocket.OPEN;
+ this.onopen?.();
+ }
+ });
+ }
+
+ send(data: any) {
+ this.sent.push(data);
+ }
+
+ close() {
+ this.readyState = MockWebSocket.CLOSED;
+ }
+
+ simulateDrop() {
+ this.readyState = MockWebSocket.CLOSED;
+ this.onclose?.({ reason: 'network drop' });
+ }
+
+ simulateJson(obj: Record<string, unknown>) {
+ this.onmessage?.({ data: JSON.stringify(obj) });
+ }
+}
+
+function makeLayer(overrides: Partial<LayerItem> = {}): LayerItem {
+ return {
+ id: overrides.id ?? 'layer-1',
+ name: overrides.name ?? 'Layer 1',
+ type: overrides.type ?? 'raster',
+ visible: overrides.visible ?? true,
+ opacity: overrides.opacity ?? 1,
+ blendMode: overrides.blendMode ?? 'normal',
+ locked: overrides.locked ?? false,
+ parentId: overrides.parentId ?? null,
+ ...overrides,
+ };
+}
+
+describe('Exponential Backoff Calculation', () => {
+ it('grows exponentially, respects max cap, applies +/-20% jitter, and calls rng once', () => {
+ const rngSpy = vi.fn(() => 0.5); // 0.8 + 0.4 * 0.5 = 1.0x
+ expect(computeReconnectDelayMs(1, rngSpy)).toBe(RECONNECT_BASE_DELAY_MS);
+ expect(rngSpy).toHaveBeenCalledTimes(1);
+
+ expect(computeReconnectDelayMs(2, () => 0.5)).toBe(2000);
+ expect(computeReconnectDelayMs(3, () => 0.5)).toBe(4000);
+ expect(computeReconnectDelayMs(4, () => 0.5)).toBe(8000);
+ expect(computeReconnectDelayMs(5, () => 0.5)).toBe(16000);
+ expect(computeReconnectDelayMs(6, () => 0.5)).toBe(RECONNECT_MAX_DELAY_MS);
+ expect(computeReconnectDelayMs(12, () => 1.0)).toBe(RECONNECT_MAX_DELAY_MS);
+
+ expect(computeReconnectDelayMs(1, () => 0)).toBe(800);
+ expect(computeReconnectDelayMs(1, () => 1)).toBe(1200);
+ });
+});
+
+describe('Room Roles, Owner Locking & Accidental Deletion Protection', () => {
+ const aliceLayer = makeLayer({
+ id: 'l-alice',
+ name: 'Alice Ink',
+ ownerPeerId: 'alice',
+ ownerPeerName: 'Alice',
+ });
+ const bobLayer = makeLayer({
+ id: 'l-bob',
+ name: 'Bob Sketch',
+ ownerPeerId: 'bob',
+ ownerPeerName: 'Bob',
+ reservedByPeerId: 'bob',
+ reservedByPeerName: 'Bob',
+ });
+ const folder = makeLayer({
+ id: 'f-1',
+ name: 'Shared Folder',
+ type: 'folder',
+ ownerPeerId: 'alice',
+ ownerPeerName: 'Alice',
+ });
+ const bobChild = makeLayer({
+ id: 'l-bob-child',
+ name: 'Bob Child',
+ parentId: 'f-1',
+ ownerPeerId: 'bob',
+ ownerPeerName: 'Bob',
+ });
+ const allLayers = [aliceLayer, bobLayer, folder, bobChild];
+
+ it('enforces Viewer read-only across edits, locks, and deletes', () => {
+ expect(canMutateCanvas('host')).toBe(true);
+ expect(canMutateCanvas('editor')).toBe(true);
+ expect(canMutateCanvas('viewer')).toBe(false);
+
+ expect(canEditLayer(aliceLayer, 'alice', 'viewer').allowed).toBe(false);
+ expect(canToggleLayerOwnerLock(aliceLayer, 'alice', 'viewer').allowed).toBe(false);
+ expect(canDeleteLayer('l-alice', allLayers, 'alice', 'viewer').allowed).toBe(false);
+ });
+
+ it('enforces layer locking by owner while allowing owner & Host', () => {
+ expect(canEditLayer(bobLayer, 'alice', 'editor').allowed).toBe(false);
+ expect(canEditLayer(bobLayer, 'bob', 'editor').allowed).toBe(true);
+ expect(canEditLayer(bobLayer, 'host-1', 'host').allowed).toBe(true);
+
+ // Non-owner Editor cannot unlock Bob's layer or lock Alice's layer
+ expect(canToggleLayerOwnerLock(bobLayer, 'alice', 'editor').allowed).toBe(false);
+ expect(canToggleLayerOwnerLock(aliceLayer, 'bob', 'editor').allowed).toBe(false);
+ // Owner and Host can lock/unlock
+ expect(canToggleLayerOwnerLock(bobLayer, 'bob', 'editor').allowed).toBe(true);
+ expect(canToggleLayerOwnerLock(aliceLayer, 'alice', 'editor').allowed).toBe(true);
+ expect(canToggleLayerOwnerLock(bobLayer, 'host-1', 'host').allowed).toBe(true);
+ });
+
+ it('prevents accidental deletion of other users layers including nested folder children', () => {
+ // Alice can delete her own unshared layer
+ expect(canDeleteLayer('l-alice', allLayers, 'alice', 'editor').allowed).toBe(true);
+ // Alice cannot delete Bob's layer
+ expect(canDeleteLayer('l-bob', allLayers, 'alice', 'editor').allowed).toBe(false);
+ // Alice cannot delete her own folder if it contains Bob's child layer!
+ const folderCheck = canDeleteLayer('f-1', allLayers, 'alice', 'editor');
+ expect(folderCheck.allowed).toBe(false);
+ expect(folderCheck.blockedLayerId).toBe('l-bob-child');
+ // Host can override and delete
+ expect(canDeleteLayer('f-1', allLayers, 'host-1', 'host').allowed).toBe(true);
+
+ // Multi-select filter spares Bob's layer while allowing Alice's
+ const filtered = filterDeletableLayerIds(['l-alice', 'l-bob'], allLayers, 'alice', 'editor');
+ expect(filtered.allowedIds).toEqual(['l-alice']);
+ expect(filtered.blockedReasons.length).toBe(1);
+ });
+
+ it('validates incoming remote mutations for defense-in-depth', () => {
+ const viewerPeer: CollabPeer = { id: 'v1', name: 'Viewer', color: '#fff', role: 'viewer' };
+ const editorPeer: CollabPeer = { id: 'alice', name: 'Alice', color: '#0f0', role: 'editor' };
+ const hostPeer: CollabPeer = { id: 'host-1', name: 'Host', color: '#00f', isHost: true, role: 'host' };
+
+ const deleteBobMsg: MultiplayerMessage = {
+ type: 'LAYER_DELETE',
+ senderId: 'alice',
+ layerId: 'l-bob',
+ };
+ expect(validateIncomingRemoteMutation(deleteBobMsg, editorPeer, allLayers).allowed).toBe(false);
+ expect(
+ validateIncomingRemoteMutation({ ...deleteBobMsg, senderId: 'host-1' }, hostPeer, allLayers).allowed
+ ).toBe(true);
+
+ const viewerTileMsg: TileStreamMessage = {
+ type: 'BINARY_TILE',
+ senderId: 'v1',
+ layerId: 'l-alice',
+ tileX: 0,
+ tileY: 0,
+ format: 'color-32bit',
+ version: 1,
+ data: new Uint8Array([1, 2, 3, 4]),
+ };
+ expect(validateIncomingRemoteMutation(viewerTileMsg, viewerPeer, allLayers).allowed).toBe(false);
+
+ const spoofRoleMsg: MultiplayerMessage = {
+ type: 'PEER_ROLE_UPDATE',
+ senderId: 'alice',
+ targetPeerId: 'bob',
+ role: 'viewer',
+ };
+ expect(validateIncomingRemoteMutation(spoofRoleMsg, editorPeer, allLayers).allowed).toBe(false);
+ });
+
+ it('sanitizes incoming role/kick/ban/access-denied JSON messages strictly', () => {
+ expect(
+ sanitizeIncomingJsonMessage({ type: 'PEER_ROLE_UPDATE', targetPeerId: 'p1', role: 'viewer' })
+ ).toEqual({
+ type: 'PEER_ROLE_UPDATE',
+ senderId: undefined,
+ targetPeerId: 'p1',
+ role: 'viewer',
+ });
+ expect(
+ sanitizeIncomingJsonMessage({ type: 'PEER_ROLE_UPDATE', targetPeerId: 'p1', role: 'superadmin' })
+ ).toBeNull();
+ expect(
+ sanitizeIncomingJsonMessage({ type: 'PEER_BAN', targetPeerId: 'p2', reason: 'Spam' })
+ ).toMatchObject({ type: 'PEER_BAN', targetPeerId: 'p2', reason: 'Spam' });
+ expect(
+ sanitizeIncomingJsonMessage({ type: 'ACCESS_DENIED', code: 'BANNED', reason: 'No access' })
+ ).toMatchObject({ type: 'ACCESS_DENIED', code: 'BANNED', reason: 'No access' });
+ });
+});
+
+describe('useMultiplayer Auto-Reconnect, Seq Catch-Up & Moderation', () => {
+ let root: Root | null = null;
+ let container: any;
+ const origWs = (globalThis as any).WebSocket;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ MockWebSocket.instances = [];
+ MockWebSocket.nextFail = false;
+ (globalThis as any).WebSocket = MockWebSocket;
+ const { doc } = installDomShim();
+ container = doc.createElement('div');
+ multiplayerService.disconnect();
+ documentStore.getActiveTileGrid().clearAll();
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => {
+ root!.unmount();
+ });
+ root = null;
+ }
+ multiplayerService.disconnect();
+ (globalThis as any).WebSocket = origWs;
+ vi.useRealTimers();
+ });
+
+ it('auto-reconnects with exponential backoff, preserves session, and catches up missed seqs/tiles', async () => {
+ const toasts: string[] = [];
+ const layerActions: MultiplayerMessage[] = [];
+ let api!: ReturnType<typeof useMultiplayer>;
+
+ function Harness() {
+ api = useMultiplayer({
+ dimensions: { width: 512, height: 512 },
+ colorMode: 'color',
+ layers: [makeLayer({ id: 'l1' })],
+ onRemoteLayerAction: (m) => layerActions.push(m),
+ showToast: (m) => toasts.push(m),
+ });
+ return null;
+ }
+
+ root = createRoot(container);
+ act(() => {
+ root!.render(React.createElement(Harness));
+ });
+
+ await act(async () => {
+ const ok = await api.joinRoom('127.0.0.1', 30303, 'Studio', 'Alice', 'secret');
+ expect(ok).toBe(true);
+ });
+
+ const ws1 = MockWebSocket.instances[0];
+ expect(ws1).toBeDefined();
+
+ // Receive initial ROOM_INFO + sequenced op seq=10
+ await act(async () => {
+ ws1.simulateJson({ type: 'ROOM_INFO', clientId: 2, roomName: 'Studio', serverSeq: 5 });
+ ws1.simulateJson({
+ type: 'JOIN_ACCEPTED',
+ seq: 6,
+ targetPeerId: api.myPeer.id,
+ roomName: 'Studio',
+ peers: [{ id: 'host-1', name: 'Host', color: '#fff', isHost: true, role: 'host' }],
+ hostId: 'host-1',
+ docDimensions: { width: 512, height: 512 },
+ colorMode: 'color',
+ assignedRole: 'editor',
+ });
+ ws1.simulateJson({
+ type: 'LAYER_RENAME',
+ seq: 10,
+ senderId: 'host-1',
+ layerId: 'l1',
+ newName: 'Before Drop',
+ });
+ });
+
+ expect(api.isConnected).toBe(true);
+ expect(api.connectionStatus).toBe('connected');
+ expect(api.peers.length).toBe(1);
+
+ // Unexpected network drop -> MUST NOT reset hostInfo / session; enters reconnecting
+ await act(async () => {
+ ws1.simulateDrop();
+ });
+
+ expect(api.isConnected).toBe(false);
+ expect(api.connectionStatus).toBe('reconnecting');
+ expect(api.hostInfo?.roomName).toBe('Studio');
+ expect(api.reconnectAttempt).toBe(1);
+
+ // First reconnect attempt fails -> backoff schedules attempt 2
+ MockWebSocket.nextFail = true;
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1500);
+ });
+ expect(api.connectionStatus).toBe('reconnecting');
+ expect(api.reconnectAttempt).toBe(2);
+
+ // Second reconnect attempt succeeds and sends JOIN_REQUEST with isReconnect + sinceSeq: 10
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3000);
+ });
+
+ expect(api.isConnected).toBe(true);
+ expect(api.connectionStatus).toBe('connected');
+ expect(api.reconnectAttempt).toBe(0);
+
+ const wsReconnected = MockWebSocket.instances[MockWebSocket.instances.length - 1];
+ const joinSent = JSON.parse(wsReconnected.sent[0]);
+ expect(joinSent.type).toBe('JOIN_REQUEST');
+ expect(joinSent.isReconnect).toBe(true);
+ expect(joinSent.sinceSeq).toBe(10);
+
+ // Server replays missed op seq=11 after reconnect
+ await act(async () => {
+ wsReconnected.simulateJson({
+ type: 'LAYER_RENAME',
+ seq: 11,
+ senderId: 'host-1',
+ layerId: 'l1',
+ newName: 'Caught Up',
+ });
+ });
+ expect(layerActions.some((m) => m.type === 'LAYER_RENAME' && (m as any).newName === 'Caught Up')).toBe(true);
+ });
+
+ it('halts auto-reconnect immediately when kicked or banned via ACCESS_DENIED', async () => {
+ const toasts: string[] = [];
+ let api!: ReturnType<typeof useMultiplayer>;
+
+ function Harness() {
+ api = useMultiplayer({
+ dimensions: { width: 512, height: 512 },
+ colorMode: 'color',
+ layers: [makeLayer({ id: 'l1' })],
+ showToast: (m) => toasts.push(m),
+ });
+ return null;
+ }
+
+ root = createRoot(container);
+ act(() => {
+ root!.render(React.createElement(Harness));
+ });
+
+ await act(async () => {
+ await api.joinRoom('127.0.0.1', 30303, 'Studio', 'Bob', 'secret');
+ });
+
+ const ws1 = MockWebSocket.instances[0];
+ await act(async () => {
+ ws1.simulateJson({
+ type: 'ACCESS_DENIED',
+ code: 'BANNED',
+ targetPeerId: api.myPeer.id,
+ reason: 'You are banned from this room',
+ });
+ });
+
+ expect(api.isConnected).toBe(false);
+ expect(api.connectionStatus).toBe('disconnected');
+ expect(api.hostInfo).toBeNull();
+ expect(toasts).toContain('You are banned from this room');
+
+ // Advancing timers must NOT spawn any reconnect sockets
+ const countAfterBan = MockWebSocket.instances.length;
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10000);
+ });
+ expect(MockWebSocket.instances.length).toBe(countAfterBan);
+ });
+
+ it('updates local role to viewer on PEER_ROLE_UPDATE and blocks outgoing mutations', async () => {
+ const toasts: string[] = [];
+ let api!: ReturnType<typeof useMultiplayer>;
+
+ function Harness() {
+ api = useMultiplayer({
+ dimensions: { width: 512, height: 512 },
+ colorMode: 'color',
+ layers: [makeLayer({ id: 'l1' })],
+ showToast: (m) => toasts.push(m),
+ });
+ return null;
+ }
+
+ root = createRoot(container);
+ act(() => {
+ root!.render(React.createElement(Harness));
+ });
+
+ await act(async () => {
+ await api.joinRoom('127.0.0.1', 30303, 'Studio', 'Guest1', 'secret');
+ });
+ const ws1 = MockWebSocket.instances[0];
+
+ await act(async () => {
+ ws1.simulateJson({
+ type: 'JOIN_ACCEPTED',
+ seq: 1,
+ targetPeerId: api.myPeer.id,
+ roomName: 'Studio',
+ peers: [{ id: 'host-1', name: 'Host', color: '#fff', isHost: true, role: 'host' }],
+ hostId: 'host-1',
+ docDimensions: { width: 512, height: 512 },
+ colorMode: 'color',
+ assignedRole: 'editor',
+ });
+ ws1.simulateJson({
+ type: 'PEER_ROLE_UPDATE',
+ seq: 2,
+ senderId: 'host-1',
+ targetPeerId: api.myPeer.id,
+ role: 'viewer',
+ });
+ });
+
+ expect(api.myRole).toBe('viewer');
+ expect(multiplayerService.getLocalRole()).toBe('viewer');
+
+ const sentBefore = ws1.sent.length;
+ multiplayerService.sendLayerDelete('l1');
+ multiplayerService.sendLayerRename('l1', 'Hacked');
+ expect(ws1.sent.length).toBe(sentBefore);
+ });
+});
diff --git a/src/utils/__tests__/psdRoundTrip.test.ts b/src/utils/__tests__/psdRoundTrip.test.ts
index fdb33f8..74d4634 100644
--- a/src/utils/__tests__/psdRoundTrip.test.ts
+++ b/src/utils/__tests__/psdRoundTrip.test.ts
@@ -113,12 +113,35 @@ describe('PSD/PSB Blend Mode Mapping & Full Round-Trip', () => {
expect(mapPsdBlendMode('darken')).toBe('darken');
expect(mapPsdBlendMode('lighten')).toBe('lighten');
expect(mapPsdBlendMode('normal')).toBe('normal');
+ expect(mapPsdBlendMode('vivid light')).toBe('vivid-light');
+ expect(mapPsdBlendMode('linear light')).toBe('linear-light');
+ expect(mapPsdBlendMode('pin light')).toBe('pin-light');
+ expect(mapPsdBlendMode('hard mix')).toBe('hard-mix');
+ expect(mapPsdBlendMode('subtract')).toBe('subtract');
+ expect(mapPsdBlendMode('subtraction')).toBe('subtract');
+ expect(mapPsdBlendMode('darker color')).toBe('darker-color');
+ expect(mapPsdBlendMode('lighter color')).toBe('lighter-color');
+ expect(mapPsdBlendMode('hue')).toBe('hue');
+ expect(mapPsdBlendMode('saturation')).toBe('saturation');
+ expect(mapPsdBlendMode('color')).toBe('color');
+ expect(mapPsdBlendMode('luminosity')).toBe('luminosity');
expect(toAgPsdBlendMode('linear-burn')).toBe('linear burn');
expect(toAgPsdBlendMode('add-glow')).toBe('linear dodge');
expect(toAgPsdBlendMode('color-dodge-glow')).toBe('color dodge');
expect(toAgPsdBlendMode('divide')).toBe('divide');
expect(toAgPsdBlendMode('pass-through')).toBe('pass through');
+ expect(toAgPsdBlendMode('vivid-light')).toBe('vivid light');
+ expect(toAgPsdBlendMode('linear-light')).toBe('linear light');
+ expect(toAgPsdBlendMode('pin-light')).toBe('pin light');
+ expect(toAgPsdBlendMode('hard-mix')).toBe('hard mix');
+ expect(toAgPsdBlendMode('subtract')).toBe('subtract');
+ expect(toAgPsdBlendMode('darker-color')).toBe('darker color');
+ expect(toAgPsdBlendMode('lighter-color')).toBe('lighter color');
+ expect(toAgPsdBlendMode('hue')).toBe('hue');
+ expect(toAgPsdBlendMode('saturation')).toBe('saturation');
+ expect(toAgPsdBlendMode('color')).toBe('color');
+ expect(toAgPsdBlendMode('luminosity')).toBe('luminosity');
});
it('round-trips all blend modes through binary PSD export and import', async () => {
@@ -126,6 +149,7 @@ describe('PSD/PSB Blend Mode Mapping & Full Round-Trip', () => {
const tileGrid = new SparseTileGrid();
const allModes: BlendMode[] = BLEND_MODES.map((m) => m.value);
+ expect(allModes.length).toBeGreaterThanOrEqual(28);
const layers: LayerItem[] = allModes.map((mode, idx) => {
const id = `layer-mode-${idx}`;
if (mode === 'pass-through') {
diff --git a/src/utils/__tests__/recentDocumentsManager.test.ts b/src/utils/__tests__/recentDocumentsManager.test.ts
index 228df58..b84ee27 100644
--- a/src/utils/__tests__/recentDocumentsManager.test.ts
+++ b/src/utils/__tests__/recentDocumentsManager.test.ts
@@ -43,8 +43,8 @@ describe('recentDocumentsManager', () => {
it('saves and updates recent documents correctly', async () => {
const newDoc: RecentDocument = {
id: 'test-doc-123',
- title: 'Manga_Test.sora',
- path: 'C:\\Users\\Test\\Manga_Test.sora',
+ title: 'Manga_Test.ink',
+ path: 'C:\\Users\\Test\\Manga_Test.ink',
size: 2048000,
isStarred: false,
lastOpened: Date.now(),
@@ -54,14 +54,14 @@ describe('recentDocumentsManager', () => {
const docs = await loadRecentDocuments();
const found = docs.find((d) => d.id === 'test-doc-123');
expect(found).toBeDefined();
- expect(found?.title).toBe('Manga_Test.sora');
+ expect(found?.title).toBe('Manga_Test.ink');
});
it('toggles star state of documents', async () => {
const testDoc: RecentDocument = {
id: 'star-toggle-doc',
- title: 'Star_Test.sora',
- path: 'C:\\Users\\Test\\Star_Test.sora',
+ title: 'Star_Test.ink',
+ path: 'C:\\Users\\Test\\Star_Test.ink',
size: 1024,
isStarred: false,
lastOpened: Date.now(),
@@ -76,8 +76,8 @@ describe('recentDocumentsManager', () => {
it('removes documents from app list', async () => {
const testDoc: RecentDocument = {
id: 'doc-to-remove',
- title: 'Remove_Test.sora',
- path: 'C:\\Users\\Test\\Remove_Test.sora',
+ title: 'Remove_Test.ink',
+ path: 'C:\\Users\\Test\\Remove_Test.ink',
size: 1024,
isStarred: false,
lastOpened: Date.now(),
@@ -91,8 +91,8 @@ describe('recentDocumentsManager', () => {
it('handles permanent delete calls gracefully', async () => {
const testDoc: RecentDocument = {
id: 'doc-to-perm-delete',
- title: 'Temp.sora',
- path: 'C:\\Invalid\\NonExistent\\Temp.sora',
+ title: 'Temp.ink',
+ path: 'C:\\Invalid\\NonExistent\\Temp.ink',
size: 1024,
isStarred: false,
lastOpened: Date.now(),
@@ -109,7 +109,7 @@ describe('recentDocumentsManager', () => {
const unsavedDummy: RecentDocument = {
id: 'doc-unsaved-1',
title: 'Untitled*',
- path: 'InkStudio\\Untitled.sora',
+ path: 'InkStudio\\Untitled.ink',
size: 524288,
isStarred: false,
lastOpened: Date.now(),
@@ -121,7 +121,7 @@ describe('recentDocumentsManager', () => {
const notSavedDoc: RecentDocument = {
id: 'doc-unsaved-2',
title: 'Manga Draft',
- path: 'C:\\Draft.sora',
+ path: 'C:\\Draft.ink',
size: 1024,
isStarred: false,
lastOpened: Date.now(),
@@ -132,13 +132,13 @@ describe('recentDocumentsManager', () => {
// Valid actually saved document
const savedDoc: RecentDocument = {
id: 'doc-saved-1',
- title: 'Finished_Page.sora',
- path: 'C:\\Users\\Artist\\Documents\\Finished_Page.sora',
+ title: 'Finished_Page.ink',
+ path: 'C:\\Users\\Artist\\Documents\\Finished_Page.ink',
size: 1572864,
isStarred: false,
lastOpened: Date.now(),
isSaved: true,
- fileType: '.sora',
+ fileType: '.ink',
};
await saveRecentDocument(savedDoc);
diff --git a/src/utils/__tests__/settings.test.ts b/src/utils/__tests__/settings.test.ts
index b68dd21..991e96f 100644
--- a/src/utils/__tests__/settings.test.ts
+++ b/src/utils/__tests__/settings.test.ts
@@ -8,6 +8,7 @@ import {
getAccentContrastColor,
hexToRgb,
MODERN_ACCENTS,
+ NICKNAME_STORAGE_KEY,
} from '../../types/settings';
describe('settings theme & accent system', () => {
@@ -132,4 +133,13 @@ describe('settings theme & accent system', () => {
expect(roundTripped.autoCheckUpdates).toBe(false);
expect(roundTripped.skippedUpdateVersion).toBe('1.2.3');
});
+
+ it('uses ink_studio_nickname and ignores removed legacy sora_paint_nickname key', () => {
+ localStorage.setItem('sora_paint_nickname', 'OldName');
+ expect(loadAppSettings().userName).toBe('');
+
+ localStorage.setItem(NICKNAME_STORAGE_KEY, 'InkArtist');
+ expect(NICKNAME_STORAGE_KEY).toBe('ink_studio_nickname');
+ expect(loadAppSettings().userName).toBe('InkArtist');
+ });
});
diff --git a/src/utils/__tests__/storageSafety.test.ts b/src/utils/__tests__/storageSafety.test.ts
index f4eefb3..da4061b 100644
--- a/src/utils/__tests__/storageSafety.test.ts
+++ b/src/utils/__tests__/storageSafety.test.ts
@@ -304,14 +304,14 @@ describe('Storage Safety, IndexedDB Migration & QuotaExceededError Handling', ()
const heavyThumb = 'data:image/jpeg;base64,' + 'T'.repeat(12_000);
const doc: RecentDocument = {
id: 'recent-1',
- title: 'Chapter1.sora',
- path: 'C:\\Art\\Chapter1.sora',
+ title: 'Chapter1.ink',
+ path: 'C:\\Art\\Chapter1.ink',
size: 2_500_000,
coverUrl: heavyThumb,
lastOpened: Date.now(),
isStarred: true,
isSaved: true,
- fileType: '.sora',
+ fileType: '.ink',
};
// Seed legacy localStorage entry with coverUrl to test migration + strip
@@ -331,7 +331,7 @@ describe('Storage Safety, IndexedDB Migration & QuotaExceededError Handling', ()
await saveRecentDocument({
...doc,
id: 'recent-2',
- title: 'Chapter2.sora',
+ title: 'Chapter2.ink',
coverUrl: heavyThumb,
});
const fallbackRaw = localStorage.getItem(RECENT_DOCS_LS_KEY) || '';
diff --git a/src/utils/__tests__/strokeHandshake.test.ts b/src/utils/__tests__/strokeHandshake.test.ts
index 073aee4..7c3802b 100644
--- a/src/utils/__tests__/strokeHandshake.test.ts
+++ b/src/utils/__tests__/strokeHandshake.test.ts
@@ -9,12 +9,12 @@ import { COMPOSITOR_FRAGMENT_SHADER, COMPOSITOR_INSTANCED_FRAGMENT_SHADER } from
import { extractCoalescedEvents } from '../../components/CanvasArea';
import { LayerPixelSampler } from '../colorMixingEngine';
import {
- drawRadialDot,
- drawRadialCubicBezierSegment,
- renderCompleteRadialStroke,
+ drawBrushDot,
+ drawBrushCubicBezierSegment,
+ renderCompleteStroke,
centripetalCatmullRomToBezier,
- RadialMixingOptions,
-} from '../stampEngine';
+ BrushRenderOptions,
+} from '../../engine/BrushEngine';
describe('Zero-Flicker Stroke Handshake & WYSIWYG Monochrome Pipeline', () => {
let grid: SparseTileGrid;
@@ -217,11 +217,18 @@ describe('Zero-Flicker Stroke Handshake & WYSIWYG Monochrome Pipeline', () => {
{ x: 45, y: 25, pressure: 0.8, width: 14 },
{ x: 70, y: 30, pressure: 0.75, width: 13 },
];
- const mixingOpts: RadialMixingOptions = {
+ const flow = 0.62;
+ const spacing = 0.05;
+ const hardness = 0.55;
+ const mixingOpts: BrushRenderOptions = {
+ hardness,
+ flow,
+ spacing,
blendTipsMode: 'darken',
adjustDensityByGap: true,
grain: 0.35,
useTilt: false,
+ useGpu: false,
};
const liveStamps: Array<{ x: number; y: number; w: number; h: number; alpha: number; op: string }> = [];
@@ -265,20 +272,41 @@ describe('Zero-Flicker Stroke Handshake & WYSIWYG Monochrome Pipeline', () => {
const liveCtx = makeMockCtx(liveStamps);
const completeCtx = makeMockCtx(completeStamps);
- const flow = 0.62;
- const spacing = 0.05;
- const hardness = 0.55;
+ const dabCounter = { count: 0 };
// 1. Live incremental rendering (initial dot + segment 0->1 + tail segment 1->2)
- drawRadialDot(liveCtx, pts[0], '#e03030', hardness, flow, false, false, mixingOpts, 1.0, 0);
+ drawBrushDot(liveCtx, pts[0], '#e03030', mixingOpts);
let rem = Math.max(0.12, pts[0].width * spacing);
const seg1 = centripetalCatmullRomToBezier(pts[0], pts[0], pts[1], pts[2]);
- rem = drawRadialCubicBezierSegment(liveCtx, pts[0], seg1.c1, seg1.c2, pts[1], '#e03030', hardness, flow, spacing, false, false, rem, 1.0, 0, mixingOpts);
+ rem = drawBrushCubicBezierSegment(liveCtx, pts[0], seg1.c1, seg1.c2, pts[1], '#e03030', mixingOpts, rem, dabCounter);
const seg2 = centripetalCatmullRomToBezier(pts[0], pts[1], pts[2], pts[2]);
- drawRadialCubicBezierSegment(liveCtx, pts[1], seg2.c1, seg2.c2, pts[2], '#e03030', hardness, flow, spacing, false, false, rem, 1.0, 0, mixingOpts);
+ drawBrushCubicBezierSegment(liveCtx, pts[1], seg2.c1, seg2.c2, pts[2], '#e03030', mixingOpts, rem, dabCounter);
// 2. Complete stroke rendering
- renderCompleteRadialStroke(completeCtx, pts, '#e03030', hardness, flow, spacing, false, false, 1.0, 0, mixingOpts);
+ renderCompleteStroke(
+ completeCtx,
+ pts,
+ {
+ size: 14,
+ minSizeFactor: 0.2,
+ opacity: 1.0,
+ color: '#e03030',
+ flow,
+ spacing,
+ hardness,
+ smoothing: true,
+ stabilization: 0,
+ usePressure: true,
+ blendTipsMode: 'darken',
+ adjustDensityByGap: true,
+ grain: 0.35,
+ useTilt: false,
+ useGpu: false,
+ },
+ 'brush',
+ 'color',
+ false
+ );
expect(liveStamps.length).toBeGreaterThan(5);
expect(liveStamps.length).toBe(completeStamps.length);
diff --git a/src/utils/__tests__/strokePipelineIntegration.test.ts b/src/utils/__tests__/strokePipelineIntegration.test.ts
index 78ff30d..453e6f4 100644
--- a/src/utils/__tests__/strokePipelineIntegration.test.ts
+++ b/src/utils/__tests__/strokePipelineIntegration.test.ts
@@ -10,14 +10,11 @@ import {
} from '../../engine/StrokePipeline';
import { CubicBezierSegment } from '../../engine/SplineGenerator';
import {
- canUseWebGlForTexturedBrush,
- canUseWebGlForRadialBrush,
- renderCompleteTexturedStroke,
- renderCompleteRadialStroke,
- TexturedBrushOptions,
-} from '../stampEngine';
-import { WebGlBrushEngine, GpuDab } from '../webglBrushEngine';
-import { renderCompleteStroke } from '../canvasUtils';
+ canUseWebGlForBrush,
+ renderCompleteStroke,
+ BrushRenderOptions,
+} from '../../engine/BrushEngine';
+import { WebGlBrushEngine, GpuDab } from '../../engine/WebGlBrushEngine';
import { BrushSettings, Point } from '../../types/editor';
function makeMock2DCtx(w = 1000, h = 1000) {
@@ -344,16 +341,37 @@ describe('WebGlBrushEngine Integration & Canvas 2D Fallback in stampEngine', ()
try {
// 1. Textured .sut/preset brush
const texMock = makeMock2DCtx(256, 256);
- const texOpts: TexturedBrushOptions = {
+ const texOpts: BrushRenderOptions = {
size: 18,
flow: 0.85,
spacing: 0.1,
antiAlias: 2,
+ tipImage: mockTipImage,
useGpu: true,
useTilt: true,
};
- expect(canUseWebGlForTexturedBrush(texOpts)).toBe(true);
- renderCompleteTexturedStroke(texMock.ctx, samplePoints, '#224488', mockTipImage, texOpts);
+ expect(canUseWebGlForBrush(texOpts)).toBe(true);
+ renderCompleteStroke(
+ texMock.ctx,
+ samplePoints,
+ {
+ size: 18,
+ minSizeFactor: 0.2,
+ color: '#224488',
+ opacity: 1,
+ flow: 0.85,
+ spacing: 0.1,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ hardness: 1,
+ antiAlias: 2,
+ customTipImage: mockTipImage,
+ useGpu: true,
+ useTilt: true,
+ },
+ 'brush'
+ );
expect(renderSpy).toHaveBeenCalledTimes(1);
expect(renderedBatches[0].length).toBeGreaterThan(5);
@@ -362,11 +380,26 @@ describe('WebGlBrushEngine Integration & Canvas 2D Fallback in stampEngine', ()
// 2. Soft radial brush
const radMock = makeMock2DCtx(256, 256);
- expect(canUseWebGlForRadialBrush({ useGpu: true, antiAlias: 2 })).toBe(true);
- renderCompleteRadialStroke(radMock.ctx, samplePoints, '#cc2244', 0.35, 0.9, 0.1, false, false, 1.0, 0, {
- useGpu: true,
- antiAlias: 2,
- });
+ expect(canUseWebGlForBrush({ useGpu: true, antiAlias: 2 })).toBe(true);
+ renderCompleteStroke(
+ radMock.ctx,
+ samplePoints,
+ {
+ size: 18,
+ minSizeFactor: 0.2,
+ color: '#cc2244',
+ opacity: 1,
+ flow: 0.9,
+ spacing: 0.1,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ hardness: 0.35,
+ antiAlias: 2,
+ useGpu: true,
+ },
+ 'brush'
+ );
expect(renderSpy).toHaveBeenCalledTimes(2);
expect(renderedBatches[1].length).toBeGreaterThan(5);
@@ -384,19 +417,34 @@ describe('WebGlBrushEngine Integration & Canvas 2D Fallback in stampEngine', ()
try {
// Eligibility gates
- expect(canUseWebGlForTexturedBrush({ size: 10, antiAlias: 0, useGpu: true })).toBe(false);
- expect(canUseWebGlForTexturedBrush({ size: 10, colorMixing: true, useGpu: true })).toBe(false);
- expect(canUseWebGlForTexturedBrush({ size: 10, useGpu: false })).toBe(false);
- expect(canUseWebGlForTexturedBrush({ size: 10, subTipImages: [mockTipImage, mockTipImage], useGpu: true })).toBe(false);
- expect(canUseWebGlForRadialBrush({ antiAlias: 0, useGpu: true })).toBe(false);
- expect(canUseWebGlForRadialBrush({ colorMixing: true, useGpu: true })).toBe(false);
+ expect(canUseWebGlForBrush({ size: 10, antiAlias: 0, useGpu: true, tipImage: mockTipImage })).toBe(false);
+ expect(canUseWebGlForBrush({ size: 10, colorMixing: true, useGpu: true, tipImage: mockTipImage })).toBe(false);
+ expect(canUseWebGlForBrush({ size: 10, useGpu: false, tipImage: mockTipImage })).toBe(false);
+ expect(canUseWebGlForBrush({ size: 10, tipImage: mockTipImage, subTipImages: [mockTipImage, mockTipImage], useGpu: true })).toBe(false);
+ expect(canUseWebGlForBrush({ antiAlias: 0, useGpu: true })).toBe(false);
+ expect(canUseWebGlForBrush({ colorMixing: true, useGpu: true })).toBe(false);
// When renderDabsToContext returns false (e.g. context lost), falls back to Canvas 2D drawImage
const fallbackMock = makeMock2DCtx(256, 256);
- renderCompleteRadialStroke(fallbackMock.ctx, samplePoints, '#112233', 0.8, 0.9, 0.15, false, false, 1.0, 0, {
- useGpu: true,
- antiAlias: 2,
- });
+ renderCompleteStroke(
+ fallbackMock.ctx,
+ samplePoints,
+ {
+ size: 18,
+ minSizeFactor: 0.2,
+ color: '#112233',
+ opacity: 1,
+ flow: 0.9,
+ spacing: 0.15,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ hardness: 0.8,
+ antiAlias: 2,
+ useGpu: true,
+ },
+ 'brush'
+ );
expect(renderSpy).toHaveBeenCalledTimes(1);
expect(fallbackMock.raw.drawImage).toHaveBeenCalled();
} finally {
diff --git a/src/utils/__tests__/tileNativeNoDuplicateCanvas.test.ts b/src/utils/__tests__/tileNativeNoDuplicateCanvas.test.ts
new file mode 100644
index 0000000..3d13ff1
--- /dev/null
+++ b/src/utils/__tests__/tileNativeNoDuplicateCanvas.test.ts
@@ -0,0 +1,357 @@
+import { describe, it, expect } from 'vitest';
+import { SparseTileGrid, BYTES_32BIT, TILE_SIZE, type TileSnapshotEntry } from '../tileEngine';
+import { executeFloodFillOnTileGrid } from '../floodFill';
+import {
+ clearSelectionInTileGrid,
+ fillSelectionInTileGrid,
+ floodSelectWandOnTileGrid,
+} from '../selectionUtils';
+import { applyFilterToTileGrid } from '../filterEngine';
+import { computeHistogramsFromTileSnapshot, applyTonalToTileGrid } from '../tonalEngine';
+import { applyLiquifyStepOnTileGrid } from '../liquifyEngine';
+import { sampleCompositedColor } from '../canvasUtils';
+import type { CanvasDimensions, CanvasSelection, LayerItem } from '../../types/editor';
+
+const DOC_600_DPI: CanvasDimensions = { width: 7016, height: 9921 };
+
+if (typeof (globalThis as unknown as { ImageData?: unknown }).ImageData === 'undefined') {
+ class PolyfillImageData {
+ data: Uint8ClampedArray;
+ width: number;
+ height: number;
+ colorSpace = 'srgb' as const;
+ constructor(dataOrWidth: Uint8ClampedArray | number, widthOrHeight: number, maybeHeight?: number) {
+ if (typeof dataOrWidth === 'number') {
+ this.width = dataOrWidth;
+ this.height = widthOrHeight;
+ this.data = new Uint8ClampedArray(this.width * this.height * 4);
+ } else {
+ this.data = dataOrWidth;
+ this.width = widthOrHeight;
+ this.height = maybeHeight ?? Math.floor(dataOrWidth.length / (widthOrHeight * 4));
+ }
+ }
+ }
+ (globalThis as unknown as { ImageData: unknown }).ImageData = PolyfillImageData;
+}
+
+function makeImageData(
+ width: number,
+ height: number,
+ fill: (x: number, y: number) => [number, number, number, number]
+): ImageData {
+ const data = new Uint8ClampedArray(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const idx = (y * width + x) * 4;
+ const [r, g, b, a] = fill(x, y);
+ data[idx] = r;
+ data[idx + 1] = g;
+ data[idx + 2] = b;
+ data[idx + 3] = a;
+ }
+ }
+ return { data, width, height, colorSpace: 'srgb' } as ImageData;
+}
+
+function makeSolid(width: number, height: number, r: number, g: number, b: number, a: number): ImageData {
+ return makeImageData(width, height, () => [r, g, b, a]);
+}
+
+function makeRasterLayer(id: string, overrides: Partial<LayerItem> = {}): LayerItem {
+ return {
+ id,
+ name: id,
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ ...overrides,
+ };
+}
+
+describe('Tile-Native Pipeline (Zero Duplicate Full-Doc HTMLCanvasElement at 600 DPI)', () => {
+ it('computes tight content bounds, samples pixels, and prunes empty tiles on 7016x9921 without allocating untouched tiles', () => {
+ const grid = new SparseTileGrid();
+ // Draw a 32x24 red block at (5010, 8020)
+ grid.writeImageData('ink', makeSolid(32, 24, 220, 40, 30, 255), 5010, 8020, 'color-32bit');
+
+ expect(grid.getMemoryStats().tileCount).toBe(1);
+ expect(grid.getMemoryStats().activeBytes).toBe(BYTES_32BIT);
+
+ expect(grid.getPixelRGBA('ink', 5020, 8030)).toEqual([220, 40, 30, 255]);
+ expect(grid.getPixelRGBA('ink', 0, 0)).toEqual([0, 0, 0, 0]);
+
+ const bounds = grid.getLayerContentBounds('ink', DOC_600_DPI, false);
+ // getLayerContentBounds includes a 4px transform margin around the tight pixel box
+ expect(bounds).toEqual({ x: 5006, y: 8016, width: 40, height: 32 });
+
+ // Clearing the region auto-prunes the emptied tile
+ grid.clearRectInLayer('ink', { x: 5010, y: 8020, width: 32, height: 24 }, false);
+ expect(grid.getMemoryStats().tileCount).toBe(0);
+
+ // Explicit pruneEmptyTiles reclaims any all-transparent tiles created directly
+ grid.getOrCreateTile('ink', 3, 4, 'color-32bit', 0);
+ expect(grid.getMemoryStats().tileCount).toBe(1);
+ expect(grid.pruneEmptyTiles('ink')).toBe(1);
+ expect(grid.getMemoryStats().tileCount).toBe(0);
+ });
+
+ it('executes bounded flood fill directly on SparseTileGrid at 600 DPI with undo/redo tile deltas', () => {
+ const grid = new SparseTileGrid();
+ const layers = [makeRasterLayer('lineart'), makeRasterLayer('fill')];
+
+ // Draw a closed 80x80 black box border at (3000, 4000) on lineart
+ const box = makeImageData(80, 80, (x, y) => {
+ if (x < 3 || x >= 77 || y < 3 || y >= 77) return [0, 0, 0, 255];
+ return [0, 0, 0, 0];
+ });
+ grid.writeImageData('lineart', box, 3000, 4000, 'color-32bit');
+
+ const res = executeFloodFillOnTileGrid({
+ grid,
+ targetLayerId: 'fill',
+ layers,
+ dimensions: DOC_600_DPI,
+ startX: 3040,
+ startY: 4040,
+ fillColorHex: '#3366ff',
+ tolerance: 10,
+ referMode: 'refer-all',
+ targetFormat: 'color-32bit',
+ });
+
+ expect(res.modified).toBe(true);
+ expect(res.tileDeltas.length).toBeGreaterThan(0);
+ // Inside box filled with #3366ff
+ expect(grid.getPixelRGBA('fill', 3040, 4040)).toEqual([0x33, 0x66, 0xff, 255]);
+ // Outside box untouched
+ expect(grid.getPixelRGBA('fill', 2990, 4040)).toEqual([0, 0, 0, 0]);
+ // At most 4 tiles allocated for fill layer (spanning at most a 2x2 tile corner) — nowhere near 7016x9921 (1092 tiles)
+ expect(grid.getLayerTiles('fill', 0).length).toBeLessThanOrEqual(4);
+
+ // Undo restores exact transparency; redo restores exact fill
+ grid.applyTileDeltas(res.tileDeltas, 'undo');
+ expect(grid.getPixelRGBA('fill', 3040, 4040)).toEqual([0, 0, 0, 0]);
+ grid.applyTileDeltas(res.tileDeltas, 'redo');
+ expect(grid.getPixelRGBA('fill', 3040, 4040)).toEqual([0x33, 0x66, 0xff, 255]);
+ });
+
+ it('runs clearSelectionInTileGrid, fillSelectionInTileGrid, and floodSelectWandOnTileGrid directly on tiles', () => {
+ const grid = new SparseTileGrid();
+ const layers = [makeRasterLayer('layer-1')];
+ const sel: CanvasSelection = {
+ type: 'rect',
+ bounds: { x: 2000, y: 3000, width: 60, height: 40 },
+ };
+
+ const fillRes = fillSelectionInTileGrid({
+ grid,
+ layerId: 'layer-1',
+ dimensions: DOC_600_DPI,
+ selection: sel,
+ colorCss: '#10a050',
+ targetFormat: 'color-32bit',
+ });
+ expect(fillRes.tileDeltas.length).toBeGreaterThan(0);
+ expect(grid.getPixelRGBA('layer-1', 2025, 3015)).toEqual([0x10, 0xa0, 0x50, 255]);
+ expect(grid.getLayerTiles('layer-1', 0).length).toBeLessThanOrEqual(2);
+
+ // Magic wand selects the exact 60x40 filled region without scanning 7016x9921
+ const wand = floodSelectWandOnTileGrid({
+ grid,
+ layers,
+ activeLayerId: 'layer-1',
+ dimensions: DOC_600_DPI,
+ startX: 2025,
+ startY: 3015,
+ settings: {
+ tolerance: 5,
+ contiguous: true,
+ referMode: 'active',
+ antiAlias: false,
+ },
+ });
+ expect(wand.bounds).toEqual({ x: 2000, y: 3000, width: 60, height: 40 });
+ expect(wand.mask[3015 * DOC_600_DPI.width + 2025]).toBe(255);
+ expect(wand.mask[2999 * DOC_600_DPI.width + 2025]).toBe(0);
+
+ const clearRes = clearSelectionInTileGrid({
+ grid,
+ layerId: 'layer-1',
+ dimensions: DOC_600_DPI,
+ selection: sel,
+ isBackground: false,
+ targetFormat: 'color-32bit',
+ });
+ expect(clearRes.tileDeltas.length).toBeGreaterThan(0);
+ expect(grid.getPixelRGBA('layer-1', 2025, 3015)).toEqual([0, 0, 0, 0]);
+ });
+
+ it('applies Gaussian blur across a tile boundary on 7016x9921 touching only populated tiles + halo', () => {
+ const grid = new SparseTileGrid();
+ // Place a 40x40 white square straddling tile boundary x=256, y=256
+ grid.writeImageData('fx', makeSolid(40, 40, 255, 255, 255, 255), 236, 236, 'color-32bit');
+
+ const res = applyFilterToTileGrid({
+ grid,
+ layerId: 'fx',
+ dimensions: DOC_600_DPI,
+ type: 'gaussian-blur',
+ filterParams: { radius: 4 },
+ targetFormat: 'color-32bit',
+ });
+
+ expect(res.tileDeltas.length).toBeGreaterThan(0);
+ // Center stays bright opaque, edge softens across boundary
+ const center = grid.getPixelRGBA('fx', 256, 256);
+ const halo = grid.getPixelRGBA('fx', 278, 256);
+ expect(center[3]).toBeGreaterThan(200);
+ expect(halo[3]).toBeGreaterThan(0);
+ expect(halo[3]).toBeLessThan(255);
+ // Only the 4 tiles around (256, 256) were allocated — not 1092 tiles
+ expect(grid.getLayerTiles('fx', 0).length).toBeLessThanOrEqual(4);
+ });
+
+ it('computes tonal histograms, previews tonal corrections, and restores exact snapshot on cancel', () => {
+ const grid = new SparseTileGrid();
+ grid.writeImageData('tone', makeSolid(30, 30, 100, 150, 200, 255), 1024, 2048, 'color-32bit');
+
+ const beforeSnapshot = grid.snapshotLayerTiles('tone');
+ const hist = computeHistogramsFromTileSnapshot(beforeSnapshot, DOC_600_DPI);
+ expect(hist.r[100]).toBe(900);
+ expect(hist.g[150]).toBe(900);
+ expect(hist.b[200]).toBe(900);
+
+ // Live preview brightness/contrast shift
+ const { tileDeltas } = applyTonalToTileGrid({
+ grid,
+ layerId: 'tone',
+ dimensions: DOC_600_DPI,
+ beforeSnapshot,
+ type: 'brightness-contrast',
+ tonalParams: { brightness: 40, contrast: 0 },
+ targetFormat: 'color-32bit',
+ });
+ expect(tileDeltas.length).toBe(1);
+ const previewPx = grid.getPixelRGBA('tone', 1030, 2055);
+ expect(previewPx[0]).toBeGreaterThan(100);
+
+ // Cancel restores exact original pixels
+ grid.restoreLayerSnapshot('tone', beforeSnapshot);
+ expect(grid.getPixelRGBA('tone', 1030, 2055)).toEqual([100, 150, 200, 255]);
+ expect(grid.getLayerTiles('tone', 0).length).toBe(1);
+ });
+
+ it('executes liquify push and reconstruct lazily on tiles without full-document snapshots', () => {
+ const grid = new SparseTileGrid();
+ // Draw a crisp red vertical bar at x=250..260, y=240..280 (straddling tile x=0 and x=1)
+ grid.writeImageData('liq', makeSolid(10, 40, 240, 20, 20, 255), 250, 240, 'color-32bit');
+
+ const beforeTileSnapshot = new Map<string, TileSnapshotEntry>();
+ const dirty = applyLiquifyStepOnTileGrid({
+ grid,
+ layerId: 'liq',
+ dimensions: DOC_600_DPI,
+ targetFormat: 'color-32bit',
+ cx: 268,
+ cy: 260,
+ prevX: 254,
+ prevY: 260,
+ settings: { mode: 'push', size: 48, strength: 100, hardness: 80, usePressure: false },
+ beforeTileSnapshot,
+ });
+
+ expect(dirty).not.toBeNull();
+ expect(beforeTileSnapshot.size).toBeLessThanOrEqual(4);
+ // Pixels were pushed right past x=260
+ expect(grid.getPixelRGBA('liq', 263, 260)[3]).toBeGreaterThan(0);
+
+ // Reconstruct restores original pixel state from beforeTileSnapshot
+ for (let i = 0; i < 6; i++) {
+ applyLiquifyStepOnTileGrid({
+ grid,
+ layerId: 'liq',
+ dimensions: DOC_600_DPI,
+ targetFormat: 'color-32bit',
+ cx: 263,
+ cy: 260,
+ prevX: 263,
+ prevY: 260,
+ settings: { mode: 'reconstruct', size: 60, strength: 100, hardness: 100, usePressure: false },
+ beforeTileSnapshot,
+ });
+ }
+ expect(grid.getPixelRGBA('liq', 263, 260)[3]).toBeLessThan(20);
+ });
+
+ it('merges layers, resizes with tile-aligned shift and offset, copies/pastes tiles, and samples composited color directly from SparseTileGrid', () => {
+ const grid = new SparseTileGrid();
+ // Bottom opaque blue, top 50% red at (512, 512)
+ grid.writeImageData('bottom', makeSolid(32, 32, 0, 0, 200, 255), 512, 512, 'color-32bit');
+ grid.writeImageData('top', makeSolid(32, 32, 200, 0, 0, 255), 512, 512, 'color-32bit');
+
+ const layers: LayerItem[] = [
+ makeRasterLayer('top', { opacity: 0.5 }),
+ makeRasterLayer('bottom', { opacity: 1 }),
+ ];
+
+ // Eyedropper samples directly from SparseTileGrid without any HTMLCanvasElement
+ const sampled = sampleCompositedColor(
+ layers,
+ grid,
+ 520,
+ 520,
+ (l) => l.visible,
+ (l) => l.opacity,
+ DOC_600_DPI.width,
+ DOC_600_DPI.height
+ );
+ expect(sampled).toBe('#640064');
+
+ // Merge top into bottom directly in SparseTileGrid
+ grid.mergeLayersInGrid('top', 'bottom', {
+ opacity: 0.5,
+ blendMode: 'normal',
+ visible: true,
+ dimensions: DOC_600_DPI,
+ dstFormat: 'color-32bit',
+ });
+ const merged = grid.getPixelRGBA('bottom', 520, 520);
+ expect(merged[0]).toBeGreaterThanOrEqual(99);
+ expect(merged[0]).toBeLessThanOrEqual(101);
+ expect(merged[2]).toBeGreaterThanOrEqual(99);
+ expect(merged[2]).toBeLessThanOrEqual(101);
+ expect(merged[3]).toBe(255);
+
+ // Copy & paste tile snapshot
+ const clip = grid.copyLayerTilesSnapshot('bottom');
+ grid.pasteLayerTilesSnapshot('pasted', clip);
+ expect(grid.getPixelRGBA('pasted', 520, 520)).toEqual(merged);
+
+ // Tile-aligned shift (+256, +512) moves zero-copy
+ grid.resizeLayerInGrid('pasted', DOC_600_DPI, DOC_600_DPI, {
+ scaleContent: false,
+ offsetX: TILE_SIZE,
+ offsetY: TILE_SIZE * 2,
+ isBackground: false,
+ backgroundColor: '#ffffff',
+ targetFormat: 'color-32bit',
+ });
+ expect(grid.getPixelRGBA('pasted', 520 + TILE_SIZE, 520 + TILE_SIZE * 2)).toEqual(merged);
+ expect(grid.getPixelRGBA('pasted', 520, 520)).toEqual([0, 0, 0, 0]);
+
+ // Sub-tile offset shift (+10, +15)
+ grid.resizeLayerInGrid('pasted', DOC_600_DPI, DOC_600_DPI, {
+ scaleContent: false,
+ offsetX: 10,
+ offsetY: 15,
+ isBackground: false,
+ backgroundColor: '#ffffff',
+ targetFormat: 'color-32bit',
+ });
+ expect(grid.getPixelRGBA('pasted', 530 + TILE_SIZE, 535 + TILE_SIZE * 2)).toEqual(merged);
+ });
+});
diff --git a/src/utils/__tests__/vectorTextBalloonSerialization.test.ts b/src/utils/__tests__/vectorTextBalloonSerialization.test.ts
index 2e8750f..454b407 100644
--- a/src/utils/__tests__/vectorTextBalloonSerialization.test.ts
+++ b/src/utils/__tests__/vectorTextBalloonSerialization.test.ts
@@ -2,11 +2,12 @@ import { describe, it, expect } from 'vitest';
import { LayerItem, TextLayerData } from '../../types/editor';
import { createDefaultSpeechBalloon } from '../balloonEngine';
import { createRectFrame } from '../frameEngine';
-import { buildSoraProjectPayload, parseSoraProjectJson } from '../saveManager';
+import { parseInkProject, serializeInkProject } from '../saveManager';
+import { parseLegacySoraV1Json } from '../legacySoraMigrator';
import { hitTestEditableVectorLayer } from '../vectorLayerRenderer';
-describe('Non-Destructive Text, Speech Balloon & Frame Folder .sora Serialization', () => {
- it('round-trips text, speech balloon, and frame-folder vector metadata through .sora JSON without loss', () => {
+describe('Non-Destructive Text, Speech Balloon & Frame Folder .ink Serialization', () => {
+ it('round-trips text, speech balloon, and frame-folder vector metadata through .ink without loss and parses legacy .sora v1 JSON', async () => {
const textData: TextLayerData = {
x: 240,
y: 180,
@@ -83,7 +84,7 @@ describe('Non-Destructive Text, Speech Balloon & Frame Folder .sora Serializatio
},
];
- const payload = buildSoraProjectPayload({
+ const serialized = await serializeInkProject({
name: 'Chapter 01 Page 05',
dimensions: { width: 1440, height: 2048, dpi: 600 },
colorMode: 'monochrome',
@@ -93,12 +94,27 @@ describe('Non-Destructive Text, Speech Balloon & Frame Folder .sora Serializatio
isLayerEffectivelyVisible: (l) => l.visible,
});
- const json = JSON.stringify(payload);
- const restored = parseSoraProjectJson(json);
+ const restored = await parseInkProject(serialized.bytes);
- expect(restored.version).toBe('1.2');
+ expect(restored.version).toBe('2.0');
expect(restored.layers).toHaveLength(4);
+ // Also verify read-only legacy .sora v1 JSON migrator retains vector metadata
+ const legacyV1 = parseLegacySoraV1Json(
+ JSON.stringify({
+ app: 'Ink Studio',
+ version: '1.2',
+ name: 'Chapter 01 Page 05',
+ dimensions: { width: 1440, height: 2048, dpi: 600 },
+ colorMode: 'monochrome',
+ layers,
+ canvases: {},
+ masks: {},
+ })
+ );
+ expect(legacyV1.layers).toHaveLength(4);
+ expect(legacyV1.layers.find((l) => l.id === 'text-layer-1')?.textData).toEqual(textData);
+
const restoredText = restored.layers.find((l) => l.id === 'text-layer-1');
expect(restoredText?.type).toBe('text');
expect(restoredText?.textData).toEqual(textData);
diff --git a/src/utils/__tests__/workspaceDock.test.tsx b/src/utils/__tests__/workspaceDock.test.tsx
index d2cacf4..bd8d921 100644
--- a/src/utils/__tests__/workspaceDock.test.tsx
+++ b/src/utils/__tests__/workspaceDock.test.tsx
@@ -425,7 +425,7 @@ describe('Activated Components (BrushSizePalette, StatusBar, DocumentTabBar) in
const docs: DocumentTab[] = [
{
id: 'doc-1',
- name: 'Chapter1.sora',
+ name: 'Chapter1.ink',
isDirty: true,
dimensions: { width: 1920, height: 1080, dpi: 300 },
colorMode: 'color',
@@ -434,7 +434,7 @@ describe('Activated Components (BrushSizePalette, StatusBar, DocumentTabBar) in
},
{
id: 'doc-2',
- name: 'Cover.sora',
+ name: 'Cover.ink',
isDirty: false,
dimensions: { width: 2480, height: 3508, dpi: 600 },
colorMode: 'monochrome',
diff --git a/src/utils/animationEngine.ts b/src/utils/animationEngine.ts
index 702c88d..096171e 100644
--- a/src/utils/animationEngine.ts
+++ b/src/utils/animationEngine.ts
@@ -1,5 +1,6 @@
import { zipSync } from 'fflate';
import { AnimationTimeline, OnionSkinSettings, LayerItem } from '../types/editor';
+import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';
export interface OnionSkinFrameInfo {
frame: number;
@@ -152,7 +153,7 @@ export function renderTintedCanvas(
/**
* Composites a single animation frame onto an offscreen canvas.
- * Renders background layers, optional colored onion skinning, active cel, and foreground layers.
+ * Reads directly from SparseTileGrid (or optional legacy layerCanvases map for tests).
*/
export function renderAnimationFrame(
frameIndex: number,
@@ -160,7 +161,8 @@ export function renderAnimationFrame(
layers: LayerItem[],
layerCanvases: Map<string, HTMLCanvasElement>,
dimensions: { width: number; height: number },
- includeOnionSkin: boolean = false
+ includeOnionSkin: boolean = false,
+ tileGrid?: SparseTileGrid
): HTMLCanvasElement {
const canvas = document.createElement('canvas');
canvas.width = dimensions.width;
@@ -168,6 +170,15 @@ export function renderAnimationFrame(
const ctx = canvas.getContext('2d');
if (!ctx) return canvas;
+ const acquireLayerCanvas = (id: string): { c: HTMLCanvasElement | null; temp: boolean } => {
+ const existing = layerCanvases.get(id);
+ if (existing) return { c: existing, temp: false };
+ if (tileGrid && tileGrid.hasLayerTiles(id)) {
+ return { c: tileGrid.exportLayerToCanvas(id, dimensions.width, dimensions.height), temp: true };
+ }
+ return { c: null, temp: false };
+ };
+
// Clear canvas
ctx.clearRect(0, 0, dimensions.width, dimensions.height);
@@ -204,7 +215,7 @@ export function renderAnimationFrame(
currentFrame: frameIndex,
});
for (const info of onionFrames) {
- const oc = layerCanvases.get(info.layerId);
+ const { c: oc, temp } = acquireLayerCanvas(info.layerId);
if (oc) {
const tinted = renderTintedCanvas(oc, info.tint, info.opacity);
ctx.save?.();
@@ -212,10 +223,12 @@ export function renderAnimationFrame(
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(tinted, 0, 0);
ctx.restore?.();
+ releaseTemporaryCanvas(tinted);
+ if (temp) releaseTemporaryCanvas(oc);
}
}
}
- const celCanvas = layerCanvases.get(activeCelLayerId);
+ const { c: celCanvas, temp: celTemp } = acquireLayerCanvas(activeCelLayerId);
if (celCanvas) {
ctx.save?.();
ctx.globalAlpha = getEffOpacity(layer);
@@ -224,12 +237,13 @@ export function renderAnimationFrame(
ctx.globalAlpha = 1.0;
ctx.globalCompositeOperation = 'source-over';
ctx.restore?.();
+ if (celTemp) releaseTemporaryCanvas(celCanvas);
}
}
continue;
}
- const c = layerCanvases.get(layer.id);
+ const { c, temp } = acquireLayerCanvas(layer.id);
if (c) {
ctx.save?.();
ctx.globalAlpha = getEffOpacity(layer);
@@ -238,6 +252,7 @@ export function renderAnimationFrame(
ctx.globalAlpha = 1.0;
ctx.globalCompositeOperation = 'source-over';
ctx.restore?.();
+ if (temp) releaseTemporaryCanvas(c);
}
}
@@ -248,13 +263,15 @@ export function renderAnimationFrame(
currentFrame: frameIndex,
});
for (const info of onionFrames) {
- const c = layerCanvases.get(info.layerId);
+ const { c, temp } = acquireLayerCanvas(info.layerId);
if (c) {
const tinted = renderTintedCanvas(c, info.tint, info.opacity);
ctx.save?.();
ctx.globalAlpha = 1.0;
ctx.drawImage(tinted, 0, 0);
ctx.restore?.();
+ releaseTemporaryCanvas(tinted);
+ if (temp) releaseTemporaryCanvas(c);
}
}
}
@@ -284,14 +301,15 @@ export async function exportAnimationToPngZip(
layers: LayerItem[],
layerCanvases: Map<string, HTMLCanvasElement>,
dimensions: { width: number; height: number },
- onProgress?: (current: number, total: number) => void
+ onProgress?: (current: number, total: number) => void,
+ tileGrid?: SparseTileGrid
): Promise<Blob> {
const files: Record<string, Uint8Array> = {};
const total = timeline.totalFrames;
for (let f = 0; f < total; f++) {
onProgress?.(f + 1, total);
- const frameCanvas = renderAnimationFrame(f, timeline, layers, layerCanvases, dimensions, false);
+ const frameCanvas = renderAnimationFrame(f, timeline, layers, layerCanvases, dimensions, false, tileGrid);
// Convert canvas to PNG bytes via DataURL
const dataUrl = frameCanvas.toDataURL('image/png');
@@ -318,7 +336,8 @@ export async function exportAnimationToVideo(
layers: LayerItem[],
layerCanvases: Map<string, HTMLCanvasElement>,
dimensions: { width: number; height: number },
- onProgress?: (current: number, total: number) => void
+ onProgress?: (current: number, total: number) => void,
+ tileGrid?: SparseTileGrid
): Promise<Blob> {
const { fps, totalFrames } = timeline;
@@ -366,9 +385,10 @@ export async function exportAnimationToVideo(
}
onProgress?.(frame + 1, totalFrames);
- const frameCanvas = renderAnimationFrame(frame, timeline, layers, layerCanvases, dimensions, false);
+ const frameCanvas = renderAnimationFrame(frame, timeline, layers, layerCanvases, dimensions, false, tileGrid);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(frameCanvas, 0, 0);
+ releaseTemporaryCanvas(frameCanvas);
frame++;
setTimeout(renderNext, delayMs);
@@ -386,7 +406,8 @@ export async function exportAnimationToGif(
layers: LayerItem[],
layerCanvases: Map<string, HTMLCanvasElement>,
dimensions: { width: number; height: number },
- onProgress?: (current: number, total: number) => void
+ onProgress?: (current: number, total: number) => void,
+ tileGrid?: SparseTileGrid
): Promise<Blob> {
const { fps, totalFrames } = timeline;
const width = Math.min(1280, dimensions.width);
@@ -415,10 +436,11 @@ export async function exportAnimationToGif(
for (let f = 0; f < totalFrames; f++) {
onProgress?.(f + 1, totalFrames);
- const fullCanvas = renderAnimationFrame(f, timeline, layers, layerCanvases, dimensions, false);
+ const fullCanvas = renderAnimationFrame(f, timeline, layers, layerCanvases, dimensions, false, tileGrid);
rCtx.clearRect(0, 0, width, height);
rCtx.drawImage(fullCanvas, 0, 0, width, height);
+ releaseTemporaryCanvas(fullCanvas);
const imgData = rCtx.getImageData(0, 0, width, height);
const pixels = imgData.data;
@@ -506,7 +528,8 @@ export async function exportAnimationToApng(
layers: LayerItem[],
layerCanvases: Map<string, HTMLCanvasElement>,
dimensions: { width: number; height: number },
- onProgress?: (current: number, total: number) => void
+ onProgress?: (current: number, total: number) => void,
+ tileGrid?: SparseTileGrid
): Promise<Blob> {
const { fps, totalFrames } = timeline;
const numFrames = totalFrames;
@@ -515,8 +538,9 @@ export async function exportAnimationToApng(
const framePngBuffers: ArrayBuffer[] = [];
for (let f = 0; f < numFrames; f++) {
onProgress?.(f + 1, numFrames);
- const canvas = renderAnimationFrame(f, timeline, layers, layerCanvases, dimensions, false);
+ const canvas = renderAnimationFrame(f, timeline, layers, layerCanvases, dimensions, false, tileGrid);
const dataUrl = canvas.toDataURL('image/png');
+ releaseTemporaryCanvas(canvas);
const base64 = dataUrl.split(',')[1];
const binStr = atob(base64);
const buf = new Uint8Array(binStr.length);
diff --git a/src/utils/asyncCompression.ts b/src/utils/asyncCompression.ts
index 8d01ef4..8cb3012 100644
--- a/src/utils/asyncCompression.ts
+++ b/src/utils/asyncCompression.ts
@@ -7,6 +7,11 @@
*/
import { deflateSync, inflateSync, zlibSync, unzlibSync } from 'fflate';
+import {
+ flateCompressNative,
+ flateDecompressNative,
+ isNativeRustAvailable,
+} from './nativeBackend';
import type {
CompressionOp,
CompressionRequest,
@@ -205,6 +210,9 @@ export function deflateAsync(
data: Uint8Array,
options?: AsyncCompressionOptions
): Promise<Uint8Array> {
+ if (isNativeRustAvailable()) {
+ return flateCompressNative('deflate', data, options?.level ?? 1);
+ }
return dispatchToWorker('deflate', data, options);
}
@@ -212,6 +220,9 @@ export function inflateAsync(
data: Uint8Array,
options?: AsyncCompressionOptions
): Promise<Uint8Array> {
+ if (isNativeRustAvailable()) {
+ return flateDecompressNative('inflate', data, options?.maxOutputBytes);
+ }
return dispatchToWorker('inflate', data, options);
}
@@ -219,6 +230,9 @@ export function zlibAsync(
data: Uint8Array,
options?: AsyncCompressionOptions
): Promise<Uint8Array> {
+ if (isNativeRustAvailable()) {
+ return flateCompressNative('zlib', data, options?.level ?? 1);
+ }
return dispatchToWorker('zlib', data, options);
}
@@ -226,6 +240,9 @@ export function unzlibAsync(
data: Uint8Array,
options?: AsyncCompressionOptions
): Promise<Uint8Array> {
+ if (isNativeRustAvailable()) {
+ return flateDecompressNative('unzlib', data, options?.maxOutputBytes);
+ }
return dispatchToWorker('unzlib', data, options);
}
diff --git a/src/utils/brushAssetSync.ts b/src/utils/brushAssetSync.ts
new file mode 100644
index 0000000..3c1f1cc
--- /dev/null
+++ b/src/utils/brushAssetSync.ts
@@ -0,0 +1,487 @@
+/**
+ * Content-addressed brush asset synchronization (tip, dualTip, paperTexture, subTips).
+ * Strips inline base64 data URLs and DOM HTMLImageElements from STROKE_START, replacing them
+ * with 128-bit content hashes and binary BRUSH_ASSET_DATA transfers verified by hash.
+ */
+
+import type { BrushSettings, CspSubTip } from '../types/editor';
+import type { BrushAssetRefs, SubTipAssetRef } from '../types/multiplayer';
+
+export const MAX_BRUSH_ASSET_BYTES = 2 * 1024 * 1024; // 2 MB per asset ceiling
+export const MAX_CACHED_BRUSH_ASSETS = 128;
+export const MAX_SUB_TIPS_PER_BRUSH = 16;
+
+const ALLOWED_MIMES = new Set(['image/png', 'image/webp', 'image/jpeg']);
+const HASH_RE = /^[0-9a-f]{32}$/;
+
+export interface BrushAssetRecord {
+ hash: string;
+ mime: string;
+ bytes: Uint8Array;
+ image: HTMLImageElement | null;
+ objectUrl: string | null;
+ ready: boolean;
+}
+
+const assetByHash = new Map<string, BrushAssetRecord>();
+const hashByDataUrl = new Map<string, string>();
+const readyListeners = new Map<string, Set<(img: HTMLImageElement) => void>>();
+
+/**
+ * Deterministic, synchronous 128-bit content hash (4 independent mixed FNV-1a/avalanche lanes)
+ * encoded as 32 lowercase hex chars. Fast enough for pointerdown without async races.
+ */
+export function computeBrushAssetHash(bytes: Uint8Array): string {
+ let h1 = 0x811c9dc5;
+ let h2 = 0x01000193;
+ let h3 = 0x9e3779b9;
+ let h4 = 0x85ebca6b;
+
+ const len = bytes.byteLength;
+ for (let i = 0; i < len; i++) {
+ const b = bytes[i];
+ h1 = Math.imul(h1 ^ b, 0x01000193);
+ h2 = Math.imul(h2 ^ ((b + i) & 0xff), 0x85ebca6b);
+ h3 = Math.imul(h3 ^ (b ^ (i >>> 8)), 0xc2b2ae35);
+ h4 = Math.imul(h4 ^ ((b * 31 + i) & 0xff), 0x27d4eb2f);
+ }
+
+ // Mix length and final avalanche
+ h1 ^= len;
+ h2 ^= len * 3;
+ h3 ^= len * 7;
+ h4 ^= len * 13;
+
+ const mix32 = (v: number): number => {
+ v ^= v >>> 16;
+ v = Math.imul(v, 0x85ebca6b);
+ v ^= v >>> 13;
+ v = Math.imul(v, 0xc2b2ae35);
+ v ^= v >>> 16;
+ return v >>> 0;
+ };
+
+ return (
+ mix32(h1 ^ h3).toString(16).padStart(8, '0') +
+ mix32(h2 ^ h4).toString(16).padStart(8, '0') +
+ mix32(h3 ^ h2).toString(16).padStart(8, '0') +
+ mix32(h4 ^ h1).toString(16).padStart(8, '0')
+ );
+}
+
+export function isValidBrushAssetHash(hash: unknown): hash is string {
+ return typeof hash === 'string' && HASH_RE.test(hash);
+}
+
+export function isAllowedBrushAssetMime(mime: unknown): mime is string {
+ return typeof mime === 'string' && ALLOWED_MIMES.has(mime);
+}
+
+function decodeBase64ToBytes(b64: string): Uint8Array | null {
+ try {
+ if (typeof atob !== 'function') return null;
+ const bin = atob(b64);
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) {
+ out[i] = bin.charCodeAt(i);
+ }
+ return out;
+ } catch {
+ return null;
+ }
+}
+
+function parseImageDataUrl(dataUrl: string): { mime: string; bytes: Uint8Array } | null {
+ if (!dataUrl.startsWith('data:')) return null;
+ const commaIdx = dataUrl.indexOf(',');
+ if (commaIdx <= 5) return null;
+ const meta = dataUrl.slice(5, commaIdx);
+ if (!meta.endsWith(';base64')) return null;
+ const mime = meta.slice(0, -7).toLowerCase();
+ if (!ALLOWED_MIMES.has(mime)) return null;
+ const b64 = dataUrl.slice(commaIdx + 1);
+ // Rough pre-check before decoding to avoid allocating huge buffers
+ if (b64.length * 0.76 > MAX_BRUSH_ASSET_BYTES + 16) return null;
+ const bytes = decodeBase64ToBytes(b64);
+ if (!bytes || bytes.byteLength === 0 || bytes.byteLength > MAX_BRUSH_ASSET_BYTES) {
+ return null;
+ }
+ return { mime, bytes };
+}
+
+function evictIfNeeded(): void {
+ while (assetByHash.size >= MAX_CACHED_BRUSH_ASSETS) {
+ const oldestKey = assetByHash.keys().next().value;
+ if (!oldestKey) break;
+ const evicted = assetByHash.get(oldestKey);
+ assetByHash.delete(oldestKey);
+ if (evicted?.objectUrl && typeof URL !== 'undefined' && typeof URL.revokeObjectURL === 'function') {
+ try {
+ URL.revokeObjectURL(evicted.objectUrl);
+ } catch {
+ // ignore revoke errors
+ }
+ }
+ }
+}
+
+function notifyAssetReady(hash: string, img: HTMLImageElement): void {
+ const listeners = readyListeners.get(hash);
+ if (!listeners || listeners.size === 0) return;
+ for (const cb of listeners) {
+ try {
+ cb(img);
+ } catch {
+ // isolate callback failures
+ }
+ }
+ readyListeners.delete(hash);
+}
+
+function decodeAssetImage(record: BrushAssetRecord, existingImage?: HTMLImageElement): void {
+ if (existingImage && existingImage.complete && (existingImage.naturalWidth || existingImage.width) > 0) {
+ record.image = existingImage;
+ record.ready = true;
+ notifyAssetReady(record.hash, existingImage);
+ return;
+ }
+ if (typeof Image === 'undefined') return;
+
+ const img = new Image();
+ img.crossOrigin = 'anonymous';
+ const markReady = () => {
+ if ((img.naturalWidth || img.width) > 0) {
+ record.image = img;
+ record.ready = true;
+ notifyAssetReady(record.hash, img);
+ }
+ };
+ img.onload = markReady;
+
+ if (
+ typeof Blob !== 'undefined' &&
+ typeof URL !== 'undefined' &&
+ typeof URL.createObjectURL === 'function'
+ ) {
+ const blobBytes = new Uint8Array(record.bytes.byteLength);
+ blobBytes.set(record.bytes);
+ const blob = new Blob([blobBytes], { type: record.mime });
+ const objUrl = URL.createObjectURL(blob);
+ record.objectUrl = objUrl;
+ img.src = objUrl;
+ } else {
+ return;
+ }
+
+ record.image = img;
+ if (typeof img.decode === 'function') {
+ img.decode().then(markReady).catch(() => {});
+ }
+}
+
+function registerLocalDataUrl(
+ dataUrl: string | undefined,
+ existingImage?: HTMLImageElement
+): BrushAssetRecord | null {
+ if (!dataUrl) return null;
+ const cachedHash = hashByDataUrl.get(dataUrl);
+ if (cachedHash) {
+ const existing = assetByHash.get(cachedHash);
+ if (existing) {
+ if (!existing.ready && existingImage?.complete && (existingImage.naturalWidth || existingImage.width) > 0) {
+ existing.image = existingImage;
+ existing.ready = true;
+ }
+ return existing;
+ }
+ }
+
+ const parsed = parseImageDataUrl(dataUrl);
+ if (!parsed) return null;
+
+ const hash = computeBrushAssetHash(parsed.bytes);
+ hashByDataUrl.set(dataUrl, hash);
+
+ const existing = assetByHash.get(hash);
+ if (existing) return existing;
+
+ evictIfNeeded();
+ const record: BrushAssetRecord = {
+ hash,
+ mime: parsed.mime,
+ bytes: parsed.bytes,
+ image: null,
+ objectUrl: null,
+ ready: false,
+ };
+ assetByHash.set(hash, record);
+ decodeAssetImage(record, existingImage);
+ return record;
+}
+
+/**
+ * Strips inline base64 URLs and non-serializable HTMLImageElements from BrushSettings,
+ * returning compact hash references and the unique binary asset records for transport.
+ */
+export function prepareBrushSettingsForWire(bs: BrushSettings): {
+ wireSettings: BrushSettings;
+ assetRefs?: BrushAssetRefs;
+ assets: BrushAssetRecord[];
+} {
+ const assetsByHash = new Map<string, BrushAssetRecord>();
+ const refs: BrushAssetRefs = {};
+
+ const tipRec = registerLocalDataUrl(bs.customTipDataUrl, bs.customTipImage);
+ if (tipRec) {
+ refs.tipHash = tipRec.hash;
+ assetsByHash.set(tipRec.hash, tipRec);
+ }
+
+ const dualRec = registerLocalDataUrl(bs.dualTipDataUrl, bs.dualTipImage);
+ if (dualRec) {
+ refs.dualTipHash = dualRec.hash;
+ assetsByHash.set(dualRec.hash, dualRec);
+ }
+
+ const paperRec = registerLocalDataUrl(bs.paperTexture, bs.paperTextureImage);
+ if (paperRec) {
+ refs.paperTextureHash = paperRec.hash;
+ assetsByHash.set(paperRec.hash, paperRec);
+ }
+
+ if (bs.subTips && bs.subTips.length > 0) {
+ const subRefs: SubTipAssetRef[] = [];
+ const limit = Math.min(bs.subTips.length, MAX_SUB_TIPS_PER_BRUSH);
+ for (let i = 0; i < limit; i++) {
+ const st = bs.subTips[i];
+ const rec = registerLocalDataUrl(st.dataUrl, bs.subTipImages?.[i]);
+ if (rec) {
+ subRefs.push({
+ hash: rec.hash,
+ width: st.width,
+ height: st.height,
+ isColor: st.isColor,
+ });
+ assetsByHash.set(rec.hash, rec);
+ }
+ }
+ if (subRefs.length > 0) {
+ refs.subTipHashes = subRefs;
+ }
+ }
+
+ const {
+ customTipDataUrl: _tipUrl,
+ customTipImage: _tipImg,
+ dualTipDataUrl: _dualUrl,
+ dualTipImage: _dualImg,
+ paperTexture: _paperUrl,
+ paperTextureImage: _paperImg,
+ subTips: _subTips,
+ subTipImages: _subImgs,
+ ...clean
+ } = bs;
+
+ const hasRefs = Boolean(
+ refs.tipHash || refs.dualTipHash || refs.paperTextureHash || refs.subTipHashes?.length
+ );
+
+ return {
+ wireSettings: clean as BrushSettings,
+ assetRefs: hasRefs ? refs : undefined,
+ assets: Array.from(assetsByHash.values()),
+ };
+}
+
+/**
+ * Verifies hash integrity and registers a binary brush asset received from a remote peer.
+ */
+export function registerRemoteBrushAsset(
+ hash: string,
+ mime: string,
+ bytes: Uint8Array
+): boolean {
+ if (!isValidBrushAssetHash(hash)) return false;
+ if (!isAllowedBrushAssetMime(mime)) return false;
+ if (!bytes || bytes.byteLength === 0 || bytes.byteLength > MAX_BRUSH_ASSET_BYTES) {
+ return false;
+ }
+
+ const actualHash = computeBrushAssetHash(bytes);
+ if (actualHash !== hash) {
+ return false;
+ }
+
+ const existing = assetByHash.get(hash);
+ if (existing) {
+ if (!existing.ready && !existing.image) {
+ decodeAssetImage(existing);
+ }
+ return true;
+ }
+
+ evictIfNeeded();
+ const ownedBytes = new Uint8Array(bytes.byteLength);
+ ownedBytes.set(bytes);
+
+ const record: BrushAssetRecord = {
+ hash,
+ mime,
+ bytes: ownedBytes,
+ image: null,
+ objectUrl: null,
+ ready: false,
+ };
+ assetByHash.set(hash, record);
+ decodeAssetImage(record);
+ return true;
+}
+
+export function getBrushAssetRecord(hash: string): BrushAssetRecord | null {
+ if (!isValidBrushAssetHash(hash)) return null;
+ return assetByHash.get(hash) ?? null;
+}
+
+export function getReadyBrushAssetImage(hash?: string): HTMLImageElement | null {
+ if (!hash || !isValidBrushAssetHash(hash)) return null;
+ const rec = assetByHash.get(hash);
+ if (!rec || !rec.ready || !rec.image) return null;
+ return rec.image;
+}
+
+export function onBrushAssetReady(
+ hash: string,
+ cb: (img: HTMLImageElement) => void
+): () => void {
+ if (!isValidBrushAssetHash(hash)) return () => {};
+ const existing = assetByHash.get(hash);
+ if (existing?.ready && existing.image) {
+ cb(existing.image);
+ return () => {};
+ }
+ let set = readyListeners.get(hash);
+ if (!set) {
+ set = new Set();
+ readyListeners.set(hash, set);
+ }
+ set.add(cb);
+ return () => {
+ set?.delete(cb);
+ if (set && set.size === 0) {
+ readyListeners.delete(hash);
+ }
+ };
+}
+
+/**
+ * Hydrates a remote BrushSettings object with decoded HTMLImageElements from the hash cache.
+ * Returns lists of missing hashes (need BRUSH_ASSET_REQUEST) and pending hashes (still decoding).
+ */
+export function hydrateBrushSettingsFromHashes(
+ bs: BrushSettings,
+ refs?: BrushAssetRefs
+): {
+ hydrated: BrushSettings;
+ missingHashes: string[];
+ pendingHashes: string[];
+} {
+ if (!refs) {
+ return { hydrated: bs, missingHashes: [], pendingHashes: [] };
+ }
+
+ const missingSet = new Set<string>();
+ const pendingSet = new Set<string>();
+ const hydrated: BrushSettings = { ...bs };
+
+ const resolveHash = (hash?: string): HTMLImageElement | undefined => {
+ if (!hash || !isValidBrushAssetHash(hash)) return undefined;
+ const rec = assetByHash.get(hash);
+ if (!rec) {
+ missingSet.add(hash);
+ return undefined;
+ }
+ if (!rec.ready || !rec.image) {
+ pendingSet.add(hash);
+ return undefined;
+ }
+ return rec.image;
+ };
+
+ if (refs.tipHash) {
+ hydrated.customTipImage = resolveHash(refs.tipHash);
+ }
+ if (refs.dualTipHash) {
+ hydrated.dualTipImage = resolveHash(refs.dualTipHash);
+ }
+ if (refs.paperTextureHash) {
+ hydrated.paperTextureImage = resolveHash(refs.paperTextureHash);
+ }
+ if (refs.subTipHashes && refs.subTipHashes.length > 0) {
+ const subImages: HTMLImageElement[] = [];
+ const subTips: CspSubTip[] = [];
+ let allReady = true;
+ for (const ref of refs.subTipHashes) {
+ const img = resolveHash(ref.hash);
+ if (!img) {
+ allReady = false;
+ } else {
+ subImages.push(img);
+ subTips.push({
+ dataUrl: '',
+ width: ref.width,
+ height: ref.height,
+ isColor: ref.isColor,
+ });
+ }
+ }
+ if (allReady && subImages.length > 0) {
+ hydrated.subTipImages = subImages;
+ hydrated.subTips = subTips;
+ }
+ }
+
+ return {
+ hydrated,
+ missingHashes: Array.from(missingSet),
+ pendingHashes: Array.from(pendingSet),
+ };
+}
+
+export function sanitizeBrushAssetRefs(raw: unknown): BrushAssetRefs | undefined {
+ if (!raw || typeof raw !== 'object') return undefined;
+ const r = raw as BrushAssetRefs;
+ const out: BrushAssetRefs = {};
+ if (isValidBrushAssetHash(r.tipHash)) out.tipHash = r.tipHash;
+ if (isValidBrushAssetHash(r.dualTipHash)) out.dualTipHash = r.dualTipHash;
+ if (isValidBrushAssetHash(r.paperTextureHash)) out.paperTextureHash = r.paperTextureHash;
+ if (Array.isArray(r.subTipHashes)) {
+ const list: SubTipAssetRef[] = [];
+ const limit = Math.min(r.subTipHashes.length, MAX_SUB_TIPS_PER_BRUSH);
+ for (let i = 0; i < limit; i++) {
+ const item = r.subTipHashes[i];
+ if (!item || typeof item !== 'object' || !isValidBrushAssetHash(item.hash)) continue;
+ const w = Number.isFinite(item.width) ? Math.max(1, Math.min(2048, Math.round(item.width))) : 64;
+ const h = Number.isFinite(item.height) ? Math.max(1, Math.min(2048, Math.round(item.height))) : 64;
+ list.push({ hash: item.hash, width: w, height: h, isColor: Boolean(item.isColor) });
+ }
+ if (list.length > 0) out.subTipHashes = list;
+ }
+ return out.tipHash || out.dualTipHash || out.paperTextureHash || out.subTipHashes
+ ? out
+ : undefined;
+}
+
+export function resetBrushAssetCache(): void {
+ for (const rec of assetByHash.values()) {
+ if (rec.objectUrl && typeof URL !== 'undefined' && typeof URL.revokeObjectURL === 'function') {
+ try {
+ URL.revokeObjectURL(rec.objectUrl);
+ } catch {
+ // ignore
+ }
+ }
+ }
+ assetByHash.clear();
+ hashByDataUrl.clear();
+ readyListeners.clear();
+}
diff --git a/src/utils/brushPresetManager.ts b/src/utils/brushPresetManager.ts
index ef3d400..658bfa6 100644
--- a/src/utils/brushPresetManager.ts
+++ b/src/utils/brushPresetManager.ts
@@ -47,10 +47,10 @@ export function stepBrushSizePreset(currentSize: number, direction: -1 | 1): num
}
}
-export const STORAGE_KEY_SETTINGS = 'sora_paint_brush_settings_by_id';
-export const STORAGE_KEY_ACTIVE_PRESET = 'sora_paint_active_brush_preset';
-export const STORAGE_KEY_BOTTOM_TAB = 'sora_paint_left_bottom_tab';
-const STORAGE_KEY_PRESET_SCHEMA = 'sora_paint_brush_preset_schema_v';
+export const STORAGE_KEY_SETTINGS = 'ink_studio_brush_settings_by_id';
+export const STORAGE_KEY_ACTIVE_PRESET = 'ink_studio_active_brush_preset';
+export const STORAGE_KEY_BOTTOM_TAB = 'ink_studio_left_bottom_tab';
+const STORAGE_KEY_PRESET_SCHEMA = 'ink_studio_brush_preset_schema_v';
const BUILTIN_PRESET_SCHEMA_VERSION = 2;
const SKETCH_PRESET_IDS = [
'mechanical-pencil',
diff --git a/src/utils/brushPreview.ts b/src/utils/brushPreview.ts
index e998337..d829bfc 100644
--- a/src/utils/brushPreview.ts
+++ b/src/utils/brushPreview.ts
@@ -8,16 +8,19 @@ import {
CspSpraySettings,
CspTipFlipMode,
} from '../types/editor';
-import { PENCIL_CONFIGS, PencilGrade, getPaperGrain, getGraphiteTipMaster } from './pencilEngine';
-import { getTintedTipMaster, getRadialDabMaster, drawSingleStamp } from './stampEngine';
import { getBuiltinBrushConfig } from './presetBrushes';
import {
+ getLegacyPencilPresetDefaults,
+ getPaperGrain,
+ getTintedTipMaster,
+ getRadialDabMaster,
+ drawSingleStamp,
evaluateFastSpline,
dabHashFloat,
computeGapAdjustedAlpha,
resolveTipFlipSigns,
applyCspPaperTextureAlpha,
-} from '../engine/CspBrushEngine';
+} from '../engine/BrushEngine';
export interface BrushPreviewOptions {
preset?: BrushPresetId;
@@ -115,18 +118,17 @@ export function renderBrushStrokePreview(
const preset = options.preset || (options.customTipImage ? 'custom' : 'g-pen');
const builtinCfg =
- !options.customTipImage && options.preset ? getBuiltinBrushConfig(options.preset) : null;
+ !options.customTipImage && options.preset
+ ? getBuiltinBrushConfig(options.preset) || getLegacyPencilPresetDefaults(options.preset)
+ : null;
const tipImage = options.customTipImage || builtinCfg?.customTipImage;
- const isPencil = !tipImage && preset.startsWith('pencil');
- const pencilConfig = isPencil ? PENCIL_CONFIGS[preset as PencilGrade] : null;
- const size = options.size ?? pencilConfig?.defaultSize ?? builtinCfg?.size ?? 14;
- const flow = options.flow ?? pencilConfig?.flow ?? builtinCfg?.flow ?? 0.85;
+ const size = options.size ?? builtinCfg?.size ?? 14;
+ const flow = options.flow ?? builtinCfg?.flow ?? 0.85;
const opacity = options.opacity ?? builtinCfg?.opacity ?? 1.0;
- const grain = options.grain ?? pencilConfig?.grain ?? builtinCfg?.grain ?? 0;
- const hardness = options.hardness ?? pencilConfig?.hardness ?? builtinCfg?.hardness ?? 1.0;
- const minSizeFactor =
- options.minSizeFactor ?? pencilConfig?.minSizeFactor ?? builtinCfg?.minSizeFactor ?? 0.15;
+ const grain = options.grain ?? builtinCfg?.grain ?? 0;
+ const hardness = options.hardness ?? builtinCfg?.hardness ?? 1.0;
+ const minSizeFactor = options.minSizeFactor ?? builtinCfg?.minSizeFactor ?? 0.15;
const thickness = options.thickness ?? builtinCfg?.thickness ?? 1.0;
const thicknessVertical = Boolean(options.thicknessVertical ?? builtinCfg?.thicknessVertical);
const customTipAngle = options.customTipAngle ?? builtinCfg?.customTipAngle ?? 0;
@@ -137,7 +139,7 @@ export function renderBrushStrokePreview(
const paperContrast = options.paperTextureContrast ?? builtinCfg?.paperTextureContrast ?? 0;
const paperBrightness = options.paperTextureBrightness ?? builtinCfg?.paperTextureBrightness ?? 0;
const paperInverted = Boolean(options.paperTextureInverted ?? builtinCfg?.paperTextureInverted);
- const spacing = options.spacing ?? builtinCfg?.spacing ?? (isPencil ? 0.07 : 0.045);
+ const spacing = options.spacing ?? builtinCfg?.spacing ?? 0.045;
const blendTipsMode = options.blendTipsMode ?? builtinCfg?.blendTipsMode ?? 'darken';
const adjustByGap = Boolean(options.adjustDensityByGap ?? builtinCfg?.adjustDensityByGap);
const aaLevel = clamp(
@@ -424,53 +426,6 @@ export function renderBrushStrokePreview(
}
}
offCtx.restore();
- } else if (isPencil && pencilConfig) {
- offCtx.save();
- offCtx.globalAlpha = clamp(opacity, 0.05, 1.0);
-
- const graphiteMaster = getGraphiteTipMaster(preset as PencilGrade, strokeColor);
- const baseThreshold = pencilConfig.thresholdBase;
- const sens = pencilConfig.thresholdPressureSensitivity;
- const effFlow = flow * pencilConfig.flow;
- const effSpacing = clamp(spacing, 0.02, 0.12);
-
- let distanceAcc = 0;
- for (let i = 0; i < pts.length - 1; i++) {
- const p1 = pts[i];
- const p2 = pts[i + 1];
- const segDist = Math.hypot(p2.x - p1.x, p2.y - p1.y);
- const stepCount = Math.max(1, Math.ceil(segDist / 0.6));
- for (let s = 0; s < stepCount; s++) {
- const t = s / stepCount;
- const curX = p1.x + t * (p2.x - p1.x);
- const curY = p1.y + t * (p2.y - p1.y);
- const curW = p1.width + t * (p2.width - p1.width);
- const curP = p1.pressure + t * (p2.pressure - p1.pressure);
- const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
-
- const requiredStep = Math.max(0.4, curW * effSpacing);
- distanceAcc += segDist / stepCount;
- if (distanceAcc >= requiredStep) {
- distanceAcc = 0;
- const paperHeight = getPaperGrain(curX * 1.6, curY * 1.6);
- const effThreshold = Math.max(15, baseThreshold - curP * sens + (1 - grain) * 40);
-
- if (paperHeight >= effThreshold) {
- const heightFactor = Math.min(1.0, (paperHeight - effThreshold + 25) / 55);
- const dabAlpha = clamp(
- effFlow * (0.35 + 0.65 * curP) * heightFactor * curTipAlpha,
- 0.04,
- 1.0
- );
- drawSingleStamp(offCtx, graphiteMaster, curX, curY, curW, curW, 0, dabAlpha);
- } else if (curP > 0.55) {
- const dabAlpha = clamp(effFlow * 0.16 * curP * curTipAlpha, 0.02, 1.0);
- drawSingleStamp(offCtx, graphiteMaster, curX, curY, curW, curW, 0, dabAlpha);
- }
- }
- }
- }
- offCtx.restore();
} else {
offCtx.save();
const effHardness = clamp(hardness, 0.0, 1.0);
@@ -549,7 +504,22 @@ export function renderBrushStrokePreview(
const baseW = Math.max(0.7, curW);
const stampW = thicknessVertical ? baseW * thickness : baseW;
const stampH = thicknessVertical ? baseW : baseW * thickness;
- const alpha = clamp(opacity * effFlow * curTipAlpha, 0.02, 1.0);
+ let alpha = clamp(opacity * effFlow * curTipAlpha, 0.02, 1.0);
+ if (grain > 0.01) {
+ const curP = p1.pressure + t * (p2.pressure - p1.pressure);
+ const gNorm = getPaperGrain((curX * 1.4) / Math.max(0.2, paperScale), (curY * 1.4) / Math.max(0.2, paperScale)) / 255.0;
+ alpha = applyCspPaperTextureAlpha(
+ alpha,
+ gNorm,
+ grain,
+ curP,
+ paperMode,
+ paperBrightness,
+ paperContrast,
+ paperInverted
+ );
+ }
+ if (alpha <= 0.005) continue;
drawSingleStamp(
offCtx,
master,
diff --git a/src/utils/brushStorage.ts b/src/utils/brushStorage.ts
index aa5d9a1..0475d69 100644
--- a/src/utils/brushStorage.ts
+++ b/src/utils/brushStorage.ts
@@ -5,10 +5,10 @@ import {
safeLocalStorageSetItem,
} from './safeStorage';
-const DB_NAME = 'SoraPaintBrushesDB';
+const DB_NAME = 'InkStudioBrushesDB';
const DB_VERSION = 1;
const STORE_NAME = 'csp_brushes';
-export const BRUSH_INDEX_LS_KEY = 'sora_paint_custom_brushes';
+export const BRUSH_INDEX_LS_KEY = 'ink_studio_custom_brushes';
export const CUSTOM_BRUSHES_CHANGED_EVENT = 'ink-custom-brushes-changed';
diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.ts
index 8e62dae..93da23b 100644
--- a/src/utils/canvasUtils.ts
+++ b/src/utils/canvasUtils.ts
@@ -1,21 +1,5 @@
-import { Point, CanvasDimensions, BlendMode, ToolType, BrushSettings, CanvasColorMode, LayerItem } from '../types/editor';
-import { enforceColorMode } from './colorUtils';
-import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from './pencilEngine';
-import {
- renderCompleteTexturedStroke,
- TexturedBrushOptions,
- drawRadialCubicBezierSegment,
- drawRadialDot,
- centripetalCatmullRomToBezier,
- renderCompleteRadialStroke,
- RadialMixingOptions,
-} from './stampEngine';
-import { LayerPixelSampler, PaintReservoir } from './colorMixingEngine';
-import { GpuDab } from './webglBrushEngine';
-import {
- evaluateFastSpline,
- applyCspPostCorrection,
-} from '../engine/CspBrushEngine';
+import { Point, CanvasDimensions, BlendMode, LayerItem } from '../types/editor';
+import { evaluateFastSpline } from '../engine/BrushEngine';
export const CANVAS_2D_CONTEXT_OPTIONS: CanvasRenderingContext2DSettings = {
alpha: true,
@@ -85,147 +69,37 @@ export function getMidPoint(p1: Point, p2: Point): Point {
};
}
-/**
- * Evaluates a quadratic Bézier curve at parameter t (0 <= t <= 1).
- */
-export function getQuadraticBezierPoint(
- p0: Point,
- control: Point,
- p2: Point,
- t: number
-): { x: number; y: number; width: number } {
- const invT = 1 - t;
- const invT2 = invT * invT;
- const t2 = t * t;
- const twoInvTT = 2 * invT * t;
-
- return {
- x: invT2 * p0.x + twoInvTT * control.x + t2 * p2.x,
- y: invT2 * p0.y + twoInvTT * control.y + t2 * p2.y,
- width: invT * p0.width + t * p2.width,
- };
-}
-
-/**
- * Converts 4 Catmull-Rom spline knots (p0, p1, p2, p3) into cubic Bézier control points (c1, c2).
- */
-export function catmullRomToBezier(
- p0: Point,
- p1: Point,
- p2: Point,
- p3: Point
-): { c1: Point; c2: Point } {
- return centripetalCatmullRomToBezier(p0, p1, p2, p3);
-}
-
-/**
- * Draws a smooth tapered segment along a cubic Bézier curve using analytical radial dabbing.
- */
-export function drawSmoothCubicBezierSegment(
- ctx: CanvasRenderingContext2D,
- p0: Point,
- c1: Point,
- c2: Point,
- p3: Point,
- color: string,
- isEraser: boolean = false,
- hardness: number = 1.0,
- flow: number = 1.0,
- spacing: number = 0.06,
- remainderDist: number = 0,
- thickness: number = 1.0,
- angleRad: number = 0,
- mixingOptions?: RadialMixingOptions,
- batchGpuDabs?: GpuDab[]
-): number {
- return drawRadialCubicBezierSegment(
- ctx,
- p0,
- c1,
- c2,
- p3,
- color,
- hardness,
- flow,
- spacing,
- isEraser,
- false,
- remainderDist,
- thickness,
- angleRad,
- mixingOptions,
- batchGpuDabs
- );
-}
-
-/**
- * Draws a smooth tapered segment along a quadratic Bézier curve by elevating to cubic.
- */
-export function drawSmoothBezierSegment(
- ctx: CanvasRenderingContext2D,
- start: Point,
- control: Point,
- end: Point,
- color: string,
- isEraser: boolean = false,
- hardness: number = 1.0,
- flow: number = 1.0,
- spacing: number = 0.06,
- remainderDist: number = 0
-): number {
- const c1: Point = {
- x: start.x + (2.0 / 3.0) * (control.x - start.x),
- y: start.y + (2.0 / 3.0) * (control.y - start.y),
- pressure: start.pressure + (2.0 / 3.0) * (control.pressure - start.pressure),
- width: start.width + (2.0 / 3.0) * (control.width - start.width),
- };
- const c2: Point = {
- x: end.x + (2.0 / 3.0) * (control.x - end.x),
- y: end.y + (2.0 / 3.0) * (control.y - end.y),
- pressure: end.pressure + (2.0 / 3.0) * (control.pressure - end.pressure),
- width: end.width + (2.0 / 3.0) * (control.width - end.width),
- };
- return drawSmoothCubicBezierSegment(ctx, start, c1, c2, end, color, isEraser, hardness, flow, spacing, remainderDist);
-}
-
-/**
- * Draws a single dot (e.g. on pointer down without movement).
- */
-export function drawDot(
- ctx: CanvasRenderingContext2D,
- point: Point,
- color: string,
- isEraser: boolean = false,
- hardness: number = 1.0,
- flow: number = 1.0,
- mixingOptions?: RadialMixingOptions,
- thickness: number = 1.0,
- angleRad: number = 0,
- batchGpuDabs?: GpuDab[]
-) {
- drawRadialDot(ctx, point, color, hardness, flow, isEraser, false, mixingOptions, thickness, angleRad, batchGpuDabs);
-}
-
let _sharedThumbCanvas: HTMLCanvasElement | null = null;
export const BLEND_MODES: { value: BlendMode; label: string }[] = [
{ value: 'pass-through', label: 'Pass Through' },
{ value: 'normal', label: 'Normal' },
+ { value: 'darken', label: 'Darken' },
{ value: 'multiply', label: 'Multiply' },
- { value: 'linear-burn', label: 'Linear Burn' },
{ value: 'color-burn', label: 'Color Burn' },
- { value: 'darken', label: 'Darken' },
+ { value: 'linear-burn', label: 'Linear Burn' },
+ { value: 'darker-color', label: 'Darker Color' },
+ { value: 'lighten', label: 'Lighten' },
{ value: 'screen', label: 'Screen' },
{ value: 'color-dodge', label: 'Color Dodge' },
{ value: 'color-dodge-glow', label: 'Glow Dodge' },
{ value: 'add-glow', label: 'Add (Glow)' },
- { value: 'lighten', label: 'Lighten' },
+ { value: 'lighter-color', label: 'Lighter Color' },
{ value: 'overlay', label: 'Overlay' },
{ value: 'soft-light', label: 'Soft Light' },
{ value: 'hard-light', label: 'Hard Light' },
+ { value: 'vivid-light', label: 'Vivid Light' },
+ { value: 'linear-light', label: 'Linear Light' },
+ { value: 'pin-light', label: 'Pin Light' },
+ { value: 'hard-mix', label: 'Hard Mix' },
{ value: 'difference', label: 'Difference' },
{ value: 'exclusion', label: 'Exclusion' },
+ { value: 'subtract', label: 'Subtract' },
{ value: 'divide', label: 'Divide' },
+ { value: 'hue', label: 'Hue' },
+ { value: 'saturation', label: 'Saturation' },
+ { value: 'color', label: 'Color' },
+ { value: 'luminosity', label: 'Luminosity' },
];
export function getCanvasCompositeOperation(blendMode: BlendMode): GlobalCompositeOperation {
@@ -240,8 +114,10 @@ export function getCanvasCompositeOperation(blendMode: BlendMode): GlobalComposi
case 'overlay':
return 'overlay';
case 'darken':
+ case 'darker-color':
return 'darken';
case 'lighten':
+ case 'lighter-color':
return 'lighten';
case 'color-dodge':
case 'color-dodge-glow':
@@ -252,14 +128,27 @@ export function getCanvasCompositeOperation(blendMode: BlendMode): GlobalComposi
case 'add-glow':
return 'lighter';
case 'hard-light':
+ case 'vivid-light':
+ case 'linear-light':
+ case 'pin-light':
+ case 'hard-mix':
return 'hard-light';
case 'soft-light':
return 'soft-light';
case 'difference':
+ case 'subtract':
case 'divide':
return 'difference';
case 'exclusion':
return 'exclusion';
+ case 'hue':
+ return 'hue';
+ case 'saturation':
+ return 'saturation';
+ case 'color':
+ return 'color';
+ case 'luminosity':
+ return 'luminosity';
default:
return 'source-over';
}
@@ -549,255 +438,16 @@ export function applyParametricTaper(
return points;
}
-export function renderCompleteStroke(
- ctx: CanvasRenderingContext2D,
- points: Point[],
- brushSettings: BrushSettings,
- tool: ToolType,
- colorMode: CanvasColorMode = 'color',
- isBgEraser: boolean = false,
- underlyingCanvas?: HTMLCanvasElement,
- alphaLocked: boolean = false,
- explicitSampler?: LayerPixelSampler,
- allowGpuForMonochrome: boolean = false
-) {
- if (!points || points.length === 0) return;
-
- const isMono = colorMode === 'monochrome';
- const postCorrLevel = brushSettings.postCorrection ?? 0;
- const postCorrectedPoints =
- postCorrLevel > 0 && points.length >= 3
- ? applyCspPostCorrection(points, postCorrLevel, brushSettings.sharpCorners !== false)
- : points;
-
- const hasTaper = Boolean(brushSettings.taper?.useOut || brushSettings.taper?.useIn);
- const effectivePoints =
- isMono && !hasTaper
- ? postCorrectedPoints.map((p) => (p.width < 1.25 ? { ...p, width: 1.25 } : p))
- : postCorrectedPoints;
-
- const isEraser = tool === 'eraser';
- const isPencil = !isEraser && !brushSettings.customTipImage && (brushSettings.preset?.startsWith('pencil') ?? false);
- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(brushSettings.color, colorMode);
- const strokeHardness = isMono ? 1.0 : (brushSettings.hardness ?? 1.0);
- const strokeFlow = isMono ? 1.0 : (brushSettings.flow ?? 1.0);
- const strokeSpacing = brushSettings.spacing ?? 0.08;
- const isTransparentInk = Boolean(brushSettings.isTransparentInk);
- const useTilt = Boolean(brushSettings.useTilt);
- const effectiveAntiAlias = isMono
- ? allowGpuForMonochrome && (brushSettings.antiAlias ?? 2) !== 0 && brushSettings.useGpu !== false
- ? (brushSettings.antiAlias ?? 2)
- : 0
- : brushSettings.antiAlias;
-
- // Textured Custom Tip (Clip Studio Paint SUT Brush & Procedural Tip Presets)
- if (brushSettings.customTipImage) {
- const tipOptions: TexturedBrushOptions = {
- size: brushSettings.size,
- minSizeFactor: brushSettings.minSizeFactor,
- opacity: brushSettings.opacity,
- flow: strokeFlow,
- adjustDensityByGap: brushSettings.adjustDensityByGap,
- blendTipsMode: brushSettings.blendTipsMode,
- spacing: strokeSpacing,
- thickness: brushSettings.thickness,
- thicknessVertical: brushSettings.thicknessVertical,
- flipH: brushSettings.flipH,
- flipV: brushSettings.flipV,
- isColorTip: brushSettings.isColorTip,
- angle: brushSettings.customTipAngle,
- angleDynamics: brushSettings.customTipAngleDynamics,
- rotationRandomScale: brushSettings.customTipRotationRandomScale,
- hardness: strokeHardness,
- antiAlias: effectiveAntiAlias,
- pressureCurve: brushSettings.pressureCurve,
- velocityCurve: brushSettings.velocityCurve,
- usePressure: brushSettings.usePressure,
- useVelocity: brushSettings.useVelocity,
- useTilt,
- tiltScale: brushSettings.tiltScale,
- sizeSensor: brushSettings.sizeSensor,
- opacitySensor: brushSettings.opacitySensor,
- densitySensor: brushSettings.densitySensor,
- subTips: brushSettings.subTips,
- subTipOrder: brushSettings.subTipOrder,
- subTipImages: brushSettings.subTipImages,
- spray: brushSettings.spray,
- taper: brushSettings.taper,
- colorMixing: brushSettings.colorMixing,
- perceptualMixing: brushSettings.perceptualMixing,
- amountOfPaint: brushSettings.amountOfPaint,
- densityOfPaint: brushSettings.densityOfPaint,
- colorStretch: brushSettings.colorStretch,
- mixingMode: brushSettings.mixingMode,
- wetEdge: brushSettings.wetEdge,
- wetEdgeRadius: brushSettings.wetEdgeRadius,
- wetEdgeAlphaPower: brushSettings.wetEdgeAlphaPower,
- wetEdgeValuePower: brushSettings.wetEdgeValuePower,
- grain: brushSettings.grain ?? brushSettings.textureDensity,
- paperTextureMode: brushSettings.paperTextureMode,
- paperTextureBrightness: brushSettings.paperTextureBrightness,
- paperTextureContrast: brushSettings.paperTextureContrast,
- paperTextureInverted: brushSettings.paperTextureInverted,
- paperTextureImage: brushSettings.paperTextureImage,
- paperTextureScale: brushSettings.paperTextureScale,
- paperTextureRotate: brushSettings.paperTextureRotate,
- dualBrush: brushSettings.dualBrush,
- dualTipImage: brushSettings.dualTipImage,
- dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
- useGpu: brushSettings.useGpu !== false,
- underlyingCanvas: underlyingCanvas || ctx.canvas,
- sampler: brushSettings.colorMixing
- ? (explicitSampler || (underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined))
- : undefined,
- reservoir: brushSettings.colorMixing && !isEraser ? new PaintReservoir(strokeColor) : undefined,
- isEraser: isEraser && !isBgEraser,
- isBgEraser,
- alphaLocked,
- isTransparentInk,
- dynamics: brushSettings.dynamics,
- secondaryColor: brushSettings.secondaryColor,
- };
- renderCompleteTexturedStroke(ctx, effectivePoints, strokeColor, brushSettings.customTipImage, tipOptions);
- return;
- }
-
- const radialMixing: RadialMixingOptions = {
- colorMixing: brushSettings.colorMixing,
- perceptualMixing: brushSettings.perceptualMixing,
- amountOfPaint: brushSettings.amountOfPaint,
- densityOfPaint: brushSettings.densityOfPaint,
- colorStretch: brushSettings.colorStretch,
- mixingMode: brushSettings.mixingMode,
- underlyingCanvas: underlyingCanvas || ctx.canvas,
- sampler: brushSettings.colorMixing
- ? (explicitSampler || (underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined))
- : undefined,
- reservoir: brushSettings.colorMixing && !isEraser ? new PaintReservoir(strokeColor) : undefined,
- alphaLocked,
- isTransparentInk,
- dynamics: brushSettings.dynamics,
- secondaryColor: brushSettings.secondaryColor,
- useGpu: brushSettings.useGpu !== false,
- dualBrush: brushSettings.dualBrush,
- dualTipImage: brushSettings.dualTipImage,
- dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
- useTilt,
- tiltScale: brushSettings.tiltScale,
- thicknessVertical: brushSettings.thicknessVertical,
- flipH: brushSettings.flipH,
- flipV: brushSettings.flipV,
- antiAlias: effectiveAntiAlias,
- angleDynamics: brushSettings.customTipAngleDynamics,
- rotationRandomScale: brushSettings.customTipRotationRandomScale,
- adjustDensityByGap: brushSettings.adjustDensityByGap,
- blendTipsMode: brushSettings.blendTipsMode,
- grain: brushSettings.grain ?? brushSettings.textureDensity,
- paperTextureMode: brushSettings.paperTextureMode,
- paperTextureBrightness: brushSettings.paperTextureBrightness,
- paperTextureContrast: brushSettings.paperTextureContrast,
- paperTextureInverted: brushSettings.paperTextureInverted,
- paperTextureImage: brushSettings.paperTextureImage,
- paperTextureScale: brushSettings.paperTextureScale,
- paperTextureRotate: brushSettings.paperTextureRotate,
- sizeSensor: brushSettings.sizeSensor,
- opacitySensor: brushSettings.opacitySensor,
- densitySensor: brushSettings.densitySensor,
- taper: brushSettings.taper,
- };
-
- if (isPencil) {
- const grade = (brushSettings.preset as PencilGrade) || 'pencil-2b';
- const pencilTilt = brushSettings.useTilt ?? true;
- drawPencilDot(
- ctx,
- effectivePoints[0],
- strokeColor,
- grade,
- isMono ? 1.0 : (brushSettings.flow ?? 0.74),
- brushSettings.grain ?? 1.0,
- strokeHardness,
- alphaLocked,
- isTransparentInk
- );
-
- if (effectivePoints.length === 1) return;
-
- const pFlow = isMono ? 1.0 : (brushSettings.flow ?? 0.74);
- const pGrain = brushSettings.grain ?? 1.0;
- let accDist = Math.max(0.25, effectivePoints[0].width * (brushSettings.spacing ?? 0.07));
-
- if (effectivePoints.length === 2) {
- const p0 = effectivePoints[0];
- const p1 = effectivePoints[1];
- const { c1, c2 } = catmullRomToBezier(p0, p0, p1, p1);
- drawPencilCubicBezierSegment(ctx, p0, c1, c2, p1, strokeColor, grade, pFlow, pGrain, strokeHardness, accDist, alphaLocked, isTransparentInk, pencilTilt);
- return;
- }
-
- const p0 = effectivePoints[0];
- const p1 = effectivePoints[1];
- const p2 = effectivePoints[2];
- const first = catmullRomToBezier(p0, p0, p1, p2);
- accDist = drawPencilCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, strokeColor, grade, pFlow, pGrain, strokeHardness, accDist, alphaLocked, isTransparentInk, pencilTilt);
-
- for (let i = 2; i < effectivePoints.length - 1; i++) {
- const seg = catmullRomToBezier(effectivePoints[i - 2], effectivePoints[i - 1], effectivePoints[i], effectivePoints[i + 1]);
- accDist = drawPencilCubicBezierSegment(ctx, effectivePoints[i - 1], seg.c1, seg.c2, effectivePoints[i], strokeColor, grade, pFlow, pGrain, strokeHardness, accDist, alphaLocked, isTransparentInk, pencilTilt);
- }
-
- const n = effectivePoints.length;
- const pPrev2 = effectivePoints[n - 3];
- const pPrev = effectivePoints[n - 2];
- const pLast = effectivePoints[n - 1];
- const last = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- drawPencilCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, strokeColor, grade, pFlow, pGrain, strokeHardness, accDist, alphaLocked, isTransparentInk, pencilTilt);
- return;
- }
-
- const baseAngleRad = ((brushSettings.customTipAngle ?? 0) * Math.PI) / 180;
- const baseThickness = brushSettings.thickness ?? 1.0;
-
- if (effectivePoints.length === 1) {
- drawDot(
- ctx,
- effectivePoints[0],
- strokeColor,
- isEraser && !isBgEraser,
- strokeHardness,
- strokeFlow,
- radialMixing,
- baseThickness,
- baseAngleRad
- );
- return;
- }
-
- renderCompleteRadialStroke(
- ctx,
- effectivePoints,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isEraser && !isBgEraser,
- isBgEraser,
- baseThickness,
- baseAngleRad,
- radialMixing
- );
-}
-
let sampleCanvas: HTMLCanvasElement | null = null;
let sampleCtx: CanvasRenderingContext2D | null = null;
/**
* Samples the composited RGBA pixel color across all visible layers at (x, y).
- * Uses a cached 1x1 canvas for minimal overhead and zero latency.
+ * Reads directly from SparseTileGrid in O(visible layers) with zero full-canvas allocation.
*/
export function sampleCompositedColor(
layers: LayerItem[],
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
+ source: SparseTileGrid | Map<string, HTMLCanvasElement>,
x: number,
y: number,
isLayerVisible: (layer: LayerItem) => boolean,
@@ -812,27 +462,66 @@ export function sampleCompositedColor(
return null;
}
- if (!sampleCanvas) {
+ const isTileGrid = 'getPixelRGBA' in source;
+
+ if (!sampleCanvas && typeof document !== 'undefined') {
sampleCanvas = document.createElement('canvas');
sampleCanvas.width = 1;
sampleCanvas.height = 1;
sampleCtx = sampleCanvas.getContext('2d', { willReadFrequently: true });
}
- if (!sampleCtx) return null;
+ const renderOrder = layers.slice().reverse();
+
+ if (isTileGrid && !sampleCtx) {
+ // Pure math headless fallback
+ let accR = 0, accG = 0, accB = 0, accA = 0;
+ const pixel: [number, number, number, number] = [0, 0, 0, 0];
+ for (const layer of renderOrder) {
+ if (layer.type === 'folder' || layer.type === 'frame-folder' || !isLayerVisible(layer)) continue;
+ source.getPixelRGBA(layer.id, px, py, pixel);
+ if (pixel[3] === 0) continue;
+ const sA = (pixel[3] / 255) * getLayerOpacity(layer);
+ const outA = sA + accA * (1 - sA);
+ if (outA > 0) {
+ accR = (pixel[0] * sA + accR * accA * (1 - sA)) / outA;
+ accG = (pixel[1] * sA + accG * accA * (1 - sA)) / outA;
+ accB = (pixel[2] * sA + accB * accA * (1 - sA)) / outA;
+ accA = outA;
+ }
+ }
+ if (accA <= 0) return '#ffffff';
+ const r = Math.round(accR * accA + 255 * (1 - accA));
+ const g = Math.round(accG * accA + 255 * (1 - accA));
+ const b = Math.round(accB * accA + 255 * (1 - accA));
+ const toHex = (n: number) => Math.max(0, Math.min(255, n)).toString(16).padStart(2, '0');
+ return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
+ }
+
+ if (!sampleCtx) return null;
sampleCtx.clearRect(0, 0, 1, 1);
- const renderOrder = layers.slice().reverse();
+ const pixel: [number, number, number, number] = [0, 0, 0, 0];
for (const layer of renderOrder) {
- if (layer.type === 'folder' || !isLayerVisible(layer)) continue;
- const lCanvas = layerCanvasesMap.get(layer.id);
- if (!lCanvas) continue;
-
- sampleCtx.save();
- sampleCtx.globalAlpha = getLayerOpacity(layer);
- sampleCtx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
- sampleCtx.drawImage(lCanvas, px, py, 1, 1, 0, 0, 1, 1);
- sampleCtx.restore();
+ if (layer.type === 'folder' || layer.type === 'frame-folder' || !isLayerVisible(layer)) continue;
+ if (isTileGrid) {
+ source.getPixelRGBA(layer.id, px, py, pixel);
+ if (pixel[3] === 0) continue;
+ sampleCtx.save();
+ sampleCtx.globalAlpha = getLayerOpacity(layer);
+ sampleCtx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
+ sampleCtx.fillStyle = `rgba(${pixel[0]},${pixel[1]},${pixel[2]},${pixel[3] / 255})`;
+ sampleCtx.fillRect(0, 0, 1, 1);
+ sampleCtx.restore();
+ } else {
+ const lCanvas = source.get(layer.id);
+ if (!lCanvas) continue;
+ sampleCtx.save();
+ sampleCtx.globalAlpha = getLayerOpacity(layer);
+ sampleCtx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
+ sampleCtx.drawImage(lCanvas, px, py, 1, 1, 0, 0, 1, 1);
+ sampleCtx.restore();
+ }
}
if (floatingSelection?.canvas) {
diff --git a/src/utils/collabPermissions.ts b/src/utils/collabPermissions.ts
new file mode 100644
index 0000000..12fd0ff
--- /dev/null
+++ b/src/utils/collabPermissions.ts
@@ -0,0 +1,327 @@
+import { LayerItem } from '../types/editor';
+import { CollabPeer, CollabRole, MultiplayerMessage } from '../types/multiplayer';
+
+export interface PermissionResult {
+ allowed: boolean;
+ reason?: string;
+ blockedLayerId?: string;
+ blockedLayerName?: string;
+}
+
+export function normalizeRole(role: unknown, isHost?: boolean): CollabRole {
+ if (isHost || role === 'host') return 'host';
+ if (role === 'viewer') return 'viewer';
+ return 'editor';
+}
+
+export function peerIdEquals(
+ a: string | number | undefined | null,
+ b: string | number | undefined | null
+): boolean {
+ if (a === undefined || a === null || b === undefined || b === null) return false;
+ const sa = String(a).trim();
+ const sb = String(b).trim();
+ return sa.length > 0 && sa === sb;
+}
+
+export function canMutateCanvas(role: CollabRole): boolean {
+ return role === 'host' || role === 'editor';
+}
+
+export function canManageRoom(role: CollabRole): boolean {
+ return role === 'host';
+}
+
+export function isLayerLockedByOther(
+ layer: Pick<LayerItem, 'reservedByPeerId'> | null | undefined,
+ myPeerId: string | number,
+ myRole: CollabRole
+): boolean {
+ if (!layer || !layer.reservedByPeerId) return false;
+ if (myRole === 'host') return false;
+ return !peerIdEquals(layer.reservedByPeerId, myPeerId);
+}
+
+export function isLayerOwnedByOther(
+ layer: Pick<LayerItem, 'ownerPeerId'> | null | undefined,
+ myPeerId: string | number,
+ myRole: CollabRole
+): boolean {
+ if (!layer || !layer.ownerPeerId) return false;
+ if (myRole === 'host') return false;
+ return !peerIdEquals(layer.ownerPeerId, myPeerId);
+}
+
+export function canEditLayer(
+ layer: Pick<LayerItem, 'reservedByPeerId' | 'reservedByPeerName'> | null | undefined,
+ myPeerId: string | number,
+ myRole: CollabRole
+): PermissionResult {
+ if (!canMutateCanvas(myRole)) {
+ return { allowed: false, reason: 'Viewers have read-only access' };
+ }
+ if (!layer) return { allowed: true };
+ if (isLayerLockedByOther(layer, myPeerId, myRole)) {
+ return {
+ allowed: false,
+ reason: `Layer is locked by ${layer.reservedByPeerName || 'its owner'}`,
+ };
+ }
+ return { allowed: true };
+}
+
+export function canToggleLayerOwnerLock(
+ layer:
+ | Pick<LayerItem, 'ownerPeerId' | 'ownerPeerName' | 'reservedByPeerId' | 'reservedByPeerName'>
+ | null
+ | undefined,
+ myPeerId: string | number,
+ myRole: CollabRole
+): PermissionResult {
+ if (!canMutateCanvas(myRole)) {
+ return { allowed: false, reason: 'Viewers cannot lock or unlock layers' };
+ }
+ if (!layer) {
+ return { allowed: false, reason: 'Layer not found' };
+ }
+ if (myRole === 'host') {
+ return { allowed: true };
+ }
+ if (layer.reservedByPeerId !== undefined && layer.reservedByPeerId !== '') {
+ if (!peerIdEquals(layer.reservedByPeerId, myPeerId)) {
+ return {
+ allowed: false,
+ reason: `Only ${layer.reservedByPeerName || 'the lock owner'} or the Host can unlock this layer`,
+ };
+ }
+ return { allowed: true };
+ }
+ if (layer.ownerPeerId !== undefined && layer.ownerPeerId !== '') {
+ if (!peerIdEquals(layer.ownerPeerId, myPeerId)) {
+ return {
+ allowed: false,
+ reason: `Only ${layer.ownerPeerName || 'the layer owner'} or the Host can lock this layer`,
+ };
+ }
+ }
+ return { allowed: true };
+}
+
+function collectTargetSubtree(
+ targetId: string,
+ allLayers: ReadonlyArray<
+ Pick<
+ LayerItem,
+ 'id' | 'name' | 'parentId' | 'ownerPeerId' | 'ownerPeerName' | 'reservedByPeerId' | 'reservedByPeerName'
+ >
+ >
+) {
+ const byId = new Map(allLayers.map((l) => [l.id, l]));
+ const root = byId.get(targetId);
+ if (!root) return [];
+
+ const collected = [root];
+ const ids = new Set<string>([targetId]);
+ let expanded = true;
+ while (expanded) {
+ expanded = false;
+ for (const l of allLayers) {
+ if (!ids.has(l.id) && l.parentId && ids.has(l.parentId)) {
+ ids.add(l.id);
+ collected.push(l);
+ expanded = true;
+ }
+ }
+ }
+ return collected;
+}
+
+export function canDeleteLayer(
+ layerId: string,
+ allLayers: ReadonlyArray<
+ Pick<
+ LayerItem,
+ 'id' | 'name' | 'parentId' | 'ownerPeerId' | 'ownerPeerName' | 'reservedByPeerId' | 'reservedByPeerName'
+ >
+ >,
+ myPeerId: string | number,
+ myRole: CollabRole
+): PermissionResult {
+ if (!canMutateCanvas(myRole)) {
+ return { allowed: false, reason: 'Viewers cannot delete layers' };
+ }
+ if (myRole === 'host') {
+ return { allowed: true };
+ }
+ const subtree = collectTargetSubtree(layerId, allLayers);
+ for (const item of subtree) {
+ if (isLayerLockedByOther(item, myPeerId, myRole)) {
+ return {
+ allowed: false,
+ reason: `Cannot delete "${item.name}" — locked by ${item.reservedByPeerName || 'another user'}`,
+ blockedLayerId: item.id,
+ blockedLayerName: item.name,
+ };
+ }
+ if (isLayerOwnedByOther(item, myPeerId, myRole)) {
+ return {
+ allowed: false,
+ reason: `Cannot delete "${item.name}" — owned by ${item.ownerPeerName || 'another user'}`,
+ blockedLayerId: item.id,
+ blockedLayerName: item.name,
+ };
+ }
+ }
+ return { allowed: true };
+}
+
+export function filterDeletableLayerIds(
+ targetIds: ReadonlyArray<string>,
+ allLayers: ReadonlyArray<
+ Pick<
+ LayerItem,
+ 'id' | 'name' | 'parentId' | 'ownerPeerId' | 'ownerPeerName' | 'reservedByPeerId' | 'reservedByPeerName'
+ >
+ >,
+ myPeerId: string | number,
+ myRole: CollabRole
+): { allowedIds: string[]; blockedReasons: string[] } {
+ const allowedIds: string[] = [];
+ const blockedReasons: string[] = [];
+ for (const id of targetIds) {
+ const res = canDeleteLayer(id, allLayers, myPeerId, myRole);
+ if (res.allowed) {
+ allowedIds.push(id);
+ } else if (res.reason) {
+ blockedReasons.push(res.reason);
+ }
+ }
+ return { allowedIds, blockedReasons };
+}
+
+/**
+ * Defense-in-depth validation of incoming remote mutations on receiving clients.
+ * Ensures a compromised or buggy peer cannot bypass role, lock, or ownership rules
+ * even when routed through a non-authoritative relay.
+ */
+export function validateIncomingRemoteMutation(
+ msg: MultiplayerMessage,
+ senderPeer: CollabPeer | undefined,
+ currentLayers: ReadonlyArray<LayerItem>
+): PermissionResult {
+ // Server-originated or unattributed system sync messages (no senderId) pass through
+ if (msg.senderId === undefined || msg.senderId === null) {
+ return { allowed: true };
+ }
+
+ const senderId = msg.senderId;
+ const senderRole: CollabRole = senderPeer
+ ? normalizeRole(senderPeer.role, senderPeer.isHost)
+ : 'editor';
+
+ if (senderRole === 'host') {
+ return { allowed: true };
+ }
+
+ // Host-only administrative messages
+ if (
+ msg.type === 'PEER_ROLE_UPDATE' ||
+ msg.type === 'PEER_KICK' ||
+ msg.type === 'PEER_BAN' ||
+ msg.type === 'PEER_UNBAN'
+ ) {
+ return { allowed: false, reason: 'Only the Host can manage room permissions' };
+ }
+
+ const isMutation =
+ msg.type === 'STROKE_START' ||
+ msg.type === 'STROKE_CHUNK' ||
+ msg.type === 'STROKE_FINISH' ||
+ msg.type === 'BINARY_TILE' ||
+ msg.type === 'BINARY_MASK' ||
+ msg.type === 'SELECTIVE_UNDO' ||
+ msg.type === 'LAYER_ADD' ||
+ msg.type === 'LAYER_DELETE' ||
+ msg.type === 'LAYER_CLEAR' ||
+ msg.type === 'LAYER_RENAME' ||
+ msg.type === 'LAYER_VISIBILITY' ||
+ msg.type === 'LAYER_OPACITY' ||
+ msg.type === 'LAYER_UPDATE' ||
+ msg.type === 'LAYER_TREE_SYNC' ||
+ msg.type === 'PERSPECTIVE_RULER_SYNC' ||
+ msg.type === 'STRAIGHT_RULER_SYNC' ||
+ msg.type === 'ANIMATION_SYNC' ||
+ msg.type === 'CANVAS_RESIZE';
+
+ if (!isMutation) {
+ return { allowed: true };
+ }
+
+ if (senderRole === 'viewer') {
+ return { allowed: false, reason: 'Viewer mutation rejected' };
+ }
+
+ if (msg.type === 'LAYER_DELETE') {
+ return canDeleteLayer(msg.layerId, currentLayers, senderId, senderRole);
+ }
+
+ if (msg.type === 'LAYER_TREE_SYNC') {
+ const incomingIds = new Set(msg.layers.map((l) => l.id));
+ for (const existing of currentLayers) {
+ if (!incomingIds.has(existing.id)) {
+ const delCheck = canDeleteLayer(existing.id, currentLayers, senderId, senderRole);
+ if (!delCheck.allowed) return delCheck;
+ } else {
+ const next = msg.layers.find((l) => l.id === existing.id);
+ if (next && isLayerLockedByOther(existing, senderId, senderRole)) {
+ // Reject unlocking or modifying locked layer owned by someone else
+ if (!peerIdEquals(next.reservedByPeerId, existing.reservedByPeerId)) {
+ return { allowed: false, reason: 'Cannot unlock another user layer' };
+ }
+ }
+ }
+ }
+ return { allowed: true };
+ }
+
+ if (msg.type === 'LAYER_UPDATE') {
+ const target = currentLayers.find((l) => l.id === msg.layerId);
+ if (!target) return { allowed: true };
+ const editCheck = canEditLayer(target, senderId, senderRole);
+ if (!editCheck.allowed) return editCheck;
+
+ const clearsLock = msg.clearedFields?.includes('reservedByPeerId');
+ const setsLock = msg.patch.reservedByPeerId !== undefined;
+ if (clearsLock || setsLock) {
+ const lockCheck = canToggleLayerOwnerLock(target, senderId, senderRole);
+ if (!lockCheck.allowed) return lockCheck;
+ if (setsLock && !peerIdEquals(msg.patch.reservedByPeerId, senderId)) {
+ return { allowed: false, reason: 'Cannot lock layer under another peer ID' };
+ }
+ }
+ const touchesOwner =
+ msg.patch.ownerPeerId !== undefined || msg.clearedFields?.includes('ownerPeerId');
+ if (touchesOwner && target.ownerPeerId && !peerIdEquals(target.ownerPeerId, senderId)) {
+ return { allowed: false, reason: 'Cannot reassign layer ownership' };
+ }
+ return { allowed: true };
+ }
+
+ if (
+ msg.type === 'LAYER_CLEAR' ||
+ msg.type === 'LAYER_RENAME' ||
+ msg.type === 'LAYER_VISIBILITY' ||
+ msg.type === 'LAYER_OPACITY' ||
+ msg.type === 'BINARY_TILE' ||
+ msg.type === 'BINARY_MASK' ||
+ msg.type === 'STROKE_START' ||
+ msg.type === 'STROKE_FINISH'
+ ) {
+ const target = currentLayers.find((l) => l.id === msg.layerId);
+ if (target) {
+ return canEditLayer(target, senderId, senderRole);
+ }
+ }
+
+ return { allowed: true };
+}
diff --git a/src/utils/collabSyncUtils.ts b/src/utils/collabSyncUtils.ts
new file mode 100644
index 0000000..d4e34cf
--- /dev/null
+++ b/src/utils/collabSyncUtils.ts
@@ -0,0 +1,914 @@
+import {
+ ALL_BLEND_MODES,
+ AdjustmentLayerData,
+ AnimationTimeline,
+ BlendMode,
+ CanvasDimensions,
+ ComicFrame,
+ DirtyRect,
+ ExpressionColor,
+ LayerItem,
+ LayerStyles,
+ LayerType,
+ SpeechBalloon,
+ TextLayerData,
+ VectorStroke,
+} from '../types/editor';
+import {
+ LayerClearableField,
+ LayerMaskDataMessage,
+ WireLayerItem,
+} from '../types/multiplayer';
+import { PerspectiveRuler, StraightRuler, VanishingPoint } from '../types/perspective';
+import { AnchorPosition, ResizeCanvasOptions } from '../types/settings';
+import { get2DContext } from './canvasUtils';
+import { releaseTemporaryCanvas } from './tileEngine';
+
+export const MAX_SYNC_LAYERS = 512;
+export const MAX_SYNC_VECTOR_STROKES = 20000;
+export const MAX_SYNC_COMIC_FRAMES = 256;
+export const MAX_SYNC_CANVAS_DIM = 16384;
+export const MAX_SYNC_ANIM_FRAMES = 10000;
+
+const ALLOWED_LAYER_TYPES = new Set<LayerType>([
+ 'raster',
+ 'folder',
+ 'frame-folder',
+ 'vector',
+ 'frame',
+ 'adjustment',
+ 'text',
+ 'balloon',
+]);
+
+const ALLOWED_BLEND_MODES = new Set<BlendMode>(ALL_BLEND_MODES);
+
+const ALLOWED_DOT_SHAPES = new Set(['circle', 'euclidean', 'line', 'diamond']);
+const ALLOWED_EXPRESSION_COLORS = new Set<ExpressionColor>(['color', 'gray', 'monochrome']);
+const ALLOWED_ANCHORS = new Set<AnchorPosition>([
+ 'top-left',
+ 'top',
+ 'top-right',
+ 'left',
+ 'center',
+ 'right',
+ 'bottom-left',
+ 'bottom',
+ 'bottom-right',
+]);
+
+const CLEARABLE_FIELDS_SET = new Set<LayerClearableField>([
+ 'alphaLocked',
+ 'clipped',
+ 'isReference',
+ 'toneEnabled',
+ 'toneFrequency',
+ 'toneAngle',
+ 'toneDotShape',
+ 'toneDensity',
+ 'toneDensityType',
+ 'layerColorEnabled',
+ 'layerColor',
+ 'layerSubColor',
+ 'expressionColor',
+ 'monoThreshold',
+ 'monoExpressBlack',
+ 'monoExpressWhite',
+ 'maskEnabled',
+ 'maskLinked',
+ 'maskVersion',
+ 'hasMask',
+ 'adjustmentData',
+ 'styles',
+ 'vectorStrokes',
+ 'comicFrames',
+ 'textData',
+ 'balloonData',
+ 'balloons',
+ 'ownerPeerId',
+ 'ownerPeerName',
+ 'reservedByPeerId',
+ 'reservedByPeerName',
+]);
+
+/** Keys compared when detecting semantic layer mutations (excludes transient UI/DOM fields). */
+const SYNCED_LAYER_KEYS: ReadonlyArray<keyof WireLayerItem> = [
+ 'name',
+ 'type',
+ 'visible',
+ 'opacity',
+ 'blendMode',
+ 'locked',
+ 'alphaLocked',
+ 'clipped',
+ 'parentId',
+ 'isReference',
+ 'toneEnabled',
+ 'toneFrequency',
+ 'toneAngle',
+ 'toneDotShape',
+ 'toneDensity',
+ 'toneDensityType',
+ 'layerColorEnabled',
+ 'layerColor',
+ 'layerSubColor',
+ 'expressionColor',
+ 'monoThreshold',
+ 'monoExpressBlack',
+ 'monoExpressWhite',
+ 'maskEnabled',
+ 'maskLinked',
+ 'hasMask',
+ 'adjustmentData',
+ 'styles',
+ 'vectorStrokes',
+ 'comicFrames',
+ 'textData',
+ 'balloonData',
+ 'balloons',
+ 'ownerPeerId',
+ 'ownerPeerName',
+ 'reservedByPeerId',
+ 'reservedByPeerName',
+];
+
+const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
+
+function clampFinite(val: unknown, min: number, max: number, fallback: number): number {
+ if (typeof val !== 'number' || !Number.isFinite(val)) return fallback;
+ return Math.max(min, Math.min(max, val));
+}
+
+function safeString(val: unknown, maxLen: number, fallback = ''): string {
+ if (typeof val !== 'string') return fallback;
+ return val.length > maxLen ? val.slice(0, maxLen) : val;
+}
+
+/** Strips prototype-pollution keys and enforces max recursion depth. */
+function cloneSafeJson<T>(val: unknown, depth = 0): T | undefined {
+ if (depth > 12) return undefined;
+ if (val === null || typeof val === 'boolean') return val as T;
+ if (typeof val === 'number') return (Number.isFinite(val) ? val : 0) as T;
+ if (typeof val === 'string') return (val.length > 65536 ? val.slice(0, 65536) : val) as T;
+ if (Array.isArray(val)) {
+ const out: unknown[] = [];
+ for (let i = 0; i < val.length; i++) {
+ out.push(cloneSafeJson(val[i], depth + 1));
+ }
+ return out as T;
+ }
+ if (typeof val === 'object') {
+ const src = val as Record<string, unknown>;
+ const out: Record<string, unknown> = {};
+ for (const k of Object.keys(src)) {
+ if (FORBIDDEN_KEYS.has(k)) continue;
+ const v = cloneSafeJson(src[k], depth + 1);
+ if (v !== undefined) out[k] = v;
+ }
+ return out as T;
+ }
+ return undefined;
+}
+
+export function deepEqualWireValue(a: unknown, b: unknown): boolean {
+ if (a === b) return true;
+ if (a === null || b === null || typeof a !== typeof b) return false;
+ if (typeof a !== 'object') return false;
+
+ if (Array.isArray(a)) {
+ if (!Array.isArray(b) || a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ if (!deepEqualWireValue(a[i], b[i])) return false;
+ }
+ return true;
+ }
+ if (Array.isArray(b)) return false;
+
+ const objA = a as Record<string, unknown>;
+ const objB = b as Record<string, unknown>;
+ const keysA = Object.keys(objA);
+ const keysB = Object.keys(objB);
+
+ let countA = 0;
+ for (let i = 0; i < keysA.length; i++) {
+ const k = keysA[i];
+ if (objA[k] === undefined) continue;
+ countA++;
+ if (!deepEqualWireValue(objA[k], objB[k])) return false;
+ }
+ let countB = 0;
+ for (let i = 0; i < keysB.length; i++) {
+ if (objB[keysB[i]] !== undefined) countB++;
+ }
+ return countA === countB;
+}
+
+/**
+ * Strips DOM/UI fields (`maskCanvas`, `thumbnailUrl`, `maskThumbnailUrl`, `collapsed`, `maskVersion`)
+ * to produce a clean canonical wire layer object.
+ */
+export function serializeLayerForWire(layer: LayerItem): WireLayerItem {
+ const {
+ maskCanvas,
+ thumbnailUrl: _thumb,
+ maskThumbnailUrl: _mThumb,
+ collapsed: _collapsed,
+ maskVersion: _mVer,
+ ...rest
+ } = layer;
+
+ const wire: WireLayerItem = {
+ ...rest,
+ hasMask: Boolean(maskCanvas || (layer as WireLayerItem).hasMask),
+ };
+
+ if (!wire.hasMask) {
+ delete wire.hasMask;
+ }
+ return wire;
+}
+
+export function sanitizeWireLayer(raw: unknown): WireLayerItem | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const src = raw as Record<string, unknown>;
+ const id = safeString(src.id, 256).trim();
+ if (!id) return null;
+
+ const type: LayerType = ALLOWED_LAYER_TYPES.has(src.type as LayerType)
+ ? (src.type as LayerType)
+ : 'raster';
+ const blendMode: BlendMode = ALLOWED_BLEND_MODES.has(src.blendMode as BlendMode)
+ ? (src.blendMode as BlendMode)
+ : type === 'folder'
+ ? 'pass-through'
+ : 'normal';
+
+ const parentId =
+ src.parentId === null || src.parentId === undefined
+ ? null
+ : safeString(src.parentId, 256) || null;
+
+ const base: WireLayerItem = {
+ id,
+ name: safeString(src.name, 256, 'Layer'),
+ type,
+ visible: src.visible !== false,
+ opacity: clampFinite(src.opacity, 0, 1, 1),
+ blendMode,
+ locked: Boolean(src.locked),
+ parentId: parentId === id ? null : parentId,
+ };
+
+ const patch = sanitizeWireLayerPatch(src);
+ return { ...base, ...patch, id, type, blendMode, parentId: base.parentId };
+}
+
+export function sanitizeWireLayerPatch(raw: unknown): Partial<WireLayerItem> {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
+ const src = raw as Record<string, unknown>;
+ const out: Partial<WireLayerItem> = {};
+
+ if (typeof src.name === 'string') out.name = safeString(src.name, 256);
+ if (ALLOWED_LAYER_TYPES.has(src.type as LayerType)) out.type = src.type as LayerType;
+ if (typeof src.visible === 'boolean') out.visible = src.visible;
+ if (typeof src.opacity === 'number' && Number.isFinite(src.opacity)) {
+ out.opacity = clampFinite(src.opacity, 0, 1, 1);
+ }
+ if (ALLOWED_BLEND_MODES.has(src.blendMode as BlendMode)) {
+ out.blendMode = src.blendMode as BlendMode;
+ }
+ if (typeof src.locked === 'boolean') out.locked = src.locked;
+ if (typeof src.alphaLocked === 'boolean') out.alphaLocked = src.alphaLocked;
+ if (typeof src.clipped === 'boolean') out.clipped = src.clipped;
+ if (src.parentId === null || typeof src.parentId === 'string') {
+ out.parentId = src.parentId === null ? null : safeString(src.parentId, 256) || null;
+ }
+ if (typeof src.isReference === 'boolean') out.isReference = src.isReference;
+
+ // Screentone
+ if (typeof src.toneEnabled === 'boolean') out.toneEnabled = src.toneEnabled;
+ if (typeof src.toneFrequency === 'number' && Number.isFinite(src.toneFrequency)) {
+ out.toneFrequency = Math.round(clampFinite(src.toneFrequency, 20, 85, 60));
+ }
+ if (typeof src.toneAngle === 'number' && Number.isFinite(src.toneAngle)) {
+ out.toneAngle = Math.round(clampFinite(src.toneAngle, 0, 90, 45));
+ }
+ if (typeof src.toneDotShape === 'string' && ALLOWED_DOT_SHAPES.has(src.toneDotShape)) {
+ out.toneDotShape = src.toneDotShape as WireLayerItem['toneDotShape'];
+ }
+ if (typeof src.toneDensity === 'number' && Number.isFinite(src.toneDensity)) {
+ out.toneDensity = Math.round(clampFinite(src.toneDensity, 1, 100, 40));
+ }
+ if (src.toneDensityType === 'specified' || src.toneDensityType === 'image') {
+ out.toneDensityType = src.toneDensityType;
+ }
+
+ // Layer Color Tint
+ if (typeof src.layerColorEnabled === 'boolean') out.layerColorEnabled = src.layerColorEnabled;
+ if (typeof src.layerColor === 'string') out.layerColor = safeString(src.layerColor, 64);
+ if (typeof src.layerSubColor === 'string') out.layerSubColor = safeString(src.layerSubColor, 64);
+
+ // Expression Color
+ if (ALLOWED_EXPRESSION_COLORS.has(src.expressionColor as ExpressionColor)) {
+ out.expressionColor = src.expressionColor as ExpressionColor;
+ }
+ if (typeof src.monoThreshold === 'number' && Number.isFinite(src.monoThreshold)) {
+ out.monoThreshold = Math.round(clampFinite(src.monoThreshold, 1, 255, 128));
+ }
+ if (typeof src.monoExpressBlack === 'boolean') out.monoExpressBlack = src.monoExpressBlack;
+ if (typeof src.monoExpressWhite === 'boolean') out.monoExpressWhite = src.monoExpressWhite;
+
+ // Layer Mask flags
+ if (typeof src.maskEnabled === 'boolean') out.maskEnabled = src.maskEnabled;
+ if (typeof src.maskLinked === 'boolean') out.maskLinked = src.maskLinked;
+ if (typeof src.hasMask === 'boolean') out.hasMask = src.hasMask;
+
+ // Structured non-destructive data (prototype-safe deep clone + caps)
+ if (src.adjustmentData && typeof src.adjustmentData === 'object') {
+ const safeAdj = cloneSafeJson<AdjustmentLayerData>(src.adjustmentData);
+ if (
+ safeAdj &&
+ (safeAdj.type === 'curves' ||
+ safeAdj.type === 'gradient-map' ||
+ safeAdj.type === 'levels' ||
+ safeAdj.type === 'color-balance')
+ ) {
+ out.adjustmentData = safeAdj;
+ }
+ }
+ if (src.styles && typeof src.styles === 'object') {
+ const safeStyles = cloneSafeJson<LayerStyles>(src.styles);
+ if (safeStyles) out.styles = safeStyles;
+ }
+ if (Array.isArray(src.vectorStrokes) && src.vectorStrokes.length <= MAX_SYNC_VECTOR_STROKES) {
+ const safeStrokes = cloneSafeJson<VectorStroke[]>(src.vectorStrokes);
+ if (safeStrokes) out.vectorStrokes = safeStrokes;
+ }
+ if (Array.isArray(src.comicFrames) && src.comicFrames.length <= MAX_SYNC_COMIC_FRAMES) {
+ const safeFrames = cloneSafeJson<ComicFrame[]>(src.comicFrames);
+ if (safeFrames) out.comicFrames = safeFrames;
+ }
+ if (src.textData && typeof src.textData === 'object') {
+ const safeText = cloneSafeJson<TextLayerData>(src.textData);
+ if (safeText && typeof safeText.text === 'string') out.textData = safeText;
+ }
+ if (src.balloonData && typeof src.balloonData === 'object') {
+ const safeBalloon = cloneSafeJson<SpeechBalloon>(src.balloonData);
+ if (safeBalloon && safeBalloon.bounds) out.balloonData = safeBalloon;
+ }
+ if (Array.isArray(src.balloons) && src.balloons.length <= 256) {
+ const safeBalloons = cloneSafeJson<SpeechBalloon[]>(src.balloons);
+ if (safeBalloons) out.balloons = safeBalloons;
+ }
+ if (typeof src.ownerPeerId === 'string' || typeof src.ownerPeerId === 'number') {
+ out.ownerPeerId =
+ typeof src.ownerPeerId === 'string' ? safeString(src.ownerPeerId, 128) : src.ownerPeerId;
+ }
+ if (typeof src.ownerPeerName === 'string') {
+ out.ownerPeerName = safeString(src.ownerPeerName, 64);
+ }
+ if (typeof src.reservedByPeerId === 'string' || typeof src.reservedByPeerId === 'number') {
+ out.reservedByPeerId =
+ typeof src.reservedByPeerId === 'string'
+ ? safeString(src.reservedByPeerId, 128)
+ : src.reservedByPeerId;
+ }
+ if (typeof src.reservedByPeerName === 'string') {
+ out.reservedByPeerName = safeString(src.reservedByPeerName, 64);
+ }
+
+ return out;
+}
+
+export function sanitizeClearedFields(raw: unknown): LayerClearableField[] {
+ if (!Array.isArray(raw)) return [];
+ const out: LayerClearableField[] = [];
+ for (let i = 0; i < raw.length && out.length < 64; i++) {
+ const f = raw[i];
+ if (typeof f === 'string' && CLEARABLE_FIELDS_SET.has(f as LayerClearableField)) {
+ out.push(f as LayerClearableField);
+ }
+ }
+ return out;
+}
+
+export function sanitizeWireLayerTree(raw: unknown): WireLayerItem[] | null {
+ if (!Array.isArray(raw) || raw.length === 0 || raw.length > MAX_SYNC_LAYERS) return null;
+ const out: WireLayerItem[] = [];
+ const seen = new Set<string>();
+ for (let i = 0; i < raw.length; i++) {
+ const item = sanitizeWireLayer(raw[i]);
+ if (!item || seen.has(item.id)) continue;
+ seen.add(item.id);
+ out.push(item);
+ }
+ if (out.length === 0) return null;
+
+ // Break invalid parent references & cycles
+ const byId = new Map(out.map((l) => [l.id, l]));
+ for (const layer of out) {
+ if (!layer.parentId) continue;
+ if (!byId.has(layer.parentId)) {
+ layer.parentId = null;
+ continue;
+ }
+ const visited = new Set<string>([layer.id]);
+ let curr: WireLayerItem | undefined = byId.get(layer.parentId);
+ while (curr) {
+ if (visited.has(curr.id)) {
+ layer.parentId = null;
+ break;
+ }
+ visited.add(curr.id);
+ curr = curr.parentId ? byId.get(curr.parentId) : undefined;
+ }
+ }
+ return out;
+}
+
+export function sanitizePerspectiveRuler(raw: unknown): PerspectiveRuler | null | undefined {
+ if (raw === null) return null;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
+ const r = raw as Record<string, unknown>;
+ if (r.type !== '1-point' && r.type !== '2-point' && r.type !== '3-point') return undefined;
+ if (!Array.isArray(r.vps) || r.vps.length === 0 || r.vps.length > 3) return undefined;
+
+ const vps: VanishingPoint[] = [];
+ for (let i = 0; i < r.vps.length; i++) {
+ const vp = r.vps[i] as Record<string, unknown>;
+ if (!vp || typeof vp !== 'object') return undefined;
+ if (vp.id !== 'vp1' && vp.id !== 'vp2' && vp.id !== 'vp3') return undefined;
+ if (typeof vp.x !== 'number' || !Number.isFinite(vp.x)) return undefined;
+ if (typeof vp.y !== 'number' || !Number.isFinite(vp.y)) return undefined;
+ vps.push({
+ id: vp.id,
+ x: clampFinite(vp.x, -1_000_000, 1_000_000, 0),
+ y: clampFinite(vp.y, -1_000_000, 1_000_000, 0),
+ label: safeString(vp.label, 32, vp.id.toUpperCase()),
+ color: safeString(vp.color, 32, '#38bdf8'),
+ });
+ }
+
+ const gridRaw = (r.grid && typeof r.grid === 'object' ? r.grid : {}) as Record<string, unknown>;
+ const plane =
+ gridRaw.plane === 'ground' ||
+ gridRaw.plane === 'wall-left' ||
+ gridRaw.plane === 'wall-right' ||
+ gridRaw.plane === 'all'
+ ? gridRaw.plane
+ : 'ground';
+
+ return {
+ id: safeString(r.id, 128, 'perspective-ruler'),
+ type: r.type,
+ enabled: Boolean(r.enabled),
+ locked: Boolean(r.locked),
+ snapEnabled: Boolean(r.snapEnabled),
+ vps,
+ horizonAngle: clampFinite(r.horizonAngle, -360, 360, 0),
+ guideRayCount: Math.round(clampFinite(r.guideRayCount, 1, 64, 12)),
+ grid: {
+ enabled: Boolean(gridRaw.enabled),
+ density: Math.round(clampFinite(gridRaw.density, 2, 100, 12)),
+ plane,
+ opacity: clampFinite(gridRaw.opacity, 0, 1, 0.35),
+ },
+ };
+}
+
+export function sanitizeStraightRuler(raw: unknown): StraightRuler | null | undefined {
+ if (raw === null) return null;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
+ const r = raw as Record<string, unknown>;
+ if (typeof r.x !== 'number' || !Number.isFinite(r.x)) return undefined;
+ if (typeof r.y !== 'number' || !Number.isFinite(r.y)) return undefined;
+ return {
+ enabled: Boolean(r.enabled),
+ x: clampFinite(r.x, -1_000_000, 1_000_000, 0),
+ y: clampFinite(r.y, -1_000_000, 1_000_000, 0),
+ angle: clampFinite(r.angle, -360, 360, 0),
+ locked: Boolean(r.locked),
+ snapEnabled: Boolean(r.snapEnabled),
+ };
+}
+
+export function sanitizeAnimationTimeline(raw: unknown): AnimationTimeline | null | undefined {
+ if (raw === null) return null;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
+ const t = raw as Record<string, unknown>;
+ const totalFrames = Math.round(clampFinite(t.totalFrames, 1, MAX_SYNC_ANIM_FRAMES, 24));
+ const celsRaw = t.cels && typeof t.cels === 'object' ? (t.cels as Record<string, unknown>) : {};
+ const cels: Record<number, string> = {};
+ let celCount = 0;
+ for (const key of Object.keys(celsRaw)) {
+ if (celCount >= MAX_SYNC_ANIM_FRAMES) break;
+ const frameIdx = Number(key);
+ const layerId = celsRaw[key];
+ if (
+ Number.isInteger(frameIdx) &&
+ frameIdx >= 0 &&
+ frameIdx < MAX_SYNC_ANIM_FRAMES &&
+ typeof layerId === 'string' &&
+ layerId.length > 0 &&
+ layerId.length <= 256
+ ) {
+ cels[frameIdx] = layerId;
+ celCount++;
+ }
+ }
+ const os = (t.onionSkin && typeof t.onionSkin === 'object'
+ ? t.onionSkin
+ : {}) as Record<string, unknown>;
+
+ return {
+ fps: Math.round(clampFinite(t.fps, 1, 120, 12)),
+ totalFrames,
+ currentFrame: Math.round(clampFinite(t.currentFrame, 0, totalFrames - 1, 0)),
+ cels,
+ onionSkin: {
+ enabled: Boolean(os.enabled),
+ prevFrames: Math.round(clampFinite(os.prevFrames, 0, 10, 1)),
+ nextFrames: Math.round(clampFinite(os.nextFrames, 0, 10, 1)),
+ prevTint: safeString(os.prevTint, 32, '#ef4444'),
+ nextTint: safeString(os.nextTint, 32, '#3b82f6'),
+ opacity: clampFinite(os.opacity, 0, 1, 0.3),
+ },
+ isPlaying: false,
+ loop: t.loop !== false,
+ };
+}
+
+export function sanitizeCanvasResize(
+ raw: unknown
+): { dimensions: CanvasDimensions; options: ResizeCanvasOptions } | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const m = raw as Record<string, unknown>;
+ const d = m.dimensions as Record<string, unknown> | undefined;
+ const o = m.options as Record<string, unknown> | undefined;
+ if (!d || typeof d !== 'object') return null;
+
+ if (
+ typeof d.width !== 'number' ||
+ !Number.isFinite(d.width) ||
+ d.width < 1 ||
+ d.width > MAX_SYNC_CANVAS_DIM ||
+ typeof d.height !== 'number' ||
+ !Number.isFinite(d.height) ||
+ d.height < 1 ||
+ d.height > MAX_SYNC_CANVAS_DIM
+ ) {
+ return null;
+ }
+ const width = Math.round(d.width);
+ const height = Math.round(d.height);
+ const dpi = d.dpi !== undefined ? Math.round(clampFinite(d.dpi, 36, 2400, 300)) : undefined;
+
+ const anchor: AnchorPosition = ALLOWED_ANCHORS.has(o?.anchor as AnchorPosition)
+ ? (o!.anchor as AnchorPosition)
+ : 'center';
+
+ return {
+ dimensions: { width, height, dpi },
+ options: {
+ width,
+ height,
+ dpi,
+ scaleContent: Boolean(o?.scaleContent),
+ anchor,
+ backgroundColor: safeString(o?.backgroundColor, 64, '#ffffff'),
+ },
+ };
+}
+
+// --- Deterministic Layer Tree Diff ---
+
+export type LayerTreeDiff =
+ | { kind: 'none' }
+ | {
+ kind: 'single-update';
+ layerId: string;
+ patch: Partial<WireLayerItem>;
+ clearedFields: LayerClearableField[];
+ maskCreated: boolean;
+ maskRemoved: boolean;
+ rasterized: boolean;
+ }
+ | {
+ kind: 'tree-sync';
+ layers: WireLayerItem[];
+ addedLayerIds: string[];
+ removedLayerIds: string[];
+ maskCreatedIds: string[];
+ maskRemovedIds: string[];
+ };
+
+export function diffWireLayerTrees(
+ prev: WireLayerItem[],
+ next: WireLayerItem[]
+): LayerTreeDiff {
+ const sameOrderAndIds =
+ prev.length === next.length && prev.every((l, i) => l.id === next[i].id);
+
+ if (sameOrderAndIds) {
+ let changedIdx = -1;
+ let changedCount = 0;
+
+ for (let i = 0; i < prev.length; i++) {
+ const a = prev[i];
+ const b = next[i];
+ let layerChanged = false;
+ for (let k = 0; k < SYNCED_LAYER_KEYS.length; k++) {
+ const key = SYNCED_LAYER_KEYS[k];
+ if (!deepEqualWireValue(a[key], b[key])) {
+ layerChanged = true;
+ break;
+ }
+ }
+ if (layerChanged) {
+ changedIdx = i;
+ changedCount++;
+ if (changedCount > 1) break;
+ }
+ }
+
+ if (changedCount === 0) return { kind: 'none' };
+
+ if (changedCount === 1) {
+ const a = prev[changedIdx];
+ const b = next[changedIdx];
+ const patch: Partial<WireLayerItem> = {};
+ const clearedFields: LayerClearableField[] = [];
+
+ for (let k = 0; k < SYNCED_LAYER_KEYS.length; k++) {
+ const key = SYNCED_LAYER_KEYS[k];
+ if (!deepEqualWireValue(a[key], b[key])) {
+ if (b[key] === undefined) {
+ if (CLEARABLE_FIELDS_SET.has(key as LayerClearableField)) {
+ clearedFields.push(key as LayerClearableField);
+ }
+ } else {
+ (patch as Record<string, unknown>)[key] = b[key];
+ }
+ }
+ }
+
+ const maskCreated = !a.hasMask && Boolean(b.hasMask);
+ const maskRemoved = Boolean(a.hasMask) && !b.hasMask;
+ const rasterized =
+ b.type === 'raster' && (a.type === 'text' || a.type === 'balloon' || a.type === 'vector');
+
+ return {
+ kind: 'single-update',
+ layerId: b.id,
+ patch,
+ clearedFields,
+ maskCreated,
+ maskRemoved,
+ rasterized,
+ };
+ }
+ }
+
+ // Structural change (add, delete, reorder, group, duplicate, merge, batch edit)
+ const prevById = new Map(prev.map((l) => [l.id, l]));
+ const nextById = new Map(next.map((l) => [l.id, l]));
+
+ const addedLayerIds: string[] = [];
+ const removedLayerIds: string[] = [];
+ const maskCreatedIds: string[] = [];
+ const maskRemovedIds: string[] = [];
+
+ for (const l of next) {
+ const old = prevById.get(l.id);
+ if (!old) {
+ addedLayerIds.push(l.id);
+ if (l.hasMask) maskCreatedIds.push(l.id);
+ } else {
+ if (!old.hasMask && l.hasMask) maskCreatedIds.push(l.id);
+ if (old.hasMask && !l.hasMask) maskRemovedIds.push(l.id);
+ }
+ }
+ for (const l of prev) {
+ if (!nextById.has(l.id)) {
+ removedLayerIds.push(l.id);
+ }
+ }
+
+ return {
+ kind: 'tree-sync',
+ layers: next,
+ addedLayerIds,
+ removedLayerIds,
+ maskCreatedIds,
+ maskRemovedIds,
+ };
+}
+
+// --- Mask Grayscale Extraction & Application ---
+
+export interface ExtractedMaskRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ pixels: Uint8Array;
+ solidValue: number | null;
+}
+
+export function extractMaskGrayscaleRect(
+ maskCanvas: HTMLCanvasElement,
+ rect?: DirtyRect
+): ExtractedMaskRect | null {
+ const cw = maskCanvas.width;
+ const ch = maskCanvas.height;
+ if (cw <= 0 || ch <= 0) return null;
+
+ const x = rect ? Math.max(0, Math.min(cw - 1, Math.floor(rect.x))) : 0;
+ const y = rect ? Math.max(0, Math.min(ch - 1, Math.floor(rect.y))) : 0;
+ const x2 = rect ? Math.max(x + 1, Math.min(cw, Math.ceil(rect.x + rect.width))) : cw;
+ const y2 = rect ? Math.max(y + 1, Math.min(ch, Math.ceil(rect.y + rect.height))) : ch;
+ const width = x2 - x;
+ const height = y2 - y;
+ if (width <= 0 || height <= 0) return null;
+
+ const ctx = get2DContext(maskCanvas);
+ if (!ctx) return null;
+
+ const rgba = ctx.getImageData(x, y, width, height).data;
+ const count = width * height;
+ const pixels = new Uint8Array(count);
+
+ let firstVal = -1;
+ let isSolid = true;
+
+ for (let i = 0; i < count; i++) {
+ const off = i << 2;
+ const a = rgba[off + 3];
+ const v =
+ a === 255
+ ? Math.round(0.299 * rgba[off] + 0.587 * rgba[off + 1] + 0.114 * rgba[off + 2])
+ : Math.round(
+ (0.299 * rgba[off] + 0.587 * rgba[off + 1] + 0.114 * rgba[off + 2]) * (a / 255)
+ );
+ pixels[i] = v;
+ if (firstVal === -1) {
+ firstVal = v;
+ } else if (isSolid && v !== firstVal) {
+ isSolid = false;
+ }
+ }
+
+ return {
+ x,
+ y,
+ width,
+ height,
+ pixels,
+ solidValue: isSolid && firstVal >= 0 ? firstVal : null,
+ };
+}
+
+export function createWhiteMaskCanvas(width: number, height: number): HTMLCanvasElement | undefined {
+ if (typeof document === 'undefined' || width <= 0 || height <= 0) return undefined;
+ const mask = document.createElement('canvas');
+ mask.width = width;
+ mask.height = height;
+ const mCtx = get2DContext(mask);
+ if (mCtx) {
+ mCtx.fillStyle = '#ffffff';
+ mCtx.fillRect(0, 0, width, height);
+ }
+ return mask;
+}
+
+export function applyMaskDataToCanvas(
+ existingCanvas: HTMLCanvasElement | undefined,
+ dims: CanvasDimensions,
+ msg: LayerMaskDataMessage
+): HTMLCanvasElement | null {
+ if (typeof document === 'undefined') return null;
+ const targetW = Math.max(dims.width, msg.isFullReplace ? msg.width : 0);
+ const targetH = Math.max(dims.height, msg.isFullReplace ? msg.height : 0);
+ if (targetW <= 0 || targetH <= 0) return null;
+
+ let canvas = existingCanvas;
+ if (!canvas || canvas.width !== targetW || canvas.height !== targetH) {
+ if (canvas) releaseTemporaryCanvas(canvas);
+ canvas = createWhiteMaskCanvas(targetW, targetH);
+ if (!canvas) return null;
+ }
+
+ const ctx = get2DContext(canvas);
+ if (!ctx) return null;
+
+ const rx = Math.max(0, Math.min(targetW, msg.x));
+ const ry = Math.max(0, Math.min(targetH, msg.y));
+ const rw = Math.max(0, Math.min(targetW - rx, msg.width));
+ const rh = Math.max(0, Math.min(targetH - ry, msg.height));
+ if (rw <= 0 || rh <= 0) return canvas;
+
+ if (msg.solidFill !== undefined) {
+ const v = Math.max(0, Math.min(255, Math.round(msg.solidFill)));
+ ctx.fillStyle = `rgb(${v},${v},${v})`;
+ ctx.fillRect(rx, ry, rw, rh);
+ return canvas;
+ }
+
+ if (!msg.data || msg.data.byteLength < msg.width * msg.height) return canvas;
+
+ const imgData = ctx.createImageData(rw, rh);
+ const dst = imgData.data;
+ const src = msg.data;
+ const srcStride = msg.width;
+
+ for (let py = 0; py < rh; py++) {
+ const srcRow = py * srcStride;
+ const dstRow = py * rw;
+ for (let px = 0; px < rw; px++) {
+ const v = src[srcRow + px];
+ const off = (dstRow + px) << 2;
+ dst[off] = v;
+ dst[off + 1] = v;
+ dst[off + 2] = v;
+ dst[off + 3] = 255;
+ }
+ }
+ ctx.putImageData(imgData, rx, ry);
+ return canvas;
+}
+
+// --- Remote Layer Merge Helpers ---
+
+export function mergeRemoteWireLayerIntoLocal(
+ local: LayerItem | undefined,
+ wire: WireLayerItem,
+ dims: CanvasDimensions
+): LayerItem {
+ const { hasMask, ...wireRest } = wire;
+ let maskCanvas = local?.maskCanvas;
+ let maskThumbnailUrl = local?.maskThumbnailUrl;
+ let maskVersion = local?.maskVersion;
+
+ if (hasMask) {
+ if (!maskCanvas) {
+ maskCanvas = createWhiteMaskCanvas(dims.width, dims.height);
+ maskVersion = 1;
+ }
+ } else if (maskCanvas) {
+ releaseTemporaryCanvas(maskCanvas);
+ maskCanvas = undefined;
+ maskThumbnailUrl = undefined;
+ maskVersion = undefined;
+ }
+
+ return {
+ ...wireRest,
+ collapsed: local?.collapsed ?? false,
+ thumbnailUrl: local?.thumbnailUrl ?? '',
+ maskCanvas,
+ maskThumbnailUrl,
+ maskVersion,
+ maskEnabled: hasMask ? wire.maskEnabled ?? true : undefined,
+ maskLinked: hasMask ? wire.maskLinked ?? true : undefined,
+ };
+}
+
+export function applyRemoteLayerPatch(
+ local: LayerItem,
+ patch: Partial<WireLayerItem>,
+ clearedFields?: LayerClearableField[],
+ dims?: CanvasDimensions
+): LayerItem {
+ const { hasMask, ...patchRest } = patch;
+ const next: LayerItem = {
+ ...local,
+ ...patchRest,
+ };
+
+ if (clearedFields && clearedFields.length > 0) {
+ for (const field of clearedFields) {
+ if (field === 'hasMask') continue;
+ delete (next as unknown as Record<string, unknown>)[field];
+ }
+ }
+
+ const maskRemoved =
+ hasMask === false || (clearedFields !== undefined && clearedFields.includes('hasMask'));
+ if (maskRemoved) {
+ if (local.maskCanvas) {
+ releaseTemporaryCanvas(local.maskCanvas);
+ }
+ next.maskCanvas = undefined;
+ next.maskThumbnailUrl = undefined;
+ next.maskVersion = undefined;
+ next.maskEnabled = undefined;
+ next.maskLinked = undefined;
+ } else if (hasMask === true && !local.maskCanvas && dims && dims.width > 0 && dims.height > 0) {
+ next.maskCanvas = createWhiteMaskCanvas(dims.width, dims.height);
+ next.maskVersion = 1;
+ next.maskEnabled = next.maskEnabled ?? true;
+ next.maskLinked = next.maskLinked ?? true;
+ }
+
+ return next;
+}
diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.ts
index 3439e64..44e5c68 100644
--- a/src/utils/colorMixingEngine.ts
+++ b/src/utils/colorMixingEngine.ts
@@ -1,5 +1,5 @@
/**
- * Real-Time Color Mixing & Subtractive Pigment Engine for Sora Paint.
+ * Real-Time Color Mixing & Subtractive Pigment Engine for Ink Studio.
* Implements authentic Clip Studio Paint (CSP) & Photoshop Mixer Brush mathematics:
* - Subtractive Pigment Mixing (OKLab + Kubelka-Munk absorption / scattering)
* (Yellow + Blue = vibrant Green, Red + Blue = Violet, Red + Yellow = Orange)
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index 024f386..40897f6 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -8,5544 +8,329 @@
* anti-moiré screentones, vector layers, and comic frame clipping.
*/
-import { LayerItem, CanvasDimensions, BlendMode, CanvasColorMode, LayerStyles, SoftProofSettings, isFolderLikeLayer } from '../types/editor';
-import { SparseTileGrid, TILE_SIZE, TileBuffer, globalTileGrid, getTileKey } from './tileEngine';
-import { getCanvasCompositeOperation } from './canvasUtils';
+import { CanvasDimensions, LayerItem } from '../types/editor';
+import { SparseTileGrid, TILE_SIZE, globalTileGrid } from './tileEngine';
+import { calculateVisibleDocumentBounds } from './compositor/bounds';
+import { disposeFboSurface, disposePingPongTarget } from './compositor/fboManager';
+import { initGL, resetGLStateOnContextLost } from './compositor/glInit';
+import { renderLowResPreview } from './compositor/previewRenderer';
+import { renderFrame } from './compositor/renderFrame';
+import { LayerStackCacheTracker } from './compositor/stackCache';
import {
- applyMultiFrameClip,
- buildFrameBorderTriangles,
- renderFrameBorder,
- triangulatePolygon,
-} from './frameEngine';
+ invalidateMaskTexture,
+ invalidateTileTextures,
+} from './compositor/tileTexturePool';
import {
- buildCurvesCombinedLut,
- buildGradientMapLut,
- buildLevelsLut,
- evaluateColorBalancePixel,
- applyAdjustment,
-} from './tonalEngine';
-
-export interface ViewportTransform {
- pan: { x: number; y: number };
- zoom: number;
- rotation: number; // in degrees
- flipX?: boolean;
- flipY?: boolean;
-}
-
-export const BLEND_MODE_MAP: Record<BlendMode, number> = {
- normal: 0,
- multiply: 1,
- screen: 2,
- overlay: 3,
- darken: 4,
- lighten: 5,
- 'color-dodge': 6,
- 'color-burn': 7,
- 'hard-light': 8,
- 'soft-light': 9,
- difference: 10,
- exclusion: 11,
- 'pass-through': 12,
- 'linear-burn': 13,
- 'add-glow': 14,
- 'color-dodge-glow': 15,
- divide: 16,
-};
-
-export interface LayerTreeNode {
- layer: LayerItem;
- children: LayerTreeNode[];
-}
-
-export function buildLayerTree(layers: LayerItem[]): LayerTreeNode[] {
- const nodeMap = new Map<string, LayerTreeNode>();
- for (const layer of layers) {
- nodeMap.set(layer.id, { layer, children: [] });
- }
-
- const rootNodes: LayerTreeNode[] = [];
- for (const layer of layers) {
- const node = nodeMap.get(layer.id)!;
- if (layer.parentId && nodeMap.has(layer.parentId)) {
- nodeMap.get(layer.parentId)!.children.push(node);
- } else {
- rootNodes.push(node);
- }
- }
-
- return rootNodes;
-}
-
-export interface TreeNodeRenderGroup {
- baseNode: LayerTreeNode;
- clippedNodes: LayerTreeNode[];
-}
-
-export function groupTreeNodesForCompositing(nodesBottomToTop: LayerTreeNode[]): TreeNodeRenderGroup[] {
- const groups: TreeNodeRenderGroup[] = [];
- let currentGroup: TreeNodeRenderGroup | null = null;
-
- for (const node of nodesBottomToTop) {
- if (node.layer.clipped && currentGroup) {
- currentGroup.clippedNodes.push(node);
- } else {
- currentGroup = {
- baseNode: node,
- clippedNodes: [],
- };
- groups.push(currentGroup);
- }
- }
-
- return groups;
-}
-
-// Document-Space Solid Polygon Shaders for Frame Border Folder Stencil Clipping & Borders
-export const FRAME_POLY_VERTEX_SHADER = `#version 300 es
-precision highp float;
-
-in vec2 a_docPos;
-uniform vec2 u_docDimensions;
-uniform vec2 u_viewportSize;
-uniform vec2 u_pan;
-uniform float u_zoom;
-uniform float u_rotationRad;
-uniform vec2 u_flip;
-uniform float u_dpr;
-
-void main() {
- vec2 centered = (a_docPos - u_docDimensions * 0.5) * u_flip;
- float cosR = cos(u_rotationRad);
- float sinR = sin(u_rotationRad);
- vec2 rotated = vec2(
- centered.x * cosR - centered.y * sinR,
- centered.x * sinR + centered.y * cosR
- );
- vec2 screenPos = (u_pan + rotated * u_zoom) * u_dpr;
- vec2 clipPos = vec2(
- (2.0 * screenPos.x / u_viewportSize.x) - 1.0,
- 1.0 - (2.0 * screenPos.y / u_viewportSize.y)
- );
- gl_Position = vec4(clipPos, 0.0, 1.0);
-}
-`;
-
-export const FRAME_POLY_FRAGMENT_SHADER = `#version 300 es
-precision highp float;
-
-uniform vec4 u_color;
-out vec4 fragColor;
-
-void main() {
- fragColor = vec4(u_color.rgb * u_color.a, u_color.a);
-}
-`;
-
-// Fullscreen blit for isolated folder compositing
-export const FOLDER_BLIT_VERTEX_SHADER = `#version 300 es
-precision highp float;
-in vec2 a_quadPos; // [0, 1] x [0, 1]
-out vec2 v_uv;
-void main() {
- v_uv = a_quadPos;
- gl_Position = vec4(a_quadPos.x * 2.0 - 1.0, a_quadPos.y * 2.0 - 1.0, 0.0, 1.0);
-}
-`;
-
-export const FOLDER_BLIT_FRAGMENT_SHADER = `#version 300 es
-precision highp float;
-in vec2 v_uv;
-uniform sampler2D u_blitTexture;
-uniform sampler2D u_backdropTexture;
-uniform int u_hasBackdrop;
-uniform int u_blendMode;
-uniform float u_blitOpacity;
-out vec4 fragColor;
-
-float blendChannelFolder(float b, float s, int mode) {
- if (mode == 1) return b * s; // multiply
- if (mode == 2) return b + s - b * s; // screen
- if (mode == 3) return b < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // overlay
- if (mode == 4) return min(b, s); // darken
- if (mode == 5) return max(b, s); // lighten
- if (mode == 6) return b <= 0.0 ? 0.0 : (s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s))); // color-dodge
- if (mode == 7) return b >= 1.0 ? 1.0 : (s <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - b) / max(0.0001, s))); // color-burn
- if (mode == 8) return s < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // hard-light
- if (mode == 9) { // soft-light
- float d = b <= 0.25 ? (((16.0 * b - 12.0) * b + 4.0) * b) : sqrt(max(0.0, b));
- return s <= 0.5 ? (b - (1.0 - 2.0 * s) * b * (1.0 - b)) : (b + (2.0 * s - 1.0) * (d - b));
- }
- if (mode == 10) return abs(b - s); // difference
- if (mode == 11) return b + s - 2.0 * b * s; // exclusion
- if (mode == 13) return max(0.0, b + s - 1.0); // linear-burn
- if (mode == 14) return min(1.0, b + s); // add-glow
- if (mode == 15) return s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s)); // color-dodge-glow
- if (mode == 16) return s <= 0.0001 ? 1.0 : clamp(b / s, 0.0, 1.0); // divide
- return s;
-}
-
-vec3 evaluateBlendModeFolder(vec3 Cb, vec3 Cs, int mode) {
- return vec3(
- blendChannelFolder(Cb.r, Cs.r, mode),
- blendChannelFolder(Cb.g, Cs.g, mode),
- blendChannelFolder(Cb.b, Cs.b, mode)
- );
-}
-
-void main() {
- vec4 srcPremul = texture(u_blitTexture, v_uv);
- float srcA = srcPremul.a * u_blitOpacity;
- if (srcA < 0.002) {
- discard;
- }
- vec3 Cs = srcPremul.a > 0.001 ? clamp(srcPremul.rgb / srcPremul.a, 0.0, 1.0) : vec3(0.0);
- if (u_hasBackdrop == 1 && u_blendMode != 0 && u_blendMode != 12) {
- vec4 dstPremul = texture(u_backdropTexture, v_uv);
- vec3 Cb = dstPremul.a > 0.001 ? clamp(dstPremul.rgb / dstPremul.a, 0.0, 1.0) : vec3(1.0);
- vec3 blended = evaluateBlendModeFolder(Cb, Cs, u_blendMode);
- Cs = mix(Cs, blended, dstPremul.a);
- }
- fragColor = vec4(Cs * srcA, srcA);
-}
-`;
-
-export interface LayerRenderGroup {
- baseLayer: LayerItem;
- clippedLayers: LayerItem[];
-}
-
-/**
- * Groups consecutive clipped layers under their immediate non-clipped base layer underneath.
- * Layers are provided in bottom-to-top rendering order.
- */
-export function groupLayersForCompositing(layersBottomToTop: LayerItem[]): LayerRenderGroup[] {
- const groups: LayerRenderGroup[] = [];
- let currentGroup: LayerRenderGroup | null = null;
-
- for (const layer of layersBottomToTop) {
- if (layer.clipped && currentGroup) {
- currentGroup.clippedLayers.push(layer);
- } else {
- currentGroup = {
- baseLayer: layer,
- clippedLayers: [],
- };
- groups.push(currentGroup);
- }
- }
-
- return groups;
-}
-
-// Vertex Shader: Affine transformation in document space mapped to WebGL clip space
-export const COMPOSITOR_VERTEX_SHADER = `#version 300 es
-precision highp float;
-
-in vec2 a_quadPos; // [0, 1] x [0, 1]
-uniform vec2 u_tileOrigin; // tile position in document space
-uniform vec2 u_tileSize; // tile or quad size in document space
-uniform vec2 u_docDimensions; // canvas width, height
-uniform vec2 u_viewportSize; // viewport width, height
-uniform vec2 u_pan;
-uniform float u_zoom;
-uniform float u_rotationRad;
-uniform vec2 u_flip;
-uniform float u_dpr;
-
-out vec2 v_texCoord;
-out vec2 v_docCoord;
-
-void main() {
- v_texCoord = a_quadPos;
-
- // Position within document space
- vec2 docPos = u_tileOrigin + a_quadPos * u_tileSize;
- v_docCoord = docPos;
-
- // Center document around (0, 0) and apply non-destructive view flip
- vec2 centered = (docPos - u_docDimensions * 0.5) * u_flip;
-
- // Rotate
- float cosR = cos(u_rotationRad);
- float sinR = sin(u_rotationRad);
- vec2 rotated = vec2(
- centered.x * cosR - centered.y * sinR,
- centered.x * sinR + centered.y * cosR
- );
-
- // Scale and translate: convert CSS screen coordinates to physical device pixels
- vec2 screenPos = (u_pan + rotated * u_zoom) * u_dpr;
-
- // Convert physical device pixels to WebGL clip coordinates [-1, 1]
- vec2 clipPos = vec2(
- (2.0 * screenPos.x / u_viewportSize.x) - 1.0,
- 1.0 - (2.0 * screenPos.y / u_viewportSize.y)
- );
-
- gl_Position = vec4(clipPos, 0.0, 1.0);
-}
-`;
-
-// Fragment Shader: Layer Blending, Screentones with Anti-Moiré, and Layer Color Tinting
-export const COMPOSITOR_FRAGMENT_SHADER = `#version 300 es
-precision highp float;
-
-in vec2 v_texCoord;
-in vec2 v_docCoord;
-
-uniform sampler2D u_tileTexture;
-uniform sampler2D u_backdropTexture;
-uniform int u_hasBackdrop;
-uniform vec2 u_viewportSize;
-uniform float u_layerOpacity;
-uniform int u_blendMode;
-
-// Background Uniforms
-uniform int u_isBackground;
-uniform int u_showCheckerboard;
-
-// Screentone Uniforms
-uniform int u_toneEnabled;
-uniform float u_toneFrequency;
-uniform float u_toneAngleRad;
-uniform float u_toneDpi;
-uniform int u_toneDotShape;
-uniform float u_toneDensity;
-uniform int u_toneDensityType;
-uniform float u_zoom;
-
-// Layer Tint Uniforms
-uniform int u_layerColorEnabled;
-uniform vec3 u_layerColor;
-uniform vec3 u_layerSubColor;
-
-// Layer Mask Uniforms
-uniform vec2 u_docDimensions;
-uniform sampler2D u_maskTexture;
-uniform int u_maskEnabled;
-
-// CSP Expression Color Uniforms (0: color, 1: gray, 2: monochrome)
-uniform int u_expressionMode;
-uniform float u_monoThreshold;
-uniform int u_monoExpressBlack;
-uniform int u_monoExpressWhite;
-
-out vec4 fragColor;
-
-float fractVal(float x) {
- return x - floor(x);
-}
-
-float blendChannel(float b, float s, int mode) {
- if (mode == 1) return b * s; // multiply
- if (mode == 2) return b + s - b * s; // screen
- if (mode == 3) return b < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // overlay
- if (mode == 4) return min(b, s); // darken
- if (mode == 5) return max(b, s); // lighten
- if (mode == 6) return b <= 0.0 ? 0.0 : (s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s))); // color-dodge
- if (mode == 7) return b >= 1.0 ? 1.0 : (s <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - b) / max(0.0001, s))); // color-burn
- if (mode == 8) return s < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // hard-light
- if (mode == 9) { // soft-light (W3C / Photoshop)
- float d = b <= 0.25 ? (((16.0 * b - 12.0) * b + 4.0) * b) : sqrt(max(0.0, b));
- return s <= 0.5 ? (b - (1.0 - 2.0 * s) * b * (1.0 - b)) : (b + (2.0 * s - 1.0) * (d - b));
- }
- if (mode == 10) return abs(b - s); // difference
- if (mode == 11) return b + s - 2.0 * b * s; // exclusion
- if (mode == 13) return max(0.0, b + s - 1.0); // linear-burn (CSP / Krita)
- if (mode == 14) return min(1.0, b + s); // add-glow (CSP / Krita)
- if (mode == 15) return s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s)); // color-dodge-glow (CSP)
- if (mode == 16) return s <= 0.0001 ? 1.0 : clamp(b / s, 0.0, 1.0); // divide (CSP / Krita)
- return s;
-}
-
-vec3 evaluateBlendMode(vec3 Cb, vec3 Cs, int mode) {
- return vec3(
- blendChannel(Cb.r, Cs.r, mode),
- blendChannel(Cb.g, Cs.g, mode),
- blendChannel(Cb.b, Cs.b, mode)
- );
-}
-
-vec4 evaluateScreentone(vec4 srcColor, vec2 docCoord) {
- if (srcColor.a < 0.0039) {
- return vec4(0.0);
- }
-
- float density;
- if (u_toneDensityType == 0) {
- // Specified density
- density = clamp(u_toneDensity * srcColor.a, 0.0, 1.0);
- } else {
- // Luminance
- float lum = dot(srcColor.rgb, vec3(0.299, 0.587, 0.114));
- density = clamp((1.0 - lum) * srcColor.a, 0.0, 1.0);
- }
-
- if (density <= 0.001) return vec4(0.0);
- if (density >= 0.999) return vec4(0.0, 0.0, 0.0, 1.0);
-
- float cellSize = max(3.5, u_toneDpi / max(1.0, u_toneFrequency));
- float cosA = cos(u_toneAngleRad);
- float sinA = sin(u_toneAngleRad);
-
- float xr = docCoord.x * cosA - docCoord.y * sinA;
- float yr = docCoord.x * sinA + docCoord.y * cosA;
-
- float u = fractVal(xr / cellSize) - 0.5;
- float v = fractVal(yr / cellSize) - 0.5;
-
- float spot;
- if (u_toneDotShape == 2) {
- // Line
- spot = 1.0 - 2.0 * abs(u);
- } else if (u_toneDotShape == 3) {
- // Diamond
- spot = 1.0 - (abs(u) + abs(v));
- } else {
- // Euclidean circle
- float absU = abs(u);
- float absV = abs(v);
- if (absU + absV <= 0.5) {
- spot = 1.0 - 2.0 * (u * u + v * v);
- } else {
- float uc = absU - 0.5;
- float vc = absV - 0.5;
- spot = 2.0 * (uc * uc + vc * vc);
- }
- }
-
- float diff = spot - (1.0 - density);
- float halfSpan = min(0.25, 0.75 / cellSize);
- float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);
- vec4 halftoneColor = vec4(0.0, 0.0, 0.0, coverage);
-
- // Anti-moiré smoothstep crossfading
- float moireBlend = smoothstep(0.35, 0.95, u_zoom);
- vec4 contColor = vec4(0.0, 0.0, 0.0, density);
- return mix(contColor, halftoneColor, moireBlend);
-}
-
-vec4 applyLayerTint(vec4 color) {
- if (u_layerColorEnabled == 0) return color;
- float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));
- vec3 tinted = mix(u_layerColor, u_layerSubColor, lum);
- return vec4(tinted, color.a);
-}
-
-void main() {
- if (u_isBackground == 1) {
- vec2 outsideDoc = max(vec2(0.0) - v_docCoord, v_docCoord - u_docDimensions);
- if (outsideDoc.x > 0.0 || outsideDoc.y > 0.0) {
- float safeZoom = max(0.01, u_zoom);
- vec2 outsidePx = outsideDoc * safeZoom;
- float borderDist = max(outsidePx.x, outsidePx.y);
- if (borderDist <= 1.0) {
- fragColor = vec4(0.086, 0.086, 0.086, 1.0);
- return;
- }
- vec2 shadowCoord = v_docCoord - vec2(0.0, 10.0 / safeZoom);
- vec2 shadowOutside = max(vec2(0.0) - shadowCoord, shadowCoord - u_docDimensions);
- float shadowDist = length(shadowOutside * safeZoom);
- float shadowA = 0.55 * exp(-shadowDist * shadowDist / 520.0) * smoothstep(48.0, 0.0, shadowDist);
- if (shadowA < 0.002) {
- discard;
- }
- fragColor = vec4(0.0, 0.0, 0.0, shadowA);
- return;
- }
- if (u_showCheckerboard == 1) {
- vec2 checkCoord = floor(v_docCoord / 16.0);
- float check = mod(checkCoord.x + checkCoord.y, 2.0);
- vec3 checkColor = check > 0.5 ? vec3(0.157, 0.157, 0.157) : vec3(0.125, 0.125, 0.125);
- fragColor = vec4(checkColor, 1.0);
- } else {
- fragColor = vec4(1.0, 1.0, 1.0, 1.0);
- }
- return;
- }
-
- vec4 rawTex = texture(u_tileTexture, v_texCoord);
-
- if (rawTex.a < 0.002) {
- discard;
- }
-
- vec4 texColor = vec4(clamp(rawTex.rgb / rawTex.a, 0.0, 1.0), rawTex.a);
- vec4 finalColor = texColor;
-
- if (u_expressionMode == 1) {
- float gLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
- finalColor.rgb = vec3(gLum);
- } else if (u_expressionMode == 2) {
- float mLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
- float monoAlpha = u_zoom >= 0.99 ? step(0.5, finalColor.a) : finalColor.a;
- if (mLum < u_monoThreshold) {
- if (u_monoExpressBlack == 1) {
- finalColor = vec4(0.0, 0.0, 0.0, monoAlpha);
- } else {
- discard;
- }
- } else {
- if (u_monoExpressWhite == 1) {
- finalColor = vec4(1.0, 1.0, 1.0, monoAlpha);
- } else {
- discard;
- }
- }
- }
-
- if (u_toneEnabled == 1) {
- finalColor = evaluateScreentone(finalColor, v_docCoord);
- }
-
- if (u_layerColorEnabled == 1) {
- finalColor = applyLayerTint(finalColor);
- }
-
- if (u_maskEnabled == 1) {
- vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);
- vec4 maskPixel = texture(u_maskTexture, maskCoord);
- float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
- finalColor.a *= maskLum;
- }
-
- finalColor.a *= u_layerOpacity;
-
- if (finalColor.a < 0.002) {
- discard;
- }
-
- if (u_hasBackdrop == 1 && u_blendMode != 0 && u_blendMode != 12) {
- vec2 screenUV = clamp(gl_FragCoord.xy / max(vec2(1.0), u_viewportSize), 0.0, 1.0);
- vec4 dstPremul = texture(u_backdropTexture, screenUV);
- vec3 Cb = dstPremul.a > 0.001 ? clamp(dstPremul.rgb / dstPremul.a, 0.0, 1.0) : vec3(1.0);
- vec3 Cs = clamp(finalColor.rgb, 0.0, 1.0);
- vec3 blended = evaluateBlendMode(Cb, Cs, u_blendMode);
- finalColor.rgb = mix(Cs, blended, dstPremul.a);
- }
-
- fragColor = vec4(finalColor.rgb * finalColor.a, finalColor.a);
-}
-`;
-
-// Instanced Vertex Shader: Batched tile rendering via TEXTURE_2D_ARRAY + drawArraysInstanced
-export const COMPOSITOR_INSTANCED_VERTEX_SHADER = `#version 300 es
-precision highp float;
-
-in vec2 a_quadPos; // [0, 1] x [0, 1]
-in vec3 a_instanceData; // xy = tileOrigin in document space, z = TEXTURE_2D_ARRAY slice index
-uniform vec2 u_tileSize; // tile size in document space (TILE_SIZE << lod)
-uniform vec2 u_docDimensions;
-uniform vec2 u_viewportSize;
-uniform vec2 u_pan;
-uniform float u_zoom;
-uniform float u_rotationRad;
-uniform vec2 u_flip;
-uniform float u_dpr;
-
-out vec2 v_texCoord;
-out vec2 v_docCoord;
-flat out float v_sliceIndex;
-
-void main() {
- v_texCoord = a_quadPos;
- v_sliceIndex = a_instanceData.z;
-
- vec2 docPos = a_instanceData.xy + a_quadPos * u_tileSize;
- v_docCoord = docPos;
-
- vec2 centered = (docPos - u_docDimensions * 0.5) * u_flip;
-
- float cosR = cos(u_rotationRad);
- float sinR = sin(u_rotationRad);
- vec2 rotated = vec2(
- centered.x * cosR - centered.y * sinR,
- centered.x * sinR + centered.y * cosR
- );
-
- vec2 screenPos = (u_pan + rotated * u_zoom) * u_dpr;
-
- vec2 clipPos = vec2(
- (2.0 * screenPos.x / u_viewportSize.x) - 1.0,
- 1.0 - (2.0 * screenPos.y / u_viewportSize.y)
- );
-
- gl_Position = vec4(clipPos, 0.0, 1.0);
-}
-`;
-
-// Instanced Fragment Shader: Samples TEXTURE_2D_ARRAY slice for batched single-draw-call layer rendering
-export const COMPOSITOR_INSTANCED_FRAGMENT_SHADER = `#version 300 es
-precision highp float;
-precision highp sampler2DArray;
-
-in vec2 v_texCoord;
-in vec2 v_docCoord;
-flat in float v_sliceIndex;
-
-uniform sampler2DArray u_tileArrayTexture;
-uniform sampler2D u_backdropTexture;
-uniform int u_hasBackdrop;
-uniform vec2 u_viewportSize;
-uniform float u_layerOpacity;
-uniform int u_blendMode;
-
-// Screentone Uniforms
-uniform int u_toneEnabled;
-uniform float u_toneFrequency;
-uniform float u_toneAngleRad;
-uniform float u_toneDpi;
-uniform int u_toneDotShape;
-uniform float u_toneDensity;
-uniform int u_toneDensityType;
-uniform float u_zoom;
-
-// Layer Tint Uniforms
-uniform int u_layerColorEnabled;
-uniform vec3 u_layerColor;
-uniform vec3 u_layerSubColor;
-
-// Layer Mask Uniforms
-uniform vec2 u_docDimensions;
-uniform sampler2D u_maskTexture;
-uniform int u_maskEnabled;
-
-// CSP Expression Color Uniforms (0: color, 1: gray, 2: monochrome)
-uniform int u_expressionMode;
-uniform float u_monoThreshold;
-uniform int u_monoExpressBlack;
-uniform int u_monoExpressWhite;
-
-out vec4 fragColor;
-
-float fractVal(float x) {
- return x - floor(x);
-}
-
-float blendChannel(float b, float s, int mode) {
- if (mode == 1) return b * s;
- if (mode == 2) return b + s - b * s;
- if (mode == 3) return b < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s));
- if (mode == 4) return min(b, s);
- if (mode == 5) return max(b, s);
- if (mode == 6) return b <= 0.0 ? 0.0 : (s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s)));
- if (mode == 7) return b >= 1.0 ? 1.0 : (s <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - b) / max(0.0001, s)));
- if (mode == 8) return s < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s));
- if (mode == 9) {
- float d = b <= 0.25 ? (((16.0 * b - 12.0) * b + 4.0) * b) : sqrt(max(0.0, b));
- return s <= 0.5 ? (b - (1.0 - 2.0 * s) * b * (1.0 - b)) : (b + (2.0 * s - 1.0) * (d - b));
- }
- if (mode == 10) return abs(b - s);
- if (mode == 11) return b + s - 2.0 * b * s;
- if (mode == 13) return max(0.0, b + s - 1.0);
- if (mode == 14) return min(1.0, b + s);
- if (mode == 15) return s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s));
- if (mode == 16) return s <= 0.0001 ? 1.0 : clamp(b / s, 0.0, 1.0);
- return s;
-}
-
-vec3 evaluateBlendMode(vec3 Cb, vec3 Cs, int mode) {
- return vec3(
- blendChannel(Cb.r, Cs.r, mode),
- blendChannel(Cb.g, Cs.g, mode),
- blendChannel(Cb.b, Cs.b, mode)
- );
-}
-
-vec4 evaluateScreentone(vec4 srcColor, vec2 docCoord) {
- if (srcColor.a < 0.0039) {
- return vec4(0.0);
- }
-
- float density;
- if (u_toneDensityType == 0) {
- density = clamp(u_toneDensity * srcColor.a, 0.0, 1.0);
- } else {
- float lum = dot(srcColor.rgb, vec3(0.299, 0.587, 0.114));
- density = clamp((1.0 - lum) * srcColor.a, 0.0, 1.0);
- }
-
- if (density <= 0.001) return vec4(0.0);
- if (density >= 0.999) return vec4(0.0, 0.0, 0.0, 1.0);
-
- float cellSize = max(3.5, u_toneDpi / max(1.0, u_toneFrequency));
- float cosA = cos(u_toneAngleRad);
- float sinA = sin(u_toneAngleRad);
-
- float xr = docCoord.x * cosA - docCoord.y * sinA;
- float yr = docCoord.x * sinA + docCoord.y * cosA;
-
- float u = fractVal(xr / cellSize) - 0.5;
- float v = fractVal(yr / cellSize) - 0.5;
-
- float spot;
- if (u_toneDotShape == 2) {
- spot = 1.0 - 2.0 * abs(u);
- } else if (u_toneDotShape == 3) {
- spot = 1.0 - (abs(u) + abs(v));
- } else {
- float absU = abs(u);
- float absV = abs(v);
- if (absU + absV <= 0.5) {
- spot = 1.0 - 2.0 * (u * u + v * v);
- } else {
- float uc = absU - 0.5;
- float vc = absV - 0.5;
- spot = 2.0 * (uc * uc + vc * vc);
- }
- }
-
- float diff = spot - (1.0 - density);
- float halfSpan = min(0.25, 0.75 / cellSize);
- float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);
- vec4 halftoneColor = vec4(0.0, 0.0, 0.0, coverage);
-
- float moireBlend = smoothstep(0.35, 0.95, u_zoom);
- vec4 contColor = vec4(0.0, 0.0, 0.0, density);
- return mix(contColor, halftoneColor, moireBlend);
-}
-
-vec4 applyLayerTint(vec4 color) {
- if (u_layerColorEnabled == 0) return color;
- float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));
- vec3 tinted = mix(u_layerColor, u_layerSubColor, lum);
- return vec4(tinted, color.a);
-}
-
-void main() {
- // Single hardware TMU fetch on premultiplied RGBA8 TEXTURE_2D_ARRAY
- vec4 rawTex = texture(u_tileArrayTexture, vec3(v_texCoord, v_sliceIndex));
-
- if (rawTex.a < 0.002) {
- discard;
- }
-
- vec4 texColor = vec4(clamp(rawTex.rgb / rawTex.a, 0.0, 1.0), rawTex.a);
- vec4 finalColor = texColor;
-
- if (u_expressionMode == 1) {
- float gLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
- finalColor.rgb = vec3(gLum);
- } else if (u_expressionMode == 2) {
- float mLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
- float monoAlpha = u_zoom >= 0.99 ? step(0.5, finalColor.a) : finalColor.a;
- if (mLum < u_monoThreshold) {
- if (u_monoExpressBlack == 1) {
- finalColor = vec4(0.0, 0.0, 0.0, monoAlpha);
- } else {
- discard;
- }
- } else {
- if (u_monoExpressWhite == 1) {
- finalColor = vec4(1.0, 1.0, 1.0, monoAlpha);
- } else {
- discard;
- }
- }
- }
-
- if (u_toneEnabled == 1) {
- finalColor = evaluateScreentone(finalColor, v_docCoord);
- }
-
- if (u_layerColorEnabled == 1) {
- finalColor = applyLayerTint(finalColor);
- }
-
- if (u_maskEnabled == 1) {
- vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);
- vec4 maskPixel = texture(u_maskTexture, maskCoord);
- float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
- finalColor.a *= maskLum;
- }
-
- finalColor.a *= u_layerOpacity;
-
- if (finalColor.a < 0.002) {
- discard;
- }
-
- if (u_hasBackdrop == 1 && u_blendMode != 0 && u_blendMode != 12) {
- vec2 screenUV = clamp(gl_FragCoord.xy / max(vec2(1.0), u_viewportSize), 0.0, 1.0);
- vec4 dstPremul = texture(u_backdropTexture, screenUV);
- vec3 Cb = dstPremul.a > 0.001 ? clamp(dstPremul.rgb / dstPremul.a, 0.0, 1.0) : vec3(1.0);
- vec3 Cs = clamp(finalColor.rgb, 0.0, 1.0);
- vec3 blended = evaluateBlendMode(Cb, Cs, u_blendMode);
- finalColor.rgb = mix(Cs, blended, dstPremul.a);
- }
-
- fragColor = vec4(finalColor.rgb * finalColor.a, finalColor.a);
-}
-`;
-
-// Viewport-Space Draft Vertex Shader: Maps a viewport-sized Canvas2D draft overlay 1:1 to screen
-// while reconstructing exact document coordinates for screentone & layer mask evaluation in-stack.
-export const VIEWPORT_DRAFT_VERTEX_SHADER = `#version 300 es
-precision highp float;
-
-in vec2 a_quadPos; // [0, 1] x [0, 1] (0,0 = top-left of viewport)
-uniform vec2 u_docDimensions;
-uniform vec2 u_viewportSize;
-uniform vec2 u_pan;
-uniform float u_zoom;
-uniform float u_rotationRad;
-uniform vec2 u_flip;
-uniform float u_dpr;
-
-out vec2 v_texCoord;
-out vec2 v_docCoord;
-
-void main() {
- v_texCoord = a_quadPos;
-
- vec2 clipPos = vec2(a_quadPos.x * 2.0 - 1.0, 1.0 - a_quadPos.y * 2.0);
- vec2 screenPos = a_quadPos * u_viewportSize;
- vec2 cssScreen = screenPos / max(0.0001, u_dpr);
- vec2 unscaled = (cssScreen - u_pan) / max(0.0001, u_zoom);
-
- float cosR = cos(u_rotationRad);
- float sinR = sin(u_rotationRad);
- vec2 unrotated = vec2(
- unscaled.x * cosR + unscaled.y * sinR,
- -unscaled.x * sinR + unscaled.y * cosR
- );
-
- v_docCoord = unrotated * u_flip + u_docDimensions * 0.5;
- gl_Position = vec4(clipPos, 0.0, 1.0);
-}
-`;
-
-// Fragment Shader: Non-Destructive Adjustment Layers with Real-Time LUT Transform
-export const ADJUSTMENT_FRAGMENT_SHADER = `#version 300 es
-precision highp float;
-
-in vec2 v_texCoord;
-in vec2 v_docCoord;
-
-uniform sampler2D u_snapshotTexture;
-uniform sampler2D u_lutTexture;
-uniform int u_adjMode; // 0: per-channel LUT (Curves/Levels), 1: luminance mapping (Gradient Map)
-uniform float u_layerOpacity;
-uniform int u_maskEnabled;
-uniform sampler2D u_maskTexture;
-uniform vec2 u_docDimensions;
-uniform vec2 u_viewportSize;
-
-out vec4 fragColor;
-
-void main() {
- vec2 screenUV = gl_FragCoord.xy / u_viewportSize;
- vec4 baseColor = texture(u_snapshotTexture, screenUV);
-
- if (baseColor.a < 0.001) {
- discard;
- }
-
- vec3 unPremult = baseColor.rgb / max(0.001, baseColor.a);
- vec3 adjusted;
-
- if (u_adjMode == 1) {
- // Gradient map: map luminance to LUT
- float lum = clamp(dot(unPremult, vec3(0.299, 0.587, 0.114)), 0.0, 1.0);
- adjusted = texture(u_lutTexture, vec2(lum, 0.5)).rgb;
- } else {
- // Curves / Levels / Color Balance
- float r = texture(u_lutTexture, vec2(clamp(unPremult.r, 0.0, 1.0), 0.5)).r;
- float g = texture(u_lutTexture, vec2(clamp(unPremult.g, 0.0, 1.0), 0.5)).g;
- float b = texture(u_lutTexture, vec2(clamp(unPremult.b, 0.0, 1.0), 0.5)).b;
- adjusted = vec3(r, g, b);
- }
-
- float maskFactor = u_layerOpacity;
- if (u_maskEnabled == 1) {
- vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);
- vec4 maskPixel = texture(u_maskTexture, maskCoord);
- float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
- maskFactor *= maskLum;
- }
-
- vec3 finalRgb = mix(unPremult, adjusted, maskFactor);
- fragColor = vec4(finalRgb * baseColor.a, baseColor.a);
-}
-`;
-
-export function hasActiveLayerStyles(styles?: LayerStyles): boolean {
- if (!styles) return false;
- const hasStroke = Boolean(styles.stroke?.enabled && styles.stroke.size > 0 && styles.stroke.opacity > 0);
- const hasShadow = Boolean(styles.dropShadow?.enabled && styles.dropShadow.opacity > 0);
- const hasGlow = Boolean(styles.outerGlow?.enabled && styles.outerGlow.opacity > 0);
- return hasStroke || hasShadow || hasGlow;
-}
-
-// Vertex Shader: Fullscreen quad for Layer Styles post-processing
-export const LAYER_STYLES_VERTEX_SHADER = `#version 300 es
-precision highp float;
-
-in vec2 a_quadPos; // [0, 1] x [0, 1]
-out vec2 v_uv;
-
-void main() {
- v_uv = a_quadPos;
- gl_Position = vec4(a_quadPos.x * 2.0 - 1.0, a_quadPos.y * 2.0 - 1.0, 0.0, 1.0);
-}
-`;
-
-// Fragment Shader: Real-Time Non-Destructive Stroke, Outer Glow, and Drop Shadow
-export const LAYER_STYLES_FRAGMENT_SHADER = `#version 300 es
-precision highp float;
-
-in vec2 v_uv;
-
-uniform sampler2D u_layerTexture;
-uniform vec2 u_viewportSize;
-uniform float u_layerOpacity;
-
-// Stroke Uniforms
-uniform int u_strokeEnabled;
-uniform float u_strokeSize; // in physical screen pixels
-uniform vec4 u_strokeColor; // rgba (includes stroke opacity)
-uniform int u_strokePosition; // 0: outside, 1: inside, 2: center
-
-// Outer Glow Uniforms
-uniform int u_glowEnabled;
-uniform vec4 u_glowColor; // rgba (includes glow opacity)
-uniform float u_glowBlur; // in physical screen pixels
-uniform float u_glowSpread; // 0.0 to 1.0
-
-// Drop Shadow Uniforms
-uniform int u_shadowEnabled;
-uniform vec4 u_shadowColor; // rgba (includes shadow opacity)
-uniform vec2 u_shadowOffset; // in physical screen pixels (dx, dy)
-uniform float u_shadowBlur; // in physical screen pixels
-uniform float u_shadowSpread; // 0.0 to 1.0
-
-out vec4 fragColor;
-
-// 16 Poisson disk sample offsets
-const vec2 POISSON_KERNEL[16] = vec2[](
- vec2(-0.326212, -0.405805),
- vec2(-0.840144, -0.073580),
- vec2(-0.695914, 0.457137),
- vec2(-0.203345, 0.620716),
- vec2( 0.962340, -0.194983),
- vec2( 0.473434, -0.480026),
- vec2( 0.519456, 0.767022),
- vec2( 0.185461, -0.893124),
- vec2( 0.507431, 0.064425),
- vec2( 0.896420, 0.412458),
- vec2(-0.321940, -0.932615),
- vec2(-0.791559, -0.597705),
- vec2(-0.504245, -0.007671),
- vec2( 0.052445, 0.375489),
- vec2( 0.284245, -0.052445),
- vec2(-0.052445, -0.284245)
-);
-
-float computeStrokeCoverage(vec2 uv, float centerAlpha, float R, int position, vec2 texel) {
- if (R <= 0.0) return 0.0;
-
- // Outside stroke
- if (position == 0) {
- if (centerAlpha >= 0.99) return 0.0;
- float minInsideDist = R + 1.0;
- for (int i = 0; i < 16; i++) {
- float ang = float(i) * 0.39269908;
- vec2 dir = vec2(cos(ang), sin(ang));
- for (int j = 1; j <= 4; j++) {
- float dist = R * (float(j) / 4.0);
- vec2 sUv = uv + dir * (dist * texel);
- if (texture(u_layerTexture, sUv).a > 0.5) {
- if (dist < minInsideDist) minInsideDist = dist;
- break;
- }
- }
- }
- if (minInsideDist <= R) {
- return clamp(R - minInsideDist + 1.0, 0.0, 1.0) * (1.0 - centerAlpha);
- }
- return 0.0;
- }
-
- // Inside stroke
- if (position == 1) {
- if (centerAlpha < 0.01) return 0.0;
- float minOutsideDist = R + 1.0;
- for (int i = 0; i < 16; i++) {
- float ang = float(i) * 0.39269908;
- vec2 dir = vec2(cos(ang), sin(ang));
- for (int j = 1; j <= 4; j++) {
- float dist = R * (float(j) / 4.0);
- vec2 sUv = uv + dir * (dist * texel);
- if (texture(u_layerTexture, sUv).a < 0.5) {
- if (dist < minOutsideDist) minOutsideDist = dist;
- break;
- }
- }
- }
- if (minOutsideDist <= R) {
- return clamp(R - minOutsideDist + 1.0, 0.0, 1.0) * centerAlpha;
- }
- return 0.0;
- }
-
- // Center stroke (half outside, half inside)
- float halfR = max(0.5, R * 0.5);
- if (centerAlpha < 0.5) {
- float minInsideDist = halfR + 1.0;
- for (int i = 0; i < 16; i++) {
- float ang = float(i) * 0.39269908;
- vec2 dir = vec2(cos(ang), sin(ang));
- for (int j = 1; j <= 4; j++) {
- float dist = halfR * (float(j) / 4.0);
- vec2 sUv = uv + dir * (dist * texel);
- if (texture(u_layerTexture, sUv).a >= 0.5) {
- if (dist < minInsideDist) minInsideDist = dist;
- break;
- }
- }
- }
- if (minInsideDist <= halfR) {
- return clamp(halfR - minInsideDist + 1.0, 0.0, 1.0);
- }
- return 0.0;
- } else {
- float minOutsideDist = halfR + 1.0;
- for (int i = 0; i < 16; i++) {
- float ang = float(i) * 0.39269908;
- vec2 dir = vec2(cos(ang), sin(ang));
- for (int j = 1; j <= 4; j++) {
- float dist = halfR * (float(j) / 4.0);
- vec2 sUv = uv + dir * (dist * texel);
- if (texture(u_layerTexture, sUv).a < 0.5) {
- if (dist < minOutsideDist) minOutsideDist = dist;
- break;
- }
- }
- }
- if (minOutsideDist <= halfR) {
- return clamp(halfR - minOutsideDist + 1.0, 0.0, 1.0);
- }
- return 0.0;
- }
-}
-
-void main() {
- vec2 texel = 1.0 / u_viewportSize;
- vec4 centerSample = texture(u_layerTexture, v_uv);
- float centerAlpha = centerSample.a;
-
- // 1. Drop Shadow Pass
- float shadowAlpha = 0.0;
- if (u_shadowEnabled == 1) {
- vec2 shadowUV = v_uv - u_shadowOffset * texel;
- if (u_shadowBlur <= 0.5) {
- shadowAlpha = texture(u_layerTexture, shadowUV).a;
- } else {
- float rad = max(1.0, u_shadowBlur);
- float accum = 0.0;
- for (int k = 0; k < 16; k++) {
- vec2 sUv = shadowUV + POISSON_KERNEL[k] * (rad * texel);
- accum += texture(u_layerTexture, sUv).a;
- }
- accum /= 16.0;
- float spreadFactor = max(0.01, 1.0 - u_shadowSpread * 0.95);
- shadowAlpha = clamp(accum / spreadFactor, 0.0, 1.0);
- }
- shadowAlpha *= u_shadowColor.a;
- }
-
- // 2. Outer Glow Pass
- float glowAlpha = 0.0;
- if (u_glowEnabled == 1 && centerAlpha < 0.99) {
- float rad = max(1.0, u_glowBlur);
- float accum = 0.0;
- for (int k = 0; k < 16; k++) {
- vec2 sUv = v_uv + POISSON_KERNEL[k] * (rad * texel);
- accum += texture(u_layerTexture, sUv).a;
- }
- accum /= 16.0;
- float spreadFactor = max(0.01, 1.0 - u_glowSpread * 0.95);
- float glowVal = clamp(accum / spreadFactor, 0.0, 1.0);
- glowAlpha = glowVal * (1.0 - centerAlpha) * u_glowColor.a;
- }
-
- // 3. Stroke Pass
- float strokeCov = 0.0;
- if (u_strokeEnabled == 1) {
- strokeCov = computeStrokeCoverage(v_uv, centerAlpha, u_strokeSize, u_strokePosition, texel);
- }
-
- // Composite layers in standard Photoshop order: Drop Shadow -> Outer Glow -> Outside Stroke -> Layer Body -> Inside Stroke
- vec4 composite = vec4(0.0);
-
- // Drop Shadow
- if (u_shadowEnabled == 1 && shadowAlpha > 0.001) {
- composite = vec4(u_shadowColor.rgb * shadowAlpha, shadowAlpha);
- }
-
- // Outer Glow
- if (u_glowEnabled == 1 && glowAlpha > 0.001) {
- vec4 glow = vec4(u_glowColor.rgb * glowAlpha, glowAlpha);
- composite = glow + composite * (1.0 - glow.a);
- }
-
- // Outside / Outer Center Stroke
- bool isOutsideOrCenter = (u_strokePosition == 0 || (u_strokePosition == 2 && centerAlpha < 0.5));
- if (u_strokeEnabled == 1 && isOutsideOrCenter && strokeCov > 0.001) {
- float sA = strokeCov * u_strokeColor.a;
- vec4 strk = vec4(u_strokeColor.rgb * sA, sA);
- composite = strk + composite * (1.0 - strk.a);
- }
-
- // Layer Content
- if (centerSample.a > 0.001) {
- composite = centerSample + composite * (1.0 - centerSample.a);
- }
-
- // Inside / Inner Center Stroke
- bool isInsideOrCenter = (u_strokePosition == 1 || (u_strokePosition == 2 && centerAlpha >= 0.5));
- if (u_strokeEnabled == 1 && isInsideOrCenter && strokeCov > 0.001) {
- float sA = strokeCov * u_strokeColor.a;
- vec4 strk = vec4(u_strokeColor.rgb * sA, sA);
- composite = strk + composite * (1.0 - strk.a);
- }
-
- // Overall Layer Opacity
- composite *= u_layerOpacity;
-
- if (composite.a < 0.002) {
- discard;
- }
-
- fragColor = composite;
-}
-`;
-
-// Soft Proofing and Gamut Warning Post-Processing Shaders
-export const SOFT_PROOF_VERTEX_SHADER = `#version 300 es
-precision highp float;
-in vec2 a_quadPos; // [0, 1] x [0, 1]
-out vec2 v_uv;
-void main() {
- v_uv = a_quadPos;
- gl_Position = vec4(a_quadPos.x * 2.0 - 1.0, a_quadPos.y * 2.0 - 1.0, 0.0, 1.0);
-}
-`;
-
-export const SOFT_PROOF_FRAGMENT_SHADER = `#version 300 es
-precision highp float;
-
-in vec2 v_uv;
-uniform sampler2D u_sceneTexture;
-uniform int u_standard; // 0: japan-color-2001, 1: us-web-coated-swop, 2: iso-coated-v2
-uniform int u_proofEnabled; // 1 or 0
-uniform int u_gamutWarning; // 1 or 0
-uniform vec3 u_gamutWarningColor;
-
-out vec4 fragColor;
-
-// sRGB to Linear RGB
-vec3 srgbToLinear(vec3 c) {
- return mix(
- c / 12.92,
- pow((c + 0.055) / 1.055, vec3(2.4)),
- step(vec3(0.04045), c)
- );
-}
-
-// Linear RGB to sRGB
-vec3 linearToSrgb(vec3 c) {
- c = clamp(c, 0.0, 1.0);
- return mix(
- c * 12.92,
- 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055,
- step(vec3(0.0031308), c)
- );
-}
-
-// Linear sRGB to CIE XYZ (D65)
-vec3 linearToXyz(vec3 rgb) {
- return vec3(
- dot(rgb, vec3(0.4124564, 0.3575761, 0.1804375)),
- dot(rgb, vec3(0.2126729, 0.7151522, 0.0721750)),
- dot(rgb, vec3(0.0193339, 0.1191920, 0.9503041))
- );
-}
-
-// CIE XYZ (D65) to CIE Lab
-float fLab(float t) {
- const float delta = 6.0 / 29.0;
- const float delta3 = delta * delta * delta;
- return (t > delta3) ? pow(t, 1.0 / 3.0) : (t / (3.0 * delta * delta) + 4.0 / 29.0);
-}
-
-vec3 xyzToLab(vec3 xyz) {
- vec3 white = vec3(0.95047, 1.0, 1.08883);
- vec3 v = xyz / white;
- float fx = fLab(v.x);
- float fy = fLab(v.y);
- float fz = fLab(v.z);
- return vec3(
- 116.0 * fy - 16.0,
- 500.0 * (fx - fy),
- 200.0 * (fy - fz)
- );
-}
-
-vec3 srgbToLab(vec3 srgb) {
- vec3 lin = srgbToLinear(clamp(srgb, 0.0, 1.0));
- vec3 xyz = linearToXyz(lin);
- return xyzToLab(xyz);
-}
-
-// CMYK soft-proofing simulation polynomial
-vec3 simulateCmyk(vec3 srgb, int standard) {
- vec3 linRgb = srgbToLinear(clamp(srgb, 0.0, 1.0));
- float c0 = 1.0 - linRgb.r;
- float m0 = 1.0 - linRgb.g;
- float y0 = 1.0 - linRgb.b;
-
- // Standard 0: Japan Color 2001 (high saturation, clean cyans, TAC ~350%)
- // Standard 1: US Web Coated (SWOP) (warm stock, heavy black, lower gamut, TAC ~300%)
- // Standard 2: ISO Coated v2 (FOGRA39) (balanced European inks, TAC ~330%)
- float tacLimit = 3.5;
- float tvi = 0.14;
- float gcrExp = 1.4;
- float ucrFactor = 0.80;
-
- vec3 densC = vec3(1.42, 0.17, 0.07);
- vec3 densM = vec3(0.06, 1.35, 0.15);
- vec3 densY = vec3(0.02, 0.04, 1.25);
- vec3 densK = vec3(1.80, 1.80, 1.78);
- vec3 paperReflect = vec3(0.96, 0.96, 0.97);
-
- if (standard == 1) {
- tacLimit = 3.0;
- tvi = 0.20;
- gcrExp = 1.15;
- ucrFactor = 0.90;
- densC = vec3(1.28, 0.24, 0.14);
- densM = vec3(0.08, 1.22, 0.22);
- densY = vec3(0.03, 0.07, 1.15);
- densK = vec3(1.65, 1.65, 1.62);
- paperReflect = vec3(0.94, 0.93, 0.88);
- } else if (standard == 2) {
- tacLimit = 3.3;
- tvi = 0.16;
- gcrExp = 1.3;
- ucrFactor = 0.85;
- densC = vec3(1.36, 0.19, 0.09);
- densM = vec3(0.07, 1.30, 0.17);
- densY = vec3(0.02, 0.05, 1.20);
- densK = vec3(1.72, 1.72, 1.70);
- paperReflect = vec3(0.95, 0.95, 0.94);
- }
-
- // Black generation (GCR)
- float k0 = min(c0, min(m0, y0));
- float k = pow(k0, gcrExp);
-
- // Under Color Removal
- float denom = max(0.001, 1.0 - k * 0.35);
- float c1 = clamp((c0 - k * ucrFactor) / denom, 0.0, 1.0);
- float m1 = clamp((m0 - k * ucrFactor) / denom, 0.0, 1.0);
- float y1 = clamp((y0 - k * ucrFactor) / denom, 0.0, 1.0);
-
- // Apply TAC limit
- float totalInk = c1 + m1 + y1 + k;
- if (totalInk > tacLimit) {
- float scale = (tacLimit - k) / max(0.001, totalInk - k);
- c1 *= scale;
- m1 *= scale;
- y1 *= scale;
- }
-
- // Tone Value Increase (dot gain)
- c1 += 4.0 * tvi * c1 * (1.0 - c1);
- m1 += 4.0 * tvi * m1 * (1.0 - m1);
- y1 += 4.0 * tvi * y1 * (1.0 - y1);
- k += 4.0 * tvi * k * (1.0 - k);
-
- c1 = clamp(c1, 0.0, 1.0);
- m1 = clamp(m1, 0.0, 1.0);
- y1 = clamp(y1, 0.0, 1.0);
- k = clamp(k, 0.0, 1.0);
-
- // Inter-ink trapping
- float cmTrap = c1 * m1 * 0.12;
- float cyTrap = c1 * y1 * 0.10;
- float myTrap = m1 * y1 * 0.10;
-
- vec3 totalDensity = c1 * densC + m1 * densM + y1 * densY + k * densK
- - cmTrap * (densC + densM) * 0.2
- - cyTrap * (densC + densY) * 0.2
- - myTrap * (densM + densY) * 0.2;
-
- // Subtractive reflectance with paper tint and gloss minimum clamp
- vec3 reflectance = paperReflect * exp(-totalDensity * 2.302585);
- reflectance += vec3(0.012);
-
- return linearToSrgb(reflectance);
-}
-
-void main() {
- vec4 sceneColor = texture(u_sceneTexture, v_uv);
-
- if (sceneColor.a < 0.002) {
- fragColor = sceneColor;
- return;
- }
-
- // Unpremultiply alpha for true color evaluation
- vec3 rgb = sceneColor.rgb / sceneColor.a;
-
- // Soft proof simulation
- vec3 proofRgb = simulateCmyk(rgb, u_standard);
-
- // Gamut evaluation in CIE Lab space
- vec3 labOrig = srgbToLab(rgb);
- vec3 labProof = srgbToLab(proofRgb);
-
- // Delta-E (CIE76): normalized scale where 100 Lab units = 1.0 (deltaE = norm / 100.0)
- vec3 dLab = labOrig - labProof;
- float deltaE = length(dLab) / 100.0;
-
- bool isOutOfGamut = (deltaE > 0.05);
-
- vec3 outRgb = rgb;
- if (u_proofEnabled == 1) {
- outRgb = proofRgb;
- }
-
- if (u_gamutWarning == 1 && isOutOfGamut) {
- outRgb = u_gamutWarningColor;
- }
-
- fragColor = vec4(outRgb * sceneColor.a, sceneColor.a);
-}
-`;
-
-export interface OnionSkinCompositorFrame {
- layerId: string;
- tint: string;
- opacity: number;
-}
-
-export interface CompositorOptions {
- dimensions: CanvasDimensions;
- colorMode?: CanvasColorMode;
- showCheckerboard?: boolean;
- transparentBackground?: boolean;
- bypassStackCache?: boolean;
- devicePixelRatio?: number;
- onionSkinFrames?: OnionSkinCompositorFrame[];
- softProof?: SoftProofSettings;
- // Active layer identifier for Baked Layer Stack Cache partitioning (below / active / above)
- activeLayerId?: string | null;
- // WYSIWYG In-Stack Live Stroke Compositing
- activeDraftCanvas?: HTMLCanvasElement | null;
- activeDraftLayerId?: string | null;
- activeDraftDirtyRect?: { x: number; y: number; width: number; height: number } | null;
- activeDraftVersion?: number;
- activeDraftSpace?: 'document' | 'viewport';
- activeDraftOpacity?: number;
- activeDraftMonochrome?: boolean;
-}
-
-// ============================================================================
-// Baked Layer Stack Cache Partitioning & Invalidation Engine
-// ============================================================================
-
-export interface CompositingUnit {
- /** Base node and its clipped siblings at this compositing level */
- group: TreeNodeRenderGroup;
- /** Accumulated opacity from enclosing pass-through folders */
- inheritedOpacity: number;
- /** All layer IDs contained in this unit (base, clipped siblings, and folder descendants) */
- containedLayerIds: Set<string>;
-}
-
-export type AboveSliceStrategy = 'empty' | 'baked-normal' | 'baked-single-blend' | 'mixed';
-
-export interface LayerStackPartition {
- /** Units strictly below the active unit (always safe to bake into belowActiveCacheFbo) */
- belowUnits: CompositingUnit[];
- /** The active unit containing activeLayerId, or null if none/hidden */
- activeUnit: CompositingUnit | null;
- /** Units above active that must render dynamically (non-associative blend modes / adjustments) */
- aboveDynamicUnits: CompositingUnit[];
- /** Units above activeDynamicUnits that can be baked into aboveActiveCacheFbo */
- aboveCachedUnits: CompositingUnit[];
- /** How aboveActiveCacheFbo should be composited over (below + active + aboveDynamic) */
- aboveStrategy: AboveSliceStrategy;
- /** Blend mode for aboveActiveCacheFbo when aboveStrategy === 'baked-single-blend' */
- aboveCacheBlendMode: BlendMode;
-}
-
-export interface LayerStackCacheInput {
- layers: LayerItem[];
- activeLayerId?: string | null;
- viewportW: number;
- viewportH: number;
- dpr: number;
- dimensions: CanvasDimensions;
- transform: ViewportTransform;
- showCheckerboard?: boolean;
- transparentBackground?: boolean;
- colorMode?: CanvasColorMode;
- onionSkinFrames?: OnionSkinCompositorFrame[];
- getLayerContentVersion: (layerId: string) => number;
- getMaskInvalidationEpoch?: (layerId: string) => number;
- gridEpoch?: number;
- gridId?: number;
-}
-
-export interface LayerStackCacheEvaluation {
- partition: LayerStackPartition;
- belowSignature: string;
- aboveSignature: string;
- belowDirty: boolean;
- aboveDirty: boolean;
-}
-
-function collectNodeLayerIds(node: LayerTreeNode, out: Set<string>): void {
- out.add(node.layer.id);
- for (const child of node.children) {
- collectNodeLayerIds(child, out);
- }
-}
-
-/**
- * Flattens pass-through folders into a bottom-to-top sequence of atomic compositing units
- * while keeping isolated folders and clipping-mask groups atomic.
- */
-export function flattenLayerTreeToUnits(
- nodes: LayerTreeNode[],
- inheritedOpacity: number = 1.0
-): CompositingUnit[] {
- const units: CompositingUnit[] = [];
- const siblingsBottomToTop = nodes.slice().reverse();
- const groups = groupTreeNodesForCompositing(siblingsBottomToTop);
-
- for (const group of groups) {
- const baseLayer = group.baseNode.layer;
- if (!baseLayer.visible || baseLayer.opacity <= 0.001) {
- continue;
- }
-
- if (baseLayer.type === 'folder' && baseLayer.blendMode === 'pass-through') {
- const nested = flattenLayerTreeToUnits(
- group.baseNode.children,
- inheritedOpacity * baseLayer.opacity
- );
- for (const u of nested) {
- units.push(u);
- }
- continue;
- }
-
- const containedLayerIds = new Set<string>();
- collectNodeLayerIds(group.baseNode, containedLayerIds);
- for (const cn of group.clippedNodes) {
- collectNodeLayerIds(cn, containedLayerIds);
- }
-
- units.push({
- group,
- inheritedOpacity,
- containedLayerIds,
- });
- }
-
- return units;
-}
-
-/**
- * Returns true if a compositing unit is strictly Porter-Duff source-over associative
- * with respect to the backdrop below it (safe to pre-bake onto transparent FBO and composite with 'normal').
- */
-export function isUnitNormalAssociative(unit: CompositingUnit): boolean {
- const baseLayer = unit.group.baseNode.layer;
- if (baseLayer.type === 'adjustment') {
- return false;
- }
- if (baseLayer.type === 'folder' || baseLayer.type === 'frame-folder') {
- // Pass-through regular folders were flattened; isolated folders and frame-folders
- // isolate their children's blend modes, so normal/pass-through is normal-associative.
- return baseLayer.blendMode === 'normal' || baseLayer.blendMode === 'pass-through';
- }
- if (baseLayer.blendMode !== 'normal' && baseLayer.blendMode !== 'pass-through') {
- return false;
- }
- for (const cn of unit.group.clippedNodes) {
- const cl = cn.layer;
- if (!cl.visible || cl.opacity <= 0.001 || isFolderLikeLayer(cl)) continue;
- if (cl.blendMode !== 'normal' && cl.blendMode !== 'pass-through') {
- return false;
- }
- }
- return true;
-}
-
-/**
- * Returns the blend mode if a single non-associative unit can be baked onto transparent
- * with 'normal' and composited over (below + active) using a single ping-pong blend pass.
- */
-export function canSingleUnitBakeWithBlendMode(unit: CompositingUnit): BlendMode | null {
- const baseLayer = unit.group.baseNode.layer;
- if (baseLayer.type === 'adjustment') {
- return null;
- }
- if (baseLayer.type === 'folder' || baseLayer.type === 'frame-folder') {
- if (baseLayer.blendMode !== 'normal' && baseLayer.blendMode !== 'pass-through') {
- return baseLayer.blendMode;
- }
- return null;
- }
- const visibleClipped = unit.group.clippedNodes.filter(
- (cn) => cn.layer.visible && cn.layer.opacity > 0.001 && !isFolderLikeLayer(cn.layer)
- );
- if (
- visibleClipped.length === 0 &&
- baseLayer.blendMode !== 'normal' &&
- baseLayer.blendMode !== 'pass-through'
- ) {
- return baseLayer.blendMode;
- }
- return null;
-}
-
-/**
- * Partitions the visible layer stack into `below`, `active`, and `above` slices relative to `activeLayerId`.
- */
-export function partitionLayerStack(
- layers: LayerItem[],
- activeLayerId?: string | null
-): LayerStackPartition {
- const tree = buildLayerTree(layers);
- const units = flattenLayerTreeToUnits(tree, 1.0);
-
- let activeIdx = -1;
- if (activeLayerId) {
- for (let i = 0; i < units.length; i++) {
- if (units[i].containedLayerIds.has(activeLayerId)) {
- activeIdx = i;
- break;
- }
- }
- }
-
- if (activeIdx === -1) {
- return {
- belowUnits: units,
- activeUnit: null,
- aboveDynamicUnits: [],
- aboveCachedUnits: [],
- aboveStrategy: 'empty',
- aboveCacheBlendMode: 'normal',
- };
- }
-
- const belowUnits = units.slice(0, activeIdx);
- const activeUnit = units[activeIdx];
- const aboveAll = units.slice(activeIdx + 1);
-
- if (aboveAll.length === 0) {
- return {
- belowUnits,
- activeUnit,
- aboveDynamicUnits: [],
- aboveCachedUnits: [],
- aboveStrategy: 'empty',
- aboveCacheBlendMode: 'normal',
- };
- }
-
- let lastNonAssocIdx = -1;
- for (let i = 0; i < aboveAll.length; i++) {
- if (!isUnitNormalAssociative(aboveAll[i])) {
- lastNonAssocIdx = i;
- }
- }
-
- if (lastNonAssocIdx === -1) {
- return {
- belowUnits,
- activeUnit,
- aboveDynamicUnits: [],
- aboveCachedUnits: aboveAll,
- aboveStrategy: 'baked-normal',
- aboveCacheBlendMode: 'normal',
- };
- }
-
- if (aboveAll.length === 1) {
- const singleBlend = canSingleUnitBakeWithBlendMode(aboveAll[0]);
- if (singleBlend) {
- return {
- belowUnits,
- activeUnit,
- aboveDynamicUnits: [],
- aboveCachedUnits: aboveAll,
- aboveStrategy: 'baked-single-blend',
- aboveCacheBlendMode: singleBlend,
- };
- }
- }
-
- return {
- belowUnits,
- activeUnit,
- aboveDynamicUnits: aboveAll.slice(0, lastNonAssocIdx + 1),
- aboveCachedUnits: aboveAll.slice(lastNonAssocIdx + 1),
- aboveStrategy: 'mixed',
- aboveCacheBlendMode: 'normal',
- };
-}
-
-function serializeLayerNodeSignature(
- node: LayerTreeNode,
- inheritedOpacity: number,
- getLayerContentVersion: (layerId: string) => number,
- getMaskInvalidationEpoch?: (layerId: string) => number
-): string {
- const l = node.layer;
- const contentVer = getLayerContentVersion(l.id);
- const maskEpoch = getMaskInvalidationEpoch ? getMaskInvalidationEpoch(l.id) : 0;
- const stylesSig = hasActiveLayerStyles(l.styles) ? JSON.stringify(l.styles) : '';
- const adjSig = l.type === 'adjustment' && l.adjustmentData ? JSON.stringify(l.adjustmentData) : '';
- const toneSig = l.toneEnabled
- ? `1:${l.toneFrequency ?? 60}:${l.toneAngle ?? 45}:${l.toneDotShape ?? ''}:${l.toneDensity ?? 40}:${l.toneDensityType ?? ''}`
- : '0';
- const tintSig = l.layerColorEnabled
- ? `1:${l.layerColor ?? ''}:${l.layerSubColor ?? ''}`
- : '0';
- const maskSig = l.maskCanvas && l.maskEnabled !== false
- ? `1:${l.maskVersion ?? 0}:${maskEpoch}:${l.maskCanvas.width}x${l.maskCanvas.height}`
- : '0';
- const exprSig = `${l.expressionColor ?? 'color'}:${l.monoThreshold ?? 128}:${l.monoExpressBlack !== false ? 1 : 0}:${l.monoExpressWhite !== false ? 1 : 0}`;
- const frameSig = l.type === 'frame-folder' && l.comicFrames ? JSON.stringify(l.comicFrames) : '';
-
- let sig = `${l.id}|${l.type}|${l.visible ? 1 : 0}|${l.opacity}|${inheritedOpacity}|${l.blendMode}|${l.clipped ? 1 : 0}|v:${contentVer}|m:${maskSig}|t:${toneSig}|c:${tintSig}|e:${exprSig}|s:${stylesSig}|a:${adjSig}|f:${frameSig}`;
-
- if (node.children.length > 0) {
- const childSigs: string[] = [];
- for (const child of node.children) {
- if (!child.layer.visible || child.layer.opacity <= 0.001) continue;
- childSigs.push(
- serializeLayerNodeSignature(child, 1.0, getLayerContentVersion, getMaskInvalidationEpoch)
- );
- }
- sig += `[${childSigs.join(',')}]`;
- }
-
- return sig;
-}
-
-function serializeUnitSignature(
- unit: CompositingUnit,
- getLayerContentVersion: (layerId: string) => number,
- getMaskInvalidationEpoch?: (layerId: string) => number
-): string {
- let sig = serializeLayerNodeSignature(
- unit.group.baseNode,
- unit.inheritedOpacity,
- getLayerContentVersion,
- getMaskInvalidationEpoch
- );
- if (unit.group.clippedNodes.length > 0) {
- const clippedSigs: string[] = [];
- for (const cn of unit.group.clippedNodes) {
- if (!cn.layer.visible || cn.layer.opacity <= 0.001 || cn.layer.type === 'folder') continue;
- clippedSigs.push(
- serializeLayerNodeSignature(cn, unit.inheritedOpacity, getLayerContentVersion, getMaskInvalidationEpoch)
- );
- }
- if (clippedSigs.length > 0) {
- sig += `{clip:${clippedSigs.join(';')}}`;
- }
- }
- return sig;
-}
-
-/**
- * Pure invalidation tracker for the Baked Layer Stack Cache (`belowActiveCacheFbo` & `aboveActiveCacheFbo`).
- * Determines independently whether the lower or upper cached FBO needs rebuilding.
- */
-export class LayerStackCacheTracker {
- private lastBelowSignature: string | null = null;
- private lastAboveSignature: string | null = null;
-
- public evaluate(input: LayerStackCacheInput): LayerStackCacheEvaluation {
- const partition = partitionLayerStack(input.layers, input.activeLayerId);
-
- const { transform, dimensions } = input;
- const viewportSig =
- `${input.viewportW}x${input.viewportH}@${input.dpr}|` +
- `${dimensions.width}x${dimensions.height}@${dimensions.dpi ?? 600}|` +
- `${transform.pan.x},${transform.pan.y},${transform.zoom},${transform.rotation},` +
- `${transform.flipX ? 1 : 0},${transform.flipY ? 1 : 0}|g:${input.gridId ?? 0}|ep:${input.gridEpoch ?? 0}`;
-
- // Onion skin frames are baked into the below cache right after the artboard background
- let onionSig = '';
- if (input.onionSkinFrames && input.onionSkinFrames.length > 0) {
- const layerMap = new Map<string, LayerItem>();
- for (const l of input.layers) layerMap.set(l.id, l);
- const parts: string[] = [];
- for (const frame of input.onionSkinFrames) {
- const target = layerMap.get(frame.layerId);
- if (target && target.visible) {
- parts.push(
- `${frame.layerId}:${frame.tint}:${frame.opacity}:v${input.getLayerContentVersion(frame.layerId)}`
- );
- }
- }
- onionSig = parts.join(',');
- }
-
- const modeTag = input.colorMode ?? 'color';
- const belowUnitSigs = partition.belowUnits.map((u) =>
- serializeUnitSignature(u, input.getLayerContentVersion, input.getMaskInvalidationEpoch)
- );
- const belowSignature = `${viewportSig}|cm:${modeTag}|cb:${input.showCheckerboard ? 1 : 0}|tb:${input.transparentBackground ? 1 : 0}|os:${onionSig}|below:[${belowUnitSigs.join('||')}]`;
-
- let aboveSignature = '';
- if (partition.aboveCachedUnits.length > 0) {
- const aboveUnitSigs = partition.aboveCachedUnits.map((u) =>
- serializeUnitSignature(u, input.getLayerContentVersion, input.getMaskInvalidationEpoch)
- );
- aboveSignature = `${viewportSig}|cm:${modeTag}|strat:${partition.aboveStrategy}:${partition.aboveCacheBlendMode}|above:[${aboveUnitSigs.join('||')}]`;
- }
-
- const belowDirty = belowSignature !== this.lastBelowSignature;
- const aboveDirty =
- partition.aboveCachedUnits.length > 0 && aboveSignature !== this.lastAboveSignature;
-
- return {
- partition,
- belowSignature,
- aboveSignature,
- belowDirty,
- aboveDirty,
- };
- }
-
- public commit(belowSignature: string, aboveSignature: string): void {
- this.lastBelowSignature = belowSignature;
- this.lastAboveSignature = aboveSignature;
- }
-
- public invalidateAll(): void {
- this.lastBelowSignature = null;
- this.lastAboveSignature = null;
- }
-
- public invalidateBelow(): void {
- this.lastBelowSignature = null;
- }
-
- public invalidateAbove(): void {
- this.lastAboveSignature = null;
- }
-
- public getLastSignatures(): { below: string | null; above: string | null } {
- return { below: this.lastBelowSignature, above: this.lastAboveSignature };
- }
-}
-
-/**
- * Calculates the document-space bounding box visible in the current camera viewport.
- * Performs frustum culling.
- */
-export function calculateVisibleDocumentBounds(
- viewportW: number,
- viewportH: number,
- transform: ViewportTransform,
- docW: number,
- docH: number
-): { minX: number; minY: number; maxX: number; maxY: number } {
- const { pan, zoom, rotation, flipX = false, flipY = false } = transform;
- const rad = (-rotation * Math.PI) / 180;
- const cosR = Math.cos(rad);
- const sinR = Math.sin(rad);
- const fx = flipX ? -1 : 1;
- const fy = flipY ? -1 : 1;
-
- // Screen corners relative to screen center/pan
- const corners = [
- { x: 0, y: 0 },
- { x: viewportW, y: 0 },
- { x: viewportW, y: viewportH },
- { x: 0, y: viewportH },
- ];
-
- let minX = Infinity;
- let minY = Infinity;
- let maxX = -Infinity;
- let maxY = -Infinity;
-
- for (const c of corners) {
- // Invert translate
- const dx = c.x - pan.x;
- const dy = c.y - pan.y;
-
- // Invert zoom
- const sx = dx / Math.max(0.001, zoom);
- const sy = dy / Math.max(0.001, zoom);
-
- // Invert rotation
- const rx = sx * cosR - sy * sinR;
- const ry = sx * sinR + sy * cosR;
-
- // Invert view flip and center offset
- const docX = rx * fx + docW * 0.5;
- const docY = ry * fy + docH * 0.5;
-
- if (docX < minX) minX = docX;
- if (docY < minY) minY = docY;
- if (docX > maxX) maxX = docX;
- if (docY > maxY) maxY = docY;
- }
-
- return {
- minX: Math.max(0, Math.floor(minX)),
- minY: Math.max(0, Math.floor(minY)),
- maxX: Math.min(docW, Math.ceil(maxX)),
- maxY: Math.min(docH, Math.ceil(maxY)),
- };
-}
-
-interface FboSurface {
- fbo: WebGLFramebuffer;
- texture: WebGLTexture;
- stencilRb: WebGLRenderbuffer | null;
- width: number;
- height: number;
-}
-
-interface PingPongTarget {
- surfaces: [FboSurface, FboSurface];
- activeIndex: 0 | 1;
-}
-
-interface LayerUniformLocs {
- uDocDimensions: WebGLUniformLocation | null;
- uViewportSize: WebGLUniformLocation | null;
- uPan: WebGLUniformLocation | null;
- uZoom: WebGLUniformLocation | null;
- uRotationRad: WebGLUniformLocation | null;
- uFlip: WebGLUniformLocation | null;
- uDpr: WebGLUniformLocation | null;
- uBackdropTexture: WebGLUniformLocation | null;
- uHasBackdrop: WebGLUniformLocation | null;
- uLayerOpacity: WebGLUniformLocation | null;
- uBlendMode: WebGLUniformLocation | null;
- uToneEnabled: WebGLUniformLocation | null;
- uToneFrequency: WebGLUniformLocation | null;
- uToneAngleRad: WebGLUniformLocation | null;
- uToneDpi: WebGLUniformLocation | null;
- uToneDotShape: WebGLUniformLocation | null;
- uToneDensity: WebGLUniformLocation | null;
- uToneDensityType: WebGLUniformLocation | null;
- uLayerColorEnabled: WebGLUniformLocation | null;
- uLayerColor: WebGLUniformLocation | null;
- uLayerSubColor: WebGLUniformLocation | null;
- uMaskTexture: WebGLUniformLocation | null;
- uMaskEnabled: WebGLUniformLocation | null;
- uExpressionMode: WebGLUniformLocation | null;
- uMonoThreshold: WebGLUniformLocation | null;
- uMonoExpressBlack: WebGLUniformLocation | null;
- uMonoExpressWhite: WebGLUniformLocation | null;
-}
-
-interface ArrayPoolSlot {
- sliceIndex: number;
- currentKey: string | null;
- version: number;
- lastUsed: number;
- lastBatchTick: number;
-}
-
-/**
- * High-performance WebGL2 Viewport Compositor
- */
-export class ViewportCompositor {
- private canvas: HTMLCanvasElement;
- private gl: WebGL2RenderingContext | null = null;
- private program: WebGLProgram | null = null;
- private quadBuffer: WebGLBuffer | null = null;
-
- // Standard compositor uniform locations
- private uTileOriginLoc: WebGLUniformLocation | null = null;
- private uTileSizeLoc: WebGLUniformLocation | null = null;
- private uIsBackgroundLoc: WebGLUniformLocation | null = null;
- private uShowCheckerboardLoc: WebGLUniformLocation | null = null;
- private uTileTextureLoc: WebGLUniformLocation | null = null;
- private stdLocs: LayerUniformLocs | null = null;
-
- // Instanced TEXTURE_2D_ARRAY batching program, VAO, buffer, & pool
- private static readonly DEFAULT_ARRAY_POOL_LAYERS = 512;
- private instancedProgram: WebGLProgram | null = null;
- private instancedLocs: LayerUniformLocs | null = null;
- private uInstTileSizeLoc: WebGLUniformLocation | null = null;
- private uInstTileArrayLoc: WebGLUniformLocation | null = null;
- private aInstQuadPosLoc: number = -1;
- private aInstDataLoc: number = -1;
- private instancedVao: WebGLVertexArrayObject | null = null;
- private instanceBuffer: WebGLBuffer | null = null;
- private instanceFloatScratch: Float32Array = new Float32Array(
- ViewportCompositor.DEFAULT_ARRAY_POOL_LAYERS * 3
- );
- private tileArrayTexture: WebGLTexture | null = null;
- private arrayPoolCapacity: number = 0;
- private arrayPoolFilterTier: number = -1;
- private arrayPoolSlots: ArrayPoolSlot[] = [];
- private freeArraySlots: ArrayPoolSlot[] = [];
- private arrayPoolByKey: Map<string, ArrayPoolSlot> = new Map();
- private arrayAccessCounter: number = 0;
- private arrayBatchCounter: number = 0;
- private uploadPremulScratch: Uint8Array = new Uint8Array(TILE_SIZE * TILE_SIZE * 4);
- private readonly preserveDrawingBuffer: boolean;
-
- // Viewport-space draft stroke program (reuses COMPOSITOR_FRAGMENT_SHADER)
- private viewportDraftProgram: WebGLProgram | null = null;
- private viewportDraftLocs: LayerUniformLocs | null = null;
- private uViewportDraftTileTexLoc: WebGLUniformLocation | null = null;
- private uViewportDraftIsBgLoc: WebGLUniformLocation | null = null;
- private aViewportDraftQuadPosLoc: number = -1;
-
- // Cached attribute locations (eliminates per-frame gl.getAttribLocation stalls)
- private aQuadPosLoc: number = -1;
- private aStylesQuadPosLoc: number = -1;
- private aBlitQuadPosLoc: number = -1;
- private aProofQuadPosLoc: number = -1;
- private contextLost: boolean = false;
- private onContextLostHandler: ((e: Event) => void) | null = null;
- private onContextRestoredHandler: (() => void) | null = null;
-
- // Mask version-tracked cache & invalidation epochs
- private maskTextureCache: Map<
- string,
- { texture: WebGLTexture; version: number; width: number; height: number }
- > = new Map();
- private maskInvalidationEpochs: Map<string, number> = new Map();
- private globalMaskEpochCounter: number = 0;
-
- // Live in-stack draft stroke texture cache
- private draftTexture: WebGLTexture | null = null;
- private draftTexWidth: number = 0;
- private draftTexHeight: number = 0;
- private draftHasMipmap: boolean = false;
- private lastDraftVersion: number = -1;
- private currentOptions: CompositorOptions | null = null;
- private currentZoom: number = 1.0;
- private currentFrameState: {
- viewportW: number;
- viewportH: number;
- dpr: number;
- dimensions: CanvasDimensions;
- transform: ViewportTransform;
- rotRad: number;
- } | null = null;
-
- // Adjustment program & uniforms
- private adjProgram: WebGLProgram | null = null;
- private uAdjTileOriginLoc: WebGLUniformLocation | null = null;
- private uAdjTileSizeLoc: WebGLUniformLocation | null = null;
- private uAdjDocDimensionsLoc: WebGLUniformLocation | null = null;
- private uAdjViewportSizeLoc: WebGLUniformLocation | null = null;
- private uAdjPanLoc: WebGLUniformLocation | null = null;
- private uAdjZoomLoc: WebGLUniformLocation | null = null;
- private uAdjRotationRadLoc: WebGLUniformLocation | null = null;
- private uAdjFlipLoc: WebGLUniformLocation | null = null;
- private uAdjDprLoc: WebGLUniformLocation | null = null;
- private uAdjSnapshotLoc: WebGLUniformLocation | null = null;
- private uAdjLutLoc: WebGLUniformLocation | null = null;
- private uAdjModeLoc: WebGLUniformLocation | null = null;
- private uAdjOpacityLoc: WebGLUniformLocation | null = null;
- private uAdjMaskEnabledLoc: WebGLUniformLocation | null = null;
- private uAdjMaskTextureLoc: WebGLUniformLocation | null = null;
-
- private lutTexture: WebGLTexture | null = null;
- private lastLutKey: string = '';
- private lastLutAdjMode: number = 0;
-
- // Layer Styles program, FBO & uniforms
- private stylesProgram: WebGLProgram | null = null;
- private stylesQuadBuffer: WebGLBuffer | null = null;
- private layerFbo: WebGLFramebuffer | null = null;
- private layerTexture: WebGLTexture | null = null;
- private layerFboWidth: number = 0;
- private layerFboHeight: number = 0;
- private layerStylesOutFbo: FboSurface | null = null;
-
- private uStylesLayerTextureLoc: WebGLUniformLocation | null = null;
- private uStylesViewportSizeLoc: WebGLUniformLocation | null = null;
- private uStylesLayerOpacityLoc: WebGLUniformLocation | null = null;
- private uStylesStrokeEnabledLoc: WebGLUniformLocation | null = null;
- private uStylesStrokeSizeLoc: WebGLUniformLocation | null = null;
- private uStylesStrokeColorLoc: WebGLUniformLocation | null = null;
- private uStylesStrokePositionLoc: WebGLUniformLocation | null = null;
- private uStylesGlowEnabledLoc: WebGLUniformLocation | null = null;
- private uStylesGlowColorLoc: WebGLUniformLocation | null = null;
- private uStylesGlowBlurLoc: WebGLUniformLocation | null = null;
- private uStylesGlowSpreadLoc: WebGLUniformLocation | null = null;
- private uStylesShadowEnabledLoc: WebGLUniformLocation | null = null;
- private uStylesShadowColorLoc: WebGLUniformLocation | null = null;
- private uStylesShadowOffsetLoc: WebGLUniformLocation | null = null;
- private uStylesShadowBlurLoc: WebGLUniformLocation | null = null;
- private uStylesShadowSpreadLoc: WebGLUniformLocation | null = null;
-
- // Folder / Cache blit program & uniforms
- private blitProgram: WebGLProgram | null = null;
- private uBlitTextureLoc: WebGLUniformLocation | null = null;
- private uBlitBackdropTextureLoc: WebGLUniformLocation | null = null;
- private uBlitHasBackdropLoc: WebGLUniformLocation | null = null;
- private uBlitBlendModeLoc: WebGLUniformLocation | null = null;
- private uBlitOpacityLoc: WebGLUniformLocation | null = null;
-
- // Frame Border Folder polygon program & dynamic vertex buffer
- private framePolyProgram: WebGLProgram | null = null;
- private framePolyBuffer: WebGLBuffer | null = null;
- private aFramePolyDocPosLoc: number = -1;
- private uFramePolyDocDimensionsLoc: WebGLUniformLocation | null = null;
- private uFramePolyViewportSizeLoc: WebGLUniformLocation | null = null;
- private uFramePolyPanLoc: WebGLUniformLocation | null = null;
- private uFramePolyZoomLoc: WebGLUniformLocation | null = null;
- private uFramePolyRotationRadLoc: WebGLUniformLocation | null = null;
- private uFramePolyFlipLoc: WebGLUniformLocation | null = null;
- private uFramePolyDprLoc: WebGLUniformLocation | null = null;
- private uFramePolyColorLoc: WebGLUniformLocation | null = null;
-
- // Ping-Pong FBOs (eliminates all gl.copyTexSubImage2D calls for custom blend modes)
- private scenePingPong: PingPongTarget | null = null;
- private folderPingPongs: PingPongTarget[] = [];
-
- // Baked Layer Stack Cache FBOs (below & above active layer)
- private belowActiveCacheFbo: FboSurface | null = null;
- private aboveActiveCacheFbo: FboSurface | null = null;
- private stackCache: LayerStackCacheTracker = new LayerStackCacheTracker();
- private stackCacheStats = { belowRebuilds: 0, aboveRebuilds: 0, cacheHits: 0 };
-
- // Soft proofing program & uniforms
- private softProofProgram: WebGLProgram | null = null;
- private uProofSceneTextureLoc: WebGLUniformLocation | null = null;
- private uProofStandardLoc: WebGLUniformLocation | null = null;
- private uProofEnabledLoc: WebGLUniformLocation | null = null;
- private uProofGamutWarningLoc: WebGLUniformLocation | null = null;
- private uProofGamutWarningColorLoc: WebGLUniformLocation | null = null;
-
- // Pre-allocated WebGL2 Texture2D Pool (overflow fallback for TEXTURE_2D_ARRAY)
- private static readonly MAX_TEXTURE_POOL_SIZE = 2048;
- private textureAccessCounter: number = 0;
- private texturePool: Array<{
- texture: WebGLTexture;
- currentKey: string | null;
- version: number;
- lastUsed: number;
- filterTier?: number;
- hasStorage?: boolean;
- hasMipmap?: boolean;
- }> = [];
- private activePoolByKey: Map<
- string,
- {
- texture: WebGLTexture;
- currentKey: string | null;
- version: number;
- lastUsed: number;
- filterTier?: number;
- hasStorage?: boolean;
- hasMipmap?: boolean;
- }
- > = new Map();
- private fallbackTileCanvas: HTMLCanvasElement | null = null;
-
- constructor(canvas: HTMLCanvasElement, options?: { preserveDrawingBuffer?: boolean }) {
- this.canvas = canvas;
- this.preserveDrawingBuffer = Boolean(options?.preserveDrawingBuffer);
- if (typeof canvas.addEventListener === 'function') {
- this.onContextLostHandler = (e: Event) => {
- e.preventDefault();
- this.contextLost = true;
- this.gl = null;
- this.program = null;
- this.instancedProgram = null;
- this.instancedVao = null;
- this.instanceBuffer = null;
- this.tileArrayTexture = null;
- this.arrayPoolSlots = [];
- this.freeArraySlots = [];
- this.arrayPoolByKey.clear();
- this.arrayPoolCapacity = 0;
- this.arrayPoolFilterTier = -1;
- this.viewportDraftProgram = null;
- this.adjProgram = null;
- this.stylesProgram = null;
- this.blitProgram = null;
- this.softProofProgram = null;
- this.texturePool = [];
- this.activePoolByKey.clear();
- this.maskTextureCache.clear();
- this.scenePingPong = null;
- this.folderPingPongs = [];
- this.belowActiveCacheFbo = null;
- this.aboveActiveCacheFbo = null;
- this.layerStylesOutFbo = null;
- this.layerFbo = null;
- this.layerTexture = null;
- this.lutTexture = null;
- this.draftTexture = null;
- this.draftTexWidth = 0;
- this.draftTexHeight = 0;
- this.draftHasMipmap = false;
- this.lastDraftVersion = -1;
- this.stackCache.invalidateAll();
- };
- this.onContextRestoredHandler = () => {
- this.contextLost = false;
- this.initGL();
- (this.lastRenderedGrid || globalTileGrid).notifyChange(true);
- };
- canvas.addEventListener('webglcontextlost', this.onContextLostHandler, false);
- canvas.addEventListener('webglcontextrestored', this.onContextRestoredHandler, false);
- }
- this.initGL();
- }
-
- public isReady(): boolean {
- return !this.contextLost && this.gl !== null && this.program !== null;
- }
-
- public getCanvas(): HTMLCanvasElement {
- return this.canvas;
- }
-
- public getMaxTextureSize(): number {
- if (!this.gl) return 2048;
- const maxTex = Number(this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE)) || 2048;
- const maxRb = Number(this.gl.getParameter(this.gl.MAX_RENDERBUFFER_SIZE)) || maxTex;
- return Math.max(256, Math.min(maxTex, maxRb));
- }
-
- public getStackCacheStats(): { belowRebuilds: number; aboveRebuilds: number; cacheHits: number } {
- return { ...this.stackCacheStats };
- }
-
- /**
- * Explicitly invalidate baked layer stack caches.
- */
- public invalidateStackCache(): void {
- this.stackCache.invalidateAll();
- }
-
- /**
- * Explicitly invalidate a cached layer mask texture (or all masks if layerId omitted).
- */
- public invalidateMaskTexture(layerId?: string): void {
- const nextEpoch = ++this.globalMaskEpochCounter;
- if (layerId) {
- const item = this.maskTextureCache.get(layerId);
- if (item) item.version = -1;
- this.maskInvalidationEpochs.set(layerId, nextEpoch);
- } else {
- for (const [id, item] of this.maskTextureCache.entries()) {
- item.version = -1;
- this.maskInvalidationEpochs.set(id, nextEpoch);
- }
- this.stackCache.invalidateAll();
- }
- }
-
- /**
- * Explicitly invalidate and clear all cached tile textures in both TEXTURE_2D and TEXTURE_2D_ARRAY pools.
- */
- public invalidateTileTextures(): void {
- if (this.gl) {
- for (const slot of this.texturePool) {
- this.gl.deleteTexture(slot.texture);
- }
- }
- this.texturePool = [];
- this.activePoolByKey.clear();
- this.freeArraySlots = [];
- for (let i = this.arrayPoolSlots.length - 1; i >= 0; i--) {
- const slot = this.arrayPoolSlots[i];
- slot.currentKey = null;
- slot.version = -1;
- slot.lastUsed = 0;
- slot.lastBatchTick = 0;
- this.freeArraySlots.push(slot);
- }
- this.arrayPoolByKey.clear();
- this.stackCache.invalidateAll();
- }
-
- private queryLayerUniformLocs(gl: WebGL2RenderingContext, prog: WebGLProgram): LayerUniformLocs {
- return {
- uDocDimensions: gl.getUniformLocation(prog, 'u_docDimensions'),
- uViewportSize: gl.getUniformLocation(prog, 'u_viewportSize'),
- uPan: gl.getUniformLocation(prog, 'u_pan'),
- uZoom: gl.getUniformLocation(prog, 'u_zoom'),
- uRotationRad: gl.getUniformLocation(prog, 'u_rotationRad'),
- uFlip: gl.getUniformLocation(prog, 'u_flip'),
- uDpr: gl.getUniformLocation(prog, 'u_dpr'),
- uBackdropTexture: gl.getUniformLocation(prog, 'u_backdropTexture'),
- uHasBackdrop: gl.getUniformLocation(prog, 'u_hasBackdrop'),
- uLayerOpacity: gl.getUniformLocation(prog, 'u_layerOpacity'),
- uBlendMode: gl.getUniformLocation(prog, 'u_blendMode'),
- uToneEnabled: gl.getUniformLocation(prog, 'u_toneEnabled'),
- uToneFrequency: gl.getUniformLocation(prog, 'u_toneFrequency'),
- uToneAngleRad: gl.getUniformLocation(prog, 'u_toneAngleRad'),
- uToneDpi: gl.getUniformLocation(prog, 'u_toneDpi'),
- uToneDotShape: gl.getUniformLocation(prog, 'u_toneDotShape'),
- uToneDensity: gl.getUniformLocation(prog, 'u_toneDensity'),
- uToneDensityType: gl.getUniformLocation(prog, 'u_toneDensityType'),
- uLayerColorEnabled: gl.getUniformLocation(prog, 'u_layerColorEnabled'),
- uLayerColor: gl.getUniformLocation(prog, 'u_layerColor'),
- uLayerSubColor: gl.getUniformLocation(prog, 'u_layerSubColor'),
- uMaskTexture: gl.getUniformLocation(prog, 'u_maskTexture'),
- uMaskEnabled: gl.getUniformLocation(prog, 'u_maskEnabled'),
- uExpressionMode: gl.getUniformLocation(prog, 'u_expressionMode'),
- uMonoThreshold: gl.getUniformLocation(prog, 'u_monoThreshold'),
- uMonoExpressBlack: gl.getUniformLocation(prog, 'u_monoExpressBlack'),
- uMonoExpressWhite: gl.getUniformLocation(prog, 'u_monoExpressWhite'),
- };
- }
-
- private initTileArrayPool(gl: WebGL2RenderingContext): void {
- if (
- typeof gl.texStorage3D !== 'function' ||
- typeof gl.texSubImage3D !== 'function' ||
- typeof gl.drawArraysInstanced !== 'function' ||
- typeof gl.vertexAttribDivisor !== 'function' ||
- !this.quadBuffer
- ) {
- return;
- }
-
- const instVs = gl.createShader(gl.VERTEX_SHADER);
- const instFs = gl.createShader(gl.FRAGMENT_SHADER);
- if (!instVs || !instFs) return;
-
- gl.shaderSource(instVs, COMPOSITOR_INSTANCED_VERTEX_SHADER);
- gl.compileShader(instVs);
- gl.shaderSource(instFs, COMPOSITOR_INSTANCED_FRAGMENT_SHADER);
- gl.compileShader(instFs);
- if (
- !gl.getShaderParameter(instVs, gl.COMPILE_STATUS) ||
- !gl.getShaderParameter(instFs, gl.COMPILE_STATUS)
- ) {
- console.error('Instanced tile shader compile error:', gl.getShaderInfoLog(instVs), gl.getShaderInfoLog(instFs));
- return;
- }
-
- const iProg = gl.createProgram();
- if (!iProg) return;
- gl.attachShader(iProg, instVs);
- gl.attachShader(iProg, instFs);
- gl.linkProgram(iProg);
- if (!gl.getProgramParameter(iProg, gl.LINK_STATUS)) {
- console.error('Instanced tile program link error:', gl.getProgramInfoLog(iProg));
- return;
- }
-
- const maxLayersParam = Number(gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS)) || ViewportCompositor.DEFAULT_ARRAY_POOL_LAYERS;
- const capacity = Math.max(1, Math.min(ViewportCompositor.DEFAULT_ARRAY_POOL_LAYERS, maxLayersParam));
-
- const arrTex = gl.createTexture();
- const instBuf = gl.createBuffer();
- if (!arrTex || !instBuf) {
- if (arrTex) gl.deleteTexture(arrTex);
- if (instBuf) gl.deleteBuffer(instBuf);
- gl.deleteProgram(iProg);
- return;
- }
-
- gl.bindTexture(gl.TEXTURE_2D_ARRAY, arrTex);
- gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, TILE_SIZE, TILE_SIZE, capacity);
- gl.bindTexture(gl.TEXTURE_2D_ARRAY, null);
-
- this.instanceFloatScratch = new Float32Array(capacity * 3);
- gl.bindBuffer(gl.ARRAY_BUFFER, instBuf);
- gl.bufferData(gl.ARRAY_BUFFER, this.instanceFloatScratch.byteLength, gl.DYNAMIC_DRAW);
-
- this.instancedProgram = iProg;
- this.instancedLocs = this.queryLayerUniformLocs(gl, iProg);
- this.uInstTileSizeLoc = gl.getUniformLocation(iProg, 'u_tileSize');
- this.uInstTileArrayLoc = gl.getUniformLocation(iProg, 'u_tileArrayTexture');
- this.aInstQuadPosLoc = gl.getAttribLocation(iProg, 'a_quadPos');
- this.aInstDataLoc = gl.getAttribLocation(iProg, 'a_instanceData');
-
- // Immediately bind distinct texture units for sampler2DArray (0) vs sampler2D (1, 2)
- // to prevent WebGL2 GL_INVALID_OPERATION sampler-type collisions on unit 0.
- gl.useProgram(iProg);
- gl.uniform1i(this.uInstTileArrayLoc, 0);
- gl.uniform1i(this.instancedLocs.uMaskTexture, 1);
- gl.uniform1i(this.instancedLocs.uBackdropTexture, 2);
- if (this.program) {
- gl.useProgram(this.program);
- }
-
- this.tileArrayTexture = arrTex;
- this.instanceBuffer = instBuf;
- this.arrayPoolCapacity = capacity;
- this.arrayPoolFilterTier = 1;
- this.arrayPoolSlots = [];
- this.freeArraySlots = [];
- this.arrayPoolByKey.clear();
- for (let i = 0; i < capacity; i++) {
- const slot: ArrayPoolSlot = {
- sliceIndex: i,
- currentKey: null,
- version: -1,
- lastUsed: 0,
- lastBatchTick: 0,
- };
- this.arrayPoolSlots.push(slot);
- }
- for (let i = capacity - 1; i >= 0; i--) {
- this.freeArraySlots.push(this.arrayPoolSlots[i]);
- }
-
- if (typeof gl.createVertexArray === 'function') {
- const vao = gl.createVertexArray();
- if (vao) {
- gl.bindVertexArray(vao);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- if (this.aInstQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aInstQuadPosLoc);
- gl.vertexAttribPointer(this.aInstQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- gl.vertexAttribDivisor(this.aInstQuadPosLoc, 0);
- }
- gl.bindBuffer(gl.ARRAY_BUFFER, this.instanceBuffer);
- if (this.aInstDataLoc >= 0) {
- gl.enableVertexAttribArray(this.aInstDataLoc);
- gl.vertexAttribPointer(this.aInstDataLoc, 3, gl.FLOAT, false, 0, 0);
- gl.vertexAttribDivisor(this.aInstDataLoc, 1);
- }
- gl.bindVertexArray(null);
- this.instancedVao = vao;
- }
- }
- }
-
- private initGL(): boolean {
- if (this.gl && this.program) return true;
-
- try {
- const gl = this.canvas.getContext('webgl2', {
- alpha: true,
- premultipliedAlpha: true,
- antialias: false,
- depth: false,
- stencil: true,
- preserveDrawingBuffer: this.preserveDrawingBuffer,
- powerPreference: 'high-performance',
- });
-
- if (!gl) return false;
- this.gl = gl;
-
- // Compile vertex shader
- const vs = gl.createShader(gl.VERTEX_SHADER);
- if (!vs) return false;
- gl.shaderSource(vs, COMPOSITOR_VERTEX_SHADER);
- gl.compileShader(vs);
- if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
- console.error('Compositor VS error:', gl.getShaderInfoLog(vs));
- return false;
- }
-
- // Compile fragment shader
- const fs = gl.createShader(gl.FRAGMENT_SHADER);
- if (!fs) return false;
- gl.shaderSource(fs, COMPOSITOR_FRAGMENT_SHADER);
- gl.compileShader(fs);
- if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
- console.error('Compositor FS error:', gl.getShaderInfoLog(fs));
- return false;
- }
-
- // Link standard compositor program
- const prog = gl.createProgram();
- if (!prog) return false;
- gl.attachShader(prog, vs);
- gl.attachShader(prog, fs);
- gl.linkProgram(prog);
- if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
- console.error('Compositor link error:', gl.getProgramInfoLog(prog));
- return false;
- }
- this.program = prog;
- this.stdLocs = this.queryLayerUniformLocs(gl, prog);
-
- // Cache standard-only uniforms
- this.uTileOriginLoc = gl.getUniformLocation(prog, 'u_tileOrigin');
- this.uTileSizeLoc = gl.getUniformLocation(prog, 'u_tileSize');
- this.uIsBackgroundLoc = gl.getUniformLocation(prog, 'u_isBackground');
- this.uShowCheckerboardLoc = gl.getUniformLocation(prog, 'u_showCheckerboard');
- this.uTileTextureLoc = gl.getUniformLocation(prog, 'u_tileTexture');
- this.aQuadPosLoc = gl.getAttribLocation(prog, 'a_quadPos');
-
- // Compile Viewport-Space Draft Shader Program (shares COMPOSITOR_FRAGMENT_SHADER)
- const draftVs = gl.createShader(gl.VERTEX_SHADER);
- if (draftVs) {
- gl.shaderSource(draftVs, VIEWPORT_DRAFT_VERTEX_SHADER);
- gl.compileShader(draftVs);
- if (gl.getShaderParameter(draftVs, gl.COMPILE_STATUS)) {
- const dProg = gl.createProgram();
- if (dProg) {
- gl.attachShader(dProg, draftVs);
- gl.attachShader(dProg, fs);
- gl.linkProgram(dProg);
- if (gl.getProgramParameter(dProg, gl.LINK_STATUS)) {
- this.viewportDraftProgram = dProg;
- this.viewportDraftLocs = this.queryLayerUniformLocs(gl, dProg);
- this.uViewportDraftTileTexLoc = gl.getUniformLocation(dProg, 'u_tileTexture');
- this.uViewportDraftIsBgLoc = gl.getUniformLocation(dProg, 'u_isBackground');
- this.aViewportDraftQuadPosLoc = gl.getAttribLocation(dProg, 'a_quadPos');
- }
- }
- }
- }
-
- // Compile Adjustment Shader Program
- const adjFs = gl.createShader(gl.FRAGMENT_SHADER);
- if (adjFs) {
- gl.shaderSource(adjFs, ADJUSTMENT_FRAGMENT_SHADER);
- gl.compileShader(adjFs);
- if (gl.getShaderParameter(adjFs, gl.COMPILE_STATUS)) {
- const aProg = gl.createProgram();
- if (aProg) {
- gl.attachShader(aProg, vs);
- gl.attachShader(aProg, adjFs);
- gl.linkProgram(aProg);
- if (gl.getProgramParameter(aProg, gl.LINK_STATUS)) {
- this.adjProgram = aProg;
- this.uAdjTileOriginLoc = gl.getUniformLocation(aProg, 'u_tileOrigin');
- this.uAdjTileSizeLoc = gl.getUniformLocation(aProg, 'u_tileSize');
- this.uAdjDocDimensionsLoc = gl.getUniformLocation(aProg, 'u_docDimensions');
- this.uAdjViewportSizeLoc = gl.getUniformLocation(aProg, 'u_viewportSize');
- this.uAdjPanLoc = gl.getUniformLocation(aProg, 'u_pan');
- this.uAdjZoomLoc = gl.getUniformLocation(aProg, 'u_zoom');
- this.uAdjRotationRadLoc = gl.getUniformLocation(aProg, 'u_rotationRad');
- this.uAdjFlipLoc = gl.getUniformLocation(aProg, 'u_flip');
- this.uAdjDprLoc = gl.getUniformLocation(aProg, 'u_dpr');
- this.uAdjSnapshotLoc = gl.getUniformLocation(aProg, 'u_snapshotTexture');
- this.uAdjLutLoc = gl.getUniformLocation(aProg, 'u_lutTexture');
- this.uAdjModeLoc = gl.getUniformLocation(aProg, 'u_adjMode');
- this.uAdjOpacityLoc = gl.getUniformLocation(aProg, 'u_layerOpacity');
- this.uAdjMaskEnabledLoc = gl.getUniformLocation(aProg, 'u_maskEnabled');
- this.uAdjMaskTextureLoc = gl.getUniformLocation(aProg, 'u_maskTexture');
- }
- }
- } else {
- console.error('Adjustment FS error:', gl.getShaderInfoLog(adjFs));
- }
- }
-
- // Compile Layer Styles Shader Program
- const stylesVs = gl.createShader(gl.VERTEX_SHADER);
- const stylesFs = gl.createShader(gl.FRAGMENT_SHADER);
- if (stylesVs && stylesFs) {
- gl.shaderSource(stylesVs, LAYER_STYLES_VERTEX_SHADER);
- gl.compileShader(stylesVs);
- gl.shaderSource(stylesFs, LAYER_STYLES_FRAGMENT_SHADER);
- gl.compileShader(stylesFs);
- if (gl.getShaderParameter(stylesVs, gl.COMPILE_STATUS) && gl.getShaderParameter(stylesFs, gl.COMPILE_STATUS)) {
- const sProg = gl.createProgram();
- if (sProg) {
- gl.attachShader(sProg, stylesVs);
- gl.attachShader(sProg, stylesFs);
- gl.linkProgram(sProg);
- if (gl.getProgramParameter(sProg, gl.LINK_STATUS)) {
- this.stylesProgram = sProg;
- this.aStylesQuadPosLoc = gl.getAttribLocation(sProg, 'a_quadPos');
- this.uStylesLayerTextureLoc = gl.getUniformLocation(sProg, 'u_layerTexture');
- this.uStylesViewportSizeLoc = gl.getUniformLocation(sProg, 'u_viewportSize');
- this.uStylesLayerOpacityLoc = gl.getUniformLocation(sProg, 'u_layerOpacity');
- this.uStylesStrokeEnabledLoc = gl.getUniformLocation(sProg, 'u_strokeEnabled');
- this.uStylesStrokeSizeLoc = gl.getUniformLocation(sProg, 'u_strokeSize');
- this.uStylesStrokeColorLoc = gl.getUniformLocation(sProg, 'u_strokeColor');
- this.uStylesStrokePositionLoc = gl.getUniformLocation(sProg, 'u_strokePosition');
- this.uStylesGlowEnabledLoc = gl.getUniformLocation(sProg, 'u_glowEnabled');
- this.uStylesGlowColorLoc = gl.getUniformLocation(sProg, 'u_glowColor');
- this.uStylesGlowBlurLoc = gl.getUniformLocation(sProg, 'u_glowBlur');
- this.uStylesGlowSpreadLoc = gl.getUniformLocation(sProg, 'u_glowSpread');
- this.uStylesShadowEnabledLoc = gl.getUniformLocation(sProg, 'u_shadowEnabled');
- this.uStylesShadowColorLoc = gl.getUniformLocation(sProg, 'u_shadowColor');
- this.uStylesShadowOffsetLoc = gl.getUniformLocation(sProg, 'u_shadowOffset');
- this.uStylesShadowBlurLoc = gl.getUniformLocation(sProg, 'u_shadowBlur');
- this.uStylesShadowSpreadLoc = gl.getUniformLocation(sProg, 'u_shadowSpread');
- }
- }
- } else {
- console.error('Layer Styles shader compile error:', gl.getShaderInfoLog(stylesFs));
- }
- }
-
- // Compile Folder / Cache Blit Shader Program
- const blitVs = gl.createShader(gl.VERTEX_SHADER);
- const blitFs = gl.createShader(gl.FRAGMENT_SHADER);
- if (blitVs && blitFs) {
- gl.shaderSource(blitVs, FOLDER_BLIT_VERTEX_SHADER);
- gl.compileShader(blitVs);
- gl.shaderSource(blitFs, FOLDER_BLIT_FRAGMENT_SHADER);
- gl.compileShader(blitFs);
- if (gl.getShaderParameter(blitVs, gl.COMPILE_STATUS) && gl.getShaderParameter(blitFs, gl.COMPILE_STATUS)) {
- const bProg = gl.createProgram();
- if (bProg) {
- gl.attachShader(bProg, blitVs);
- gl.attachShader(bProg, blitFs);
- gl.linkProgram(bProg);
- if (gl.getProgramParameter(bProg, gl.LINK_STATUS)) {
- this.blitProgram = bProg;
- this.aBlitQuadPosLoc = gl.getAttribLocation(bProg, 'a_quadPos');
- this.uBlitTextureLoc = gl.getUniformLocation(bProg, 'u_blitTexture');
- this.uBlitBackdropTextureLoc = gl.getUniformLocation(bProg, 'u_backdropTexture');
- this.uBlitHasBackdropLoc = gl.getUniformLocation(bProg, 'u_hasBackdrop');
- this.uBlitBlendModeLoc = gl.getUniformLocation(bProg, 'u_blendMode');
- this.uBlitOpacityLoc = gl.getUniformLocation(bProg, 'u_blitOpacity');
- }
- }
- }
- }
-
- // Compile Soft Proof Shader Program
- const proofVs = gl.createShader(gl.VERTEX_SHADER);
- const proofFs = gl.createShader(gl.FRAGMENT_SHADER);
- if (proofVs && proofFs) {
- gl.shaderSource(proofVs, SOFT_PROOF_VERTEX_SHADER);
- gl.compileShader(proofVs);
- gl.shaderSource(proofFs, SOFT_PROOF_FRAGMENT_SHADER);
- gl.compileShader(proofFs);
- if (gl.getShaderParameter(proofVs, gl.COMPILE_STATUS) && gl.getShaderParameter(proofFs, gl.COMPILE_STATUS)) {
- const pProg = gl.createProgram();
- if (pProg) {
- gl.attachShader(pProg, proofVs);
- gl.attachShader(pProg, proofFs);
- gl.linkProgram(pProg);
- if (gl.getProgramParameter(pProg, gl.LINK_STATUS)) {
- this.softProofProgram = pProg;
- this.aProofQuadPosLoc = gl.getAttribLocation(pProg, 'a_quadPos');
- this.uProofSceneTextureLoc = gl.getUniformLocation(pProg, 'u_sceneTexture');
- this.uProofStandardLoc = gl.getUniformLocation(pProg, 'u_standard');
- this.uProofEnabledLoc = gl.getUniformLocation(pProg, 'u_proofEnabled');
- this.uProofGamutWarningLoc = gl.getUniformLocation(pProg, 'u_gamutWarning');
- this.uProofGamutWarningColorLoc = gl.getUniformLocation(pProg, 'u_gamutWarningColor');
- } else {
- console.error('Soft proof link error:', gl.getProgramInfoLog(pProg));
- }
- }
- } else {
- console.error('Soft proof shader compile error:', gl.getShaderInfoLog(proofVs), gl.getShaderInfoLog(proofFs));
- }
- }
-
- // Compile Frame Border Folder Polygon Program
- const frameVs = gl.createShader(gl.VERTEX_SHADER);
- const frameFs = gl.createShader(gl.FRAGMENT_SHADER);
- if (frameVs && frameFs) {
- gl.shaderSource(frameVs, FRAME_POLY_VERTEX_SHADER);
- gl.compileShader(frameVs);
- gl.shaderSource(frameFs, FRAME_POLY_FRAGMENT_SHADER);
- gl.compileShader(frameFs);
- if (gl.getShaderParameter(frameVs, gl.COMPILE_STATUS) && gl.getShaderParameter(frameFs, gl.COMPILE_STATUS)) {
- const fProg = gl.createProgram();
- if (fProg) {
- gl.attachShader(fProg, frameVs);
- gl.attachShader(fProg, frameFs);
- gl.linkProgram(fProg);
- if (gl.getProgramParameter(fProg, gl.LINK_STATUS)) {
- this.framePolyProgram = fProg;
- this.aFramePolyDocPosLoc = gl.getAttribLocation(fProg, 'a_docPos');
- this.uFramePolyDocDimensionsLoc = gl.getUniformLocation(fProg, 'u_docDimensions');
- this.uFramePolyViewportSizeLoc = gl.getUniformLocation(fProg, 'u_viewportSize');
- this.uFramePolyPanLoc = gl.getUniformLocation(fProg, 'u_pan');
- this.uFramePolyZoomLoc = gl.getUniformLocation(fProg, 'u_zoom');
- this.uFramePolyRotationRadLoc = gl.getUniformLocation(fProg, 'u_rotationRad');
- this.uFramePolyFlipLoc = gl.getUniformLocation(fProg, 'u_flip');
- this.uFramePolyDprLoc = gl.getUniformLocation(fProg, 'u_dpr');
- this.uFramePolyColorLoc = gl.getUniformLocation(fProg, 'u_color');
- this.framePolyBuffer = gl.createBuffer();
- }
- }
- }
- }
-
- // Create Layer Styles Quad Buffer [0, 1]
- const stylesQuad = gl.createBuffer();
- if (stylesQuad) {
- gl.bindBuffer(gl.ARRAY_BUFFER, stylesQuad);
- gl.bufferData(
- gl.ARRAY_BUFFER,
- new Float32Array([
- 0.0, 0.0,
- 1.0, 0.0,
- 0.0, 1.0,
- 0.0, 1.0,
- 1.0, 0.0,
- 1.0, 1.0,
- ]),
- gl.STATIC_DRAW
- );
- this.stylesQuadBuffer = stylesQuad;
- }
-
- // Create Unit Quad Buffer [0, 1]
- const quad = gl.createBuffer();
- if (!quad) return false;
- gl.bindBuffer(gl.ARRAY_BUFFER, quad);
- gl.bufferData(
- gl.ARRAY_BUFFER,
- new Float32Array([
- 0.0, 0.0,
- 1.0, 0.0,
- 0.0, 1.0,
- 0.0, 1.0,
- 1.0, 0.0,
- 1.0, 1.0,
- ]),
- gl.STATIC_DRAW
- );
- this.quadBuffer = quad;
-
- // Initialize TEXTURE_2D_ARRAY + instanced batch rendering pipeline
- this.initTileArrayPool(gl);
-
- // Enable blending
- gl.enable(gl.BLEND);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
-
- return true;
- } catch (err) {
- console.warn('WebGL2 not available for compositor:', err);
- return false;
- }
- }
-
- /**
- * Resize viewport canvas to physical screen pixels.
- */
- public resize(width: number, height: number): void {
- const nextW = Math.max(1, width);
- const nextH = Math.max(1, height);
- if (this.canvas.width !== nextW || this.canvas.height !== nextH) {
- this.canvas.width = nextW;
- this.canvas.height = nextH;
- this.stackCache.invalidateAll();
- if (this.gl) {
- this.gl.viewport(0, 0, this.canvas.width, this.canvas.height);
- }
- }
- }
-
- /**
- * Calculates the document-space bounding box visible in the current camera viewport.
- * Performs frustum culling.
- */
- public calculateVisibleDocumentBounds(
- viewportW: number,
- viewportH: number,
- transform: ViewportTransform,
- docW: number,
- docH: number
- ): { minX: number; minY: number; maxX: number; maxY: number } {
- return calculateVisibleDocumentBounds(viewportW, viewportH, transform, docW, docH);
- }
-
- // ============================================================================
- // Ping-Pong FBO & Offscreen Cache Surface Management
- // ============================================================================
-
- private createFboSurface(gl: WebGL2RenderingContext, withStencil: boolean = true): FboSurface | null {
- const fbo = gl.createFramebuffer();
- const texture = gl.createTexture();
- if (!fbo || !texture) {
- if (fbo) gl.deleteFramebuffer(fbo);
- if (texture) gl.deleteTexture(texture);
- return null;
- }
- const stencilRb =
- withStencil && typeof gl.createRenderbuffer === 'function' ? gl.createRenderbuffer() : null;
- return { fbo, texture, stencilRb, width: 0, height: 0 };
- }
-
- private ensureFboSurfaceSize(
- gl: WebGL2RenderingContext,
- surface: FboSurface,
- width: number,
- height: number
- ): boolean {
- if (surface.width === width && surface.height === height) {
- return true;
- }
-
- const prevFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;
-
- gl.bindTexture(gl.TEXTURE_2D, surface.texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
-
- gl.bindFramebuffer(gl.FRAMEBUFFER, surface.fbo);
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, surface.texture, 0);
-
- if (surface.stencilRb && typeof gl.bindRenderbuffer === 'function') {
- gl.bindRenderbuffer(gl.RENDERBUFFER, surface.stencilRb);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, width, height);
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, surface.stencilRb);
- }
-
- const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
- gl.bindFramebuffer(gl.FRAMEBUFFER, prevFbo);
-
- if (status !== gl.FRAMEBUFFER_COMPLETE) {
- console.error('Compositor FBO surface incomplete:', status);
- return false;
- }
-
- surface.width = width;
- surface.height = height;
- return true;
- }
-
- private ensurePingPongTarget(
- gl: WebGL2RenderingContext,
- existing: PingPongTarget | null,
- width: number,
- height: number
- ): PingPongTarget | null {
- let target = existing;
- if (!target) {
- const s0 = this.createFboSurface(gl, true);
- const s1 = this.createFboSurface(gl, true);
- if (!s0 || !s1) {
- this.disposeFboSurface(gl, s0);
- this.disposeFboSurface(gl, s1);
- return null;
- }
- target = { surfaces: [s0, s1], activeIndex: 0 };
- }
- if (
- !this.ensureFboSurfaceSize(gl, target.surfaces[0], width, height) ||
- !this.ensureFboSurfaceSize(gl, target.surfaces[1], width, height)
- ) {
- return null;
- }
- return target;
- }
-
- private ensureFolderPingPong(
- gl: WebGL2RenderingContext,
- depth: number,
- width: number,
- height: number
- ): PingPongTarget | null {
- while (this.folderPingPongs.length <= depth) {
- const created = this.ensurePingPongTarget(gl, null, width, height);
- if (!created) return null;
- this.folderPingPongs.push(created);
- }
- const target = this.ensurePingPongTarget(gl, this.folderPingPongs[depth], width, height);
- if (!target) return null;
- this.folderPingPongs[depth] = target;
- return target;
- }
-
- private disposeFboSurface(gl: WebGL2RenderingContext, surface: FboSurface | null): void {
- if (!surface) return;
- gl.deleteFramebuffer(surface.fbo);
- gl.deleteTexture(surface.texture);
- if (surface.stencilRb && typeof gl.deleteRenderbuffer === 'function') {
- gl.deleteRenderbuffer(surface.stencilRb);
- }
- }
-
- private disposePingPongTarget(gl: WebGL2RenderingContext, target: PingPongTarget | null): void {
- if (!target) return;
- this.disposeFboSurface(gl, target.surfaces[0]);
- this.disposeFboSurface(gl, target.surfaces[1]);
- }
-
- /**
- * Fast GPU-to-GPU FBO copy via gl.blitFramebuffer (with fullscreen quad fallback).
- * Eliminates all gl.copyTexSubImage2D calls and preserves stencil buffer when requested.
- */
- private copyFboSurface(
- gl: WebGL2RenderingContext,
- src: FboSurface,
- dst: FboSurface,
- width: number,
- height: number,
- copyStencil: boolean = false
- ): void {
- if (
- typeof gl.blitFramebuffer === 'function' &&
- gl.READ_FRAMEBUFFER !== undefined &&
- gl.DRAW_FRAMEBUFFER !== undefined
- ) {
- gl.bindFramebuffer(gl.READ_FRAMEBUFFER, src.fbo);
- gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, dst.fbo);
- const mask = copyStencil && src.stencilRb && dst.stencilRb
- ? (gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT)
- : gl.COLOR_BUFFER_BIT;
- gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST);
- gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
- gl.viewport(0, 0, width, height);
- return;
- }
-
- // Fallback: fullscreen quad copy using blitProgram (zero copyTexSubImage2D)
- gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
- gl.viewport(0, 0, width, height);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT);
- if (!this.blitProgram) return;
-
- const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
- if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
- gl.disable(gl.BLEND);
-
- gl.useProgram(this.blitProgram);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer || this.quadBuffer);
- if (this.aBlitQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aBlitQuadPosLoc);
- gl.vertexAttribPointer(this.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, src.texture);
- gl.uniform1i(this.uBlitTextureLoc, 0);
- gl.uniform1i(this.uBlitBackdropTextureLoc, 2);
- gl.uniform1i(this.uBlitHasBackdropLoc, 0);
- gl.uniform1i(this.uBlitBlendModeLoc, 0);
- gl.uniform1f(this.uBlitOpacityLoc, 1.0);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
-
- this.unbindSceneTextureUnits(gl);
- gl.enable(gl.BLEND);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
- this.restoreStandardProgram(gl);
- }
-
- /**
- * Unbinds offscreen FBO textures from TEXTURE0 and TEXTURE2 so no texture attached
- * to the next bound DRAW_FRAMEBUFFER can trigger a WebGL2 feedback loop error.
- */
- private unbindSceneTextureUnits(gl: WebGL2RenderingContext): void {
- gl.activeTexture(gl.TEXTURE2);
- gl.bindTexture(gl.TEXTURE_2D, null);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, null);
- }
-
- /**
- * Swaps Ping-Pong FBOs for a programmable blend / adjustment pass:
- * copies current surface -> opposite surface and returns current surface's immutable texture as backdrop.
- * ZERO gl.copyTexSubImage2D calls!
- */
- private prepareBackdropFromPingPong(
- gl: WebGL2RenderingContext,
- target: PingPongTarget,
- viewportW: number,
- viewportH: number,
- preserveStencil: boolean
- ): WebGLTexture {
- const src = target.surfaces[target.activeIndex];
- const nextIdx: 0 | 1 = target.activeIndex === 0 ? 1 : 0;
- const dst = target.surfaces[nextIdx];
-
- this.copyFboSurface(gl, src, dst, viewportW, viewportH, preserveStencil);
- target.activeIndex = nextIdx;
- gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
- gl.viewport(0, 0, viewportW, viewportH);
-
- return src.texture;
- }
-
- private restoreStandardProgram(gl: WebGL2RenderingContext): void {
- if (this.program) {
- gl.useProgram(this.program);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- if (this.aQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aQuadPosLoc);
- gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
- }
- }
-
- private syncFrameUniforms(gl: WebGL2RenderingContext, locs: LayerUniformLocs): void {
- const fs = this.currentFrameState;
- if (!fs) return;
- gl.uniform2f(locs.uViewportSize, fs.viewportW, fs.viewportH);
- gl.uniform2f(locs.uDocDimensions, fs.dimensions.width, fs.dimensions.height);
- gl.uniform2f(locs.uPan, fs.transform.pan.x, fs.transform.pan.y);
- gl.uniform1f(locs.uZoom, fs.transform.zoom);
- gl.uniform1f(locs.uRotationRad, fs.rotRad);
- gl.uniform2f(locs.uFlip, fs.transform.flipX ? -1.0 : 1.0, fs.transform.flipY ? -1.0 : 1.0);
- gl.uniform1f(locs.uDpr, fs.dpr);
- }
-
- private applyLayerUniforms(
- gl: WebGL2RenderingContext,
- locs: LayerUniformLocs,
- layer: LayerItem,
- dimensions: CanvasDimensions,
- effectiveOpacity: number,
- modeCode: number,
- backdropTex: WebGLTexture | null,
- maskTex: WebGLTexture | null
- ): void {
- gl.uniform1f(locs.uLayerOpacity, effectiveOpacity);
- gl.uniform1i(locs.uBlendMode, modeCode);
-
- // Always bind distinct sampler units (mask = 1, backdrop = 2) so sampler2D never
- // collides with sampler2DArray on unit 0 in WebGL2.
- gl.uniform1i(locs.uBackdropTexture, 2);
- gl.uniform1i(locs.uMaskTexture, 1);
-
- if (backdropTex && modeCode !== 0 && modeCode !== 12) {
- gl.activeTexture(gl.TEXTURE2);
- gl.bindTexture(gl.TEXTURE_2D, backdropTex);
- gl.uniform1i(locs.uHasBackdrop, 1);
- } else {
- gl.activeTexture(gl.TEXTURE2);
- gl.bindTexture(gl.TEXTURE_2D, null);
- gl.uniform1i(locs.uHasBackdrop, 0);
- }
-
- // Expression Color Uniforms
- const isBgLayer = layer.id === 'layer-bg' || layer.id.startsWith('layer-bg');
- const docColorMode = this.currentOptions?.colorMode;
- const exprMode = isBgLayer
- ? 0
- : layer.expressionColor === 'monochrome' || docColorMode === 'monochrome'
- ? 2
- : layer.expressionColor === 'gray' || docColorMode === 'grayscale'
- ? 1
- : 0;
- gl.uniform1i(locs.uExpressionMode, exprMode);
- if (exprMode === 2) {
- gl.uniform1f(locs.uMonoThreshold, (layer.monoThreshold ?? 128) / 255.0);
- gl.uniform1i(locs.uMonoExpressBlack, layer.monoExpressBlack !== false ? 1 : 0);
- gl.uniform1i(locs.uMonoExpressWhite, layer.monoExpressWhite !== false ? 1 : 0);
- }
-
- // Screentone Uniforms
- const toneEnabled = Boolean(layer.toneEnabled);
- gl.uniform1i(locs.uToneEnabled, toneEnabled ? 1 : 0);
- if (toneEnabled) {
- gl.uniform1f(locs.uToneFrequency, layer.toneFrequency || 60);
- gl.uniform1f(locs.uToneAngleRad, ((layer.toneAngle || 45) * Math.PI) / 180);
- gl.uniform1f(locs.uToneDpi, dimensions.dpi || 600);
- const dotShapeCode =
- layer.toneDotShape === 'line'
- ? 2
- : layer.toneDotShape === 'diamond'
- ? 3
- : layer.toneDotShape === 'euclidean'
- ? 1
- : 0;
- gl.uniform1i(locs.uToneDotShape, dotShapeCode);
- gl.uniform1f(locs.uToneDensity, (layer.toneDensity ?? 40) / 100);
- gl.uniform1i(locs.uToneDensityType, layer.toneDensityType === 'image' ? 1 : 0);
- }
-
- // Layer Tint Uniforms
- const tintEnabled = Boolean(layer.layerColorEnabled);
- gl.uniform1i(locs.uLayerColorEnabled, tintEnabled ? 1 : 0);
- if (tintEnabled) {
- const prim = this.parseHexColor(layer.layerColor || '#1c73c2');
- const sub = this.parseHexColor(layer.layerSubColor || '#ffffff');
- gl.uniform3f(locs.uLayerColor, prim[0], prim[1], prim[2]);
- gl.uniform3f(locs.uLayerSubColor, sub[0], sub[1], sub[2]);
- }
-
- // Layer Mask Uniforms
- if (maskTex) {
- gl.activeTexture(gl.TEXTURE1);
- gl.bindTexture(gl.TEXTURE_2D, maskTex);
- gl.uniform1i(locs.uMaskEnabled, 1);
- } else {
- gl.activeTexture(gl.TEXTURE1);
- gl.bindTexture(gl.TEXTURE_2D, null);
- gl.uniform1i(locs.uMaskEnabled, 0);
- }
-
- gl.activeTexture(gl.TEXTURE0);
- }
-
- // ============================================================================
- // Tile Texture Streaming (Zero-CPU Premultiply via UNPACK_PREMULTIPLY_ALPHA_WEBGL)
- // ============================================================================
-
- /**
- * Allocates or updates a slice inside the TEXTURE_2D_ARRAY pool using hardware UNPACK_PREMULTIPLY_ALPHA_WEBGL.
- * Never evicts slices pinned by the current batchTick.
- */
- private premultiplyTileBytes(srcBytes: Uint8Array, tile: TileBuffer): Uint8Array {
- // 1-bit monochrome, 8-bit grayscale, and opaque solid-fill tiles only contain alpha 0 or 255
- // so straight-alpha bytes are already premultiplied (zero-copy fast path).
- if (
- tile.format === 'monochrome-1bit' ||
- tile.format === 'grayscale-8bit' ||
- (tile.solidColorU32 !== undefined && srcBytes[3] === 255)
- ) {
- return srcBytes;
- }
-
- const dst = this.uploadPremulScratch;
- const len = srcBytes.byteLength;
- const src32 = new Uint32Array(srcBytes.buffer, srcBytes.byteOffset, len >> 2);
- const dst32 = new Uint32Array(dst.buffer, dst.byteOffset, len >> 2);
-
- for (let p = 0, i = 0; i < len; p++, i += 4) {
- const a = srcBytes[i + 3];
- if (a === 255) {
- dst32[p] = src32[p];
- } else if (a === 0) {
- dst32[p] = 0;
- } else {
- dst[i] = ((srcBytes[i] * a + 128) * 257) >> 16;
- dst[i + 1] = ((srcBytes[i + 1] * a + 128) * 257) >> 16;
- dst[i + 2] = ((srcBytes[i + 2] * a + 128) * 257) >> 16;
- dst[i + 3] = a;
- }
- }
- return dst;
- }
-
- private getOrUploadArrayTileSlice(
- gl: WebGL2RenderingContext,
- tile: TileBuffer,
- grid: SparseTileGrid,
- batchTick: number
- ): number {
- const gridId = typeof grid.getGridId === 'function' ? grid.getGridId() : 0;
- const key = `${gridId}:${getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0)}`;
- const accessTick = ++this.arrayAccessCounter;
- let slot = this.arrayPoolByKey.get(key);
-
- if (slot) {
- // O(1) LRU promotion via JS Map insertion order
- this.arrayPoolByKey.delete(key);
- this.arrayPoolByKey.set(key, slot);
- } else {
- if (this.freeArraySlots.length > 0) {
- slot = this.freeArraySlots.pop()!;
- } else {
- // Evict oldest unpinned slot from front of Map (O(1) amortized)
- for (const candidate of this.arrayPoolByKey.values()) {
- if (candidate.lastBatchTick !== batchTick) {
- slot = candidate;
- break;
- }
- }
- if (!slot) return -1;
- if (slot.currentKey) {
- this.arrayPoolByKey.delete(slot.currentKey);
- }
- }
- slot.currentKey = key;
- slot.version = -1;
- this.arrayPoolByKey.set(key, slot);
- }
-
- slot.lastUsed = accessTick;
- slot.lastBatchTick = batchTick;
-
- if (slot.version !== tile.version) {
- const rgbaData = grid.getTileAsRGBA(tile);
- const srcBytes =
- rgbaData instanceof Uint8Array
- ? rgbaData
- : new Uint8Array(rgbaData.buffer, rgbaData.byteOffset, rgbaData.byteLength);
-
- // Premultiply once on upload into reusable scratch buffer (TileBuffer remains straight-alpha;
- // UNPACK_PREMULTIPLY_ALPHA_WEBGL stays false for WebGL2 spec compliance on texSubImage3D).
- const uploadBytes = this.premultiplyTileBytes(srcBytes, tile);
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
- gl.texSubImage3D(
- gl.TEXTURE_2D_ARRAY,
- 0,
- 0,
- 0,
- slot.sliceIndex,
- TILE_SIZE,
- TILE_SIZE,
- 1,
- gl.RGBA,
- gl.UNSIGNED_BYTE,
- uploadBytes
- );
-
- slot.version = tile.version;
- }
-
- return slot.sliceIndex;
- }
-
- /**
- * Get or upload a WebGLTexture from the fallback TEXTURE_2D pool with adaptive zoom filtering.
- * Uses gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true) directly — zero CPU premultiply loop!
- */
- private getTileTexture(tile: TileBuffer, grid: SparseTileGrid): WebGLTexture | null {
- if (!this.gl) return null;
- const gl = this.gl;
- const gridId = typeof grid.getGridId === 'function' ? grid.getGridId() : 0;
- const key = `${gridId}:${getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0)}`;
- const accessTick = ++this.textureAccessCounter;
-
- let slot = this.activePoolByKey.get(key);
-
- if (slot) {
- // O(1) LRU promotion via JS Map insertion order
- this.activePoolByKey.delete(key);
- this.activePoolByKey.set(key, slot);
- } else {
- if (this.texturePool.length < ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
- const tex = gl.createTexture();
- if (!tex) return null;
- slot = {
- texture: tex,
- currentKey: key,
- version: -1,
- lastUsed: accessTick,
- filterTier: -1,
- hasStorage: false,
- hasMipmap: false,
- };
- this.texturePool.push(slot);
- this.activePoolByKey.set(key, slot);
- } else {
- // O(1) LRU eviction from front of activePoolByKey Map
- const oldestEntry = this.activePoolByKey.entries().next();
- if (!oldestEntry.done) {
- slot = oldestEntry.value[1];
- this.activePoolByKey.delete(oldestEntry.value[0]);
- } else {
- slot = this.texturePool[0];
- }
- slot.currentKey = key;
- slot.version = -1;
- slot.lastUsed = accessTick;
- slot.filterTier = -1;
- slot.hasMipmap = false;
- this.activePoolByKey.set(key, slot);
- }
- }
-
- slot.lastUsed = accessTick;
- const desiredTier = this.currentZoom < 0.99 ? 0 : this.currentZoom < 2.0 ? 1 : 2;
-
- // Re-upload if version changed (direct GPU unpack premultiplication, zero JS pixel loop)
- if (slot.version !== tile.version) {
- gl.bindTexture(gl.TEXTURE_2D, slot.texture);
-
- const rgbaData = grid.getTileAsRGBA(tile);
- const srcBytes =
- rgbaData instanceof Uint8Array
- ? rgbaData
- : new Uint8Array(rgbaData.buffer, rgbaData.byteOffset, rgbaData.byteLength);
-
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
- if (slot.hasStorage && typeof gl.texSubImage2D === 'function') {
- gl.texSubImage2D(
- gl.TEXTURE_2D,
- 0,
- 0,
- 0,
- TILE_SIZE,
- TILE_SIZE,
- gl.RGBA,
- gl.UNSIGNED_BYTE,
- srcBytes
- );
- } else {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texImage2D(
- gl.TEXTURE_2D,
- 0,
- gl.RGBA,
- TILE_SIZE,
- TILE_SIZE,
- 0,
- gl.RGBA,
- gl.UNSIGNED_BYTE,
- srcBytes
- );
- slot.hasStorage = true;
- }
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
-
- slot.hasMipmap = false;
- slot.version = tile.version;
- slot.filterTier = -1; // Force filter parameter refresh
- }
-
- if (slot.filterTier !== desiredTier) {
- gl.bindTexture(gl.TEXTURE_2D, slot.texture);
- if (desiredTier <= 1) {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- } else {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- }
- slot.filterTier = desiredTier;
- }
-
- return slot.texture;
- }
-
- /**
- * Hex color parser to RGB normalized float array [r, g, b].
- */
- private parseHexColor(hex: string): [number, number, number] {
- let clean = hex.replace('#', '');
- if (clean.length === 3) {
- clean = clean.split('').map((c) => c + c).join('');
- }
- const num = parseInt(clean, 16);
- if (isNaN(num)) return [0, 0, 0];
- return [
- ((num >> 16) & 255) / 255,
- ((num >> 8) & 255) / 255,
- (num & 255) / 255,
- ];
- }
-
- private renderArtboardBackground(
- gl: WebGL2RenderingContext,
- dimensions: CanvasDimensions,
- showCheckerboard: boolean,
- drawShadow: boolean = true
- ): void {
- if (!this.program || !this.stdLocs) return;
- this.unbindSceneTextureUnits(gl);
- this.restoreStandardProgram(gl);
- this.syncFrameUniforms(gl, this.stdLocs);
- gl.uniform1i(this.uTileTextureLoc, 0);
- gl.uniform1i(this.stdLocs.uMaskTexture, 1);
- gl.uniform1i(this.stdLocs.uBackdropTexture, 2);
- gl.uniform1i(this.stdLocs.uMaskEnabled, 0);
- gl.uniform1i(this.stdLocs.uHasBackdrop, 0);
- gl.blendFunc(gl.ONE, drawShadow ? gl.ONE_MINUS_SRC_ALPHA : gl.ZERO);
- gl.uniform1i(this.uIsBackgroundLoc, 1);
- gl.uniform1i(this.stdLocs.uExpressionMode, 0);
- gl.uniform1i(this.uShowCheckerboardLoc, showCheckerboard ? 1 : 0);
- if (drawShadow) {
- const marginDoc = 56 / Math.max(0.01, this.currentZoom);
- gl.uniform2f(this.uTileOriginLoc, -marginDoc, -marginDoc);
- gl.uniform2f(
- this.uTileSizeLoc,
- dimensions.width + marginDoc * 2,
- dimensions.height + marginDoc * 2
- );
- } else {
- gl.uniform2f(this.uTileOriginLoc, 0, 0);
- gl.uniform2f(this.uTileSizeLoc, dimensions.width, dimensions.height);
- }
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- gl.uniform1i(this.uIsBackgroundLoc, 0);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- }
-
- private renderOnionSkins(
- gl: WebGL2RenderingContext,
- layers: LayerItem[],
- onionSkinFrames: OnionSkinCompositorFrame[] | undefined,
- dimensions: CanvasDimensions,
- grid: SparseTileGrid,
- frustum: { minX: number; minY: number; maxX: number; maxY: number },
- target: PingPongTarget | null
- ): void {
- if (!onionSkinFrames || onionSkinFrames.length === 0) return;
- for (const onion of onionSkinFrames) {
- const targetLayer = layers.find((l) => l.id === onion.layerId);
- if (targetLayer && targetLayer.visible) {
- const virtualOnionLayer: LayerItem = {
- ...targetLayer,
- opacity: onion.opacity,
- layerColorEnabled: true,
- layerColor: onion.tint,
- layerSubColor: '#ffffff',
- blendMode: 'normal',
- };
- this.renderSingleLayer(gl, virtualOnionLayer, dimensions, grid, frustum, 1.0, target, false);
- }
- }
- }
-
- private presentTextureToScreen(
- gl: WebGL2RenderingContext,
- texture: WebGLTexture,
- viewportW: number,
- viewportH: number,
- softProof?: SoftProofSettings
- ): void {
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.disable(gl.STENCIL_TEST);
-
- if (softProof && (softProof.enabled || softProof.gamutWarning) && this.softProofProgram) {
- this.applySoftProofPass(gl, viewportW, viewportH, softProof, texture);
- return;
- }
-
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT);
-
- if (!this.blitProgram) return;
- gl.disable(gl.BLEND);
- gl.useProgram(this.blitProgram);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer || this.quadBuffer);
- if (this.aBlitQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aBlitQuadPosLoc);
- gl.vertexAttribPointer(this.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
-
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(this.uBlitTextureLoc, 0);
- gl.uniform1i(this.uBlitBackdropTextureLoc, 2);
- gl.uniform1i(this.uBlitHasBackdropLoc, 0);
- gl.uniform1i(this.uBlitBlendModeLoc, 0);
- gl.uniform1f(this.uBlitOpacityLoc, 1.0);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
-
- this.unbindSceneTextureUnits(gl);
- gl.enable(gl.BLEND);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- this.restoreStandardProgram(gl);
- }
-
- /**
- * Main Render Pass: Composite all visible layers onto the viewport canvas using:
- * 1. Ping-Pong FBOs (zero gl.copyTexSubImage2D calls for all 16 blend modes, adjustments, & soft proof)
- * 2. Baked Layer Stack Cache (`belowActiveCacheFbo` + `activeUnit` + `aboveActiveCacheFbo`)
- * 3. TEXTURE_2D_ARRAY + gl.drawArraysInstanced tile batching
- */
- private lastRenderedGrid: SparseTileGrid | null = null;
-
- public render(
- layers: LayerItem[],
- transform: ViewportTransform,
- dimensions: CanvasDimensions,
- grid: SparseTileGrid = globalTileGrid,
- _options: CompositorOptions = { dimensions }
- ): void {
- this.lastRenderedGrid = grid;
- const gl = this.gl;
- this.currentOptions = _options;
- this.currentZoom = transform.zoom;
-
- if (!gl || !this.program || !this.stdLocs) {
- this.render2DFallback(layers, transform, dimensions, grid, _options);
- return;
- }
-
- const viewportW = Math.max(1, this.canvas.width);
- const viewportH = Math.max(1, this.canvas.height);
- const dpr = _options.devicePixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
- const rotRad = (transform.rotation * Math.PI) / 180;
-
- this.currentFrameState = {
- viewportW,
- viewportH,
- dpr,
- dimensions,
- transform,
- rotRad,
- };
-
- // Calculate Frustum Culling document bounds
- const viewportCssW = viewportW / dpr;
- const viewportCssH = viewportH / dpr;
- const frustum = this.calculateVisibleDocumentBounds(
- viewportCssW,
- viewportCssH,
- transform,
- dimensions.width,
- dimensions.height
- );
-
- // Dynamic Frustum Culling & Memory Budget Sync
- const activeLayerId = _options.activeLayerId ?? _options.activeDraftLayerId ?? null;
- const layerVis = new Map<string, boolean>();
- for (const l of layers) {
- layerVis.set(l.id, l.visible);
- }
- grid.getMemoryManager()?.updateViewport(frustum, activeLayerId, layerVis);
-
- // Ensure Ping-Pong Scene FBOs & Baked Layer Stack Cache FBOs
- const scenePP = this.ensurePingPongTarget(gl, this.scenePingPong, viewportW, viewportH);
- this.scenePingPong = scenePP;
-
- const bypassStackCache = Boolean(_options.bypassStackCache);
- let belowCacheReady = false;
- let aboveCacheReady = false;
- if (scenePP && !bypassStackCache) {
- if (!this.belowActiveCacheFbo) {
- this.belowActiveCacheFbo = this.createFboSurface(gl, false);
- }
- if (this.belowActiveCacheFbo) {
- belowCacheReady = this.ensureFboSurfaceSize(gl, this.belowActiveCacheFbo, viewportW, viewportH);
- }
- if (!this.aboveActiveCacheFbo) {
- this.aboveActiveCacheFbo = this.createFboSurface(gl, false);
- }
- if (this.aboveActiveCacheFbo) {
- aboveCacheReady = this.ensureFboSurfaceSize(gl, this.aboveActiveCacheFbo, viewportW, viewportH);
- }
- }
-
- if (bypassStackCache && scenePP) {
- this.restoreStandardProgram(gl);
- this.syncFrameUniforms(gl, this.stdLocs);
- gl.uniform1i(this.uTileTextureLoc, 0);
- gl.uniform1i(this.stdLocs.uHasBackdrop, 0);
-
- scenePP.activeIndex = 0;
- const surf = scenePP.surfaces[0];
- gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.disable(gl.STENCIL_TEST);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
-
- if (!_options.transparentBackground) {
- this.renderArtboardBackground(gl, dimensions, Boolean(_options.showCheckerboard), false);
- }
- this.renderOnionSkins(gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, scenePP);
-
- const tree = buildLayerTree(layers);
- this.renderNodeList(
- gl,
- tree,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- scenePP,
- 0,
- 1.0
- );
-
- this.presentTextureToScreen(
- gl,
- scenePP.surfaces[scenePP.activeIndex].texture,
- viewportW,
- viewportH,
- _options.softProof
- );
- } else if (scenePP && belowCacheReady && aboveCacheReady && this.belowActiveCacheFbo && this.aboveActiveCacheFbo) {
- // Evaluate Baked Layer Stack Cache invalidation (below / active / above)
- const cacheEval = this.stackCache.evaluate({
- layers,
- activeLayerId,
- viewportW,
- viewportH,
- dpr,
- dimensions,
- transform,
- showCheckerboard: Boolean(_options.showCheckerboard),
- transparentBackground: Boolean(_options.transparentBackground),
- colorMode: _options.colorMode,
- onionSkinFrames: _options.onionSkinFrames,
- getLayerContentVersion: (id) =>
- typeof grid.getLayerVersion === 'function' ? grid.getLayerVersion(id) : 0,
- getMaskInvalidationEpoch: (id) => this.maskInvalidationEpochs.get(id) ?? 0,
- gridEpoch: typeof grid.getGridEpoch === 'function' ? grid.getGridEpoch() : 0,
- gridId: typeof grid.getGridId === 'function' ? grid.getGridId() : 0,
- });
-
- const { partition } = cacheEval;
- this.restoreStandardProgram(gl);
- this.syncFrameUniforms(gl, this.stdLocs);
- gl.uniform1i(this.uTileTextureLoc, 0);
- gl.uniform1i(this.stdLocs.uHasBackdrop, 0);
-
- // Step 1: Rebuild aboveActiveCacheFbo ONLY when upper slice metadata/content/camera changed
- if (cacheEval.aboveDirty && partition.aboveCachedUnits.length > 0) {
- scenePP.activeIndex = 0;
- const surf = scenePP.surfaces[0];
- gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.disable(gl.STENCIL_TEST);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
-
- const overrideRootBlend = partition.aboveStrategy === 'baked-single-blend';
- for (const unit of partition.aboveCachedUnits) {
- this.renderCompositingUnit(
- gl,
- unit,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- scenePP,
- 0,
- overrideRootBlend
- );
- }
-
- this.copyFboSurface(
- gl,
- scenePP.surfaces[scenePP.activeIndex],
- this.aboveActiveCacheFbo,
- viewportW,
- viewportH,
- false
- );
- this.stackCacheStats.aboveRebuilds++;
- }
-
- // Step 2: Populate scenePP with below slice (either rebuild belowActiveCacheFbo or fast GPU blit)
- if (cacheEval.belowDirty) {
- scenePP.activeIndex = 0;
- const surf = scenePP.surfaces[0];
- gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.disable(gl.STENCIL_TEST);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
-
- if (!_options.transparentBackground) {
- this.renderArtboardBackground(gl, dimensions, Boolean(_options.showCheckerboard));
- }
- this.renderOnionSkins(gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, scenePP);
-
- for (const unit of partition.belowUnits) {
- this.renderCompositingUnit(
- gl,
- unit,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- scenePP,
- 0,
- false
- );
- }
-
- this.copyFboSurface(
- gl,
- scenePP.surfaces[scenePP.activeIndex],
- this.belowActiveCacheFbo,
- viewportW,
- viewportH,
- false
- );
- // Ensure scenePP's current surface remains bound for activeUnit
- gl.bindFramebuffer(gl.FRAMEBUFFER, scenePP.surfaces[scenePP.activeIndex].fbo);
- gl.viewport(0, 0, viewportW, viewportH);
- this.stackCacheStats.belowRebuilds++;
- } else {
- scenePP.activeIndex = 0;
- this.copyFboSurface(
- gl,
- this.belowActiveCacheFbo,
- scenePP.surfaces[0],
- viewportW,
- viewportH,
- false
- );
- if (!cacheEval.aboveDirty) {
- this.stackCacheStats.cacheHits++;
- }
- }
-
- // Step 3: Render active unit (+ live activeDraftCanvas in-stack!)
- if (partition.activeUnit) {
- this.renderCompositingUnit(
- gl,
- partition.activeUnit,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- scenePP,
- 0,
- false
- );
- }
-
- // Step 4: Render any dynamic non-associative upper units (via Ping-Pong FBOs, zero copyTexSubImage2D)
- for (const unit of partition.aboveDynamicUnits) {
- this.renderCompositingUnit(
- gl,
- unit,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- scenePP,
- 0,
- false
- );
- }
-
- // Step 5: Composite baked aboveActiveCacheFbo (1 single quad / 1 ping-pong blend pass)
- if (partition.aboveCachedUnits.length > 0) {
- const aboveBlend: BlendMode =
- partition.aboveStrategy === 'baked-single-blend'
- ? partition.aboveCacheBlendMode
- : 'normal';
- this.blitFolderTexture(
- gl,
- this.aboveActiveCacheFbo.texture,
- aboveBlend,
- 1.0,
- viewportW,
- viewportH,
- scenePP,
- false
- );
- }
-
- this.stackCache.commit(cacheEval.belowSignature, cacheEval.aboveSignature);
-
- // Step 6: Present final composited Ping-Pong surface to screen (with optional CMYK soft proofing)
- this.presentTextureToScreen(
- gl,
- scenePP.surfaces[scenePP.activeIndex].texture,
- viewportW,
- viewportH,
- _options.softProof
- );
- } else {
- // Safe fallback when offscreen FBOs are unsupported in a minimal WebGL context
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
-
- if (!_options.transparentBackground) {
- this.renderArtboardBackground(gl, dimensions, Boolean(_options.showCheckerboard), false);
- }
- this.renderOnionSkins(gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, null);
-
- const tree = buildLayerTree(layers);
- this.renderNodeList(
- gl,
- tree,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- null,
- 0,
- 1.0
- );
- }
-
- // Prune mask textures belonging to deleted layers
- if (this.maskTextureCache.size > layers.length) {
- for (const cachedLayerId of Array.from(this.maskTextureCache.keys())) {
- if (!layerVis.has(cachedLayerId)) {
- const entry = this.maskTextureCache.get(cachedLayerId);
- if (entry) gl.deleteTexture(entry.texture);
- this.maskTextureCache.delete(cachedLayerId);
- this.maskInvalidationEpochs.delete(cachedLayerId);
- }
- }
- }
-
- // Clean up stale textures if fallback pool exceeded limit
- if (this.texturePool.length > ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
- this.evictStaleTextures();
- }
- }
-
- /**
- * Renders a single atomic CompositingUnit (an isolated folder, adjustment layer, or base + clipped group)
- * into the active Ping-Pong target.
- */
- private renderCompositingUnit(
- gl: WebGL2RenderingContext,
- unit: CompositingUnit,
- dimensions: CanvasDimensions,
- grid: SparseTileGrid,
- frustum: { minX: number; minY: number; maxX: number; maxY: number },
- viewportW: number,
- viewportH: number,
- transform: ViewportTransform,
- dpr: number,
- target: PingPongTarget | null,
- depth: number,
- overrideRootBlendNormal: boolean
- ): void {
- const group = unit.group;
- const baseNode = group.baseNode;
- const baseLayer = overrideRootBlendNormal
- ? { ...baseNode.layer, blendMode: 'normal' as BlendMode }
- : baseNode.layer;
-
- if (!baseLayer.visible || baseLayer.opacity <= 0.001) {
- return;
- }
-
- if (baseLayer.type === 'frame-folder') {
- const folderTarget = this.ensureFolderPingPong(gl, depth, viewportW, viewportH);
- if (!folderTarget) return;
-
- const frames = (baseLayer.comicFrames || []).filter((f) => f.polygon.length >= 3);
-
- // 1. Render nested child layers into folderTarget.surfaces[0] cleanly (no stencil conflict with child clipping masks)
- folderTarget.activeIndex = 0;
- const childSurf = folderTarget.surfaces[0];
- gl.bindFramebuffer(gl.FRAMEBUFFER, childSurf.fbo);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.disable(gl.STENCIL_TEST);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
-
- if (baseNode.children.length > 0) {
- this.renderNodeList(
- gl,
- baseNode.children,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- folderTarget,
- depth + 1,
- 1.0
- );
- }
-
- const renderedChildrenTex = folderTarget.surfaces[folderTarget.activeIndex].texture;
- const outIdx: 0 | 1 = folderTarget.activeIndex === 0 ? 1 : 0;
- const outSurf = folderTarget.surfaces[outIdx];
-
- gl.bindFramebuffer(gl.FRAMEBUFFER, outSurf.fbo);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.disable(gl.STENCIL_TEST);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
-
- const shouldClip = frames.length > 0 && frames.some((f) => f.clipChildren !== false);
-
- if (frames.length > 0 && this.framePolyProgram && this.framePolyBuffer) {
- // 2. Write frame polygon interiors into stencil buffer (and optional background fill)
- if (shouldClip) {
- gl.enable(gl.STENCIL_TEST);
- gl.stencilMask(0xFF);
- gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
- }
-
- for (const frame of frames) {
- const fillVerts = triangulatePolygon(frame.polygon);
- if (fillVerts.length < 6) continue;
- const doFill = frame.fillBackground !== false;
- if (!doFill) {
- gl.colorMask(false, false, false, false);
- }
- const [fr, fg, fb] = this.parseHexColor(frame.fillColor || '#ffffff');
- this.drawFramePolygonTriangles(
- gl,
- fillVerts,
- fr,
- fg,
- fb,
- 1.0,
- dimensions,
- viewportW,
- viewportH,
- transform,
- dpr
- );
- if (!doFill) {
- gl.colorMask(true, true, true, true);
- }
- }
-
- // 3. Blit rendered children strictly inside stencil == 1
- if (shouldClip) {
- gl.stencilMask(0x00);
- gl.stencilFunc(gl.EQUAL, 1, 0xFF);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
- }
-
- this.blitFolderTexture(
- gl,
- renderedChildrenTex,
- 'normal',
- 1.0,
- viewportW,
- viewportH,
- null,
- shouldClip
- );
-
- gl.stencilMask(0xFF);
- gl.disable(gl.STENCIL_TEST);
-
- // 4. Draw crisp frame borders ON TOP of clipped folder contents
- for (const frame of frames) {
- const borderVerts = buildFrameBorderTriangles(frame.polygon, frame.borderWidth || 3);
- if (borderVerts.length < 6) continue;
- const [sr, sg, sb] = this.parseHexColor(frame.strokeColor || '#000000');
- this.drawFramePolygonTriangles(
- gl,
- borderVerts,
- sr,
- sg,
- sb,
- 1.0,
- dimensions,
- viewportW,
- viewportH,
- transform,
- dpr
- );
- }
-
- folderTarget.activeIndex = outIdx;
- }
-
- // 5. Composite finished frame folder onto parent framebuffer
- const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
- gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
- gl.viewport(0, 0, viewportW, viewportH);
-
- const folderBlend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;
- this.blitFolderTexture(
- gl,
- folderTarget.surfaces[folderTarget.activeIndex].texture,
- folderBlend,
- baseLayer.opacity * unit.inheritedOpacity,
- viewportW,
- viewportH,
- target,
- false
- );
- return;
- }
-
- if (baseLayer.type === 'folder') {
- const folderTarget = this.ensureFolderPingPong(gl, depth, viewportW, viewportH);
- if (!folderTarget) return;
-
- folderTarget.activeIndex = 0;
- const folderSurf = folderTarget.surfaces[0];
- gl.bindFramebuffer(gl.FRAMEBUFFER, folderSurf.fbo);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.disable(gl.STENCIL_TEST);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
-
- this.renderNodeList(
- gl,
- baseNode.children,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- folderTarget,
- depth + 1,
- 1.0
- );
-
- // Restore parent target framebuffer and blit isolated folder result
- const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
- gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
- gl.viewport(0, 0, viewportW, viewportH);
-
- this.blitFolderTexture(
- gl,
- folderTarget.surfaces[folderTarget.activeIndex].texture,
- baseLayer.blendMode,
- baseLayer.opacity * unit.inheritedOpacity,
- viewportW,
- viewportH,
- target,
- false
- );
- return;
- }
-
- const activeClippedLayers = group.clippedNodes
- .map((n) => n.layer)
- .filter((cl) => cl.visible && cl.opacity > 0.001 && !isFolderLikeLayer(cl));
-
- const baseEffectiveOpacity = unit.inheritedOpacity;
-
- if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
- this.renderAdjustmentLayer(
- gl,
- baseLayer,
- transform,
- dimensions,
- viewportW,
- viewportH,
- dpr,
- baseEffectiveOpacity,
- target,
- false
- );
- return;
- }
-
- const baseHasStyles = hasActiveLayerStyles(baseLayer.styles);
-
- if (activeClippedLayers.length > 0) {
- // Record base layer silhouette in stencil buffer of the current Ping-Pong surface
- gl.enable(gl.STENCIL_TEST);
- gl.clear(gl.STENCIL_BUFFER_BIT);
- gl.stencilMask(0xFF);
- gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
-
- if (baseHasStyles) {
- // Record base layer silhouette in stencil without writing colors
- gl.colorMask(false, false, false, false);
- this.renderSingleLayer(
- gl,
- { ...baseLayer, blendMode: 'normal' },
- dimensions,
- grid,
- frustum,
- baseEffectiveOpacity,
- target,
- true
- );
- gl.colorMask(true, true, true, true);
-
- // Draw base layer with styles (do not overwrite stencil with shadow/glow)
- gl.stencilMask(0x00);
- this.renderLayerWithStyles(
- gl,
- baseLayer,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- baseEffectiveOpacity,
- target,
- true
- );
- gl.stencilMask(0xFF);
- } else {
- this.renderSingleLayer(
- gl,
- baseLayer,
- dimensions,
- grid,
- frustum,
- baseEffectiveOpacity,
- target,
- true
- );
- }
-
- // Render clipped layers: only draw over opaque pixels of base layer (stencil == 1)
- gl.stencilMask(0x00);
- gl.stencilFunc(gl.EQUAL, 1, 0xFF);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
-
- for (const clippedLayer of activeClippedLayers) {
- if (hasActiveLayerStyles(clippedLayer.styles)) {
- this.renderLayerWithStyles(
- gl,
- clippedLayer,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- baseEffectiveOpacity,
- target,
- true
- );
- } else {
- this.renderSingleLayer(
- gl,
- clippedLayer,
- dimensions,
- grid,
- frustum,
- baseEffectiveOpacity,
- target,
- true
- );
- }
- }
-
- gl.stencilMask(0xFF);
- gl.disable(gl.STENCIL_TEST);
- } else {
- gl.disable(gl.STENCIL_TEST);
- if (baseHasStyles) {
- this.renderLayerWithStyles(
- gl,
- baseLayer,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- baseEffectiveOpacity,
- target,
- false
- );
- } else {
- this.renderSingleLayer(
- gl,
- baseLayer,
- dimensions,
- grid,
- frustum,
- baseEffectiveOpacity,
- target,
- false
- );
- }
- }
- }
-
- /**
- * Recursively composite a layer hierarchy, supporting folder pass-through and isolated offscreen rendering.
- */
- private renderNodeList(
- gl: WebGL2RenderingContext,
- nodes: LayerTreeNode[],
- dimensions: CanvasDimensions,
- grid: SparseTileGrid,
- frustum: { minX: number; minY: number; maxX: number; maxY: number },
- viewportW: number,
- viewportH: number,
- transform: ViewportTransform,
- dpr: number,
- target: PingPongTarget | null,
- depth: number,
- inheritedOpacity: number
- ): void {
- const units = flattenLayerTreeToUnits(nodes, inheritedOpacity);
- for (const unit of units) {
- this.renderCompositingUnit(
- gl,
- unit,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- target,
- depth,
- false
- );
- }
- }
-
- /**
- * Get or upload a WebGLTexture for a layer's mask canvas with dirty-version caching.
- */
- private getMaskTexture(layer: LayerItem): WebGLTexture | null {
- if (!this.gl || !layer.maskCanvas) return null;
- const gl = this.gl;
- let cached = this.maskTextureCache.get(layer.id);
- const currentVersion = layer.maskVersion ?? 0;
- const maskW = layer.maskCanvas.width;
- const maskH = layer.maskCanvas.height;
-
- if (!cached) {
- const tex = gl.createTexture();
- if (!tex) return null;
- cached = { texture: tex, version: -1, width: 0, height: 0 };
- this.maskTextureCache.set(layer.id, cached);
- }
-
- if (cached.version !== currentVersion || cached.width !== maskW || cached.height !== maskH) {
- gl.bindTexture(gl.TEXTURE_2D, cached.texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
-
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
- gl.texImage2D(
- gl.TEXTURE_2D,
- 0,
- gl.RGBA,
- gl.RGBA,
- gl.UNSIGNED_BYTE,
- layer.maskCanvas
- );
-
- cached.version = currentVersion;
- cached.width = maskW;
- cached.height = maskH;
- }
-
- return cached.texture;
- }
-
- /**
- * Evaluates non-destructive adjustment layers via Ping-Pong FBO backdrop and version-cached LUT evaluation.
- */
- private renderAdjustmentLayer(
- gl: WebGL2RenderingContext,
- layer: LayerItem,
- transform: ViewportTransform,
- dimensions: CanvasDimensions,
- viewportW: number,
- viewportH: number,
- dpr: number,
- opacityMultiplier: number = 1.0,
- target: PingPongTarget | null = null,
- preserveStencil: boolean = false
- ): void {
- if (!this.adjProgram || !layer.adjustmentData || !target) return;
-
- // 1. Ping-Pong swap to sample accumulated backdrop texture without copyTexSubImage2D
- const backdropTex = this.prepareBackdropFromPingPong(gl, target, viewportW, viewportH, preserveStencil);
-
- // 2. Prepare 256x1 LUT (Cached by AdjustmentLayerData signature)
- if (!this.lutTexture) {
- this.lutTexture = gl.createTexture();
- this.lastLutKey = '';
- }
- const adj = layer.adjustmentData;
- const lutKey = JSON.stringify(adj);
-
- if (lutKey !== this.lastLutKey) {
- let lutData: Uint8Array;
- let adjMode = 0; // 0 = per-channel, 1 = gradient map
-
- if (adj.type === 'curves') {
- const { rLut, gLut, bLut } = buildCurvesCombinedLut(adj.curves);
- lutData = new Uint8Array(256 * 4);
- for (let i = 0; i < 256; i++) {
- const off = i * 4;
- lutData[off] = rLut[i];
- lutData[off + 1] = gLut[i];
- lutData[off + 2] = bLut[i];
- lutData[off + 3] = 255;
- }
- } else if (adj.type === 'gradient-map') {
- adjMode = 1;
- const gMap = buildGradientMapLut(adj.stops, adj.interpolation || 'linear');
- lutData = new Uint8Array(gMap.buffer, gMap.byteOffset, gMap.byteLength);
- } else if (adj.type === 'levels') {
- const lLut = buildLevelsLut(adj.blackPoint, adj.whitePoint, adj.gamma, adj.outputMin ?? 0, adj.outputMax ?? 255);
- const ch = adj.channel || 'rgb';
- lutData = new Uint8Array(256 * 4);
- for (let i = 0; i < 256; i++) {
- const off = i * 4;
- lutData[off] = ch === 'rgb' || ch === 'r' ? lLut[i] : i;
- lutData[off + 1] = ch === 'rgb' || ch === 'g' ? lLut[i] : i;
- lutData[off + 2] = ch === 'rgb' || ch === 'b' ? lLut[i] : i;
- lutData[off + 3] = 255;
- }
- } else {
- lutData = new Uint8Array(256 * 4);
- for (let i = 0; i < 256; i++) {
- const [r, g, b] = evaluateColorBalancePixel(i, i, i, adj);
- const off = i * 4;
- lutData[off] = r;
- lutData[off + 1] = g;
- lutData[off + 2] = b;
- lutData[off + 3] = 255;
- }
- }
-
- gl.activeTexture(gl.TEXTURE3);
- gl.bindTexture(gl.TEXTURE_2D, this.lutTexture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, lutData);
-
- this.lastLutKey = lutKey;
- this.lastLutAdjMode = adjMode;
- }
-
- // 3. Switch to Adjustment Program
- gl.useProgram(this.adjProgram);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- if (this.aQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aQuadPosLoc);
- gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
-
- gl.uniform2f(this.uAdjViewportSizeLoc, viewportW, viewportH);
- gl.uniform2f(this.uAdjDocDimensionsLoc, dimensions.width, dimensions.height);
- gl.uniform2f(this.uAdjPanLoc, transform.pan.x, transform.pan.y);
- gl.uniform1f(this.uAdjZoomLoc, transform.zoom);
- const rotRad = (transform.rotation * Math.PI) / 180;
- gl.uniform1f(this.uAdjRotationRadLoc, rotRad);
- gl.uniform2f(this.uAdjFlipLoc, transform.flipX ? -1.0 : 1.0, transform.flipY ? -1.0 : 1.0);
- gl.uniform1f(this.uAdjDprLoc, dpr);
-
- gl.uniform2f(this.uAdjTileOriginLoc, 0, 0);
- gl.uniform2f(this.uAdjTileSizeLoc, dimensions.width, dimensions.height);
-
- gl.activeTexture(gl.TEXTURE2);
- gl.bindTexture(gl.TEXTURE_2D, backdropTex);
- gl.uniform1i(this.uAdjSnapshotLoc, 2);
-
- gl.activeTexture(gl.TEXTURE3);
- gl.bindTexture(gl.TEXTURE_2D, this.lutTexture);
- gl.uniform1i(this.uAdjLutLoc, 3);
-
- gl.uniform1i(this.uAdjModeLoc, this.lastLutAdjMode);
- gl.uniform1f(this.uAdjOpacityLoc, layer.opacity * opacityMultiplier);
-
- const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
- gl.uniform1i(this.uAdjMaskEnabledLoc, hasMask ? 1 : 0);
- if (hasMask && layer.maskCanvas) {
- const maskTex = this.getMaskTexture(layer);
- if (maskTex) {
- gl.activeTexture(gl.TEXTURE1);
- gl.bindTexture(gl.TEXTURE_2D, maskTex);
- gl.uniform1i(this.uAdjMaskTextureLoc, 1);
- }
- }
-
- // Overwrite document region with filtered result
- gl.blendFunc(gl.ONE, gl.ZERO);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
-
- // Revert program, unbind backdrop texture to avoid feedback loops, and restore blend func
- this.unbindSceneTextureUnits(gl);
- gl.enable(gl.BLEND);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- this.restoreStandardProgram(gl);
- }
-
- /**
- * Renders all visible tiles of a single layer onto WebGL2 context using:
- * - TEXTURE_2D_ARRAY + gl.drawArraysInstanced batching when all visible tiles fit in the pool
- * - Safe per-tile TEXTURE_2D fallback on pool overflow
- * - Ping-Pong FBO backdrop sampling for custom blend modes (zero gl.copyTexSubImage2D)
- * - In-stack WYSIWYG live draft stroke compositing
- */
- private renderSingleLayer(
- gl: WebGL2RenderingContext,
- layer: LayerItem,
- dimensions: CanvasDimensions,
- grid: SparseTileGrid,
- frustum: { minX: number; minY: number; maxX: number; maxY: number },
- opacityMultiplier: number = 1.0,
- target: PingPongTarget | null = null,
- preserveStencil: boolean = false
- ): void {
- if (!this.stdLocs) return;
-
- // Adaptive LOD Selection & Frustum Culling
- const targetLod =
- this.currentZoom <= 0.125 ? 3 :
- this.currentZoom <= 0.25 ? 2 :
- this.currentZoom <= 0.5 ? 1 : 0;
-
- const lodScale = 1 << targetLod;
- const lodTileDocSize = TILE_SIZE * lodScale;
-
- const startTileX = Math.floor(frustum.minX / lodTileDocSize);
- const endTileX = Math.floor(frustum.maxX / lodTileDocSize);
- const startTileY = Math.floor(frustum.minY / lodTileDocSize);
- const endTileY = Math.floor(frustum.maxY / lodTileDocSize);
-
- const visibleTiles: TileBuffer[] = [];
- const hasLayerTiles =
- typeof grid.hasLayerTiles === 'function' ? grid.hasLayerTiles(layer.id) : true;
- const hasOccCheck = typeof grid.hasPopulatedLodTile === 'function';
-
- if (hasLayerTiles) {
- for (let ty = startTileY; ty <= endTileY; ty++) {
- for (let tx = startTileX; tx <= endTileX; tx++) {
- if (targetLod > 0 && hasOccCheck && !grid.hasPopulatedLodTile(layer.id, tx, ty, targetLod)) {
- continue;
- }
- let tile = grid.getTile(layer.id, tx, ty, targetLod);
- if (targetLod > 0 && (!tile || tile.data === null || grid.isLodTileDirty(layer.id, tx, ty, targetLod))) {
- tile = grid.generateLodTile(layer.id, tx, ty, targetLod);
- }
- if (tile) {
- visibleTiles.push(tile);
- }
- }
- }
- }
-
- const opts = this.currentOptions;
- const draftCanvas = opts?.activeDraftLayerId === layer.id ? opts.activeDraftCanvas : null;
- const hasDraft = Boolean(
- draftCanvas &&
- draftCanvas.width > 0 &&
- draftCanvas.height > 0 &&
- (draftCanvas as any).__draftHasContent !== false
- );
- const draftOp = hasDraft && draftCanvas
- ? ((draftCanvas as any).__draftCompositeOp as GlobalCompositeOperation | undefined)
- : undefined;
- const needsIsolatedDraftFbo =
- hasDraft &&
- draftCanvas !== null &&
- (draftOp === 'destination-out' || draftOp === 'source-atop');
-
- if (visibleTiles.length === 0 && !hasDraft) {
- return;
- }
-
- const fs = this.currentFrameState;
- const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
- const maskTex = hasMask && layer.maskCanvas ? this.getMaskTexture(layer) : null;
- const effectiveOpacity = layer.opacity * opacityMultiplier;
-
- // Isolated GPU FBO path for WYSIWYG live Eraser (destination-out) and Alpha Lock (source-atop)
- // Erases/paints strictly against this layer's tiles without affecting underlying layers and with zero getImageData!
- if (
- needsIsolatedDraftFbo &&
- draftCanvas &&
- target &&
- fs &&
- fs.viewportW > 0 &&
- fs.viewportH > 0 &&
- this.ensureLayerFbo(fs.viewportW, fs.viewportH) &&
- this.layerFbo &&
- this.layerTexture &&
- this.blitProgram
- ) {
- const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
- if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
-
- gl.bindFramebuffer(gl.FRAMEBUFFER, this.layerFbo);
- gl.viewport(0, 0, fs.viewportW, fs.viewportH);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
-
- if (visibleTiles.length > 0) {
- this.drawVisibleTiles(
- gl,
- visibleTiles,
- grid,
- layer,
- dimensions,
- lodTileDocSize,
- 1.0,
- 0,
- null,
- maskTex
- );
- }
-
- if (draftOp === 'destination-out') {
- gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA);
- } else {
- gl.blendFunc(gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
- }
-
- this.renderActiveDraftForLayer(
- gl,
- draftCanvas,
- layer,
- dimensions,
- opts?.activeDraftOpacity ?? 1.0,
- 0,
- null,
- draftOp === 'destination-out' ? null : maskTex,
- opts?.activeDraftVersion,
- opts?.activeDraftSpace ?? 'document',
- draftOp === 'destination-out'
- );
-
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- gl.bindFramebuffer(gl.FRAMEBUFFER, target.surfaces[target.activeIndex].fbo);
- gl.viewport(0, 0, fs.viewportW, fs.viewportH);
- if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
-
- this.blitFolderTexture(
- gl,
- this.layerTexture,
- layer.blendMode,
- effectiveOpacity,
- fs.viewportW,
- fs.viewportH,
- target,
- preserveStencil
- );
-
- if (this.stdLocs) {
- if (maskTex) {
- gl.uniform1i(this.stdLocs.uMaskEnabled, 0);
- }
- gl.uniform1i(this.stdLocs.uHasBackdrop, 0);
- }
- this.unbindSceneTextureUnits(gl);
- return;
- }
-
- // Prepare Ping-Pong backdrop if custom blend mode is active (zero copyTexSubImage2D)
- const modeCode = BLEND_MODE_MAP[layer.blendMode] ?? 0;
- let backdropTex: WebGLTexture | null = null;
- if (modeCode !== 0 && modeCode !== 12 && target && fs && fs.viewportW > 0 && fs.viewportH > 0) {
- backdropTex = this.prepareBackdropFromPingPong(
- gl,
- target,
- fs.viewportW,
- fs.viewportH,
- preserveStencil
- );
- }
-
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
-
- if (visibleTiles.length > 0) {
- this.drawVisibleTiles(
- gl,
- visibleTiles,
- grid,
- layer,
- dimensions,
- lodTileDocSize,
- effectiveOpacity,
- modeCode,
- backdropTex,
- maskTex
- );
- }
-
- // WYSIWYG In-Stack Live Stroke Compositing
- if (hasDraft && draftCanvas) {
- if (draftOp === 'destination-out') {
- gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA);
- } else if (draftOp === 'source-atop') {
- gl.blendFunc(gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
- }
- this.renderActiveDraftForLayer(
- gl,
- draftCanvas,
- layer,
- dimensions,
- effectiveOpacity * (opts?.activeDraftOpacity ?? 1.0),
- modeCode,
- backdropTex,
- draftOp === 'destination-out' ? null : maskTex,
- opts?.activeDraftVersion,
- opts?.activeDraftSpace ?? 'document',
- draftOp === 'destination-out'
- );
- if (draftOp === 'destination-out' || draftOp === 'source-atop') {
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- }
- }
-
- if (this.stdLocs) {
- if (maskTex) {
- gl.uniform1i(this.stdLocs.uMaskEnabled, 0);
- }
- gl.uniform1i(this.stdLocs.uHasBackdrop, 0);
- }
- this.unbindSceneTextureUnits(gl);
- }
-
- /**
- * Unified tile draw path used by both normal layers and isolated live Eraser/Alpha-Lock FBOs.
- * Batches via TEXTURE_2D_ARRAY + drawArraysInstanced and orphans instanceBuffer via STREAM_DRAW
- * to prevent ANGLE/D3D11 instance attribute read-after-write hazards across consecutive draws.
- */
- private drawVisibleTiles(
- gl: WebGL2RenderingContext,
- visibleTiles: TileBuffer[],
- grid: SparseTileGrid,
- layer: LayerItem,
- dimensions: CanvasDimensions,
- lodTileDocSize: number,
- effectiveOpacity: number,
- modeCode: number,
- backdropTex: WebGLTexture | null,
- maskTex: WebGLTexture | null
- ): void {
- const canBatch =
- visibleTiles.length > 0 &&
- this.instancedProgram !== null &&
- this.instancedLocs !== null &&
- this.tileArrayTexture !== null &&
- this.instanceBuffer !== null &&
- visibleTiles.length <= this.arrayPoolCapacity;
-
- if (canBatch && this.instancedProgram && this.instancedLocs && this.tileArrayTexture && this.instanceBuffer) {
- const batchTick = ++this.arrayBatchCounter;
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.tileArrayTexture);
-
- const desiredTier = this.currentZoom < 0.99 ? 0 : this.currentZoom < 2.0 ? 1 : 2;
- if (this.arrayPoolFilterTier !== desiredTier) {
- const filter = desiredTier <= 1 ? gl.LINEAR : gl.NEAREST;
- gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, filter);
- gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, filter);
- this.arrayPoolFilterTier = desiredTier;
- }
-
- let instanceCount = 0;
- let overflowed = false;
- for (let i = 0; i < visibleTiles.length; i++) {
- const tile = visibleTiles[i];
- const sliceIdx = this.getOrUploadArrayTileSlice(gl, tile, grid, batchTick);
- if (sliceIdx < 0) {
- overflowed = true;
- break;
- }
- const off = instanceCount * 3;
- this.instanceFloatScratch[off] = tile.tileX * lodTileDocSize;
- this.instanceFloatScratch[off + 1] = tile.tileY * lodTileDocSize;
- this.instanceFloatScratch[off + 2] = sliceIdx;
- instanceCount++;
- }
-
- if (!overflowed && instanceCount > 0) {
- gl.useProgram(this.instancedProgram);
- this.syncFrameUniforms(gl, this.instancedLocs);
- gl.uniform2f(this.uInstTileSizeLoc, lodTileDocSize, lodTileDocSize);
- gl.uniform1i(this.uInstTileArrayLoc, 0);
- this.applyLayerUniforms(
- gl,
- this.instancedLocs,
- layer,
- dimensions,
- effectiveOpacity,
- modeCode,
- backdropTex,
- maskTex
- );
-
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.tileArrayTexture);
-
- if (this.instancedVao) {
- gl.bindVertexArray(this.instancedVao);
- } else {
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- if (this.aInstQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aInstQuadPosLoc);
- gl.vertexAttribPointer(this.aInstQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- gl.vertexAttribDivisor(this.aInstQuadPosLoc, 0);
- }
- gl.bindBuffer(gl.ARRAY_BUFFER, this.instanceBuffer);
- if (this.aInstDataLoc >= 0) {
- gl.enableVertexAttribArray(this.aInstDataLoc);
- gl.vertexAttribPointer(this.aInstDataLoc, 3, gl.FLOAT, false, 0, 0);
- gl.vertexAttribDivisor(this.aInstDataLoc, 1);
- }
- }
-
- gl.bindBuffer(gl.ARRAY_BUFFER, this.instanceBuffer);
- gl.bufferData(
- gl.ARRAY_BUFFER,
- this.instanceFloatScratch.subarray(0, instanceCount * 3),
- gl.STREAM_DRAW
- );
- gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, instanceCount);
-
- if (this.instancedVao) {
- gl.bindVertexArray(null);
- } else if (this.aInstDataLoc >= 0) {
- gl.vertexAttribDivisor(this.aInstDataLoc, 0);
- gl.disableVertexAttribArray(this.aInstDataLoc);
- }
- this.restoreStandardProgram(gl);
- return;
- }
- }
-
- this.drawTilesFallback2D(
- gl,
- visibleTiles,
- grid,
- layer,
- dimensions,
- lodTileDocSize,
- effectiveOpacity,
- modeCode,
- backdropTex,
- maskTex
- );
- }
-
- /**
- * Fallback per-tile TEXTURE_2D draw loop when visible tile count exceeds TEXTURE_2D_ARRAY pool capacity.
- */
- private drawTilesFallback2D(
- gl: WebGL2RenderingContext,
- visibleTiles: TileBuffer[],
- grid: SparseTileGrid,
- layer: LayerItem,
- dimensions: CanvasDimensions,
- lodTileDocSize: number,
- effectiveOpacity: number,
- modeCode: number,
- backdropTex: WebGLTexture | null,
- maskTex: WebGLTexture | null
- ): void {
- if (!this.stdLocs) return;
- this.restoreStandardProgram(gl);
- this.syncFrameUniforms(gl, this.stdLocs);
- gl.uniform1i(this.uTileTextureLoc, 0);
- gl.uniform1i(this.uIsBackgroundLoc, 0);
- this.applyLayerUniforms(
- gl,
- this.stdLocs,
- layer,
- dimensions,
- effectiveOpacity,
- modeCode,
- backdropTex,
- maskTex
- );
- gl.uniform2f(this.uTileSizeLoc, lodTileDocSize, lodTileDocSize);
-
- for (const tile of visibleTiles) {
- const tex = this.getTileTexture(tile, grid);
- if (!tex) continue;
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, tex);
- gl.uniform2f(this.uTileOriginLoc, tile.tileX * lodTileDocSize, tile.tileY * lodTileDocSize);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- }
- }
-
- /**
- * Uploads and renders the active draft canvas in-stack for the active layer.
- * Supports both viewport-space overlays (from CanvasArea) and document-space draft canvases.
- */
- private renderActiveDraftForLayer(
- gl: WebGL2RenderingContext,
- draftCanvas: HTMLCanvasElement,
- layer: LayerItem,
- dimensions: CanvasDimensions,
- effectiveOpacity: number,
- modeCode: number,
- backdropTex: WebGLTexture | null,
- maskTex: WebGLTexture | null,
- draftVersion?: number,
- draftSpace: 'document' | 'viewport' = 'document',
- isDestinationOutMask: boolean = false
- ): void {
- if (draftCanvas.width <= 0 || draftCanvas.height <= 0) return;
- if ((draftCanvas as any).__draftHasContent === false) return;
- if (!this.draftTexture) {
- this.draftTexture = gl.createTexture();
- }
- if (!this.draftTexture) return;
-
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, this.draftTexture);
-
- const ver = draftVersion ?? -1;
- const hasGenerateMipmap = typeof gl.generateMipmap === 'function';
- const needsMipmap = hasGenerateMipmap && draftSpace === 'document' && this.currentZoom < 0.99;
- const sizeChanged =
- this.draftTexWidth !== draftCanvas.width || this.draftTexHeight !== draftCanvas.height;
-
- if (ver === -1 || ver !== this.lastDraftVersion || sizeChanged) {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(
- gl.TEXTURE_2D,
- gl.TEXTURE_MIN_FILTER,
- needsMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
- );
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
- if (!sizeChanged && this.draftTexWidth > 0 && typeof gl.texSubImage2D === 'function') {
- gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
- } else {
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
- }
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
- if (needsMipmap) {
- gl.generateMipmap(gl.TEXTURE_2D);
- this.draftHasMipmap = true;
- } else {
- this.draftHasMipmap = false;
- }
- this.draftTexWidth = draftCanvas.width;
- this.draftTexHeight = draftCanvas.height;
- this.lastDraftVersion = ver;
- } else {
- if (needsMipmap && !this.draftHasMipmap) {
- gl.generateMipmap(gl.TEXTURE_2D);
- this.draftHasMipmap = true;
- }
- gl.texParameteri(
- gl.TEXTURE_2D,
- gl.TEXTURE_MIN_FILTER,
- needsMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
- );
- }
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.currentZoom >= 2.0 ? gl.NEAREST : gl.LINEAR);
+ CompositorOptions,
+ CompositorState,
+ DEFAULT_ARRAY_POOL_LAYERS,
+ ViewportTransform,
+} from './compositor/types';
+
+export {
+ BLEND_MODE_MAP,
+ type ViewportTransform,
+ type OnionSkinCompositorFrame,
+ type CompositorOptions,
+} from './compositor/types';
+
+export {
+ type LayerTreeNode,
+ buildLayerTree,
+ type TreeNodeRenderGroup,
+ groupTreeNodesForCompositing,
+ type LayerRenderGroup,
+ groupLayersForCompositing,
+ type CompositingUnit,
+ type AboveSliceStrategy,
+ type LayerStackPartition,
+ flattenLayerTreeToUnits,
+ isUnitNormalAssociative,
+ canSingleUnitBakeWithBlendMode,
+ partitionLayerStack,
+} from './compositor/layerTree';
+
+export {
+ FRAME_POLY_VERTEX_SHADER,
+ FRAME_POLY_FRAGMENT_SHADER,
+ FOLDER_BLIT_VERTEX_SHADER,
+ FOLDER_BLIT_FRAGMENT_SHADER,
+ COMPOSITOR_VERTEX_SHADER,
+ COMPOSITOR_FRAGMENT_SHADER,
+ VIEWPORT_DRAFT_VERTEX_SHADER,
+} from './compositor/shaders/coreShaders';
+
+export {
+ COMPOSITOR_INSTANCED_VERTEX_SHADER,
+ COMPOSITOR_INSTANCED_FRAGMENT_SHADER,
+} from './compositor/shaders/instancedShaders';
+
+export {
+ ADJUSTMENT_FRAGMENT_SHADER,
+ hasActiveLayerStyles,
+ LAYER_STYLES_VERTEX_SHADER,
+ LAYER_STYLES_FRAGMENT_SHADER,
+} from './compositor/shaders/effectShaders';
+
+export {
+ SOFT_PROOF_VERTEX_SHADER,
+ SOFT_PROOF_FRAGMENT_SHADER,
+} from './compositor/shaders/softProofShaders';
+
+export {
+ type LayerStackCacheInput,
+ type LayerStackCacheEvaluation,
+ LayerStackCacheTracker,
+} from './compositor/stackCache';
+
+export { calculateVisibleDocumentBounds } from './compositor/bounds';
+
+function createInitialCompositorState(
+ canvas: HTMLCanvasElement,
+ preserveDrawingBuffer: boolean
+): CompositorState {
+ return {
+ canvas,
+ gl: null,
+ program: null,
+ quadBuffer: null,
+ uTileOriginLoc: null,
+ uTileSizeLoc: null,
+ uIsBackgroundLoc: null,
+ uShowCheckerboardLoc: null,
+ uTileTextureLoc: null,
+ stdLocs: null,
+ instancedProgram: null,
+ instancedLocs: null,
+ uInstTileSizeLoc: null,
+ uInstTileArrayLoc: null,
+ aInstQuadPosLoc: -1,
+ aInstDataLoc: -1,
+ instancedVao: null,
+ instanceBuffer: null,
+ instanceFloatScratch: new Float32Array(DEFAULT_ARRAY_POOL_LAYERS * 3),
+ tileArrayTexture: null,
+ arrayPoolCapacity: 0,
+ arrayPoolFilterTier: -1,
+ arrayPoolSlots: [],
+ freeArraySlots: [],
+ arrayPoolByKey: new Map(),
+ arrayAccessCounter: 0,
+ arrayBatchCounter: 0,
+ uploadPremulScratch: new Uint8Array(TILE_SIZE * TILE_SIZE * 4),
+ preserveDrawingBuffer,
+ viewportDraftProgram: null,
+ viewportDraftLocs: null,
+ uViewportDraftTileTexLoc: null,
+ uViewportDraftIsBgLoc: null,
+ aViewportDraftQuadPosLoc: -1,
+ aQuadPosLoc: -1,
+ aStylesQuadPosLoc: -1,
+ aBlitQuadPosLoc: -1,
+ aProofQuadPosLoc: -1,
+ contextLost: false,
+ onContextLostHandler: null,
+ onContextRestoredHandler: null,
+ maskTextureCache: new Map(),
+ maskInvalidationEpochs: new Map(),
+ globalMaskEpochCounter: 0,
+ draftTexture: null,
+ draftTexWidth: 0,
+ draftTexHeight: 0,
+ draftHasMipmap: false,
+ lastDraftVersion: -1,
+ currentOptions: null,
+ currentZoom: 1.0,
+ currentFrameState: null,
+ adjProgram: null,
+ uAdjTileOriginLoc: null,
+ uAdjTileSizeLoc: null,
+ uAdjDocDimensionsLoc: null,
+ uAdjViewportSizeLoc: null,
+ uAdjPanLoc: null,
+ uAdjZoomLoc: null,
+ uAdjRotationRadLoc: null,
+ uAdjFlipLoc: null,
+ uAdjDprLoc: null,
+ uAdjSnapshotLoc: null,
+ uAdjLutLoc: null,
+ uAdjModeLoc: null,
+ uAdjOpacityLoc: null,
+ uAdjMaskEnabledLoc: null,
+ uAdjMaskTextureLoc: null,
+ lutTexture: null,
+ lastLutKey: '',
+ lastLutAdjMode: 0,
+ stylesProgram: null,
+ stylesQuadBuffer: null,
+ layerFbo: null,
+ layerTexture: null,
+ layerFboWidth: 0,
+ layerFboHeight: 0,
+ layerStylesOutFbo: null,
+ uStylesLayerTextureLoc: null,
+ uStylesViewportSizeLoc: null,
+ uStylesLayerOpacityLoc: null,
+ uStylesStrokeEnabledLoc: null,
+ uStylesStrokeSizeLoc: null,
+ uStylesStrokeColorLoc: null,
+ uStylesStrokePositionLoc: null,
+ uStylesGlowEnabledLoc: null,
+ uStylesGlowColorLoc: null,
+ uStylesGlowBlurLoc: null,
+ uStylesGlowSpreadLoc: null,
+ uStylesShadowEnabledLoc: null,
+ uStylesShadowColorLoc: null,
+ uStylesShadowOffsetLoc: null,
+ uStylesShadowBlurLoc: null,
+ uStylesShadowSpreadLoc: null,
+ blitProgram: null,
+ uBlitTextureLoc: null,
+ uBlitBackdropTextureLoc: null,
+ uBlitHasBackdropLoc: null,
+ uBlitBlendModeLoc: null,
+ uBlitOpacityLoc: null,
+ framePolyProgram: null,
+ framePolyBuffer: null,
+ aFramePolyDocPosLoc: -1,
+ uFramePolyDocDimensionsLoc: null,
+ uFramePolyViewportSizeLoc: null,
+ uFramePolyPanLoc: null,
+ uFramePolyZoomLoc: null,
+ uFramePolyRotationRadLoc: null,
+ uFramePolyFlipLoc: null,
+ uFramePolyDprLoc: null,
+ uFramePolyColorLoc: null,
+ scenePingPong: null,
+ folderPingPongs: [],
+ belowActiveCacheFbo: null,
+ aboveActiveCacheFbo: null,
+ stackCache: new LayerStackCacheTracker(),
+ stackCacheStats: { belowRebuilds: 0, aboveRebuilds: 0, cacheHits: 0 },
+ softProofProgram: null,
+ uProofSceneTextureLoc: null,
+ uProofStandardLoc: null,
+ uProofEnabledLoc: null,
+ uProofGamutWarningLoc: null,
+ uProofGamutWarningColorLoc: null,
+ textureAccessCounter: 0,
+ texturePool: [],
+ activePoolByKey: new Map(),
+ fallbackTileCanvas: null,
+ lastRenderedGrid: null,
+ };
+}
- let effectiveDraftLayer: LayerItem =
- this.currentOptions?.activeDraftMonochrome && layer.expressionColor !== 'monochrome'
- ? { ...layer, expressionColor: 'monochrome' }
- : layer;
+/**
+ * High-performance WebGL2 Viewport Compositor
+ */
+export class ViewportCompositor {
+ private state: CompositorState;
- if (isDestinationOutMask) {
- // Destination-out draft is a pure alpha eraser mask; never modulate it by screentone, tint, or mono ink-channel exclusions
- effectiveDraftLayer = {
- ...effectiveDraftLayer,
- toneEnabled: false,
- layerColorEnabled: false,
- monoExpressBlack: true,
- monoExpressWhite: true,
+ constructor(canvas: HTMLCanvasElement, options?: { preserveDrawingBuffer?: boolean }) {
+ this.state = createInitialCompositorState(canvas, Boolean(options?.preserveDrawingBuffer));
+ if (typeof canvas.addEventListener === 'function') {
+ this.state.onContextLostHandler = (e: Event) => {
+ e.preventDefault();
+ resetGLStateOnContextLost(this.state);
};
+ this.state.onContextRestoredHandler = () => {
+ this.state.contextLost = false;
+ initGL(this.state);
+ (this.state.lastRenderedGrid || globalTileGrid).notifyChange(true);
+ };
+ canvas.addEventListener('webglcontextlost', this.state.onContextLostHandler, false);
+ canvas.addEventListener('webglcontextrestored', this.state.onContextRestoredHandler, false);
}
-
- if (draftSpace === 'viewport' && this.viewportDraftProgram && this.viewportDraftLocs) {
- gl.useProgram(this.viewportDraftProgram);
- this.syncFrameUniforms(gl, this.viewportDraftLocs);
- gl.uniform1i(this.uViewportDraftTileTexLoc, 0);
- gl.uniform1i(this.uViewportDraftIsBgLoc, 0);
- this.applyLayerUniforms(
- gl,
- this.viewportDraftLocs,
- effectiveDraftLayer,
- dimensions,
- effectiveOpacity,
- modeCode,
- backdropTex,
- maskTex
- );
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- if (this.aViewportDraftQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aViewportDraftQuadPosLoc);
- gl.vertexAttribPointer(this.aViewportDraftQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, this.draftTexture);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- this.restoreStandardProgram(gl);
- } else if (this.stdLocs) {
- const docRect = this.currentOptions?.activeDraftDirtyRect;
- const originX = docRect ? docRect.x : 0;
- const originY = docRect ? docRect.y : 0;
- const spanW = docRect ? docRect.width : dimensions.width;
- const spanH = docRect ? docRect.height : dimensions.height;
-
- this.restoreStandardProgram(gl);
- this.syncFrameUniforms(gl, this.stdLocs);
- gl.uniform1i(this.uTileTextureLoc, 0);
- gl.uniform1i(this.uIsBackgroundLoc, 0);
- this.applyLayerUniforms(
- gl,
- this.stdLocs,
- effectiveDraftLayer,
- dimensions,
- effectiveOpacity,
- modeCode,
- backdropTex,
- maskTex
- );
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, this.draftTexture);
- gl.uniform2f(this.uTileOriginLoc, originX, originY);
- gl.uniform2f(this.uTileSizeLoc, spanW, spanH);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- gl.uniform2f(this.uTileSizeLoc, TILE_SIZE, TILE_SIZE);
- }
+ initGL(this.state);
}
- /**
- * Ensures an offscreen framebuffer and texture exist for isolated layer style rendering.
- */
- private ensureLayerFbo(width: number, height: number): boolean {
- if (!this.gl) return false;
- const gl = this.gl;
-
- if (this.layerFbo && this.layerTexture && this.layerFboWidth === width && this.layerFboHeight === height) {
- return true;
- }
-
- const prevFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;
-
- if (!this.layerFbo) {
- this.layerFbo = gl.createFramebuffer();
- }
- if (!this.layerTexture) {
- this.layerTexture = gl.createTexture();
- }
-
- this.layerFboWidth = width;
- this.layerFboHeight = height;
-
- gl.bindTexture(gl.TEXTURE_2D, this.layerTexture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
-
- gl.bindFramebuffer(gl.FRAMEBUFFER, this.layerFbo);
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.layerTexture, 0);
-
- const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
- gl.bindFramebuffer(gl.FRAMEBUFFER, prevFbo);
-
- if (status !== gl.FRAMEBUFFER_COMPLETE) {
- console.error('Layer FBO incomplete:', status);
- return false;
- }
-
- return true;
+ public isReady(): boolean {
+ return !this.state.contextLost && this.state.gl !== null && this.state.program !== null;
}
- private drawFramePolygonTriangles(
- gl: WebGL2RenderingContext,
- vertices: Float32Array,
- r: number,
- g: number,
- b: number,
- a: number,
- dimensions: CanvasDimensions,
- viewportW: number,
- viewportH: number,
- transform: ViewportTransform,
- dpr: number
- ): void {
- if (!this.framePolyProgram || !this.framePolyBuffer || vertices.length < 6) return;
- gl.useProgram(this.framePolyProgram);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.framePolyBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW);
- if (this.aFramePolyDocPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aFramePolyDocPosLoc);
- gl.vertexAttribPointer(this.aFramePolyDocPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
- gl.uniform2f(this.uFramePolyDocDimensionsLoc, dimensions.width, dimensions.height);
- gl.uniform2f(this.uFramePolyViewportSizeLoc, viewportW, viewportH);
- gl.uniform2f(this.uFramePolyPanLoc, transform.pan.x, transform.pan.y);
- gl.uniform1f(this.uFramePolyZoomLoc, transform.zoom);
- gl.uniform1f(this.uFramePolyRotationRadLoc, (transform.rotation * Math.PI) / 180);
- gl.uniform2f(this.uFramePolyFlipLoc, transform.flipX ? -1.0 : 1.0, transform.flipY ? -1.0 : 1.0);
- gl.uniform1f(this.uFramePolyDprLoc, dpr);
- gl.uniform4f(this.uFramePolyColorLoc, r, g, b, a);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- gl.drawArrays(gl.TRIANGLES, 0, vertices.length / 2);
- this.restoreStandardProgram(gl);
+ public getCanvas(): HTMLCanvasElement {
+ return this.state.canvas;
}
- /**
- * Blits an isolated folder or baked cache texture onto the active Ping-Pong target
- * with full programmable blend mode support and zero gl.copyTexSubImage2D calls.
- */
- private blitFolderTexture(
- gl: WebGL2RenderingContext,
- texture: WebGLTexture,
- blendMode: BlendMode,
- opacity: number,
- viewportW: number,
- viewportH: number,
- target: PingPongTarget | null = null,
- preserveStencil: boolean = false
- ): void {
- if (!this.blitProgram) return;
-
- const modeCode = BLEND_MODE_MAP[blendMode] ?? 0;
- let hasBackdrop = 0;
- if (modeCode !== 0 && modeCode !== 12 && target && viewportW > 0 && viewportH > 0) {
- const backdropTex = this.prepareBackdropFromPingPong(
- gl,
- target,
- viewportW,
- viewportH,
- preserveStencil
- );
- gl.activeTexture(gl.TEXTURE2);
- gl.bindTexture(gl.TEXTURE_2D, backdropTex);
- hasBackdrop = 1;
- }
-
- gl.viewport(0, 0, viewportW, viewportH);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
-
- gl.useProgram(this.blitProgram);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer || this.quadBuffer);
- if (this.aBlitQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aBlitQuadPosLoc);
- gl.vertexAttribPointer(this.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
-
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(this.uBlitTextureLoc, 0);
- gl.uniform1i(this.uBlitBackdropTextureLoc, 2);
- gl.uniform1i(this.uBlitHasBackdropLoc, hasBackdrop);
- gl.uniform1i(this.uBlitBlendModeLoc, modeCode);
- gl.uniform1f(this.uBlitOpacityLoc, opacity);
-
- gl.drawArrays(gl.TRIANGLES, 0, 6);
+ public getMaxTextureSize(): number {
+ if (!this.state.gl) return 2048;
+ const maxTex = Number(this.state.gl.getParameter(this.state.gl.MAX_TEXTURE_SIZE)) || 2048;
+ const maxRb = Number(this.state.gl.getParameter(this.state.gl.MAX_RENDERBUFFER_SIZE)) || maxTex;
+ return Math.max(256, Math.min(maxTex, maxRb));
+ }
- this.unbindSceneTextureUnits(gl);
- this.restoreStandardProgram(gl);
+ public getStackCacheStats(): { belowRebuilds: number; aboveRebuilds: number; cacheHits: number } {
+ return { ...this.state.stackCacheStats };
}
/**
- * Post-processing pass: CMYK Soft Proofing and Gamut Warning.
- * Samples directly from the Ping-Pong scene FBO texture into the default framebuffer (zero copyTexSubImage2D).
+ * Explicitly invalidate baked layer stack caches.
*/
- private applySoftProofPass(
- gl: WebGL2RenderingContext,
- viewportW: number,
- viewportH: number,
- settings: SoftProofSettings,
- sceneTexture: WebGLTexture
- ): void {
- if (!this.softProofProgram) return;
-
- gl.useProgram(this.softProofProgram);
-
- const standardIndex = settings.standard === 'japan-color-2001' ? 0 : settings.standard === 'us-web-coated-swop' ? 1 : 2;
- gl.uniform1i(this.uProofStandardLoc, standardIndex);
- gl.uniform1i(this.uProofEnabledLoc, settings.enabled ? 1 : 0);
- gl.uniform1i(this.uProofGamutWarningLoc, settings.gamutWarning ? 1 : 0);
-
- const warnRgb = this.parseHexColor(settings.gamutWarningColor || '#7f7f7f');
- gl.uniform3f(this.uProofGamutWarningColorLoc, warnRgb[0], warnRgb[1], warnRgb[2]);
-
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, sceneTexture);
- gl.uniform1i(this.uProofSceneTextureLoc, 0);
-
- gl.disable(gl.STENCIL_TEST);
- gl.disable(gl.BLEND);
-
- const quadBuffer = this.stylesQuadBuffer || this.quadBuffer;
- if (quadBuffer) {
- gl.bindBuffer(gl.ARRAY_BUFFER, quadBuffer);
- if (this.aProofQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aProofQuadPosLoc);
- gl.vertexAttribPointer(this.aProofQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
-
- gl.viewport(0, 0, viewportW, viewportH);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- }
-
- this.unbindSceneTextureUnits(gl);
- gl.enable(gl.BLEND);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- this.restoreStandardProgram(gl);
+ public invalidateStackCache(): void {
+ this.state.stackCache.invalidateAll();
}
/**
- * Evaluates non-destructive GPU layer styles (Stroke, Drop Shadow, Outer Glow)
- * by rendering the layer into an isolated FBO and processing through LAYER_STYLES_FRAGMENT_SHADER.
+ * Explicitly invalidate a cached layer mask texture (or all masks if layerId omitted).
*/
- private renderLayerWithStyles(
- gl: WebGL2RenderingContext,
- layer: LayerItem,
- dimensions: CanvasDimensions,
- grid: SparseTileGrid,
- frustum: { minX: number; minY: number; maxX: number; maxY: number },
- viewportW: number,
- viewportH: number,
- transform: ViewportTransform,
- dpr: number,
- opacityMultiplier: number = 1.0,
- target: PingPongTarget | null = null,
- preserveStencil: boolean = false
- ): void {
- if (!this.ensureLayerFbo(viewportW, viewportH) || !this.stylesProgram) {
- this.renderSingleLayer(gl, layer, dimensions, grid, frustum, opacityMultiplier, target, preserveStencil);
- return;
- }
-
- const styles = layer.styles;
- if (!styles) {
- this.renderSingleLayer(gl, layer, dimensions, grid, frustum, opacityMultiplier, target, preserveStencil);
- return;
- }
-
- let maxStyleMargin = 0;
- if (styles.stroke?.enabled) {
- maxStyleMargin = Math.max(maxStyleMargin, styles.stroke.size || 0);
- }
- if (styles.dropShadow?.enabled) {
- maxStyleMargin = Math.max(maxStyleMargin, (styles.dropShadow.distance || 0) + (styles.dropShadow.blur || 0));
- }
- if (styles.outerGlow?.enabled) {
- maxStyleMargin = Math.max(maxStyleMargin, styles.outerGlow.blur || 0);
- }
-
- const expandedFrustum = {
- minX: Math.max(0, frustum.minX - maxStyleMargin),
- minY: Math.max(0, frustum.minY - maxStyleMargin),
- maxX: Math.min(dimensions.width, frustum.maxX + maxStyleMargin),
- maxY: Math.min(dimensions.height, frustum.maxY + maxStyleMargin),
- };
-
- // 1. Render layer into isolated FBO with opacity 1.0 (opacity is modulated by stylesProgram)
- const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
- if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
-
- gl.bindFramebuffer(gl.FRAMEBUFFER, this.layerFbo);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT);
-
- const virtualLayer: LayerItem = { ...layer, opacity: 1.0, blendMode: 'normal' };
- this.renderSingleLayer(gl, virtualLayer, dimensions, grid, expandedFrustum, 1.0, null, false);
-
- // 2. Determine whether custom blend mode requires routing styled output through Ping-Pong blit
- const modeCode = BLEND_MODE_MAP[layer.blendMode] ?? 0;
- const needsCustomBlend = modeCode !== 0 && modeCode !== 12 && target !== null;
-
- if (needsCustomBlend) {
- if (!this.layerStylesOutFbo) {
- this.layerStylesOutFbo = this.createFboSurface(gl, false);
- }
- if (this.layerStylesOutFbo && this.ensureFboSurfaceSize(gl, this.layerStylesOutFbo, viewportW, viewportH)) {
- gl.bindFramebuffer(gl.FRAMEBUFFER, this.layerStylesOutFbo.fbo);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT);
- gl.blendFunc(gl.ONE, gl.ZERO);
- } else {
- const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
- gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
- gl.viewport(0, 0, viewportW, viewportH);
- if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- }
- } else {
- const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
- gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
- gl.viewport(0, 0, viewportW, viewportH);
- if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- }
-
- // 3. Activate styles program and bind uniforms
- gl.useProgram(this.stylesProgram);
-
- gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer);
- if (this.aStylesQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aStylesQuadPosLoc);
- gl.vertexAttribPointer(this.aStylesQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
-
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, this.layerTexture);
- gl.uniform1i(this.uStylesLayerTextureLoc, 0);
-
- gl.uniform2f(this.uStylesViewportSizeLoc, viewportW, viewportH);
- gl.uniform1f(this.uStylesLayerOpacityLoc, layer.opacity * opacityMultiplier);
-
- const stroke = styles.stroke;
- const strokeActive = Boolean(stroke?.enabled && stroke.size > 0 && stroke.opacity > 0);
- gl.uniform1i(this.uStylesStrokeEnabledLoc, strokeActive ? 1 : 0);
- if (strokeActive && stroke) {
- const strokePx = stroke.size * transform.zoom * dpr;
- gl.uniform1f(this.uStylesStrokeSizeLoc, strokePx);
- const [sr, sg, sb] = this.parseHexColor(stroke.color || '#000000');
- gl.uniform4f(this.uStylesStrokeColorLoc, sr, sg, sb, stroke.opacity);
- const posCode = stroke.position === 'inside' ? 1 : stroke.position === 'center' ? 2 : 0;
- gl.uniform1i(this.uStylesStrokePositionLoc, posCode);
- }
-
- const glow = styles.outerGlow;
- const glowActive = Boolean(glow?.enabled && glow.opacity > 0 && glow.blur > 0);
- gl.uniform1i(this.uStylesGlowEnabledLoc, glowActive ? 1 : 0);
- if (glowActive && glow) {
- const glowBlurPx = glow.blur * transform.zoom * dpr;
- gl.uniform1f(this.uStylesGlowBlurLoc, glowBlurPx);
- const [gr, gg, gb] = this.parseHexColor(glow.color || '#ffff00');
- gl.uniform4f(this.uStylesGlowColorLoc, gr, gg, gb, glow.opacity);
- gl.uniform1f(this.uStylesGlowSpreadLoc, (glow.spread || 0) / 100);
- }
-
- const shadow = styles.dropShadow;
- const shadowActive = Boolean(shadow?.enabled && shadow.opacity > 0);
- gl.uniform1i(this.uStylesShadowEnabledLoc, shadowActive ? 1 : 0);
- if (shadowActive && shadow) {
- const rad = ((shadow.angle || 0) * Math.PI) / 180;
- const distPx = (shadow.distance || 0) * transform.zoom * dpr;
- const dx = Math.cos(rad) * distPx * (transform.flipX ? -1 : 1);
- const dy = Math.sin(rad) * distPx * (transform.flipY ? -1 : 1);
- gl.uniform2f(this.uStylesShadowOffsetLoc, dx, -dy);
- const shadowBlurPx = (shadow.blur || 0) * transform.zoom * dpr;
- gl.uniform1f(this.uStylesShadowBlurLoc, shadowBlurPx);
- const [dr, dg, db] = this.parseHexColor(shadow.color || '#000000');
- gl.uniform4f(this.uStylesShadowColorLoc, dr, dg, db, shadow.opacity);
- gl.uniform1f(this.uStylesShadowSpreadLoc, (shadow.spread || 0) / 100);
- }
-
- // 4. Draw fullscreen quad
- gl.drawArrays(gl.TRIANGLES, 0, 6);
-
- // 5. If custom blend mode was routed to layerStylesOutFbo, composite onto parent Ping-Pong target
- if (needsCustomBlend && this.layerStylesOutFbo && target) {
- const parentFbo = target.surfaces[target.activeIndex].fbo;
- gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
- gl.viewport(0, 0, viewportW, viewportH);
- if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
- this.blitFolderTexture(
- gl,
- this.layerStylesOutFbo.texture,
- layer.blendMode,
- 1.0,
- viewportW,
- viewportH,
- target,
- preserveStencil
- );
- return;
- }
-
- // 6. Restore standard program and quad buffer
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- this.restoreStandardProgram(gl);
+ public invalidateMaskTexture(layerId?: string): void {
+ invalidateMaskTexture(this.state, layerId);
}
-
/**
- * Evict least recently used tile textures when texture pool exceeds threshold.
+ * Explicitly invalidate and clear all cached tile textures in both TEXTURE_2D and TEXTURE_2D_ARRAY pools.
*/
- private evictStaleTextures(): void {
- if (!this.gl || this.texturePool.length <= ViewportCompositor.MAX_TEXTURE_POOL_SIZE) return;
- this.texturePool.sort((a, b) => a.lastUsed - b.lastUsed);
- while (this.texturePool.length > ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
- const slot = this.texturePool.shift();
- if (slot) {
- if (slot.currentKey) this.activePoolByKey.delete(slot.currentKey);
- this.gl.deleteTexture(slot.texture);
- }
- }
+ public invalidateTileTextures(): void {
+ invalidateTileTextures(this.state);
}
/**
- * Helper to render a single layer onto a 2D canvas context.
+ * Resize viewport canvas to physical screen pixels.
*/
- private render2DSingleLayer(
- targetCtx: CanvasRenderingContext2D,
- layer: LayerItem,
- grid: SparseTileGrid,
- tileCtx: CanvasRenderingContext2D | null | undefined,
- opacityMultiplier: number = 1.0
- ): void {
- targetCtx.save();
- targetCtx.globalAlpha = Math.max(0, Math.min(1, layer.opacity * opacityMultiplier));
- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
-
- const tiles = grid.getLayerTiles(layer.id);
- const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
- const maskCtx = hasMask && layer.maskCanvas ? layer.maskCanvas.getContext('2d', { willReadFrequently: true }) : null;
-
- // Helper to render tiles into target context
- const drawTiles = (ctx: CanvasRenderingContext2D) => {
- for (const tile of tiles) {
- if (!tileCtx || !this.fallbackTileCanvas) continue;
- const rgba = grid.getTileAsRGBA(tile);
- const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
- imgData.data.set(rgba);
-
- if (hasMask && maskCtx) {
- const maskImgData = maskCtx.getImageData(tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE, TILE_SIZE, TILE_SIZE);
- const md = maskImgData.data;
- const d = imgData.data;
- for (let i = 0; i < d.length; i += 4) {
- if (d[i + 3] === 0) continue;
- const maskLum = (0.299 * md[i] + 0.587 * md[i + 1] + 0.114 * md[i + 2]) / 255 * (md[i + 3] / 255);
- d[i + 3] = Math.round(d[i + 3] * maskLum);
- }
- }
-
- tileCtx.putImageData(imgData, 0, 0);
- ctx.drawImage(this.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
- }
- };
-
- const styles = layer.styles;
- const hasStyles = hasActiveLayerStyles(styles);
-
- // 2D Layer Styles: Draw Drop Shadow
- if (hasStyles && styles?.dropShadow?.enabled && styles.dropShadow.opacity > 0) {
- targetCtx.save();
- const rad = ((styles.dropShadow.angle || 0) * Math.PI) / 180;
- const dist = styles.dropShadow.distance || 0;
- targetCtx.shadowColor = styles.dropShadow.color || '#000000';
- targetCtx.shadowBlur = styles.dropShadow.blur || 0;
- targetCtx.shadowOffsetX = Math.cos(rad) * dist;
- targetCtx.shadowOffsetY = Math.sin(rad) * dist;
- targetCtx.globalAlpha = layer.opacity * opacityMultiplier * styles.dropShadow.opacity;
- drawTiles(targetCtx);
- targetCtx.restore();
- }
-
- // 2D Layer Styles: Draw Outer Glow
- if (hasStyles && styles?.outerGlow?.enabled && styles.outerGlow.opacity > 0) {
- targetCtx.save();
- targetCtx.shadowColor = styles.outerGlow.color || '#ffff00';
- targetCtx.shadowBlur = styles.outerGlow.blur || 0;
- targetCtx.shadowOffsetX = 0;
- targetCtx.shadowOffsetY = 0;
- targetCtx.globalAlpha = layer.opacity * opacityMultiplier * styles.outerGlow.opacity;
- drawTiles(targetCtx);
- targetCtx.restore();
- }
-
- // WYSIWYG 2D fallback in-stack live draft compositing
- const opts = this.currentOptions;
- const has2DDraft = Boolean(
- opts?.activeDraftLayerId === layer.id &&
- opts.activeDraftCanvas &&
- (opts.activeDraftCanvas as any).__draftHasContent !== false
- );
- const draftOp2D = has2DDraft && opts?.activeDraftCanvas
- ? ((opts.activeDraftCanvas as any).__draftCompositeOp as GlobalCompositeOperation | undefined)
- : undefined;
-
- if (
- has2DDraft &&
- opts?.activeDraftCanvas &&
- (draftOp2D === 'destination-out' || draftOp2D === 'source-atop') &&
- typeof document !== 'undefined' &&
- targetCtx.canvas
- ) {
- const iso = document.createElement('canvas');
- iso.width = targetCtx.canvas.width;
- iso.height = targetCtx.canvas.height;
- const isoCtx = iso.getContext('2d');
- if (isoCtx) {
- if (typeof targetCtx.getTransform === 'function' && typeof isoCtx.setTransform === 'function') {
- isoCtx.setTransform(targetCtx.getTransform());
- }
- drawTiles(isoCtx);
- isoCtx.save();
- isoCtx.globalAlpha = opts.activeDraftOpacity ?? 1.0;
- isoCtx.globalCompositeOperation = draftOp2D;
- if (opts.activeDraftSpace === 'viewport' && typeof isoCtx.setTransform === 'function') {
- isoCtx.setTransform(1, 0, 0, 1, 0, 0);
- isoCtx.drawImage(opts.activeDraftCanvas, 0, 0);
- } else if (opts.activeDraftDirtyRect) {
- const dr = opts.activeDraftDirtyRect;
- isoCtx.drawImage(opts.activeDraftCanvas, dr.x, dr.y, dr.width, dr.height);
- } else {
- isoCtx.drawImage(
- opts.activeDraftCanvas,
- 0,
- 0,
- opts.dimensions?.width ?? opts.activeDraftCanvas.width,
- opts.dimensions?.height ?? opts.activeDraftCanvas.height
- );
- }
- isoCtx.restore();
-
- targetCtx.save();
- if (typeof targetCtx.setTransform === 'function') {
- targetCtx.setTransform(1, 0, 0, 1, 0, 0);
- }
- targetCtx.drawImage(iso, 0, 0);
- targetCtx.restore();
- targetCtx.restore();
- return;
- }
- }
-
- // Draw main layer content
- drawTiles(targetCtx);
-
- if (has2DDraft && opts?.activeDraftCanvas) {
- targetCtx.save();
- targetCtx.globalAlpha *= opts.activeDraftOpacity ?? 1.0;
- if (opts.activeDraftSpace === 'viewport' && typeof targetCtx.setTransform === 'function') {
- targetCtx.setTransform(1, 0, 0, 1, 0, 0);
- targetCtx.drawImage(opts.activeDraftCanvas, 0, 0);
- } else if (opts.activeDraftDirtyRect) {
- const dr = opts.activeDraftDirtyRect;
- targetCtx.drawImage(opts.activeDraftCanvas, dr.x, dr.y, dr.width, dr.height);
- } else {
- targetCtx.drawImage(
- opts.activeDraftCanvas,
- 0,
- 0,
- opts.dimensions?.width ?? opts.activeDraftCanvas.width,
- opts.dimensions?.height ?? opts.activeDraftCanvas.height
- );
+ public resize(width: number, height: number): void {
+ const nextW = Math.max(1, width);
+ const nextH = Math.max(1, height);
+ if (this.state.canvas.width !== nextW || this.state.canvas.height !== nextH) {
+ this.state.canvas.width = nextW;
+ this.state.canvas.height = nextH;
+ this.state.stackCache.invalidateAll();
+ if (this.state.gl) {
+ this.state.gl.viewport(0, 0, this.state.canvas.width, this.state.canvas.height);
}
- targetCtx.restore();
}
-
- targetCtx.restore();
}
/**
- * Recursive tree rendering for 2D fallback context supporting pass-through and isolated folders.
+ * Calculates the document-space bounding box visible in the current camera viewport.
+ * Performs frustum culling.
*/
- private render2DNodeList(
- targetCtx: CanvasRenderingContext2D,
- nodes: LayerTreeNode[],
- dimensions: CanvasDimensions,
- grid: SparseTileGrid,
- tileCtx: CanvasRenderingContext2D | null | undefined,
- opacityMultiplier: number = 1.0
- ): void {
- const renderOrder = nodes.slice().reverse();
- const groups = groupTreeNodesForCompositing(renderOrder);
-
- for (const group of groups) {
- const baseNode = group.baseNode;
- const baseLayer = baseNode.layer;
- if (!baseLayer.visible || baseLayer.opacity <= 0.001) continue;
-
- if (baseLayer.type === 'frame-folder') {
- const folderEffectiveOpacity = opacityMultiplier * baseLayer.opacity;
- const frames = (baseLayer.comicFrames || []).filter((f) => f.polygon.length >= 3);
- const shouldClip = frames.length > 0 && frames.some((f) => f.clipChildren !== false);
- let folderCanvas: HTMLCanvasElement | null = null;
- if (typeof document !== 'undefined') {
- folderCanvas = document.createElement('canvas');
- folderCanvas.width = dimensions.width;
- folderCanvas.height = dimensions.height;
- }
- const fCtx = folderCanvas?.getContext('2d');
- if (fCtx && folderCanvas) {
- fCtx.save();
- if (shouldClip) {
- applyMultiFrameClip(fCtx, frames);
- }
- for (const frame of frames) {
- if (frame.fillBackground !== false) {
- fCtx.fillStyle = frame.fillColor || '#ffffff';
- fCtx.beginPath();
- fCtx.moveTo(frame.polygon[0].x, frame.polygon[0].y);
- for (let i = 1; i < frame.polygon.length; i++) {
- fCtx.lineTo(frame.polygon[i].x, frame.polygon[i].y);
- }
- fCtx.closePath();
- fCtx.fill();
- }
- }
- if (baseNode.children.length > 0) {
- this.render2DNodeList(fCtx, baseNode.children, dimensions, grid, tileCtx, 1.0);
- }
- fCtx.restore();
-
- // Render frame borders on top of clipped folder contents
- for (const frame of frames) {
- renderFrameBorder(fCtx, frame, false);
- }
-
- targetCtx.save();
- targetCtx.globalAlpha = Math.max(0, Math.min(1, folderEffectiveOpacity));
- const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;
- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);
- targetCtx.drawImage(folderCanvas, 0, 0);
- targetCtx.restore();
- }
- continue;
- }
-
- if (baseLayer.type === 'folder') {
- const isPassThrough = baseLayer.blendMode === 'pass-through';
- const folderEffectiveOpacity = opacityMultiplier * baseLayer.opacity;
-
- if (isPassThrough) {
- if (baseNode.children.length > 0) {
- this.render2DNodeList(
- targetCtx,
- baseNode.children,
- dimensions,
- grid,
- tileCtx,
- folderEffectiveOpacity
- );
- }
- } else {
- let folderCanvas: HTMLCanvasElement | null = null;
- if (typeof document !== 'undefined') {
- folderCanvas = document.createElement('canvas');
- folderCanvas.width = dimensions.width;
- folderCanvas.height = dimensions.height;
- }
- const fCtx = folderCanvas?.getContext('2d');
- if (fCtx && folderCanvas) {
- if (baseNode.children.length > 0) {
- this.render2DNodeList(
- fCtx,
- baseNode.children,
- dimensions,
- grid,
- tileCtx,
- 1.0
- );
- }
- targetCtx.save();
- targetCtx.globalAlpha = Math.max(0, Math.min(1, folderEffectiveOpacity));
- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
- targetCtx.drawImage(folderCanvas, 0, 0);
- targetCtx.restore();
- }
- }
- continue;
- }
-
- if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
- const imgData = targetCtx.getImageData(0, 0, dimensions.width, dimensions.height);
- applyAdjustment(imgData, baseLayer.adjustmentData, baseLayer.maskCanvas, baseLayer.opacity * opacityMultiplier);
- targetCtx.putImageData(imgData, 0, 0);
- continue;
- }
-
- const activeClipped = group.clippedNodes.filter(
- (cn) => cn.layer.visible && cn.layer.opacity > 0.001 && !isFolderLikeLayer(cn.layer)
- );
-
- if (activeClipped.length === 0) {
- this.render2DSingleLayer(targetCtx, baseLayer, grid, tileCtx, opacityMultiplier);
- } else {
- let groupCanvas: HTMLCanvasElement | null = null;
- if (typeof document !== 'undefined') {
- groupCanvas = document.createElement('canvas');
- groupCanvas.width = dimensions.width;
- groupCanvas.height = dimensions.height;
- }
- const gCtx = groupCanvas?.getContext('2d');
- if (!gCtx || !groupCanvas) {
- this.render2DSingleLayer(targetCtx, baseLayer, grid, tileCtx, opacityMultiplier);
- continue;
- }
-
- this.render2DSingleLayer(gCtx, baseLayer, grid, tileCtx, 1.0);
-
- for (const clippedNode of activeClipped) {
- const clipped = clippedNode.layer;
- gCtx.save();
- gCtx.globalAlpha = clipped.opacity;
- gCtx.globalCompositeOperation = 'source-atop';
-
- const tiles = grid.getLayerTiles(clipped.id);
- for (const tile of tiles) {
- if (!tileCtx || !this.fallbackTileCanvas) continue;
- const rgba = grid.getTileAsRGBA(tile);
- const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
- imgData.data.set(rgba);
- tileCtx.putImageData(imgData, 0, 0);
- gCtx.drawImage(this.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
- }
- gCtx.restore();
- }
-
- targetCtx.save();
- targetCtx.globalAlpha = Math.max(0, Math.min(1, opacityMultiplier));
- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
- targetCtx.drawImage(groupCanvas, 0, 0);
- targetCtx.restore();
- }
- }
+ public calculateVisibleDocumentBounds(
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ docW: number,
+ docH: number
+ ): { minX: number; minY: number; maxX: number; maxY: number } {
+ return calculateVisibleDocumentBounds(viewportW, viewportH, transform, docW, docH);
}
/**
- * 2D Canvas Fallback Pass: Blits tiles when WebGL2 context is unavailable.
+ * Main Render Pass: Composite all visible layers onto the viewport canvas using:
+ * 1. Ping-Pong FBOs (zero gl.copyTexSubImage2D calls for all 16 blend modes, adjustments, & soft proof)
+ * 2. Baked Layer Stack Cache (`belowActiveCacheFbo` + `activeUnit` + `aboveActiveCacheFbo`)
+ * 3. TEXTURE_2D_ARRAY + gl.drawArraysInstanced tile batching
*/
- private render2DFallback(
+ public render(
layers: LayerItem[],
transform: ViewportTransform,
dimensions: CanvasDimensions,
- grid: SparseTileGrid,
- _options: CompositorOptions
+ grid: SparseTileGrid = globalTileGrid,
+ _options: CompositorOptions = { dimensions }
): void {
- const ctx = this.canvas.getContext('2d');
- if (!ctx) return;
-
- const viewportW = this.canvas.width;
- const viewportH = this.canvas.height;
- const dpr = _options.devicePixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
-
- ctx.save();
- ctx.clearRect(0, 0, viewportW, viewportH);
-
- ctx.scale(dpr, dpr);
- ctx.translate(transform.pan.x, transform.pan.y);
- ctx.rotate((transform.rotation * Math.PI) / 180);
- ctx.scale(
- (transform.flipX ? -1 : 1) * transform.zoom,
- (transform.flipY ? -1 : 1) * transform.zoom
- );
- ctx.translate(-dimensions.width / 2, -dimensions.height / 2);
-
- if (_options.showCheckerboard) {
- ctx.fillStyle = '#1e1e1e';
- } else {
- ctx.fillStyle = '#ffffff';
- }
- ctx.fillRect(0, 0, dimensions.width, dimensions.height);
-
- if (!this.fallbackTileCanvas && typeof document !== 'undefined') {
- this.fallbackTileCanvas = document.createElement('canvas');
- this.fallbackTileCanvas.width = TILE_SIZE;
- this.fallbackTileCanvas.height = TILE_SIZE;
- }
- const tileCtx = this.fallbackTileCanvas?.getContext('2d', { willReadFrequently: true });
-
- const tree = buildLayerTree(layers);
- this.render2DNodeList(ctx, tree, dimensions, grid, tileCtx, 1.0);
-
- ctx.restore();
+ renderFrame(this.state, layers, transform, dimensions, grid, _options);
}
- private static previewTileCanvas: HTMLCanvasElement | null = null;
- private static previewTileImgData: ImageData | null = null;
- private static previewScratchCanvas: HTMLCanvasElement | null = null;
-
/**
* Lightweight low-LOD composite preview renderer for Navigator & thumbnails.
* Reads directly from SparseTileGrid mipmap LOD tiles (no WebGL context creation, no GPU readPixels stall).
@@ -5557,332 +342,117 @@ export class ViewportCompositor {
grid: SparseTileGrid = globalTileGrid,
options: { showCheckerboard?: boolean } = {}
): void {
- if (typeof document === 'undefined') return;
- const ctx = targetCanvas.getContext('2d');
- if (!ctx) return;
-
- const outW = Math.max(1, Math.floor(targetCanvas.width));
- const outH = Math.max(1, Math.floor(targetCanvas.height));
- const docW = Math.max(1, dimensions.width);
- const docH = Math.max(1, dimensions.height);
-
- // Choose lowest sufficient LOD based on downscale ratio (avoids reading full-res tiles on 4K+ canvases)
- const ratio = Math.max(docW / outW, docH / outH);
- const targetLod = ratio >= 7 ? 3 : ratio >= 3.5 ? 2 : ratio >= 1.8 ? 1 : 0;
- const lodDocSize = TILE_SIZE << targetLod;
- const scaleX = outW / docW;
- const scaleY = outH / docH;
-
- // 1. Background
- ctx.save();
- ctx.setTransform(1, 0, 0, 1, 0, 0);
- ctx.globalCompositeOperation = 'source-over';
- ctx.globalAlpha = 1;
- if (options.showCheckerboard) {
- const cell = 6;
- ctx.fillStyle = '#202020';
- ctx.fillRect(0, 0, outW, outH);
- ctx.fillStyle = '#2a2a2a';
- for (let y = 0; y < outH; y += cell) {
- const offset = ((y / cell) & 1) * cell;
- for (let x = offset; x < outW; x += cell * 2) {
- ctx.fillRect(x, y, cell, cell);
- }
- }
- } else {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, outW, outH);
- }
-
- if (!ViewportCompositor.previewTileCanvas) {
- ViewportCompositor.previewTileCanvas = document.createElement('canvas');
- ViewportCompositor.previewTileCanvas.width = TILE_SIZE;
- ViewportCompositor.previewTileCanvas.height = TILE_SIZE;
- }
- const tileCanvas = ViewportCompositor.previewTileCanvas;
- const tileCtx = tileCanvas.getContext('2d', { willReadFrequently: true });
- if (!tileCtx) {
- ctx.restore();
- return;
- }
-
- const drawSingleLayer = (
- dstCtx: CanvasRenderingContext2D,
- layer: LayerItem,
- opacityMul: number,
- compositeOverride?: GlobalCompositeOperation
- ) => {
- const alpha = Math.max(0, Math.min(1, layer.opacity * opacityMul));
- if (alpha <= 0.001) return;
-
- const tiles = grid.getOrBuildLodTiles(layer.id, targetLod);
- if (tiles.length === 0) return;
-
- dstCtx.save();
- dstCtx.globalAlpha = alpha;
- dstCtx.globalCompositeOperation = compositeOverride ?? getCanvasCompositeOperation(layer.blendMode);
- dstCtx.imageSmoothingEnabled = true;
-
- if (!ViewportCompositor.previewTileImgData) {
- ViewportCompositor.previewTileImgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
- }
- const reusedImgData = ViewportCompositor.previewTileImgData;
-
- for (const tile of tiles) {
- const rgba = grid.getTileAsRGBA(tile);
- reusedImgData.data.set(rgba);
- tileCtx.putImageData(reusedImgData, 0, 0);
-
- const dx = tile.tileX * lodDocSize * scaleX;
- const dy = tile.tileY * lodDocSize * scaleY;
- const dw = lodDocSize * scaleX;
- const dh = lodDocSize * scaleY;
- dstCtx.drawImage(tileCanvas, dx, dy, dw, dh);
- }
-
- dstCtx.restore();
- };
-
- const renderNodes = (
- dstCtx: CanvasRenderingContext2D,
- nodes: LayerTreeNode[],
- opacityMul: number
- ) => {
- const renderOrder = nodes.slice().reverse();
- const groups = groupTreeNodesForCompositing(renderOrder);
-
- for (const group of groups) {
- const baseNode = group.baseNode;
- const baseLayer = baseNode.layer;
- if (!baseLayer.visible || baseLayer.opacity <= 0.001) continue;
-
- if (baseLayer.type === 'frame-folder') {
- const folderOpacity = opacityMul * baseLayer.opacity;
- const frames = (baseLayer.comicFrames || []).filter((f) => f.polygon.length >= 3);
- const shouldClip = frames.length > 0 && frames.some((f) => f.clipChildren !== false);
- const tmp = document.createElement('canvas');
- tmp.width = outW;
- tmp.height = outH;
- const tmpCtx = tmp.getContext('2d');
- if (tmpCtx) {
- const scaledFrames = frames.map((f) => ({
- ...f,
- borderWidth: Math.max(1, (f.borderWidth || 3) * Math.min(scaleX, scaleY)),
- polygon: f.polygon.map((p) => ({ x: p.x * scaleX, y: p.y * scaleY })),
- }));
- tmpCtx.save();
- if (shouldClip) {
- applyMultiFrameClip(tmpCtx, scaledFrames);
- }
- for (const sf of scaledFrames) {
- if (sf.fillBackground !== false) {
- tmpCtx.fillStyle = sf.fillColor || '#ffffff';
- tmpCtx.beginPath();
- tmpCtx.moveTo(sf.polygon[0].x, sf.polygon[0].y);
- for (let i = 1; i < sf.polygon.length; i++) {
- tmpCtx.lineTo(sf.polygon[i].x, sf.polygon[i].y);
- }
- tmpCtx.closePath();
- tmpCtx.fill();
- }
- }
- if (baseNode.children.length > 0) {
- renderNodes(tmpCtx, baseNode.children, 1.0);
- }
- tmpCtx.restore();
- for (const sf of scaledFrames) {
- renderFrameBorder(tmpCtx, sf, false);
- }
- dstCtx.save();
- dstCtx.globalAlpha = Math.max(0, Math.min(1, folderOpacity));
- const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;
- dstCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);
- dstCtx.drawImage(tmp, 0, 0);
- dstCtx.restore();
- }
- continue;
- }
-
- if (baseLayer.type === 'folder') {
- const folderOpacity = opacityMul * baseLayer.opacity;
- if (baseLayer.blendMode === 'pass-through') {
- if (baseNode.children.length > 0) {
- renderNodes(dstCtx, baseNode.children, folderOpacity);
- }
- } else {
- const tmp = document.createElement('canvas');
- tmp.width = outW;
- tmp.height = outH;
- const tmpCtx = tmp.getContext('2d');
- if (tmpCtx) {
- if (baseNode.children.length > 0) {
- renderNodes(tmpCtx, baseNode.children, 1.0);
- }
- dstCtx.save();
- dstCtx.globalAlpha = Math.max(0, Math.min(1, folderOpacity));
- dstCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
- dstCtx.drawImage(tmp, 0, 0);
- dstCtx.restore();
- }
- }
- continue;
- }
-
- if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
- try {
- const imgData = dstCtx.getImageData(0, 0, outW, outH);
- applyAdjustment(imgData, baseLayer.adjustmentData, undefined, baseLayer.opacity * opacityMul);
- dstCtx.putImageData(imgData, 0, 0);
- } catch {
- // Ignore in headless/mock contexts without getImageData
- }
- continue;
- }
-
- const activeClipped = group.clippedNodes.filter(
- (cn) => cn.layer.visible && cn.layer.opacity > 0.001 && !isFolderLikeLayer(cn.layer)
- );
-
- if (activeClipped.length === 0) {
- drawSingleLayer(dstCtx, baseLayer, opacityMul);
- } else {
- if (!ViewportCompositor.previewScratchCanvas) {
- ViewportCompositor.previewScratchCanvas = document.createElement('canvas');
- }
- const grpCanvas = ViewportCompositor.previewScratchCanvas;
- if (grpCanvas.width !== outW) grpCanvas.width = outW;
- if (grpCanvas.height !== outH) grpCanvas.height = outH;
- const grpCtx = grpCanvas.getContext('2d');
- if (!grpCtx) {
- drawSingleLayer(dstCtx, baseLayer, opacityMul);
- continue;
- }
- grpCtx.clearRect(0, 0, outW, outH);
- drawSingleLayer(grpCtx, baseLayer, 1.0, 'source-over');
- for (const cn of activeClipped) {
- drawSingleLayer(grpCtx, cn.layer, 1.0, 'source-atop');
- }
- dstCtx.save();
- dstCtx.globalAlpha = Math.max(0, Math.min(1, opacityMul));
- dstCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
- dstCtx.drawImage(grpCanvas, 0, 0);
- dstCtx.restore();
- }
- }
- };
-
- const tree = buildLayerTree(layers);
- renderNodes(ctx, tree, 1.0);
- ctx.restore();
+ renderLowResPreview(targetCanvas, layers, dimensions, grid, options);
}
/**
* Clear all allocated WebGL textures, FBOs, buffers, and programs.
*/
public dispose(): void {
- if (this.gl) {
- const gl = this.gl;
- this.invalidateTileTextures();
- for (const item of this.maskTextureCache.values()) {
+ const s = this.state;
+ if (s.gl) {
+ const gl = s.gl;
+ invalidateTileTextures(s);
+ for (const item of s.maskTextureCache.values()) {
gl.deleteTexture(item.texture);
}
- this.maskTextureCache.clear();
- this.maskInvalidationEpochs.clear();
- if (this.draftTexture) {
- gl.deleteTexture(this.draftTexture);
- this.draftTexture = null;
- }
- if (this.lutTexture) {
- gl.deleteTexture(this.lutTexture);
- this.lutTexture = null;
- }
- if (this.tileArrayTexture) {
- gl.deleteTexture(this.tileArrayTexture);
- this.tileArrayTexture = null;
- }
- if (this.instanceBuffer) {
- gl.deleteBuffer(this.instanceBuffer);
- this.instanceBuffer = null;
- }
- if (this.instancedVao && typeof gl.deleteVertexArray === 'function') {
- gl.deleteVertexArray(this.instancedVao);
- this.instancedVao = null;
- }
- if (this.quadBuffer) {
- gl.deleteBuffer(this.quadBuffer);
- this.quadBuffer = null;
- }
- if (this.program) {
- gl.deleteProgram(this.program);
- this.program = null;
- }
- if (this.instancedProgram) {
- gl.deleteProgram(this.instancedProgram);
- this.instancedProgram = null;
- }
- if (this.viewportDraftProgram) {
- gl.deleteProgram(this.viewportDraftProgram);
- this.viewportDraftProgram = null;
- }
- if (this.adjProgram) {
- gl.deleteProgram(this.adjProgram);
- this.adjProgram = null;
- }
- if (this.stylesProgram) {
- gl.deleteProgram(this.stylesProgram);
- this.stylesProgram = null;
- }
- if (this.blitProgram) {
- gl.deleteProgram(this.blitProgram);
- this.blitProgram = null;
- }
- if (this.framePolyProgram) {
- gl.deleteProgram(this.framePolyProgram);
- this.framePolyProgram = null;
- }
- if (this.framePolyBuffer) {
- gl.deleteBuffer(this.framePolyBuffer);
- this.framePolyBuffer = null;
- }
- if (this.softProofProgram) {
- gl.deleteProgram(this.softProofProgram);
- this.softProofProgram = null;
- }
- this.disposePingPongTarget(gl, this.scenePingPong);
- this.scenePingPong = null;
- for (const fpp of this.folderPingPongs) {
- this.disposePingPongTarget(gl, fpp);
- }
- this.folderPingPongs = [];
- this.disposeFboSurface(gl, this.belowActiveCacheFbo);
- this.belowActiveCacheFbo = null;
- this.disposeFboSurface(gl, this.aboveActiveCacheFbo);
- this.aboveActiveCacheFbo = null;
- this.disposeFboSurface(gl, this.layerStylesOutFbo);
- this.layerStylesOutFbo = null;
- if (this.layerFbo) {
- gl.deleteFramebuffer(this.layerFbo);
- this.layerFbo = null;
- }
- if (this.layerTexture) {
- gl.deleteTexture(this.layerTexture);
- this.layerTexture = null;
- }
- if (this.stylesQuadBuffer) {
- gl.deleteBuffer(this.stylesQuadBuffer);
- this.stylesQuadBuffer = null;
- }
- }
- this.stackCache.invalidateAll();
- if (this.fallbackTileCanvas) {
- this.fallbackTileCanvas = null;
- }
- if (typeof this.canvas.removeEventListener === 'function') {
- if (this.onContextLostHandler) {
- this.canvas.removeEventListener('webglcontextlost', this.onContextLostHandler);
- }
- if (this.onContextRestoredHandler) {
- this.canvas.removeEventListener('webglcontextrestored', this.onContextRestoredHandler);
+ s.maskTextureCache.clear();
+ s.maskInvalidationEpochs.clear();
+ if (s.draftTexture) {
+ gl.deleteTexture(s.draftTexture);
+ s.draftTexture = null;
+ }
+ if (s.lutTexture) {
+ gl.deleteTexture(s.lutTexture);
+ s.lutTexture = null;
+ }
+ if (s.tileArrayTexture) {
+ gl.deleteTexture(s.tileArrayTexture);
+ s.tileArrayTexture = null;
+ }
+ if (s.instanceBuffer) {
+ gl.deleteBuffer(s.instanceBuffer);
+ s.instanceBuffer = null;
+ }
+ if (s.instancedVao && typeof gl.deleteVertexArray === 'function') {
+ gl.deleteVertexArray(s.instancedVao);
+ s.instancedVao = null;
+ }
+ if (s.quadBuffer) {
+ gl.deleteBuffer(s.quadBuffer);
+ s.quadBuffer = null;
+ }
+ if (s.program) {
+ gl.deleteProgram(s.program);
+ s.program = null;
+ }
+ if (s.instancedProgram) {
+ gl.deleteProgram(s.instancedProgram);
+ s.instancedProgram = null;
+ }
+ if (s.viewportDraftProgram) {
+ gl.deleteProgram(s.viewportDraftProgram);
+ s.viewportDraftProgram = null;
+ }
+ if (s.adjProgram) {
+ gl.deleteProgram(s.adjProgram);
+ s.adjProgram = null;
+ }
+ if (s.stylesProgram) {
+ gl.deleteProgram(s.stylesProgram);
+ s.stylesProgram = null;
+ }
+ if (s.blitProgram) {
+ gl.deleteProgram(s.blitProgram);
+ s.blitProgram = null;
+ }
+ if (s.framePolyProgram) {
+ gl.deleteProgram(s.framePolyProgram);
+ s.framePolyProgram = null;
+ }
+ if (s.framePolyBuffer) {
+ gl.deleteBuffer(s.framePolyBuffer);
+ s.framePolyBuffer = null;
+ }
+ if (s.softProofProgram) {
+ gl.deleteProgram(s.softProofProgram);
+ s.softProofProgram = null;
+ }
+ disposePingPongTarget(gl, s.scenePingPong);
+ s.scenePingPong = null;
+ for (const fpp of s.folderPingPongs) {
+ disposePingPongTarget(gl, fpp);
+ }
+ s.folderPingPongs = [];
+ disposeFboSurface(gl, s.belowActiveCacheFbo);
+ s.belowActiveCacheFbo = null;
+ disposeFboSurface(gl, s.aboveActiveCacheFbo);
+ s.aboveActiveCacheFbo = null;
+ disposeFboSurface(gl, s.layerStylesOutFbo);
+ s.layerStylesOutFbo = null;
+ if (s.layerFbo) {
+ gl.deleteFramebuffer(s.layerFbo);
+ s.layerFbo = null;
+ }
+ if (s.layerTexture) {
+ gl.deleteTexture(s.layerTexture);
+ s.layerTexture = null;
+ }
+ if (s.stylesQuadBuffer) {
+ gl.deleteBuffer(s.stylesQuadBuffer);
+ s.stylesQuadBuffer = null;
+ }
+ }
+ s.stackCache.invalidateAll();
+ if (s.fallbackTileCanvas) {
+ s.fallbackTileCanvas = null;
+ }
+ if (typeof s.canvas.removeEventListener === 'function') {
+ if (s.onContextLostHandler) {
+ s.canvas.removeEventListener('webglcontextlost', s.onContextLostHandler);
+ }
+ if (s.onContextRestoredHandler) {
+ s.canvas.removeEventListener('webglcontextrestored', s.onContextRestoredHandler);
}
}
}
diff --git a/src/utils/compositor/bounds.ts b/src/utils/compositor/bounds.ts
new file mode 100644
index 0000000..b7df4c5
--- /dev/null
+++ b/src/utils/compositor/bounds.ts
@@ -0,0 +1,120 @@
+import { TileBuffer } from '../tileEngine';
+import { DocumentBounds, ViewportTransform } from './types';
+
+/**
+ * Calculates the document-space bounding box visible in the current camera viewport.
+ * Performs frustum culling.
+ */
+export function calculateVisibleDocumentBounds(
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ docW: number,
+ docH: number
+): DocumentBounds {
+ const { pan, zoom, rotation, flipX = false, flipY = false } = transform;
+ const rad = (-rotation * Math.PI) / 180;
+ const cosR = Math.cos(rad);
+ const sinR = Math.sin(rad);
+ const fx = flipX ? -1 : 1;
+ const fy = flipY ? -1 : 1;
+
+ // Screen corners relative to screen center/pan
+ const corners = [
+ { x: 0, y: 0 },
+ { x: viewportW, y: 0 },
+ { x: viewportW, y: viewportH },
+ { x: 0, y: viewportH },
+ ];
+
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+
+ for (const c of corners) {
+ // Invert translate
+ const dx = c.x - pan.x;
+ const dy = c.y - pan.y;
+
+ // Invert zoom
+ const sx = dx / Math.max(0.001, zoom);
+ const sy = dy / Math.max(0.001, zoom);
+
+ // Invert rotation
+ const rx = sx * cosR - sy * sinR;
+ const ry = sx * sinR + sy * cosR;
+
+ // Invert view flip and center offset
+ const docX = rx * fx + docW * 0.5;
+ const docY = ry * fy + docH * 0.5;
+
+ if (docX < minX) minX = docX;
+ if (docY < minY) minY = docY;
+ if (docX > maxX) maxX = docX;
+ if (docY > maxY) maxY = docY;
+ }
+
+ return {
+ minX: Math.max(0, Math.floor(minX)),
+ minY: Math.max(0, Math.floor(minY)),
+ maxX: Math.min(docW, Math.ceil(maxX)),
+ maxY: Math.min(docH, Math.ceil(maxY)),
+ };
+}
+
+/**
+ * Hex color parser to RGB normalized float array [r, g, b].
+ */
+export function parseHexColor(hex: string): [number, number, number] {
+ let clean = hex.replace('#', '');
+ if (clean.length === 3) {
+ clean = clean.split('').map((c) => c + c).join('');
+ }
+ const num = parseInt(clean, 16);
+ if (isNaN(num)) return [0, 0, 0];
+ return [
+ ((num >> 16) & 255) / 255,
+ ((num >> 8) & 255) / 255,
+ (num & 255) / 255,
+ ];
+}
+
+/**
+ * Premultiplies straight-alpha RGBA tile bytes into a reusable scratch buffer.
+ * 1-bit monochrome, 8-bit grayscale, and opaque solid-fill tiles return `srcBytes` directly.
+ */
+export function premultiplyTileBytes(
+ srcBytes: Uint8Array,
+ tile: TileBuffer,
+ dst: Uint8Array
+): Uint8Array {
+ // 1-bit monochrome, 8-bit grayscale, and opaque solid-fill tiles only contain alpha 0 or 255
+ // so straight-alpha bytes are already premultiplied (zero-copy fast path).
+ if (
+ tile.format === 'monochrome-1bit' ||
+ tile.format === 'grayscale-8bit' ||
+ (tile.solidColorU32 !== undefined && srcBytes[3] === 255)
+ ) {
+ return srcBytes;
+ }
+
+ const len = srcBytes.byteLength;
+ const src32 = new Uint32Array(srcBytes.buffer, srcBytes.byteOffset, len >> 2);
+ const dst32 = new Uint32Array(dst.buffer, dst.byteOffset, len >> 2);
+
+ for (let p = 0, i = 0; i < len; p++, i += 4) {
+ const a = srcBytes[i + 3];
+ if (a === 255) {
+ dst32[p] = src32[p];
+ } else if (a === 0) {
+ dst32[p] = 0;
+ } else {
+ dst[i] = ((srcBytes[i] * a + 128) * 257) >> 16;
+ dst[i + 1] = ((srcBytes[i + 1] * a + 128) * 257) >> 16;
+ dst[i + 2] = ((srcBytes[i + 2] * a + 128) * 257) >> 16;
+ dst[i + 3] = a;
+ }
+ }
+ return dst;
+}
diff --git a/src/utils/compositor/effectsPass.ts b/src/utils/compositor/effectsPass.ts
new file mode 100644
index 0000000..5018226
--- /dev/null
+++ b/src/utils/compositor/effectsPass.ts
@@ -0,0 +1,351 @@
+import { BlendMode, CanvasDimensions, LayerItem, SoftProofSettings } from '../../types/editor';
+import {
+ buildCurvesCombinedLut,
+ buildGradientMapLut,
+ buildLevelsLut,
+ evaluateColorBalancePixel,
+} from '../tonalEngine';
+import { parseHexColor } from './bounds';
+import { prepareBackdropFromPingPong } from './fboManager';
+import { restoreStandardProgram, unbindSceneTextureUnits } from './layerUniforms';
+import { getMaskTexture } from './tileTexturePool';
+import { BLEND_MODE_MAP, CompositorState, PingPongTarget, ViewportTransform } from './types';
+
+/**
+ * Evaluates non-destructive adjustment layers via Ping-Pong FBO backdrop and version-cached LUT evaluation.
+ */
+export function renderAdjustmentLayer(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ layer: LayerItem,
+ transform: ViewportTransform,
+ dimensions: CanvasDimensions,
+ viewportW: number,
+ viewportH: number,
+ dpr: number,
+ opacityMultiplier: number = 1.0,
+ target: PingPongTarget | null = null,
+ preserveStencil: boolean = false
+): void {
+ if (!state.adjProgram || !layer.adjustmentData || !target) return;
+
+ // 1. Ping-Pong swap to sample accumulated backdrop texture without copyTexSubImage2D
+ const backdropTex = prepareBackdropFromPingPong(
+ state,
+ gl,
+ target,
+ viewportW,
+ viewportH,
+ preserveStencil
+ );
+
+ // 2. Prepare 256x1 LUT (Cached by AdjustmentLayerData signature)
+ if (!state.lutTexture) {
+ state.lutTexture = gl.createTexture();
+ state.lastLutKey = '';
+ }
+ const adj = layer.adjustmentData;
+ const lutKey = JSON.stringify(adj);
+
+ if (lutKey !== state.lastLutKey) {
+ let lutData: Uint8Array;
+ let adjMode = 0; // 0 = per-channel, 1 = gradient map
+
+ if (adj.type === 'curves') {
+ const { rLut, gLut, bLut } = buildCurvesCombinedLut(adj.curves);
+ lutData = new Uint8Array(256 * 4);
+ for (let i = 0; i < 256; i++) {
+ const off = i * 4;
+ lutData[off] = rLut[i];
+ lutData[off + 1] = gLut[i];
+ lutData[off + 2] = bLut[i];
+ lutData[off + 3] = 255;
+ }
+ } else if (adj.type === 'gradient-map') {
+ adjMode = 1;
+ const gMap = buildGradientMapLut(adj.stops, adj.interpolation || 'linear');
+ lutData = new Uint8Array(gMap.buffer, gMap.byteOffset, gMap.byteLength);
+ } else if (adj.type === 'levels') {
+ const lLut = buildLevelsLut(
+ adj.blackPoint,
+ adj.whitePoint,
+ adj.gamma,
+ adj.outputMin ?? 0,
+ adj.outputMax ?? 255
+ );
+ const ch = adj.channel || 'rgb';
+ lutData = new Uint8Array(256 * 4);
+ for (let i = 0; i < 256; i++) {
+ const off = i * 4;
+ lutData[off] = ch === 'rgb' || ch === 'r' ? lLut[i] : i;
+ lutData[off + 1] = ch === 'rgb' || ch === 'g' ? lLut[i] : i;
+ lutData[off + 2] = ch === 'rgb' || ch === 'b' ? lLut[i] : i;
+ lutData[off + 3] = 255;
+ }
+ } else {
+ lutData = new Uint8Array(256 * 4);
+ for (let i = 0; i < 256; i++) {
+ const [r, g, b] = evaluateColorBalancePixel(i, i, i, adj);
+ const off = i * 4;
+ lutData[off] = r;
+ lutData[off + 1] = g;
+ lutData[off + 2] = b;
+ lutData[off + 3] = 255;
+ }
+ }
+
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, state.lutTexture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, lutData);
+
+ state.lastLutKey = lutKey;
+ state.lastLutAdjMode = adjMode;
+ }
+
+ // 3. Switch to Adjustment Program
+ gl.useProgram(state.adjProgram);
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.quadBuffer);
+ if (state.aQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aQuadPosLoc);
+ gl.vertexAttribPointer(state.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+
+ gl.uniform2f(state.uAdjViewportSizeLoc, viewportW, viewportH);
+ gl.uniform2f(state.uAdjDocDimensionsLoc, dimensions.width, dimensions.height);
+ gl.uniform2f(state.uAdjPanLoc, transform.pan.x, transform.pan.y);
+ gl.uniform1f(state.uAdjZoomLoc, transform.zoom);
+ const rotRad = (transform.rotation * Math.PI) / 180;
+ gl.uniform1f(state.uAdjRotationRadLoc, rotRad);
+ gl.uniform2f(state.uAdjFlipLoc, transform.flipX ? -1.0 : 1.0, transform.flipY ? -1.0 : 1.0);
+ gl.uniform1f(state.uAdjDprLoc, dpr);
+
+ gl.uniform2f(state.uAdjTileOriginLoc, 0, 0);
+ gl.uniform2f(state.uAdjTileSizeLoc, dimensions.width, dimensions.height);
+
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, backdropTex);
+ gl.uniform1i(state.uAdjSnapshotLoc, 2);
+
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, state.lutTexture);
+ gl.uniform1i(state.uAdjLutLoc, 3);
+
+ gl.uniform1i(state.uAdjModeLoc, state.lastLutAdjMode);
+ gl.uniform1f(state.uAdjOpacityLoc, layer.opacity * opacityMultiplier);
+
+ const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
+ gl.uniform1i(state.uAdjMaskEnabledLoc, hasMask ? 1 : 0);
+ if (hasMask && layer.maskCanvas) {
+ const maskTex = getMaskTexture(state, layer);
+ if (maskTex) {
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, maskTex);
+ gl.uniform1i(state.uAdjMaskTextureLoc, 1);
+ }
+ }
+
+ // Overwrite document region with filtered result
+ gl.blendFunc(gl.ONE, gl.ZERO);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ // Revert program, unbind backdrop texture to avoid feedback loops, and restore blend func
+ unbindSceneTextureUnits(gl);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ restoreStandardProgram(state, gl);
+}
+
+export function drawFramePolygonTriangles(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ vertices: Float32Array,
+ r: number,
+ g: number,
+ b: number,
+ a: number,
+ dimensions: CanvasDimensions,
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ dpr: number
+): void {
+ if (!state.framePolyProgram || !state.framePolyBuffer || vertices.length < 6) return;
+ gl.useProgram(state.framePolyProgram);
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.framePolyBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW);
+ if (state.aFramePolyDocPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aFramePolyDocPosLoc);
+ gl.vertexAttribPointer(state.aFramePolyDocPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+ gl.uniform2f(state.uFramePolyDocDimensionsLoc, dimensions.width, dimensions.height);
+ gl.uniform2f(state.uFramePolyViewportSizeLoc, viewportW, viewportH);
+ gl.uniform2f(state.uFramePolyPanLoc, transform.pan.x, transform.pan.y);
+ gl.uniform1f(state.uFramePolyZoomLoc, transform.zoom);
+ gl.uniform1f(state.uFramePolyRotationRadLoc, (transform.rotation * Math.PI) / 180);
+ gl.uniform2f(state.uFramePolyFlipLoc, transform.flipX ? -1.0 : 1.0, transform.flipY ? -1.0 : 1.0);
+ gl.uniform1f(state.uFramePolyDprLoc, dpr);
+ gl.uniform4f(state.uFramePolyColorLoc, r, g, b, a);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ gl.drawArrays(gl.TRIANGLES, 0, vertices.length / 2);
+ restoreStandardProgram(state, gl);
+}
+
+/**
+ * Blits an isolated folder or baked cache texture onto the active Ping-Pong target
+ * with full programmable blend mode support and zero gl.copyTexSubImage2D calls.
+ */
+export function blitFolderTexture(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ texture: WebGLTexture,
+ blendMode: BlendMode,
+ opacity: number,
+ viewportW: number,
+ viewportH: number,
+ target: PingPongTarget | null = null,
+ preserveStencil: boolean = false
+): void {
+ if (!state.blitProgram) return;
+
+ const modeCode = BLEND_MODE_MAP[blendMode] ?? 0;
+ let hasBackdrop = 0;
+ if (modeCode !== 0 && modeCode !== 12 && target && viewportW > 0 && viewportH > 0) {
+ const backdropTex = prepareBackdropFromPingPong(
+ state,
+ gl,
+ target,
+ viewportW,
+ viewportH,
+ preserveStencil
+ );
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, backdropTex);
+ hasBackdrop = 1;
+ }
+
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ gl.useProgram(state.blitProgram);
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.stylesQuadBuffer || state.quadBuffer);
+ if (state.aBlitQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aBlitQuadPosLoc);
+ gl.vertexAttribPointer(state.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.uniform1i(state.uBlitTextureLoc, 0);
+ gl.uniform1i(state.uBlitBackdropTextureLoc, 2);
+ gl.uniform1i(state.uBlitHasBackdropLoc, hasBackdrop);
+ gl.uniform1i(state.uBlitBlendModeLoc, modeCode);
+ gl.uniform1f(state.uBlitOpacityLoc, opacity);
+
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ unbindSceneTextureUnits(gl);
+ restoreStandardProgram(state, gl);
+}
+
+/**
+ * Post-processing pass: CMYK Soft Proofing and Gamut Warning.
+ * Samples directly from the Ping-Pong scene FBO texture into the default framebuffer (zero copyTexSubImage2D).
+ */
+export function applySoftProofPass(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ viewportW: number,
+ viewportH: number,
+ settings: SoftProofSettings,
+ sceneTexture: WebGLTexture
+): void {
+ if (!state.softProofProgram) return;
+
+ gl.useProgram(state.softProofProgram);
+
+ const standardIndex =
+ settings.standard === 'japan-color-2001'
+ ? 0
+ : settings.standard === 'us-web-coated-swop'
+ ? 1
+ : 2;
+ gl.uniform1i(state.uProofStandardLoc, standardIndex);
+ gl.uniform1i(state.uProofEnabledLoc, settings.enabled ? 1 : 0);
+ gl.uniform1i(state.uProofGamutWarningLoc, settings.gamutWarning ? 1 : 0);
+
+ const warnRgb = parseHexColor(settings.gamutWarningColor || '#7f7f7f');
+ gl.uniform3f(state.uProofGamutWarningColorLoc, warnRgb[0], warnRgb[1], warnRgb[2]);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, sceneTexture);
+ gl.uniform1i(state.uProofSceneTextureLoc, 0);
+
+ gl.disable(gl.STENCIL_TEST);
+ gl.disable(gl.BLEND);
+
+ const quadBuffer = state.stylesQuadBuffer || state.quadBuffer;
+ if (quadBuffer) {
+ gl.bindBuffer(gl.ARRAY_BUFFER, quadBuffer);
+ if (state.aProofQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aProofQuadPosLoc);
+ gl.vertexAttribPointer(state.aProofQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ }
+
+ unbindSceneTextureUnits(gl);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ restoreStandardProgram(state, gl);
+}
+
+export function presentTextureToScreen(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ texture: WebGLTexture,
+ viewportW: number,
+ viewportH: number,
+ softProof?: SoftProofSettings
+): void {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+
+ if (softProof && (softProof.enabled || softProof.gamutWarning) && state.softProofProgram) {
+ applySoftProofPass(state, gl, viewportW, viewportH, softProof, texture);
+ return;
+ }
+
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ if (!state.blitProgram) return;
+ gl.disable(gl.BLEND);
+ gl.useProgram(state.blitProgram);
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.stylesQuadBuffer || state.quadBuffer);
+ if (state.aBlitQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aBlitQuadPosLoc);
+ gl.vertexAttribPointer(state.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.uniform1i(state.uBlitTextureLoc, 0);
+ gl.uniform1i(state.uBlitBackdropTextureLoc, 2);
+ gl.uniform1i(state.uBlitHasBackdropLoc, 0);
+ gl.uniform1i(state.uBlitBlendModeLoc, 0);
+ gl.uniform1f(state.uBlitOpacityLoc, 1.0);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ unbindSceneTextureUnits(gl);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ restoreStandardProgram(state, gl);
+}
diff --git a/src/utils/compositor/fallback2d.ts b/src/utils/compositor/fallback2d.ts
new file mode 100644
index 0000000..34b02be
--- /dev/null
+++ b/src/utils/compositor/fallback2d.ts
@@ -0,0 +1,389 @@
+import { CanvasDimensions, LayerItem, isFolderLikeLayer } from '../../types/editor';
+import { getCanvasCompositeOperation } from '../canvasUtils';
+import { applyMultiFrameClip, renderFrameBorder } from '../frameEngine';
+import { SparseTileGrid, TILE_SIZE } from '../tileEngine';
+import { applyAdjustment } from '../tonalEngine';
+import { buildLayerTree, groupTreeNodesForCompositing } from './layerTree';
+import { hasActiveLayerStyles } from './shaders/effectShaders';
+import {
+ CompositorOptions,
+ CompositorState,
+ LayerTreeNode,
+ ViewportTransform,
+} from './types';
+
+/**
+ * Helper to render a single layer onto a 2D canvas context.
+ */
+export function render2DSingleLayer(
+ state: CompositorState,
+ targetCtx: CanvasRenderingContext2D,
+ layer: LayerItem,
+ grid: SparseTileGrid,
+ tileCtx: CanvasRenderingContext2D | null | undefined,
+ opacityMultiplier: number = 1.0
+): void {
+ targetCtx.save();
+ targetCtx.globalAlpha = Math.max(0, Math.min(1, layer.opacity * opacityMultiplier));
+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
+
+ const tiles = grid.getLayerTiles(layer.id);
+ const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
+ const maskCtx = hasMask && layer.maskCanvas ? layer.maskCanvas.getContext('2d', { willReadFrequently: true }) : null;
+
+ // Helper to render tiles into target context
+ const drawTiles = (ctx: CanvasRenderingContext2D) => {
+ for (const tile of tiles) {
+ if (!tileCtx || !state.fallbackTileCanvas) continue;
+ const rgba = grid.getTileAsRGBA(tile);
+ const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
+ imgData.data.set(rgba);
+
+ if (hasMask && maskCtx) {
+ const maskImgData = maskCtx.getImageData(tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE, TILE_SIZE, TILE_SIZE);
+ const md = maskImgData.data;
+ const d = imgData.data;
+ for (let i = 0; i < d.length; i += 4) {
+ if (d[i + 3] === 0) continue;
+ const maskLum = (0.299 * md[i] + 0.587 * md[i + 1] + 0.114 * md[i + 2]) / 255 * (md[i + 3] / 255);
+ d[i + 3] = Math.round(d[i + 3] * maskLum);
+ }
+ }
+
+ tileCtx.putImageData(imgData, 0, 0);
+ ctx.drawImage(state.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ }
+ };
+
+ const styles = layer.styles;
+ const hasStyles = hasActiveLayerStyles(styles);
+
+ // 2D Layer Styles: Draw Drop Shadow
+ if (hasStyles && styles?.dropShadow?.enabled && styles.dropShadow.opacity > 0) {
+ targetCtx.save();
+ const rad = ((styles.dropShadow.angle || 0) * Math.PI) / 180;
+ const dist = styles.dropShadow.distance || 0;
+ targetCtx.shadowColor = styles.dropShadow.color || '#000000';
+ targetCtx.shadowBlur = styles.dropShadow.blur || 0;
+ targetCtx.shadowOffsetX = Math.cos(rad) * dist;
+ targetCtx.shadowOffsetY = Math.sin(rad) * dist;
+ targetCtx.globalAlpha = layer.opacity * opacityMultiplier * styles.dropShadow.opacity;
+ drawTiles(targetCtx);
+ targetCtx.restore();
+ }
+
+ // 2D Layer Styles: Draw Outer Glow
+ if (hasStyles && styles?.outerGlow?.enabled && styles.outerGlow.opacity > 0) {
+ targetCtx.save();
+ targetCtx.shadowColor = styles.outerGlow.color || '#ffff00';
+ targetCtx.shadowBlur = styles.outerGlow.blur || 0;
+ targetCtx.shadowOffsetX = 0;
+ targetCtx.shadowOffsetY = 0;
+ targetCtx.globalAlpha = layer.opacity * opacityMultiplier * styles.outerGlow.opacity;
+ drawTiles(targetCtx);
+ targetCtx.restore();
+ }
+
+ // WYSIWYG 2D fallback in-stack live draft compositing
+ const opts = state.currentOptions;
+ const has2DDraft = Boolean(
+ opts?.activeDraftLayerId === layer.id &&
+ opts.activeDraftCanvas &&
+ (opts.activeDraftCanvas as any).__draftHasContent !== false
+ );
+ const draftOp2D = has2DDraft && opts?.activeDraftCanvas
+ ? ((opts.activeDraftCanvas as any).__draftCompositeOp as GlobalCompositeOperation | undefined)
+ : undefined;
+
+ if (
+ has2DDraft &&
+ opts?.activeDraftCanvas &&
+ (draftOp2D === 'destination-out' || draftOp2D === 'source-atop') &&
+ typeof document !== 'undefined' &&
+ targetCtx.canvas
+ ) {
+ const iso = document.createElement('canvas');
+ iso.width = targetCtx.canvas.width;
+ iso.height = targetCtx.canvas.height;
+ const isoCtx = iso.getContext('2d');
+ if (isoCtx) {
+ if (typeof targetCtx.getTransform === 'function' && typeof isoCtx.setTransform === 'function') {
+ isoCtx.setTransform(targetCtx.getTransform());
+ }
+ drawTiles(isoCtx);
+ isoCtx.save();
+ isoCtx.globalAlpha = opts.activeDraftOpacity ?? 1.0;
+ isoCtx.globalCompositeOperation = draftOp2D;
+ if (opts.activeDraftSpace === 'viewport' && typeof isoCtx.setTransform === 'function') {
+ isoCtx.setTransform(1, 0, 0, 1, 0, 0);
+ isoCtx.drawImage(opts.activeDraftCanvas, 0, 0);
+ } else if (opts.activeDraftDirtyRect) {
+ const dr = opts.activeDraftDirtyRect;
+ isoCtx.drawImage(opts.activeDraftCanvas, dr.x, dr.y, dr.width, dr.height);
+ } else {
+ isoCtx.drawImage(
+ opts.activeDraftCanvas,
+ 0,
+ 0,
+ opts.dimensions?.width ?? opts.activeDraftCanvas.width,
+ opts.dimensions?.height ?? opts.activeDraftCanvas.height
+ );
+ }
+ isoCtx.restore();
+
+ targetCtx.save();
+ if (typeof targetCtx.setTransform === 'function') {
+ targetCtx.setTransform(1, 0, 0, 1, 0, 0);
+ }
+ targetCtx.drawImage(iso, 0, 0);
+ targetCtx.restore();
+ targetCtx.restore();
+ return;
+ }
+ }
+
+ // Draw main layer content
+ drawTiles(targetCtx);
+
+ if (has2DDraft && opts?.activeDraftCanvas) {
+ targetCtx.save();
+ targetCtx.globalAlpha *= opts.activeDraftOpacity ?? 1.0;
+ if (opts.activeDraftSpace === 'viewport' && typeof targetCtx.setTransform === 'function') {
+ targetCtx.setTransform(1, 0, 0, 1, 0, 0);
+ targetCtx.drawImage(opts.activeDraftCanvas, 0, 0);
+ } else if (opts.activeDraftDirtyRect) {
+ const dr = opts.activeDraftDirtyRect;
+ targetCtx.drawImage(opts.activeDraftCanvas, dr.x, dr.y, dr.width, dr.height);
+ } else {
+ targetCtx.drawImage(
+ opts.activeDraftCanvas,
+ 0,
+ 0,
+ opts.dimensions?.width ?? opts.activeDraftCanvas.width,
+ opts.dimensions?.height ?? opts.activeDraftCanvas.height
+ );
+ }
+ targetCtx.restore();
+ }
+
+ targetCtx.restore();
+}
+
+/**
+ * Recursive tree rendering for 2D fallback context supporting pass-through and isolated folders.
+ */
+export function render2DNodeList(
+ state: CompositorState,
+ targetCtx: CanvasRenderingContext2D,
+ nodes: LayerTreeNode[],
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ tileCtx: CanvasRenderingContext2D | null | undefined,
+ opacityMultiplier: number = 1.0
+): void {
+ const renderOrder = nodes.slice().reverse();
+ const groups = groupTreeNodesForCompositing(renderOrder);
+
+ for (const group of groups) {
+ const baseNode = group.baseNode;
+ const baseLayer = baseNode.layer;
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001) continue;
+
+ if (baseLayer.type === 'frame-folder') {
+ const folderEffectiveOpacity = opacityMultiplier * baseLayer.opacity;
+ const frames = (baseLayer.comicFrames || []).filter((f) => f.polygon.length >= 3);
+ const shouldClip = frames.length > 0 && frames.some((f) => f.clipChildren !== false);
+ let folderCanvas: HTMLCanvasElement | null = null;
+ if (typeof document !== 'undefined') {
+ folderCanvas = document.createElement('canvas');
+ folderCanvas.width = dimensions.width;
+ folderCanvas.height = dimensions.height;
+ }
+ const fCtx = folderCanvas?.getContext('2d');
+ if (fCtx && folderCanvas) {
+ fCtx.save();
+ if (shouldClip) {
+ applyMultiFrameClip(fCtx, frames);
+ }
+ for (const frame of frames) {
+ if (frame.fillBackground !== false) {
+ fCtx.fillStyle = frame.fillColor || '#ffffff';
+ fCtx.beginPath();
+ fCtx.moveTo(frame.polygon[0].x, frame.polygon[0].y);
+ for (let i = 1; i < frame.polygon.length; i++) {
+ fCtx.lineTo(frame.polygon[i].x, frame.polygon[i].y);
+ }
+ fCtx.closePath();
+ fCtx.fill();
+ }
+ }
+ if (baseNode.children.length > 0) {
+ render2DNodeList(state, fCtx, baseNode.children, dimensions, grid, tileCtx, 1.0);
+ }
+ fCtx.restore();
+
+ // Render frame borders on top of clipped folder contents
+ for (const frame of frames) {
+ renderFrameBorder(fCtx, frame, false);
+ }
+
+ targetCtx.save();
+ targetCtx.globalAlpha = Math.max(0, Math.min(1, folderEffectiveOpacity));
+ const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;
+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);
+ targetCtx.drawImage(folderCanvas, 0, 0);
+ targetCtx.restore();
+ }
+ continue;
+ }
+
+ if (baseLayer.type === 'folder') {
+ const isPassThrough = baseLayer.blendMode === 'pass-through';
+ const folderEffectiveOpacity = opacityMultiplier * baseLayer.opacity;
+
+ if (isPassThrough) {
+ if (baseNode.children.length > 0) {
+ render2DNodeList(
+ state,
+ targetCtx,
+ baseNode.children,
+ dimensions,
+ grid,
+ tileCtx,
+ folderEffectiveOpacity
+ );
+ }
+ } else {
+ let folderCanvas: HTMLCanvasElement | null = null;
+ if (typeof document !== 'undefined') {
+ folderCanvas = document.createElement('canvas');
+ folderCanvas.width = dimensions.width;
+ folderCanvas.height = dimensions.height;
+ }
+ const fCtx = folderCanvas?.getContext('2d');
+ if (fCtx && folderCanvas) {
+ if (baseNode.children.length > 0) {
+ render2DNodeList(
+ state,
+ fCtx,
+ baseNode.children,
+ dimensions,
+ grid,
+ tileCtx,
+ 1.0
+ );
+ }
+ targetCtx.save();
+ targetCtx.globalAlpha = Math.max(0, Math.min(1, folderEffectiveOpacity));
+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ targetCtx.drawImage(folderCanvas, 0, 0);
+ targetCtx.restore();
+ }
+ }
+ continue;
+ }
+
+ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
+ const imgData = targetCtx.getImageData(0, 0, dimensions.width, dimensions.height);
+ applyAdjustment(imgData, baseLayer.adjustmentData, baseLayer.maskCanvas, baseLayer.opacity * opacityMultiplier);
+ targetCtx.putImageData(imgData, 0, 0);
+ continue;
+ }
+
+ const activeClipped = group.clippedNodes.filter(
+ (cn) => cn.layer.visible && cn.layer.opacity > 0.001 && !isFolderLikeLayer(cn.layer)
+ );
+
+ if (activeClipped.length === 0) {
+ render2DSingleLayer(state, targetCtx, baseLayer, grid, tileCtx, opacityMultiplier);
+ } else {
+ let groupCanvas: HTMLCanvasElement | null = null;
+ if (typeof document !== 'undefined') {
+ groupCanvas = document.createElement('canvas');
+ groupCanvas.width = dimensions.width;
+ groupCanvas.height = dimensions.height;
+ }
+ const gCtx = groupCanvas?.getContext('2d');
+ if (!gCtx || !groupCanvas) {
+ render2DSingleLayer(state, targetCtx, baseLayer, grid, tileCtx, opacityMultiplier);
+ continue;
+ }
+
+ render2DSingleLayer(state, gCtx, baseLayer, grid, tileCtx, 1.0);
+
+ for (const clippedNode of activeClipped) {
+ const clipped = clippedNode.layer;
+ gCtx.save();
+ gCtx.globalAlpha = clipped.opacity;
+ gCtx.globalCompositeOperation = 'source-atop';
+
+ const tiles = grid.getLayerTiles(clipped.id);
+ for (const tile of tiles) {
+ if (!tileCtx || !state.fallbackTileCanvas) continue;
+ const rgba = grid.getTileAsRGBA(tile);
+ const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
+ imgData.data.set(rgba);
+ tileCtx.putImageData(imgData, 0, 0);
+ gCtx.drawImage(state.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ }
+ gCtx.restore();
+ }
+
+ targetCtx.save();
+ targetCtx.globalAlpha = Math.max(0, Math.min(1, opacityMultiplier));
+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ targetCtx.drawImage(groupCanvas, 0, 0);
+ targetCtx.restore();
+ }
+ }
+}
+
+/**
+ * 2D Canvas Fallback Pass: Blits tiles when WebGL2 context is unavailable.
+ */
+export function render2DFallback(
+ state: CompositorState,
+ layers: LayerItem[],
+ transform: ViewportTransform,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ _options: CompositorOptions
+): void {
+ const ctx = state.canvas.getContext('2d');
+ if (!ctx) return;
+
+ const viewportW = state.canvas.width;
+ const viewportH = state.canvas.height;
+ const dpr = _options.devicePixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
+
+ ctx.save();
+ ctx.clearRect(0, 0, viewportW, viewportH);
+
+ ctx.scale(dpr, dpr);
+ ctx.translate(transform.pan.x, transform.pan.y);
+ ctx.rotate((transform.rotation * Math.PI) / 180);
+ ctx.scale(
+ (transform.flipX ? -1 : 1) * transform.zoom,
+ (transform.flipY ? -1 : 1) * transform.zoom
+ );
+ ctx.translate(-dimensions.width / 2, -dimensions.height / 2);
+
+ if (_options.showCheckerboard) {
+ ctx.fillStyle = '#1e1e1e';
+ } else {
+ ctx.fillStyle = '#ffffff';
+ }
+ ctx.fillRect(0, 0, dimensions.width, dimensions.height);
+
+ if (!state.fallbackTileCanvas && typeof document !== 'undefined') {
+ state.fallbackTileCanvas = document.createElement('canvas');
+ state.fallbackTileCanvas.width = TILE_SIZE;
+ state.fallbackTileCanvas.height = TILE_SIZE;
+ }
+ const tileCtx = state.fallbackTileCanvas?.getContext('2d', { willReadFrequently: true });
+
+ const tree = buildLayerTree(layers);
+ render2DNodeList(state, ctx, tree, dimensions, grid, tileCtx, 1.0);
+
+ ctx.restore();
+}
diff --git a/src/utils/compositor/fboManager.ts b/src/utils/compositor/fboManager.ts
new file mode 100644
index 0000000..b2f2044
--- /dev/null
+++ b/src/utils/compositor/fboManager.ts
@@ -0,0 +1,265 @@
+import { restoreStandardProgram, unbindSceneTextureUnits } from './layerUniforms';
+import { CompositorState, FboSurface, PingPongTarget } from './types';
+
+export { unbindSceneTextureUnits };
+
+export function createFboSurface(
+ gl: WebGL2RenderingContext,
+ withStencil: boolean = true
+): FboSurface | null {
+ const fbo = gl.createFramebuffer();
+ const texture = gl.createTexture();
+ if (!fbo || !texture) {
+ if (fbo) gl.deleteFramebuffer(fbo);
+ if (texture) gl.deleteTexture(texture);
+ return null;
+ }
+ const stencilRb =
+ withStencil && typeof gl.createRenderbuffer === 'function' ? gl.createRenderbuffer() : null;
+ return { fbo, texture, stencilRb, width: 0, height: 0 };
+}
+
+export function ensureFboSurfaceSize(
+ gl: WebGL2RenderingContext,
+ surface: FboSurface,
+ width: number,
+ height: number
+): boolean {
+ if (surface.width === width && surface.height === height) {
+ return true;
+ }
+
+ const prevFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;
+
+ gl.bindTexture(gl.TEXTURE_2D, surface.texture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+
+ gl.bindFramebuffer(gl.FRAMEBUFFER, surface.fbo);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, surface.texture, 0);
+
+ if (surface.stencilRb && typeof gl.bindRenderbuffer === 'function') {
+ gl.bindRenderbuffer(gl.RENDERBUFFER, surface.stencilRb);
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, width, height);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, surface.stencilRb);
+ }
+
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, prevFbo);
+
+ if (status !== gl.FRAMEBUFFER_COMPLETE) {
+ console.error('Compositor FBO surface incomplete:', status);
+ return false;
+ }
+
+ surface.width = width;
+ surface.height = height;
+ return true;
+}
+
+export function disposeFboSurface(gl: WebGL2RenderingContext, surface: FboSurface | null): void {
+ if (!surface) return;
+ gl.deleteFramebuffer(surface.fbo);
+ gl.deleteTexture(surface.texture);
+ if (surface.stencilRb && typeof gl.deleteRenderbuffer === 'function') {
+ gl.deleteRenderbuffer(surface.stencilRb);
+ }
+}
+
+export function disposePingPongTarget(
+ gl: WebGL2RenderingContext,
+ target: PingPongTarget | null
+): void {
+ if (!target) return;
+ disposeFboSurface(gl, target.surfaces[0]);
+ disposeFboSurface(gl, target.surfaces[1]);
+}
+
+export function ensurePingPongTarget(
+ gl: WebGL2RenderingContext,
+ existing: PingPongTarget | null,
+ width: number,
+ height: number
+): PingPongTarget | null {
+ let target = existing;
+ if (!target) {
+ const s0 = createFboSurface(gl, true);
+ const s1 = createFboSurface(gl, true);
+ if (!s0 || !s1) {
+ disposeFboSurface(gl, s0);
+ disposeFboSurface(gl, s1);
+ return null;
+ }
+ target = { surfaces: [s0, s1], activeIndex: 0 };
+ }
+ if (
+ !ensureFboSurfaceSize(gl, target.surfaces[0], width, height) ||
+ !ensureFboSurfaceSize(gl, target.surfaces[1], width, height)
+ ) {
+ return null;
+ }
+ return target;
+}
+
+export function ensureFolderPingPong(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ depth: number,
+ width: number,
+ height: number
+): PingPongTarget | null {
+ while (state.folderPingPongs.length <= depth) {
+ const created = ensurePingPongTarget(gl, null, width, height);
+ if (!created) return null;
+ state.folderPingPongs.push(created);
+ }
+ const target = ensurePingPongTarget(gl, state.folderPingPongs[depth], width, height);
+ if (!target) return null;
+ state.folderPingPongs[depth] = target;
+ return target;
+}
+
+/**
+ * Fast GPU-to-GPU FBO copy via gl.blitFramebuffer (with fullscreen quad fallback).
+ * Eliminates all gl.copyTexSubImage2D calls and preserves stencil buffer when requested.
+ */
+export function copyFboSurface(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ src: FboSurface,
+ dst: FboSurface,
+ width: number,
+ height: number,
+ copyStencil: boolean = false
+): void {
+ if (
+ typeof gl.blitFramebuffer === 'function' &&
+ gl.READ_FRAMEBUFFER !== undefined &&
+ gl.DRAW_FRAMEBUFFER !== undefined
+ ) {
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, src.fbo);
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, dst.fbo);
+ const mask = copyStencil && src.stencilRb && dst.stencilRb
+ ? (gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT)
+ : gl.COLOR_BUFFER_BIT;
+ gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
+ gl.viewport(0, 0, width, height);
+ return;
+ }
+
+ // Fallback: fullscreen quad copy using blitProgram (zero copyTexSubImage2D)
+ gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
+ gl.viewport(0, 0, width, height);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ if (!state.blitProgram) return;
+
+ const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
+ if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
+ gl.disable(gl.BLEND);
+
+ gl.useProgram(state.blitProgram);
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.stylesQuadBuffer || state.quadBuffer);
+ if (state.aBlitQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aBlitQuadPosLoc);
+ gl.vertexAttribPointer(state.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, src.texture);
+ gl.uniform1i(state.uBlitTextureLoc, 0);
+ gl.uniform1i(state.uBlitBackdropTextureLoc, 2);
+ gl.uniform1i(state.uBlitHasBackdropLoc, 0);
+ gl.uniform1i(state.uBlitBlendModeLoc, 0);
+ gl.uniform1f(state.uBlitOpacityLoc, 1.0);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ unbindSceneTextureUnits(gl);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+ restoreStandardProgram(state, gl);
+}
+
+/**
+ * Swaps Ping-Pong FBOs for a programmable blend / adjustment pass:
+ * copies current surface -> opposite surface and returns current surface's immutable texture as backdrop.
+ * ZERO gl.copyTexSubImage2D calls!
+ */
+export function prepareBackdropFromPingPong(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ target: PingPongTarget,
+ viewportW: number,
+ viewportH: number,
+ preserveStencil: boolean
+): WebGLTexture {
+ const src = target.surfaces[target.activeIndex];
+ const nextIdx: 0 | 1 = target.activeIndex === 0 ? 1 : 0;
+ const dst = target.surfaces[nextIdx];
+
+ copyFboSurface(state, gl, src, dst, viewportW, viewportH, preserveStencil);
+ target.activeIndex = nextIdx;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+
+ return src.texture;
+}
+
+/**
+ * Ensures an offscreen framebuffer and texture exist for isolated layer style / eraser rendering.
+ */
+export function ensureLayerFbo(
+ state: CompositorState,
+ width: number,
+ height: number
+): boolean {
+ if (!state.gl) return false;
+ const gl = state.gl;
+
+ if (
+ state.layerFbo &&
+ state.layerTexture &&
+ state.layerFboWidth === width &&
+ state.layerFboHeight === height
+ ) {
+ return true;
+ }
+
+ const prevFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;
+
+ if (!state.layerFbo) {
+ state.layerFbo = gl.createFramebuffer();
+ }
+ if (!state.layerTexture) {
+ state.layerTexture = gl.createTexture();
+ }
+
+ state.layerFboWidth = width;
+ state.layerFboHeight = height;
+
+ gl.bindTexture(gl.TEXTURE_2D, state.layerTexture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+
+ gl.bindFramebuffer(gl.FRAMEBUFFER, state.layerFbo);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, state.layerTexture, 0);
+
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, prevFbo);
+
+ if (status !== gl.FRAMEBUFFER_COMPLETE) {
+ console.error('Layer FBO incomplete:', status);
+ return false;
+ }
+
+ return true;
+}
diff --git a/src/utils/compositor/glInit.ts b/src/utils/compositor/glInit.ts
new file mode 100644
index 0000000..b856004
--- /dev/null
+++ b/src/utils/compositor/glInit.ts
@@ -0,0 +1,488 @@
+import { TILE_SIZE } from '../tileEngine';
+import {
+ COMPOSITOR_FRAGMENT_SHADER,
+ COMPOSITOR_VERTEX_SHADER,
+ FOLDER_BLIT_FRAGMENT_SHADER,
+ FOLDER_BLIT_VERTEX_SHADER,
+ FRAME_POLY_FRAGMENT_SHADER,
+ FRAME_POLY_VERTEX_SHADER,
+ VIEWPORT_DRAFT_VERTEX_SHADER,
+} from './shaders/coreShaders';
+import {
+ COMPOSITOR_INSTANCED_FRAGMENT_SHADER,
+ COMPOSITOR_INSTANCED_VERTEX_SHADER,
+} from './shaders/instancedShaders';
+import {
+ ADJUSTMENT_FRAGMENT_SHADER,
+ LAYER_STYLES_FRAGMENT_SHADER,
+ LAYER_STYLES_VERTEX_SHADER,
+} from './shaders/effectShaders';
+import {
+ SOFT_PROOF_FRAGMENT_SHADER,
+ SOFT_PROOF_VERTEX_SHADER,
+} from './shaders/softProofShaders';
+import {
+ ArrayPoolSlot,
+ CompositorState,
+ DEFAULT_ARRAY_POOL_LAYERS,
+ LayerUniformLocs,
+} from './types';
+
+function compileShader(
+ gl: WebGL2RenderingContext,
+ type: number,
+ source: string
+): WebGLShader | null {
+ const shader = gl.createShader(type);
+ if (!shader) return null;
+ gl.shaderSource(shader, source);
+ gl.compileShader(shader);
+ return shader;
+}
+
+function linkProgram(
+ gl: WebGL2RenderingContext,
+ vs: WebGLShader,
+ fs: WebGLShader
+): WebGLProgram | null {
+ const prog = gl.createProgram();
+ if (!prog) return null;
+ gl.attachShader(prog, vs);
+ gl.attachShader(prog, fs);
+ gl.linkProgram(prog);
+ return prog;
+}
+
+export function queryLayerUniformLocs(
+ gl: WebGL2RenderingContext,
+ prog: WebGLProgram
+): LayerUniformLocs {
+ return {
+ uDocDimensions: gl.getUniformLocation(prog, 'u_docDimensions'),
+ uViewportSize: gl.getUniformLocation(prog, 'u_viewportSize'),
+ uPan: gl.getUniformLocation(prog, 'u_pan'),
+ uZoom: gl.getUniformLocation(prog, 'u_zoom'),
+ uRotationRad: gl.getUniformLocation(prog, 'u_rotationRad'),
+ uFlip: gl.getUniformLocation(prog, 'u_flip'),
+ uDpr: gl.getUniformLocation(prog, 'u_dpr'),
+ uBackdropTexture: gl.getUniformLocation(prog, 'u_backdropTexture'),
+ uHasBackdrop: gl.getUniformLocation(prog, 'u_hasBackdrop'),
+ uLayerOpacity: gl.getUniformLocation(prog, 'u_layerOpacity'),
+ uBlendMode: gl.getUniformLocation(prog, 'u_blendMode'),
+ uToneEnabled: gl.getUniformLocation(prog, 'u_toneEnabled'),
+ uToneFrequency: gl.getUniformLocation(prog, 'u_toneFrequency'),
+ uToneAngleRad: gl.getUniformLocation(prog, 'u_toneAngleRad'),
+ uToneDpi: gl.getUniformLocation(prog, 'u_toneDpi'),
+ uToneDotShape: gl.getUniformLocation(prog, 'u_toneDotShape'),
+ uToneDensity: gl.getUniformLocation(prog, 'u_toneDensity'),
+ uToneDensityType: gl.getUniformLocation(prog, 'u_toneDensityType'),
+ uLayerColorEnabled: gl.getUniformLocation(prog, 'u_layerColorEnabled'),
+ uLayerColor: gl.getUniformLocation(prog, 'u_layerColor'),
+ uLayerSubColor: gl.getUniformLocation(prog, 'u_layerSubColor'),
+ uMaskTexture: gl.getUniformLocation(prog, 'u_maskTexture'),
+ uMaskEnabled: gl.getUniformLocation(prog, 'u_maskEnabled'),
+ uExpressionMode: gl.getUniformLocation(prog, 'u_expressionMode'),
+ uMonoThreshold: gl.getUniformLocation(prog, 'u_monoThreshold'),
+ uMonoExpressBlack: gl.getUniformLocation(prog, 'u_monoExpressBlack'),
+ uMonoExpressWhite: gl.getUniformLocation(prog, 'u_monoExpressWhite'),
+ };
+}
+
+export function initTileArrayPool(state: CompositorState, gl: WebGL2RenderingContext): void {
+ if (
+ typeof gl.texStorage3D !== 'function' ||
+ typeof gl.texSubImage3D !== 'function' ||
+ typeof gl.drawArraysInstanced !== 'function' ||
+ typeof gl.vertexAttribDivisor !== 'function' ||
+ !state.quadBuffer
+ ) {
+ return;
+ }
+
+ const instVs = compileShader(gl, gl.VERTEX_SHADER, COMPOSITOR_INSTANCED_VERTEX_SHADER);
+ const instFs = compileShader(gl, gl.FRAGMENT_SHADER, COMPOSITOR_INSTANCED_FRAGMENT_SHADER);
+ if (!instVs || !instFs) return;
+
+ if (
+ !gl.getShaderParameter(instVs, gl.COMPILE_STATUS) ||
+ !gl.getShaderParameter(instFs, gl.COMPILE_STATUS)
+ ) {
+ console.error(
+ 'Instanced tile shader compile error:',
+ gl.getShaderInfoLog(instVs),
+ gl.getShaderInfoLog(instFs)
+ );
+ return;
+ }
+
+ const iProg = linkProgram(gl, instVs, instFs);
+ if (!iProg) return;
+ if (!gl.getProgramParameter(iProg, gl.LINK_STATUS)) {
+ console.error('Instanced tile program link error:', gl.getProgramInfoLog(iProg));
+ return;
+ }
+
+ const maxLayersParam =
+ Number(gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS)) || DEFAULT_ARRAY_POOL_LAYERS;
+ const capacity = Math.max(1, Math.min(DEFAULT_ARRAY_POOL_LAYERS, maxLayersParam));
+
+ const arrTex = gl.createTexture();
+ const instBuf = gl.createBuffer();
+ if (!arrTex || !instBuf) {
+ if (arrTex) gl.deleteTexture(arrTex);
+ if (instBuf) gl.deleteBuffer(instBuf);
+ gl.deleteProgram(iProg);
+ return;
+ }
+
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, arrTex);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, TILE_SIZE, TILE_SIZE, capacity);
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, null);
+
+ state.instanceFloatScratch = new Float32Array(capacity * 3);
+ gl.bindBuffer(gl.ARRAY_BUFFER, instBuf);
+ gl.bufferData(gl.ARRAY_BUFFER, state.instanceFloatScratch.byteLength, gl.DYNAMIC_DRAW);
+
+ state.instancedProgram = iProg;
+ state.instancedLocs = queryLayerUniformLocs(gl, iProg);
+ state.uInstTileSizeLoc = gl.getUniformLocation(iProg, 'u_tileSize');
+ state.uInstTileArrayLoc = gl.getUniformLocation(iProg, 'u_tileArrayTexture');
+ state.aInstQuadPosLoc = gl.getAttribLocation(iProg, 'a_quadPos');
+ state.aInstDataLoc = gl.getAttribLocation(iProg, 'a_instanceData');
+
+ // Immediately bind distinct texture units for sampler2DArray (0) vs sampler2D (1, 2)
+ // to prevent WebGL2 GL_INVALID_OPERATION sampler-type collisions on unit 0.
+ gl.useProgram(iProg);
+ gl.uniform1i(state.uInstTileArrayLoc, 0);
+ gl.uniform1i(state.instancedLocs.uMaskTexture, 1);
+ gl.uniform1i(state.instancedLocs.uBackdropTexture, 2);
+ if (state.program) {
+ gl.useProgram(state.program);
+ }
+
+ state.tileArrayTexture = arrTex;
+ state.instanceBuffer = instBuf;
+ state.arrayPoolCapacity = capacity;
+ state.arrayPoolFilterTier = 1;
+ state.arrayPoolSlots = [];
+ state.freeArraySlots = [];
+ state.arrayPoolByKey.clear();
+ for (let i = 0; i < capacity; i++) {
+ const slot: ArrayPoolSlot = {
+ sliceIndex: i,
+ currentKey: null,
+ version: -1,
+ lastUsed: 0,
+ lastBatchTick: 0,
+ };
+ state.arrayPoolSlots.push(slot);
+ }
+ for (let i = capacity - 1; i >= 0; i--) {
+ state.freeArraySlots.push(state.arrayPoolSlots[i]);
+ }
+
+ if (typeof gl.createVertexArray === 'function') {
+ const vao = gl.createVertexArray();
+ if (vao) {
+ gl.bindVertexArray(vao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.quadBuffer);
+ if (state.aInstQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aInstQuadPosLoc);
+ gl.vertexAttribPointer(state.aInstQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ gl.vertexAttribDivisor(state.aInstQuadPosLoc, 0);
+ }
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.instanceBuffer);
+ if (state.aInstDataLoc >= 0) {
+ gl.enableVertexAttribArray(state.aInstDataLoc);
+ gl.vertexAttribPointer(state.aInstDataLoc, 3, gl.FLOAT, false, 0, 0);
+ gl.vertexAttribDivisor(state.aInstDataLoc, 1);
+ }
+ gl.bindVertexArray(null);
+ state.instancedVao = vao;
+ }
+ }
+}
+
+export function resetGLStateOnContextLost(state: CompositorState): void {
+ state.contextLost = true;
+ state.gl = null;
+ state.program = null;
+ state.instancedProgram = null;
+ state.instancedVao = null;
+ state.instanceBuffer = null;
+ state.tileArrayTexture = null;
+ state.arrayPoolSlots = [];
+ state.freeArraySlots = [];
+ state.arrayPoolByKey.clear();
+ state.arrayPoolCapacity = 0;
+ state.arrayPoolFilterTier = -1;
+ state.viewportDraftProgram = null;
+ state.adjProgram = null;
+ state.stylesProgram = null;
+ state.blitProgram = null;
+ state.framePolyProgram = null;
+ state.framePolyBuffer = null;
+ state.softProofProgram = null;
+ state.texturePool = [];
+ state.activePoolByKey.clear();
+ state.maskTextureCache.clear();
+ state.scenePingPong = null;
+ state.folderPingPongs = [];
+ state.belowActiveCacheFbo = null;
+ state.aboveActiveCacheFbo = null;
+ state.layerStylesOutFbo = null;
+ state.layerFbo = null;
+ state.layerTexture = null;
+ state.lutTexture = null;
+ state.draftTexture = null;
+ state.draftTexWidth = 0;
+ state.draftTexHeight = 0;
+ state.draftHasMipmap = false;
+ state.lastDraftVersion = -1;
+ state.stackCache.invalidateAll();
+}
+
+export function initGL(state: CompositorState): boolean {
+ if (state.gl && state.program) return true;
+
+ try {
+ const gl = state.canvas.getContext('webgl2', {
+ alpha: true,
+ premultipliedAlpha: true,
+ antialias: false,
+ depth: false,
+ stencil: true,
+ preserveDrawingBuffer: state.preserveDrawingBuffer,
+ powerPreference: 'high-performance',
+ });
+
+ if (!gl) return false;
+ state.gl = gl;
+
+ // Compile vertex shader
+ const vs = compileShader(gl, gl.VERTEX_SHADER, COMPOSITOR_VERTEX_SHADER);
+ if (!vs) return false;
+ if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
+ console.error('Compositor VS error:', gl.getShaderInfoLog(vs));
+ return false;
+ }
+
+ // Compile fragment shader
+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, COMPOSITOR_FRAGMENT_SHADER);
+ if (!fs) return false;
+ if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
+ console.error('Compositor FS error:', gl.getShaderInfoLog(fs));
+ return false;
+ }
+
+ // Link standard compositor program
+ const prog = linkProgram(gl, vs, fs);
+ if (!prog) return false;
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
+ console.error('Compositor link error:', gl.getProgramInfoLog(prog));
+ return false;
+ }
+ state.program = prog;
+ state.stdLocs = queryLayerUniformLocs(gl, prog);
+
+ // Cache standard-only uniforms
+ state.uTileOriginLoc = gl.getUniformLocation(prog, 'u_tileOrigin');
+ state.uTileSizeLoc = gl.getUniformLocation(prog, 'u_tileSize');
+ state.uIsBackgroundLoc = gl.getUniformLocation(prog, 'u_isBackground');
+ state.uShowCheckerboardLoc = gl.getUniformLocation(prog, 'u_showCheckerboard');
+ state.uTileTextureLoc = gl.getUniformLocation(prog, 'u_tileTexture');
+ state.aQuadPosLoc = gl.getAttribLocation(prog, 'a_quadPos');
+
+ // Compile Viewport-Space Draft Shader Program (shares COMPOSITOR_FRAGMENT_SHADER)
+ const draftVs = compileShader(gl, gl.VERTEX_SHADER, VIEWPORT_DRAFT_VERTEX_SHADER);
+ if (draftVs && gl.getShaderParameter(draftVs, gl.COMPILE_STATUS)) {
+ const dProg = linkProgram(gl, draftVs, fs);
+ if (dProg && gl.getProgramParameter(dProg, gl.LINK_STATUS)) {
+ state.viewportDraftProgram = dProg;
+ state.viewportDraftLocs = queryLayerUniformLocs(gl, dProg);
+ state.uViewportDraftTileTexLoc = gl.getUniformLocation(dProg, 'u_tileTexture');
+ state.uViewportDraftIsBgLoc = gl.getUniformLocation(dProg, 'u_isBackground');
+ state.aViewportDraftQuadPosLoc = gl.getAttribLocation(dProg, 'a_quadPos');
+ }
+ }
+
+ // Compile Adjustment Shader Program
+ const adjFs = compileShader(gl, gl.FRAGMENT_SHADER, ADJUSTMENT_FRAGMENT_SHADER);
+ if (adjFs) {
+ if (gl.getShaderParameter(adjFs, gl.COMPILE_STATUS)) {
+ const aProg = linkProgram(gl, vs, adjFs);
+ if (aProg && gl.getProgramParameter(aProg, gl.LINK_STATUS)) {
+ state.adjProgram = aProg;
+ state.uAdjTileOriginLoc = gl.getUniformLocation(aProg, 'u_tileOrigin');
+ state.uAdjTileSizeLoc = gl.getUniformLocation(aProg, 'u_tileSize');
+ state.uAdjDocDimensionsLoc = gl.getUniformLocation(aProg, 'u_docDimensions');
+ state.uAdjViewportSizeLoc = gl.getUniformLocation(aProg, 'u_viewportSize');
+ state.uAdjPanLoc = gl.getUniformLocation(aProg, 'u_pan');
+ state.uAdjZoomLoc = gl.getUniformLocation(aProg, 'u_zoom');
+ state.uAdjRotationRadLoc = gl.getUniformLocation(aProg, 'u_rotationRad');
+ state.uAdjFlipLoc = gl.getUniformLocation(aProg, 'u_flip');
+ state.uAdjDprLoc = gl.getUniformLocation(aProg, 'u_dpr');
+ state.uAdjSnapshotLoc = gl.getUniformLocation(aProg, 'u_snapshotTexture');
+ state.uAdjLutLoc = gl.getUniformLocation(aProg, 'u_lutTexture');
+ state.uAdjModeLoc = gl.getUniformLocation(aProg, 'u_adjMode');
+ state.uAdjOpacityLoc = gl.getUniformLocation(aProg, 'u_layerOpacity');
+ state.uAdjMaskEnabledLoc = gl.getUniformLocation(aProg, 'u_maskEnabled');
+ state.uAdjMaskTextureLoc = gl.getUniformLocation(aProg, 'u_maskTexture');
+ }
+ } else {
+ console.error('Adjustment FS error:', gl.getShaderInfoLog(adjFs));
+ }
+ }
+
+ // Compile Layer Styles Shader Program
+ const stylesVs = compileShader(gl, gl.VERTEX_SHADER, LAYER_STYLES_VERTEX_SHADER);
+ const stylesFs = compileShader(gl, gl.FRAGMENT_SHADER, LAYER_STYLES_FRAGMENT_SHADER);
+ if (stylesVs && stylesFs) {
+ if (
+ gl.getShaderParameter(stylesVs, gl.COMPILE_STATUS) &&
+ gl.getShaderParameter(stylesFs, gl.COMPILE_STATUS)
+ ) {
+ const sProg = linkProgram(gl, stylesVs, stylesFs);
+ if (sProg && gl.getProgramParameter(sProg, gl.LINK_STATUS)) {
+ state.stylesProgram = sProg;
+ state.aStylesQuadPosLoc = gl.getAttribLocation(sProg, 'a_quadPos');
+ state.uStylesLayerTextureLoc = gl.getUniformLocation(sProg, 'u_layerTexture');
+ state.uStylesViewportSizeLoc = gl.getUniformLocation(sProg, 'u_viewportSize');
+ state.uStylesLayerOpacityLoc = gl.getUniformLocation(sProg, 'u_layerOpacity');
+ state.uStylesStrokeEnabledLoc = gl.getUniformLocation(sProg, 'u_strokeEnabled');
+ state.uStylesStrokeSizeLoc = gl.getUniformLocation(sProg, 'u_strokeSize');
+ state.uStylesStrokeColorLoc = gl.getUniformLocation(sProg, 'u_strokeColor');
+ state.uStylesStrokePositionLoc = gl.getUniformLocation(sProg, 'u_strokePosition');
+ state.uStylesGlowEnabledLoc = gl.getUniformLocation(sProg, 'u_glowEnabled');
+ state.uStylesGlowColorLoc = gl.getUniformLocation(sProg, 'u_glowColor');
+ state.uStylesGlowBlurLoc = gl.getUniformLocation(sProg, 'u_glowBlur');
+ state.uStylesGlowSpreadLoc = gl.getUniformLocation(sProg, 'u_glowSpread');
+ state.uStylesShadowEnabledLoc = gl.getUniformLocation(sProg, 'u_shadowEnabled');
+ state.uStylesShadowColorLoc = gl.getUniformLocation(sProg, 'u_shadowColor');
+ state.uStylesShadowOffsetLoc = gl.getUniformLocation(sProg, 'u_shadowOffset');
+ state.uStylesShadowBlurLoc = gl.getUniformLocation(sProg, 'u_shadowBlur');
+ state.uStylesShadowSpreadLoc = gl.getUniformLocation(sProg, 'u_shadowSpread');
+ }
+ } else {
+ console.error('Layer Styles shader compile error:', gl.getShaderInfoLog(stylesFs));
+ }
+ }
+
+ // Compile Folder / Cache Blit Shader Program
+ const blitVs = compileShader(gl, gl.VERTEX_SHADER, FOLDER_BLIT_VERTEX_SHADER);
+ const blitFs = compileShader(gl, gl.FRAGMENT_SHADER, FOLDER_BLIT_FRAGMENT_SHADER);
+ if (
+ blitVs &&
+ blitFs &&
+ gl.getShaderParameter(blitVs, gl.COMPILE_STATUS) &&
+ gl.getShaderParameter(blitFs, gl.COMPILE_STATUS)
+ ) {
+ const bProg = linkProgram(gl, blitVs, blitFs);
+ if (bProg && gl.getProgramParameter(bProg, gl.LINK_STATUS)) {
+ state.blitProgram = bProg;
+ state.aBlitQuadPosLoc = gl.getAttribLocation(bProg, 'a_quadPos');
+ state.uBlitTextureLoc = gl.getUniformLocation(bProg, 'u_blitTexture');
+ state.uBlitBackdropTextureLoc = gl.getUniformLocation(bProg, 'u_backdropTexture');
+ state.uBlitHasBackdropLoc = gl.getUniformLocation(bProg, 'u_hasBackdrop');
+ state.uBlitBlendModeLoc = gl.getUniformLocation(bProg, 'u_blendMode');
+ state.uBlitOpacityLoc = gl.getUniformLocation(bProg, 'u_blitOpacity');
+ }
+ }
+
+ // Compile Soft Proof Shader Program
+ const proofVs = compileShader(gl, gl.VERTEX_SHADER, SOFT_PROOF_VERTEX_SHADER);
+ const proofFs = compileShader(gl, gl.FRAGMENT_SHADER, SOFT_PROOF_FRAGMENT_SHADER);
+ if (proofVs && proofFs) {
+ if (
+ gl.getShaderParameter(proofVs, gl.COMPILE_STATUS) &&
+ gl.getShaderParameter(proofFs, gl.COMPILE_STATUS)
+ ) {
+ const pProg = linkProgram(gl, proofVs, proofFs);
+ if (pProg) {
+ if (gl.getProgramParameter(pProg, gl.LINK_STATUS)) {
+ state.softProofProgram = pProg;
+ state.aProofQuadPosLoc = gl.getAttribLocation(pProg, 'a_quadPos');
+ state.uProofSceneTextureLoc = gl.getUniformLocation(pProg, 'u_sceneTexture');
+ state.uProofStandardLoc = gl.getUniformLocation(pProg, 'u_standard');
+ state.uProofEnabledLoc = gl.getUniformLocation(pProg, 'u_proofEnabled');
+ state.uProofGamutWarningLoc = gl.getUniformLocation(pProg, 'u_gamutWarning');
+ state.uProofGamutWarningColorLoc = gl.getUniformLocation(pProg, 'u_gamutWarningColor');
+ } else {
+ console.error('Soft proof link error:', gl.getProgramInfoLog(pProg));
+ }
+ }
+ } else {
+ console.error(
+ 'Soft proof shader compile error:',
+ gl.getShaderInfoLog(proofVs),
+ gl.getShaderInfoLog(proofFs)
+ );
+ }
+ }
+
+ // Compile Frame Border Folder Polygon Program
+ const frameVs = compileShader(gl, gl.VERTEX_SHADER, FRAME_POLY_VERTEX_SHADER);
+ const frameFs = compileShader(gl, gl.FRAGMENT_SHADER, FRAME_POLY_FRAGMENT_SHADER);
+ if (
+ frameVs &&
+ frameFs &&
+ gl.getShaderParameter(frameVs, gl.COMPILE_STATUS) &&
+ gl.getShaderParameter(frameFs, gl.COMPILE_STATUS)
+ ) {
+ const fProg = linkProgram(gl, frameVs, frameFs);
+ if (fProg && gl.getProgramParameter(fProg, gl.LINK_STATUS)) {
+ state.framePolyProgram = fProg;
+ state.aFramePolyDocPosLoc = gl.getAttribLocation(fProg, 'a_docPos');
+ state.uFramePolyDocDimensionsLoc = gl.getUniformLocation(fProg, 'u_docDimensions');
+ state.uFramePolyViewportSizeLoc = gl.getUniformLocation(fProg, 'u_viewportSize');
+ state.uFramePolyPanLoc = gl.getUniformLocation(fProg, 'u_pan');
+ state.uFramePolyZoomLoc = gl.getUniformLocation(fProg, 'u_zoom');
+ state.uFramePolyRotationRadLoc = gl.getUniformLocation(fProg, 'u_rotationRad');
+ state.uFramePolyFlipLoc = gl.getUniformLocation(fProg, 'u_flip');
+ state.uFramePolyDprLoc = gl.getUniformLocation(fProg, 'u_dpr');
+ state.uFramePolyColorLoc = gl.getUniformLocation(fProg, 'u_color');
+ state.framePolyBuffer = gl.createBuffer();
+ }
+ }
+
+ const unitQuadVerts = new Float32Array([
+ 0.0, 0.0,
+ 1.0, 0.0,
+ 0.0, 1.0,
+ 0.0, 1.0,
+ 1.0, 0.0,
+ 1.0, 1.0,
+ ]);
+
+ // Create Layer Styles Quad Buffer [0, 1]
+ const stylesQuad = gl.createBuffer();
+ if (stylesQuad) {
+ gl.bindBuffer(gl.ARRAY_BUFFER, stylesQuad);
+ gl.bufferData(gl.ARRAY_BUFFER, unitQuadVerts, gl.STATIC_DRAW);
+ state.stylesQuadBuffer = stylesQuad;
+ }
+
+ // Create Unit Quad Buffer [0, 1]
+ const quad = gl.createBuffer();
+ if (!quad) return false;
+ gl.bindBuffer(gl.ARRAY_BUFFER, quad);
+ gl.bufferData(gl.ARRAY_BUFFER, unitQuadVerts, gl.STATIC_DRAW);
+ state.quadBuffer = quad;
+
+ // Initialize TEXTURE_2D_ARRAY + instanced batch rendering pipeline
+ initTileArrayPool(state, gl);
+
+ // Enable blending
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ return true;
+ } catch (err) {
+ console.warn('WebGL2 not available for compositor:', err);
+ return false;
+ }
+}
diff --git a/src/utils/compositor/layerRenderer.ts b/src/utils/compositor/layerRenderer.ts
new file mode 100644
index 0000000..fd7f28a
--- /dev/null
+++ b/src/utils/compositor/layerRenderer.ts
@@ -0,0 +1,455 @@
+import { CanvasDimensions, LayerItem } from '../../types/editor';
+import { SparseTileGrid, TILE_SIZE, TileBuffer } from '../tileEngine';
+import { parseHexColor } from './bounds';
+import { blitFolderTexture } from './effectsPass';
+import {
+ createFboSurface,
+ ensureFboSurfaceSize,
+ ensureLayerFbo,
+ prepareBackdropFromPingPong,
+} from './fboManager';
+import { restoreStandardProgram, unbindSceneTextureUnits } from './layerUniforms';
+import { drawVisibleTiles, renderActiveDraftForLayer } from './tileDraw';
+import { getMaskTexture } from './tileTexturePool';
+import {
+ BLEND_MODE_MAP,
+ CompositorState,
+ DocumentBounds,
+ OnionSkinCompositorFrame,
+ PingPongTarget,
+ ViewportTransform,
+} from './types';
+
+/**
+ * Renders all visible tiles of a single layer onto WebGL2 context using:
+ * - TEXTURE_2D_ARRAY + gl.drawArraysInstanced batching when all visible tiles fit in the pool
+ * - Safe per-tile TEXTURE_2D fallback on pool overflow
+ * - Ping-Pong FBO backdrop sampling for custom blend modes (zero gl.copyTexSubImage2D)
+ * - In-stack WYSIWYG live draft stroke compositing
+ */
+export function renderSingleLayer(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ frustum: DocumentBounds,
+ opacityMultiplier: number = 1.0,
+ target: PingPongTarget | null = null,
+ preserveStencil: boolean = false
+): void {
+ if (!state.stdLocs) return;
+
+ // Adaptive LOD Selection & Frustum Culling
+ const targetLod =
+ state.currentZoom <= 0.125 ? 3 :
+ state.currentZoom <= 0.25 ? 2 :
+ state.currentZoom <= 0.5 ? 1 : 0;
+
+ const lodScale = 1 << targetLod;
+ const lodTileDocSize = TILE_SIZE * lodScale;
+
+ const startTileX = Math.floor(frustum.minX / lodTileDocSize);
+ const endTileX = Math.floor(frustum.maxX / lodTileDocSize);
+ const startTileY = Math.floor(frustum.minY / lodTileDocSize);
+ const endTileY = Math.floor(frustum.maxY / lodTileDocSize);
+
+ const visibleTiles: TileBuffer[] = [];
+ const hasLayerTiles =
+ typeof grid.hasLayerTiles === 'function' ? grid.hasLayerTiles(layer.id) : true;
+ const hasOccCheck = typeof grid.hasPopulatedLodTile === 'function';
+
+ if (hasLayerTiles) {
+ for (let ty = startTileY; ty <= endTileY; ty++) {
+ for (let tx = startTileX; tx <= endTileX; tx++) {
+ if (targetLod > 0 && hasOccCheck && !grid.hasPopulatedLodTile(layer.id, tx, ty, targetLod)) {
+ continue;
+ }
+ let tile = grid.getTile(layer.id, tx, ty, targetLod);
+ if (targetLod > 0 && (!tile || tile.data === null || grid.isLodTileDirty(layer.id, tx, ty, targetLod))) {
+ tile = grid.generateLodTile(layer.id, tx, ty, targetLod);
+ }
+ if (tile) {
+ visibleTiles.push(tile);
+ }
+ }
+ }
+ }
+
+ const opts = state.currentOptions;
+ const draftCanvas = opts?.activeDraftLayerId === layer.id ? opts.activeDraftCanvas : null;
+ const hasDraft = Boolean(
+ draftCanvas &&
+ draftCanvas.width > 0 &&
+ draftCanvas.height > 0 &&
+ (draftCanvas as any).__draftHasContent !== false
+ );
+ const draftOp = hasDraft && draftCanvas
+ ? ((draftCanvas as any).__draftCompositeOp as GlobalCompositeOperation | undefined)
+ : undefined;
+ const needsIsolatedDraftFbo =
+ hasDraft &&
+ draftCanvas !== null &&
+ (draftOp === 'destination-out' || draftOp === 'source-atop');
+
+ if (visibleTiles.length === 0 && !hasDraft) {
+ return;
+ }
+
+ const fs = state.currentFrameState;
+ const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
+ const maskTex = hasMask && layer.maskCanvas ? getMaskTexture(state, layer) : null;
+ const effectiveOpacity = layer.opacity * opacityMultiplier;
+
+ // Isolated GPU FBO path for WYSIWYG live Eraser (destination-out) and Alpha Lock (source-atop)
+ // Erases/paints strictly against this layer's tiles without affecting underlying layers and with zero getImageData!
+ if (
+ needsIsolatedDraftFbo &&
+ draftCanvas &&
+ target &&
+ fs &&
+ fs.viewportW > 0 &&
+ fs.viewportH > 0 &&
+ ensureLayerFbo(state, fs.viewportW, fs.viewportH) &&
+ state.layerFbo &&
+ state.layerTexture &&
+ state.blitProgram
+ ) {
+ const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
+ if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
+
+ gl.bindFramebuffer(gl.FRAMEBUFFER, state.layerFbo);
+ gl.viewport(0, 0, fs.viewportW, fs.viewportH);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ if (visibleTiles.length > 0) {
+ drawVisibleTiles(
+ state,
+ gl,
+ visibleTiles,
+ grid,
+ layer,
+ dimensions,
+ lodTileDocSize,
+ 1.0,
+ 0,
+ null,
+ maskTex
+ );
+ }
+
+ if (draftOp === 'destination-out') {
+ gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA);
+ } else {
+ gl.blendFunc(gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
+ }
+
+ renderActiveDraftForLayer(
+ state,
+ gl,
+ draftCanvas,
+ layer,
+ dimensions,
+ opts?.activeDraftOpacity ?? 1.0,
+ 0,
+ null,
+ draftOp === 'destination-out' ? null : maskTex,
+ opts?.activeDraftVersion,
+ opts?.activeDraftSpace ?? 'document',
+ draftOp === 'destination-out'
+ );
+
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, target.surfaces[target.activeIndex].fbo);
+ gl.viewport(0, 0, fs.viewportW, fs.viewportH);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+
+ blitFolderTexture(
+ state,
+ gl,
+ state.layerTexture,
+ layer.blendMode,
+ effectiveOpacity,
+ fs.viewportW,
+ fs.viewportH,
+ target,
+ preserveStencil
+ );
+
+ if (state.stdLocs) {
+ if (maskTex) {
+ gl.uniform1i(state.stdLocs.uMaskEnabled, 0);
+ }
+ gl.uniform1i(state.stdLocs.uHasBackdrop, 0);
+ }
+ unbindSceneTextureUnits(gl);
+ return;
+ }
+
+ // Prepare Ping-Pong backdrop if custom blend mode is active (zero copyTexSubImage2D)
+ const modeCode = BLEND_MODE_MAP[layer.blendMode] ?? 0;
+ let backdropTex: WebGLTexture | null = null;
+ if (modeCode !== 0 && modeCode !== 12 && target && fs && fs.viewportW > 0 && fs.viewportH > 0) {
+ backdropTex = prepareBackdropFromPingPong(
+ state,
+ gl,
+ target,
+ fs.viewportW,
+ fs.viewportH,
+ preserveStencil
+ );
+ }
+
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ if (visibleTiles.length > 0) {
+ drawVisibleTiles(
+ state,
+ gl,
+ visibleTiles,
+ grid,
+ layer,
+ dimensions,
+ lodTileDocSize,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+ }
+
+ // WYSIWYG In-Stack Live Stroke Compositing
+ if (hasDraft && draftCanvas) {
+ if (draftOp === 'destination-out') {
+ gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA);
+ } else if (draftOp === 'source-atop') {
+ gl.blendFunc(gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
+ }
+ renderActiveDraftForLayer(
+ state,
+ gl,
+ draftCanvas,
+ layer,
+ dimensions,
+ effectiveOpacity * (opts?.activeDraftOpacity ?? 1.0),
+ modeCode,
+ backdropTex,
+ draftOp === 'destination-out' ? null : maskTex,
+ opts?.activeDraftVersion,
+ opts?.activeDraftSpace ?? 'document',
+ draftOp === 'destination-out'
+ );
+ if (draftOp === 'destination-out' || draftOp === 'source-atop') {
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+ }
+
+ if (state.stdLocs) {
+ if (maskTex) {
+ gl.uniform1i(state.stdLocs.uMaskEnabled, 0);
+ }
+ gl.uniform1i(state.stdLocs.uHasBackdrop, 0);
+ }
+ unbindSceneTextureUnits(gl);
+}
+
+/**
+ * Evaluates non-destructive GPU layer styles (Stroke, Drop Shadow, Outer Glow)
+ * by rendering the layer into an isolated FBO and processing through LAYER_STYLES_FRAGMENT_SHADER.
+ */
+export function renderLayerWithStyles(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ frustum: DocumentBounds,
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ dpr: number,
+ opacityMultiplier: number = 1.0,
+ target: PingPongTarget | null = null,
+ preserveStencil: boolean = false
+): void {
+ if (!ensureLayerFbo(state, viewportW, viewportH) || !state.stylesProgram) {
+ renderSingleLayer(state, gl, layer, dimensions, grid, frustum, opacityMultiplier, target, preserveStencil);
+ return;
+ }
+
+ const styles = layer.styles;
+ if (!styles) {
+ renderSingleLayer(state, gl, layer, dimensions, grid, frustum, opacityMultiplier, target, preserveStencil);
+ return;
+ }
+
+ let maxStyleMargin = 0;
+ if (styles.stroke?.enabled) {
+ maxStyleMargin = Math.max(maxStyleMargin, styles.stroke.size || 0);
+ }
+ if (styles.dropShadow?.enabled) {
+ maxStyleMargin = Math.max(maxStyleMargin, (styles.dropShadow.distance || 0) + (styles.dropShadow.blur || 0));
+ }
+ if (styles.outerGlow?.enabled) {
+ maxStyleMargin = Math.max(maxStyleMargin, styles.outerGlow.blur || 0);
+ }
+
+ const expandedFrustum = {
+ minX: Math.max(0, frustum.minX - maxStyleMargin),
+ minY: Math.max(0, frustum.minY - maxStyleMargin),
+ maxX: Math.min(dimensions.width, frustum.maxX + maxStyleMargin),
+ maxY: Math.min(dimensions.height, frustum.maxY + maxStyleMargin),
+ };
+
+ // 1. Render layer into isolated FBO with opacity 1.0 (opacity is modulated by stylesProgram)
+ const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
+ if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
+
+ gl.bindFramebuffer(gl.FRAMEBUFFER, state.layerFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ const virtualLayer: LayerItem = { ...layer, opacity: 1.0, blendMode: 'normal' };
+ renderSingleLayer(state, gl, virtualLayer, dimensions, grid, expandedFrustum, 1.0, null, false);
+
+ // 2. Determine whether custom blend mode requires routing styled output through Ping-Pong blit
+ const modeCode = BLEND_MODE_MAP[layer.blendMode] ?? 0;
+ const needsCustomBlend = modeCode !== 0 && modeCode !== 12 && target !== null;
+
+ if (needsCustomBlend) {
+ if (!state.layerStylesOutFbo) {
+ state.layerStylesOutFbo = createFboSurface(gl, false);
+ }
+ if (state.layerStylesOutFbo && ensureFboSurfaceSize(gl, state.layerStylesOutFbo, viewportW, viewportH)) {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, state.layerStylesOutFbo.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.blendFunc(gl.ONE, gl.ZERO);
+ } else {
+ const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+ } else {
+ const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+
+ // 3. Activate styles program and bind uniforms
+ gl.useProgram(state.stylesProgram);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.stylesQuadBuffer);
+ if (state.aStylesQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aStylesQuadPosLoc);
+ gl.vertexAttribPointer(state.aStylesQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, state.layerTexture);
+ gl.uniform1i(state.uStylesLayerTextureLoc, 0);
+
+ gl.uniform2f(state.uStylesViewportSizeLoc, viewportW, viewportH);
+ gl.uniform1f(state.uStylesLayerOpacityLoc, layer.opacity * opacityMultiplier);
+
+ const stroke = styles.stroke;
+ const strokeActive = Boolean(stroke?.enabled && stroke.size > 0 && stroke.opacity > 0);
+ gl.uniform1i(state.uStylesStrokeEnabledLoc, strokeActive ? 1 : 0);
+ if (strokeActive && stroke) {
+ const strokePx = stroke.size * transform.zoom * dpr;
+ gl.uniform1f(state.uStylesStrokeSizeLoc, strokePx);
+ const [sr, sg, sb] = parseHexColor(stroke.color || '#000000');
+ gl.uniform4f(state.uStylesStrokeColorLoc, sr, sg, sb, stroke.opacity);
+ const posCode = stroke.position === 'inside' ? 1 : stroke.position === 'center' ? 2 : 0;
+ gl.uniform1i(state.uStylesStrokePositionLoc, posCode);
+ }
+
+ const glow = styles.outerGlow;
+ const glowActive = Boolean(glow?.enabled && glow.opacity > 0 && glow.blur > 0);
+ gl.uniform1i(state.uStylesGlowEnabledLoc, glowActive ? 1 : 0);
+ if (glowActive && glow) {
+ const glowBlurPx = glow.blur * transform.zoom * dpr;
+ gl.uniform1f(state.uStylesGlowBlurLoc, glowBlurPx);
+ const [gr, gg, gb] = parseHexColor(glow.color || '#ffff00');
+ gl.uniform4f(state.uStylesGlowColorLoc, gr, gg, gb, glow.opacity);
+ gl.uniform1f(state.uStylesGlowSpreadLoc, (glow.spread || 0) / 100);
+ }
+
+ const shadow = styles.dropShadow;
+ const shadowActive = Boolean(shadow?.enabled && shadow.opacity > 0);
+ gl.uniform1i(state.uStylesShadowEnabledLoc, shadowActive ? 1 : 0);
+ if (shadowActive && shadow) {
+ const rad = ((shadow.angle || 0) * Math.PI) / 180;
+ const distPx = (shadow.distance || 0) * transform.zoom * dpr;
+ const dx = Math.cos(rad) * distPx * (transform.flipX ? -1 : 1);
+ const dy = Math.sin(rad) * distPx * (transform.flipY ? -1 : 1);
+ gl.uniform2f(state.uStylesShadowOffsetLoc, dx, -dy);
+ const shadowBlurPx = (shadow.blur || 0) * transform.zoom * dpr;
+ gl.uniform1f(state.uStylesShadowBlurLoc, shadowBlurPx);
+ const [dr, dg, db] = parseHexColor(shadow.color || '#000000');
+ gl.uniform4f(state.uStylesShadowColorLoc, dr, dg, db, shadow.opacity);
+ gl.uniform1f(state.uStylesShadowSpreadLoc, (shadow.spread || 0) / 100);
+ }
+
+ // 4. Draw fullscreen quad
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ // 5. If custom blend mode was routed to layerStylesOutFbo, composite onto parent Ping-Pong target
+ if (needsCustomBlend && state.layerStylesOutFbo && target) {
+ const parentFbo = target.surfaces[target.activeIndex].fbo;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+ blitFolderTexture(
+ state,
+ gl,
+ state.layerStylesOutFbo.texture,
+ layer.blendMode,
+ 1.0,
+ viewportW,
+ viewportH,
+ target,
+ preserveStencil
+ );
+ return;
+ }
+
+ // 6. Restore standard program and quad buffer
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ restoreStandardProgram(state, gl);
+}
+
+export function renderOnionSkins(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ layers: LayerItem[],
+ onionSkinFrames: OnionSkinCompositorFrame[] | undefined,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ frustum: DocumentBounds,
+ target: PingPongTarget | null
+): void {
+ if (!onionSkinFrames || onionSkinFrames.length === 0) return;
+ for (const onion of onionSkinFrames) {
+ const targetLayer = layers.find((l) => l.id === onion.layerId);
+ if (targetLayer && targetLayer.visible) {
+ const virtualOnionLayer: LayerItem = {
+ ...targetLayer,
+ opacity: onion.opacity,
+ layerColorEnabled: true,
+ layerColor: onion.tint,
+ layerSubColor: '#ffffff',
+ blendMode: 'normal',
+ };
+ renderSingleLayer(state, gl, virtualOnionLayer, dimensions, grid, frustum, 1.0, target, false);
+ }
+ }
+}
diff --git a/src/utils/compositor/layerTree.ts b/src/utils/compositor/layerTree.ts
new file mode 100644
index 0000000..9da29f4
--- /dev/null
+++ b/src/utils/compositor/layerTree.ts
@@ -0,0 +1,274 @@
+import { BlendMode, LayerItem, isFolderLikeLayer } from '../../types/editor';
+import {
+ AboveSliceStrategy,
+ CompositingUnit,
+ LayerRenderGroup,
+ LayerStackPartition,
+ LayerTreeNode,
+ TreeNodeRenderGroup,
+} from './types';
+
+export type {
+ LayerTreeNode,
+ TreeNodeRenderGroup,
+ LayerRenderGroup,
+ CompositingUnit,
+ AboveSliceStrategy,
+ LayerStackPartition,
+};
+
+export function buildLayerTree(layers: LayerItem[]): LayerTreeNode[] {
+ const nodeMap = new Map<string, LayerTreeNode>();
+ for (const layer of layers) {
+ nodeMap.set(layer.id, { layer, children: [] });
+ }
+
+ const rootNodes: LayerTreeNode[] = [];
+ for (const layer of layers) {
+ const node = nodeMap.get(layer.id)!;
+ if (layer.parentId && nodeMap.has(layer.parentId)) {
+ nodeMap.get(layer.parentId)!.children.push(node);
+ } else {
+ rootNodes.push(node);
+ }
+ }
+
+ return rootNodes;
+}
+
+export function groupTreeNodesForCompositing(nodesBottomToTop: LayerTreeNode[]): TreeNodeRenderGroup[] {
+ const groups: TreeNodeRenderGroup[] = [];
+ let currentGroup: TreeNodeRenderGroup | null = null;
+
+ for (const node of nodesBottomToTop) {
+ if (node.layer.clipped && currentGroup) {
+ currentGroup.clippedNodes.push(node);
+ } else {
+ currentGroup = {
+ baseNode: node,
+ clippedNodes: [],
+ };
+ groups.push(currentGroup);
+ }
+ }
+
+ return groups;
+}
+
+/**
+ * Groups consecutive clipped layers under their immediate non-clipped base layer underneath.
+ * Layers are provided in bottom-to-top rendering order.
+ */
+export function groupLayersForCompositing(layersBottomToTop: LayerItem[]): LayerRenderGroup[] {
+ const groups: LayerRenderGroup[] = [];
+ let currentGroup: LayerRenderGroup | null = null;
+
+ for (const layer of layersBottomToTop) {
+ if (layer.clipped && currentGroup) {
+ currentGroup.clippedLayers.push(layer);
+ } else {
+ currentGroup = {
+ baseLayer: layer,
+ clippedLayers: [],
+ };
+ groups.push(currentGroup);
+ }
+ }
+
+ return groups;
+}
+
+function collectNodeLayerIds(node: LayerTreeNode, out: Set<string>): void {
+ out.add(node.layer.id);
+ for (const child of node.children) {
+ collectNodeLayerIds(child, out);
+ }
+}
+
+/**
+ * Flattens pass-through folders into a bottom-to-top sequence of atomic compositing units
+ * while keeping isolated folders and clipping-mask groups atomic.
+ */
+export function flattenLayerTreeToUnits(
+ nodes: LayerTreeNode[],
+ inheritedOpacity: number = 1.0
+): CompositingUnit[] {
+ const units: CompositingUnit[] = [];
+ const siblingsBottomToTop = nodes.slice().reverse();
+ const groups = groupTreeNodesForCompositing(siblingsBottomToTop);
+
+ for (const group of groups) {
+ const baseLayer = group.baseNode.layer;
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001) {
+ continue;
+ }
+
+ if (baseLayer.type === 'folder' && baseLayer.blendMode === 'pass-through') {
+ const nested = flattenLayerTreeToUnits(
+ group.baseNode.children,
+ inheritedOpacity * baseLayer.opacity
+ );
+ for (const u of nested) {
+ units.push(u);
+ }
+ continue;
+ }
+
+ const containedLayerIds = new Set<string>();
+ collectNodeLayerIds(group.baseNode, containedLayerIds);
+ for (const cn of group.clippedNodes) {
+ collectNodeLayerIds(cn, containedLayerIds);
+ }
+
+ units.push({
+ group,
+ inheritedOpacity,
+ containedLayerIds,
+ });
+ }
+
+ return units;
+}
+
+/**
+ * Returns true if a compositing unit is strictly Porter-Duff source-over associative
+ * with respect to the backdrop below it (safe to pre-bake onto transparent FBO and composite with 'normal').
+ */
+export function isUnitNormalAssociative(unit: CompositingUnit): boolean {
+ const baseLayer = unit.group.baseNode.layer;
+ if (baseLayer.type === 'adjustment') {
+ return false;
+ }
+ if (baseLayer.type === 'folder' || baseLayer.type === 'frame-folder') {
+ // Pass-through regular folders were flattened; isolated folders and frame-folders
+ // isolate their children's blend modes, so normal/pass-through is normal-associative.
+ return baseLayer.blendMode === 'normal' || baseLayer.blendMode === 'pass-through';
+ }
+ if (baseLayer.blendMode !== 'normal' && baseLayer.blendMode !== 'pass-through') {
+ return false;
+ }
+ for (const cn of unit.group.clippedNodes) {
+ const cl = cn.layer;
+ if (!cl.visible || cl.opacity <= 0.001 || isFolderLikeLayer(cl)) continue;
+ if (cl.blendMode !== 'normal' && cl.blendMode !== 'pass-through') {
+ return false;
+ }
+ }
+ return true;
+}
+
+/**
+ * Returns the blend mode if a single non-associative unit can be baked onto transparent
+ * with 'normal' and composited over (below + active) using a single ping-pong blend pass.
+ */
+export function canSingleUnitBakeWithBlendMode(unit: CompositingUnit): BlendMode | null {
+ const baseLayer = unit.group.baseNode.layer;
+ if (baseLayer.type === 'adjustment') {
+ return null;
+ }
+ if (baseLayer.type === 'folder' || baseLayer.type === 'frame-folder') {
+ if (baseLayer.blendMode !== 'normal' && baseLayer.blendMode !== 'pass-through') {
+ return baseLayer.blendMode;
+ }
+ return null;
+ }
+ const visibleClipped = unit.group.clippedNodes.filter(
+ (cn) => cn.layer.visible && cn.layer.opacity > 0.001 && !isFolderLikeLayer(cn.layer)
+ );
+ if (
+ visibleClipped.length === 0 &&
+ baseLayer.blendMode !== 'normal' &&
+ baseLayer.blendMode !== 'pass-through'
+ ) {
+ return baseLayer.blendMode;
+ }
+ return null;
+}
+
+/**
+ * Partitions the visible layer stack into `below`, `active`, and `above` slices relative to `activeLayerId`.
+ */
+export function partitionLayerStack(
+ layers: LayerItem[],
+ activeLayerId?: string | null
+): LayerStackPartition {
+ const tree = buildLayerTree(layers);
+ const units = flattenLayerTreeToUnits(tree, 1.0);
+
+ let activeIdx = -1;
+ if (activeLayerId) {
+ for (let i = 0; i < units.length; i++) {
+ if (units[i].containedLayerIds.has(activeLayerId)) {
+ activeIdx = i;
+ break;
+ }
+ }
+ }
+
+ if (activeIdx === -1) {
+ return {
+ belowUnits: units,
+ activeUnit: null,
+ aboveDynamicUnits: [],
+ aboveCachedUnits: [],
+ aboveStrategy: 'empty',
+ aboveCacheBlendMode: 'normal',
+ };
+ }
+
+ const belowUnits = units.slice(0, activeIdx);
+ const activeUnit = units[activeIdx];
+ const aboveAll = units.slice(activeIdx + 1);
+
+ if (aboveAll.length === 0) {
+ return {
+ belowUnits,
+ activeUnit,
+ aboveDynamicUnits: [],
+ aboveCachedUnits: [],
+ aboveStrategy: 'empty',
+ aboveCacheBlendMode: 'normal',
+ };
+ }
+
+ let lastNonAssocIdx = -1;
+ for (let i = 0; i < aboveAll.length; i++) {
+ if (!isUnitNormalAssociative(aboveAll[i])) {
+ lastNonAssocIdx = i;
+ }
+ }
+
+ if (lastNonAssocIdx === -1) {
+ return {
+ belowUnits,
+ activeUnit,
+ aboveDynamicUnits: [],
+ aboveCachedUnits: aboveAll,
+ aboveStrategy: 'baked-normal',
+ aboveCacheBlendMode: 'normal',
+ };
+ }
+
+ if (aboveAll.length === 1) {
+ const singleBlend = canSingleUnitBakeWithBlendMode(aboveAll[0]);
+ if (singleBlend) {
+ return {
+ belowUnits,
+ activeUnit,
+ aboveDynamicUnits: [],
+ aboveCachedUnits: aboveAll,
+ aboveStrategy: 'baked-single-blend',
+ aboveCacheBlendMode: singleBlend,
+ };
+ }
+ }
+
+ return {
+ belowUnits,
+ activeUnit,
+ aboveDynamicUnits: aboveAll.slice(0, lastNonAssocIdx + 1),
+ aboveCachedUnits: aboveAll.slice(lastNonAssocIdx + 1),
+ aboveStrategy: 'mixed',
+ aboveCacheBlendMode: 'normal',
+ };
+}
diff --git a/src/utils/compositor/layerUniforms.ts b/src/utils/compositor/layerUniforms.ts
new file mode 100644
index 0000000..52032ed
--- /dev/null
+++ b/src/utils/compositor/layerUniforms.ts
@@ -0,0 +1,171 @@
+import { CanvasDimensions, LayerItem } from '../../types/editor';
+import { parseHexColor } from './bounds';
+import { CompositorState, LayerUniformLocs } from './types';
+
+/**
+ * Unbinds offscreen FBO textures from TEXTURE0 and TEXTURE2 so no texture attached
+ * to the next bound DRAW_FRAMEBUFFER can trigger a WebGL2 feedback loop error.
+ */
+export function unbindSceneTextureUnits(gl: WebGL2RenderingContext): void {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+}
+
+export function restoreStandardProgram(
+ state: CompositorState,
+ gl: WebGL2RenderingContext
+): void {
+ if (state.program) {
+ gl.useProgram(state.program);
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.quadBuffer);
+ if (state.aQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aQuadPosLoc);
+ gl.vertexAttribPointer(state.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+ }
+}
+
+export function syncFrameUniforms(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ locs: LayerUniformLocs
+): void {
+ const fs = state.currentFrameState;
+ if (!fs) return;
+ gl.uniform2f(locs.uViewportSize, fs.viewportW, fs.viewportH);
+ gl.uniform2f(locs.uDocDimensions, fs.dimensions.width, fs.dimensions.height);
+ gl.uniform2f(locs.uPan, fs.transform.pan.x, fs.transform.pan.y);
+ gl.uniform1f(locs.uZoom, fs.transform.zoom);
+ gl.uniform1f(locs.uRotationRad, fs.rotRad);
+ gl.uniform2f(locs.uFlip, fs.transform.flipX ? -1.0 : 1.0, fs.transform.flipY ? -1.0 : 1.0);
+ gl.uniform1f(locs.uDpr, fs.dpr);
+}
+
+export function applyLayerUniforms(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ locs: LayerUniformLocs,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ effectiveOpacity: number,
+ modeCode: number,
+ backdropTex: WebGLTexture | null,
+ maskTex: WebGLTexture | null
+): void {
+ gl.uniform1f(locs.uLayerOpacity, effectiveOpacity);
+ gl.uniform1i(locs.uBlendMode, modeCode);
+
+ // Always bind distinct sampler units (mask = 1, backdrop = 2) so sampler2D never
+ // collides with sampler2DArray on unit 0 in WebGL2.
+ gl.uniform1i(locs.uBackdropTexture, 2);
+ gl.uniform1i(locs.uMaskTexture, 1);
+
+ if (backdropTex && modeCode !== 0 && modeCode !== 12) {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, backdropTex);
+ gl.uniform1i(locs.uHasBackdrop, 1);
+ } else {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.uniform1i(locs.uHasBackdrop, 0);
+ }
+
+ // Expression Color Uniforms
+ const isBgLayer = layer.id === 'layer-bg' || layer.id.startsWith('layer-bg');
+ const docColorMode = state.currentOptions?.colorMode;
+ const exprMode = isBgLayer
+ ? 0
+ : layer.expressionColor === 'monochrome' || docColorMode === 'monochrome'
+ ? 2
+ : layer.expressionColor === 'gray' || docColorMode === 'grayscale'
+ ? 1
+ : 0;
+ gl.uniform1i(locs.uExpressionMode, exprMode);
+ if (exprMode === 2) {
+ gl.uniform1f(locs.uMonoThreshold, (layer.monoThreshold ?? 128) / 255.0);
+ gl.uniform1i(locs.uMonoExpressBlack, layer.monoExpressBlack !== false ? 1 : 0);
+ gl.uniform1i(locs.uMonoExpressWhite, layer.monoExpressWhite !== false ? 1 : 0);
+ }
+
+ // Screentone Uniforms
+ const toneEnabled = Boolean(layer.toneEnabled);
+ gl.uniform1i(locs.uToneEnabled, toneEnabled ? 1 : 0);
+ if (toneEnabled) {
+ gl.uniform1f(locs.uToneFrequency, layer.toneFrequency || 60);
+ gl.uniform1f(locs.uToneAngleRad, ((layer.toneAngle || 45) * Math.PI) / 180);
+ gl.uniform1f(locs.uToneDpi, dimensions.dpi || 600);
+ const dotShapeCode =
+ layer.toneDotShape === 'line'
+ ? 2
+ : layer.toneDotShape === 'diamond'
+ ? 3
+ : layer.toneDotShape === 'euclidean'
+ ? 1
+ : 0;
+ gl.uniform1i(locs.uToneDotShape, dotShapeCode);
+ gl.uniform1f(locs.uToneDensity, (layer.toneDensity ?? 40) / 100);
+ gl.uniform1i(locs.uToneDensityType, layer.toneDensityType === 'image' ? 1 : 0);
+ }
+
+ // Layer Tint Uniforms
+ const tintEnabled = Boolean(layer.layerColorEnabled);
+ gl.uniform1i(locs.uLayerColorEnabled, tintEnabled ? 1 : 0);
+ if (tintEnabled) {
+ const prim = parseHexColor(layer.layerColor || '#1c73c2');
+ const sub = parseHexColor(layer.layerSubColor || '#ffffff');
+ gl.uniform3f(locs.uLayerColor, prim[0], prim[1], prim[2]);
+ gl.uniform3f(locs.uLayerSubColor, sub[0], sub[1], sub[2]);
+ }
+
+ // Layer Mask Uniforms
+ if (maskTex) {
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, maskTex);
+ gl.uniform1i(locs.uMaskEnabled, 1);
+ } else {
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.uniform1i(locs.uMaskEnabled, 0);
+ }
+
+ gl.activeTexture(gl.TEXTURE0);
+}
+
+export function renderArtboardBackground(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ dimensions: CanvasDimensions,
+ showCheckerboard: boolean,
+ drawShadow: boolean = true
+): void {
+ if (!state.program || !state.stdLocs) return;
+ unbindSceneTextureUnits(gl);
+ restoreStandardProgram(state, gl);
+ syncFrameUniforms(state, gl, state.stdLocs);
+ gl.uniform1i(state.uTileTextureLoc, 0);
+ gl.uniform1i(state.stdLocs.uMaskTexture, 1);
+ gl.uniform1i(state.stdLocs.uBackdropTexture, 2);
+ gl.uniform1i(state.stdLocs.uMaskEnabled, 0);
+ gl.uniform1i(state.stdLocs.uHasBackdrop, 0);
+ gl.blendFunc(gl.ONE, drawShadow ? gl.ONE_MINUS_SRC_ALPHA : gl.ZERO);
+ gl.uniform1i(state.uIsBackgroundLoc, 1);
+ gl.uniform1i(state.stdLocs.uExpressionMode, 0);
+ gl.uniform1i(state.uShowCheckerboardLoc, showCheckerboard ? 1 : 0);
+ if (drawShadow) {
+ const marginDoc = 56 / Math.max(0.01, state.currentZoom);
+ gl.uniform2f(state.uTileOriginLoc, -marginDoc, -marginDoc);
+ gl.uniform2f(
+ state.uTileSizeLoc,
+ dimensions.width + marginDoc * 2,
+ dimensions.height + marginDoc * 2
+ );
+ } else {
+ gl.uniform2f(state.uTileOriginLoc, 0, 0);
+ gl.uniform2f(state.uTileSizeLoc, dimensions.width, dimensions.height);
+ }
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ gl.uniform1i(state.uIsBackgroundLoc, 0);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+}
diff --git a/src/utils/compositor/previewRenderer.ts b/src/utils/compositor/previewRenderer.ts
new file mode 100644
index 0000000..87ae2c4
--- /dev/null
+++ b/src/utils/compositor/previewRenderer.ts
@@ -0,0 +1,241 @@
+import { CanvasDimensions, LayerItem, isFolderLikeLayer } from '../../types/editor';
+import { getCanvasCompositeOperation } from '../canvasUtils';
+import { applyMultiFrameClip, renderFrameBorder } from '../frameEngine';
+import { SparseTileGrid, TILE_SIZE, globalTileGrid } from '../tileEngine';
+import { applyAdjustment } from '../tonalEngine';
+import { buildLayerTree, groupTreeNodesForCompositing } from './layerTree';
+import { LayerTreeNode } from './types';
+
+let previewTileCanvas: HTMLCanvasElement | null = null;
+let previewTileImgData: ImageData | null = null;
+let previewScratchCanvas: HTMLCanvasElement | null = null;
+
+/**
+ * Lightweight low-LOD composite preview renderer for Navigator & thumbnails.
+ * Reads directly from SparseTileGrid mipmap LOD tiles (no WebGL context creation, no GPU readPixels stall).
+ */
+export function renderLowResPreview(
+ targetCanvas: HTMLCanvasElement,
+ layers: LayerItem[],
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid = globalTileGrid,
+ options: { showCheckerboard?: boolean } = {}
+): void {
+ if (typeof document === 'undefined') return;
+ const ctx = targetCanvas.getContext('2d');
+ if (!ctx) return;
+
+ const outW = Math.max(1, Math.floor(targetCanvas.width));
+ const outH = Math.max(1, Math.floor(targetCanvas.height));
+ const docW = Math.max(1, dimensions.width);
+ const docH = Math.max(1, dimensions.height);
+
+ // Choose lowest sufficient LOD based on downscale ratio (avoids reading full-res tiles on 4K+ canvases)
+ const ratio = Math.max(docW / outW, docH / outH);
+ const targetLod = ratio >= 7 ? 3 : ratio >= 3.5 ? 2 : ratio >= 1.8 ? 1 : 0;
+ const lodDocSize = TILE_SIZE << targetLod;
+ const scaleX = outW / docW;
+ const scaleY = outH / docH;
+
+ // 1. Background
+ ctx.save();
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.globalAlpha = 1;
+ if (options.showCheckerboard) {
+ const cell = 6;
+ ctx.fillStyle = '#202020';
+ ctx.fillRect(0, 0, outW, outH);
+ ctx.fillStyle = '#2a2a2a';
+ for (let y = 0; y < outH; y += cell) {
+ const offset = ((y / cell) & 1) * cell;
+ for (let x = offset; x < outW; x += cell * 2) {
+ ctx.fillRect(x, y, cell, cell);
+ }
+ }
+ } else {
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, outW, outH);
+ }
+
+ if (!previewTileCanvas) {
+ previewTileCanvas = document.createElement('canvas');
+ previewTileCanvas.width = TILE_SIZE;
+ previewTileCanvas.height = TILE_SIZE;
+ }
+ const tileCanvas = previewTileCanvas;
+ const tileCtx = tileCanvas.getContext('2d', { willReadFrequently: true });
+ if (!tileCtx) {
+ ctx.restore();
+ return;
+ }
+
+ const drawSingleLayer = (
+ dstCtx: CanvasRenderingContext2D,
+ layer: LayerItem,
+ opacityMul: number,
+ compositeOverride?: GlobalCompositeOperation
+ ) => {
+ const alpha = Math.max(0, Math.min(1, layer.opacity * opacityMul));
+ if (alpha <= 0.001) return;
+
+ const tiles = grid.getOrBuildLodTiles(layer.id, targetLod);
+ if (tiles.length === 0) return;
+
+ dstCtx.save();
+ dstCtx.globalAlpha = alpha;
+ dstCtx.globalCompositeOperation = compositeOverride ?? getCanvasCompositeOperation(layer.blendMode);
+ dstCtx.imageSmoothingEnabled = true;
+
+ if (!previewTileImgData) {
+ previewTileImgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
+ }
+ const reusedImgData = previewTileImgData;
+
+ for (const tile of tiles) {
+ const rgba = grid.getTileAsRGBA(tile);
+ reusedImgData.data.set(rgba);
+ tileCtx.putImageData(reusedImgData, 0, 0);
+
+ const dx = tile.tileX * lodDocSize * scaleX;
+ const dy = tile.tileY * lodDocSize * scaleY;
+ const dw = lodDocSize * scaleX;
+ const dh = lodDocSize * scaleY;
+ dstCtx.drawImage(tileCanvas, dx, dy, dw, dh);
+ }
+
+ dstCtx.restore();
+ };
+
+ const renderNodes = (
+ dstCtx: CanvasRenderingContext2D,
+ nodes: LayerTreeNode[],
+ opacityMul: number
+ ) => {
+ const renderOrder = nodes.slice().reverse();
+ const groups = groupTreeNodesForCompositing(renderOrder);
+
+ for (const group of groups) {
+ const baseNode = group.baseNode;
+ const baseLayer = baseNode.layer;
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001) continue;
+
+ if (baseLayer.type === 'frame-folder') {
+ const folderOpacity = opacityMul * baseLayer.opacity;
+ const frames = (baseLayer.comicFrames || []).filter((f) => f.polygon.length >= 3);
+ const shouldClip = frames.length > 0 && frames.some((f) => f.clipChildren !== false);
+ const tmp = document.createElement('canvas');
+ tmp.width = outW;
+ tmp.height = outH;
+ const tmpCtx = tmp.getContext('2d');
+ if (tmpCtx) {
+ const scaledFrames = frames.map((f) => ({
+ ...f,
+ borderWidth: Math.max(1, (f.borderWidth || 3) * Math.min(scaleX, scaleY)),
+ polygon: f.polygon.map((p) => ({ x: p.x * scaleX, y: p.y * scaleY })),
+ }));
+ tmpCtx.save();
+ if (shouldClip) {
+ applyMultiFrameClip(tmpCtx, scaledFrames);
+ }
+ for (const sf of scaledFrames) {
+ if (sf.fillBackground !== false) {
+ tmpCtx.fillStyle = sf.fillColor || '#ffffff';
+ tmpCtx.beginPath();
+ tmpCtx.moveTo(sf.polygon[0].x, sf.polygon[0].y);
+ for (let i = 1; i < sf.polygon.length; i++) {
+ tmpCtx.lineTo(sf.polygon[i].x, sf.polygon[i].y);
+ }
+ tmpCtx.closePath();
+ tmpCtx.fill();
+ }
+ }
+ if (baseNode.children.length > 0) {
+ renderNodes(tmpCtx, baseNode.children, 1.0);
+ }
+ tmpCtx.restore();
+ for (const sf of scaledFrames) {
+ renderFrameBorder(tmpCtx, sf, false);
+ }
+ dstCtx.save();
+ dstCtx.globalAlpha = Math.max(0, Math.min(1, folderOpacity));
+ const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;
+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);
+ dstCtx.drawImage(tmp, 0, 0);
+ dstCtx.restore();
+ }
+ continue;
+ }
+
+ if (baseLayer.type === 'folder') {
+ const folderOpacity = opacityMul * baseLayer.opacity;
+ if (baseLayer.blendMode === 'pass-through') {
+ if (baseNode.children.length > 0) {
+ renderNodes(dstCtx, baseNode.children, folderOpacity);
+ }
+ } else {
+ const tmp = document.createElement('canvas');
+ tmp.width = outW;
+ tmp.height = outH;
+ const tmpCtx = tmp.getContext('2d');
+ if (tmpCtx) {
+ if (baseNode.children.length > 0) {
+ renderNodes(tmpCtx, baseNode.children, 1.0);
+ }
+ dstCtx.save();
+ dstCtx.globalAlpha = Math.max(0, Math.min(1, folderOpacity));
+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ dstCtx.drawImage(tmp, 0, 0);
+ dstCtx.restore();
+ }
+ }
+ continue;
+ }
+
+ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
+ try {
+ const imgData = dstCtx.getImageData(0, 0, outW, outH);
+ applyAdjustment(imgData, baseLayer.adjustmentData, undefined, baseLayer.opacity * opacityMul);
+ dstCtx.putImageData(imgData, 0, 0);
+ } catch {
+ // Ignore in headless/mock contexts without getImageData
+ }
+ continue;
+ }
+
+ const activeClipped = group.clippedNodes.filter(
+ (cn) => cn.layer.visible && cn.layer.opacity > 0.001 && !isFolderLikeLayer(cn.layer)
+ );
+
+ if (activeClipped.length === 0) {
+ drawSingleLayer(dstCtx, baseLayer, opacityMul);
+ } else {
+ if (!previewScratchCanvas) {
+ previewScratchCanvas = document.createElement('canvas');
+ }
+ const grpCanvas = previewScratchCanvas;
+ if (grpCanvas.width !== outW) grpCanvas.width = outW;
+ if (grpCanvas.height !== outH) grpCanvas.height = outH;
+ const grpCtx = grpCanvas.getContext('2d');
+ if (!grpCtx) {
+ drawSingleLayer(dstCtx, baseLayer, opacityMul);
+ continue;
+ }
+ grpCtx.clearRect(0, 0, outW, outH);
+ drawSingleLayer(grpCtx, baseLayer, 1.0, 'source-over');
+ for (const cn of activeClipped) {
+ drawSingleLayer(grpCtx, cn.layer, 1.0, 'source-atop');
+ }
+ dstCtx.save();
+ dstCtx.globalAlpha = Math.max(0, Math.min(1, opacityMul));
+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ dstCtx.drawImage(grpCanvas, 0, 0);
+ dstCtx.restore();
+ }
+ }
+ };
+
+ const tree = buildLayerTree(layers);
+ renderNodes(ctx, tree, 1.0);
+ ctx.restore();
+}
diff --git a/src/utils/compositor/renderFrame.ts b/src/utils/compositor/renderFrame.ts
new file mode 100644
index 0000000..2b2a9b7
--- /dev/null
+++ b/src/utils/compositor/renderFrame.ts
@@ -0,0 +1,401 @@
+import { BlendMode, CanvasDimensions, LayerItem } from '../../types/editor';
+import { SparseTileGrid, globalTileGrid } from '../tileEngine';
+import { calculateVisibleDocumentBounds } from './bounds';
+import { blitFolderTexture, presentTextureToScreen } from './effectsPass';
+import { render2DFallback } from './fallback2d';
+import {
+ copyFboSurface,
+ createFboSurface,
+ ensureFboSurfaceSize,
+ ensurePingPongTarget,
+} from './fboManager';
+import { renderOnionSkins } from './layerRenderer';
+import { buildLayerTree } from './layerTree';
+import {
+ renderArtboardBackground,
+ restoreStandardProgram,
+ syncFrameUniforms,
+} from './layerUniforms';
+import { evictStaleTextures } from './tileTexturePool';
+import {
+ CompositorOptions,
+ CompositorState,
+ MAX_TEXTURE_POOL_SIZE,
+ ViewportTransform,
+} from './types';
+import { renderCompositingUnit, renderNodeList } from './unitRenderer';
+
+/**
+ * Main Render Pass: Composite all visible layers onto the viewport canvas using:
+ * 1. Ping-Pong FBOs (zero gl.copyTexSubImage2D calls for all 16 blend modes, adjustments, & soft proof)
+ * 2. Baked Layer Stack Cache (`belowActiveCacheFbo` + `activeUnit` + `aboveActiveCacheFbo`)
+ * 3. TEXTURE_2D_ARRAY + gl.drawArraysInstanced tile batching
+ */
+export function renderFrame(
+ state: CompositorState,
+ layers: LayerItem[],
+ transform: ViewportTransform,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid = globalTileGrid,
+ _options: CompositorOptions = { dimensions }
+): void {
+ state.lastRenderedGrid = grid;
+ const gl = state.gl;
+ state.currentOptions = _options;
+ state.currentZoom = transform.zoom;
+
+ if (!gl || !state.program || !state.stdLocs) {
+ render2DFallback(state, layers, transform, dimensions, grid, _options);
+ return;
+ }
+
+ const viewportW = Math.max(1, state.canvas.width);
+ const viewportH = Math.max(1, state.canvas.height);
+ const dpr = _options.devicePixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
+ const rotRad = (transform.rotation * Math.PI) / 180;
+
+ state.currentFrameState = {
+ viewportW,
+ viewportH,
+ dpr,
+ dimensions,
+ transform,
+ rotRad,
+ };
+
+ // Calculate Frustum Culling document bounds
+ const viewportCssW = viewportW / dpr;
+ const viewportCssH = viewportH / dpr;
+ const frustum = calculateVisibleDocumentBounds(
+ viewportCssW,
+ viewportCssH,
+ transform,
+ dimensions.width,
+ dimensions.height
+ );
+
+ // Dynamic Frustum Culling & Memory Budget Sync
+ const activeLayerId = _options.activeLayerId ?? _options.activeDraftLayerId ?? null;
+ const layerVis = new Map<string, boolean>();
+ for (const l of layers) {
+ layerVis.set(l.id, l.visible);
+ }
+ grid.getMemoryManager()?.updateViewport(frustum, activeLayerId, layerVis);
+
+ // Ensure Ping-Pong Scene FBOs & Baked Layer Stack Cache FBOs
+ const scenePP = ensurePingPongTarget(gl, state.scenePingPong, viewportW, viewportH);
+ state.scenePingPong = scenePP;
+
+ const bypassStackCache = Boolean(_options.bypassStackCache);
+ let belowCacheReady = false;
+ let aboveCacheReady = false;
+ if (scenePP && !bypassStackCache) {
+ if (!state.belowActiveCacheFbo) {
+ state.belowActiveCacheFbo = createFboSurface(gl, false);
+ }
+ if (state.belowActiveCacheFbo) {
+ belowCacheReady = ensureFboSurfaceSize(gl, state.belowActiveCacheFbo, viewportW, viewportH);
+ }
+ if (!state.aboveActiveCacheFbo) {
+ state.aboveActiveCacheFbo = createFboSurface(gl, false);
+ }
+ if (state.aboveActiveCacheFbo) {
+ aboveCacheReady = ensureFboSurfaceSize(gl, state.aboveActiveCacheFbo, viewportW, viewportH);
+ }
+ }
+
+ if (bypassStackCache && scenePP) {
+ restoreStandardProgram(state, gl);
+ syncFrameUniforms(state, gl, state.stdLocs);
+ gl.uniform1i(state.uTileTextureLoc, 0);
+ gl.uniform1i(state.stdLocs.uHasBackdrop, 0);
+
+ scenePP.activeIndex = 0;
+ const surf = scenePP.surfaces[0];
+ gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ if (!_options.transparentBackground) {
+ renderArtboardBackground(state, gl, dimensions, Boolean(_options.showCheckerboard), false);
+ }
+ renderOnionSkins(state, gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, scenePP);
+
+ const tree = buildLayerTree(layers);
+ renderNodeList(
+ state,
+ gl,
+ tree,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ 1.0
+ );
+
+ presentTextureToScreen(
+ state,
+ gl,
+ scenePP.surfaces[scenePP.activeIndex].texture,
+ viewportW,
+ viewportH,
+ _options.softProof
+ );
+ } else if (
+ scenePP &&
+ belowCacheReady &&
+ aboveCacheReady &&
+ state.belowActiveCacheFbo &&
+ state.aboveActiveCacheFbo
+ ) {
+ // Evaluate Baked Layer Stack Cache invalidation (below / active / above)
+ const cacheEval = state.stackCache.evaluate({
+ layers,
+ activeLayerId,
+ viewportW,
+ viewportH,
+ dpr,
+ dimensions,
+ transform,
+ showCheckerboard: Boolean(_options.showCheckerboard),
+ transparentBackground: Boolean(_options.transparentBackground),
+ colorMode: _options.colorMode,
+ onionSkinFrames: _options.onionSkinFrames,
+ getLayerContentVersion: (id) =>
+ typeof grid.getLayerVersion === 'function' ? grid.getLayerVersion(id) : 0,
+ getMaskInvalidationEpoch: (id) => state.maskInvalidationEpochs.get(id) ?? 0,
+ gridEpoch: typeof grid.getGridEpoch === 'function' ? grid.getGridEpoch() : 0,
+ gridId: typeof grid.getGridId === 'function' ? grid.getGridId() : 0,
+ });
+
+ const { partition } = cacheEval;
+ restoreStandardProgram(state, gl);
+ syncFrameUniforms(state, gl, state.stdLocs);
+ gl.uniform1i(state.uTileTextureLoc, 0);
+ gl.uniform1i(state.stdLocs.uHasBackdrop, 0);
+
+ // Step 1: Rebuild aboveActiveCacheFbo ONLY when upper slice metadata/content/camera changed
+ if (cacheEval.aboveDirty && partition.aboveCachedUnits.length > 0) {
+ scenePP.activeIndex = 0;
+ const surf = scenePP.surfaces[0];
+ gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ const overrideRootBlend = partition.aboveStrategy === 'baked-single-blend';
+ for (const unit of partition.aboveCachedUnits) {
+ renderCompositingUnit(
+ state,
+ gl,
+ unit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ overrideRootBlend
+ );
+ }
+
+ copyFboSurface(
+ state,
+ gl,
+ scenePP.surfaces[scenePP.activeIndex],
+ state.aboveActiveCacheFbo,
+ viewportW,
+ viewportH,
+ false
+ );
+ state.stackCacheStats.aboveRebuilds++;
+ }
+
+ // Step 2: Populate scenePP with below slice (either rebuild belowActiveCacheFbo or fast GPU blit)
+ if (cacheEval.belowDirty) {
+ scenePP.activeIndex = 0;
+ const surf = scenePP.surfaces[0];
+ gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ if (!_options.transparentBackground) {
+ renderArtboardBackground(state, gl, dimensions, Boolean(_options.showCheckerboard));
+ }
+ renderOnionSkins(state, gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, scenePP);
+
+ for (const unit of partition.belowUnits) {
+ renderCompositingUnit(
+ state,
+ gl,
+ unit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ false
+ );
+ }
+
+ copyFboSurface(
+ state,
+ gl,
+ scenePP.surfaces[scenePP.activeIndex],
+ state.belowActiveCacheFbo,
+ viewportW,
+ viewportH,
+ false
+ );
+ // Ensure scenePP's current surface remains bound for activeUnit
+ gl.bindFramebuffer(gl.FRAMEBUFFER, scenePP.surfaces[scenePP.activeIndex].fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ state.stackCacheStats.belowRebuilds++;
+ } else {
+ scenePP.activeIndex = 0;
+ copyFboSurface(
+ state,
+ gl,
+ state.belowActiveCacheFbo,
+ scenePP.surfaces[0],
+ viewportW,
+ viewportH,
+ false
+ );
+ if (!cacheEval.aboveDirty) {
+ state.stackCacheStats.cacheHits++;
+ }
+ }
+
+ // Step 3: Render active unit (+ live activeDraftCanvas in-stack!)
+ if (partition.activeUnit) {
+ renderCompositingUnit(
+ state,
+ gl,
+ partition.activeUnit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ false
+ );
+ }
+
+ // Step 4: Render any dynamic non-associative upper units (via Ping-Pong FBOs, zero copyTexSubImage2D)
+ for (const unit of partition.aboveDynamicUnits) {
+ renderCompositingUnit(
+ state,
+ gl,
+ unit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ false
+ );
+ }
+
+ // Step 5: Composite baked aboveActiveCacheFbo (1 single quad / 1 ping-pong blend pass)
+ if (partition.aboveCachedUnits.length > 0) {
+ const aboveBlend: BlendMode =
+ partition.aboveStrategy === 'baked-single-blend'
+ ? partition.aboveCacheBlendMode
+ : 'normal';
+ blitFolderTexture(
+ state,
+ gl,
+ state.aboveActiveCacheFbo.texture,
+ aboveBlend,
+ 1.0,
+ viewportW,
+ viewportH,
+ scenePP,
+ false
+ );
+ }
+
+ state.stackCache.commit(cacheEval.belowSignature, cacheEval.aboveSignature);
+
+ // Step 6: Present final composited Ping-Pong surface to screen (with optional CMYK soft proofing)
+ presentTextureToScreen(
+ state,
+ gl,
+ scenePP.surfaces[scenePP.activeIndex].texture,
+ viewportW,
+ viewportH,
+ _options.softProof
+ );
+ } else {
+ // Safe fallback when offscreen FBOs are unsupported in a minimal WebGL context
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ if (!_options.transparentBackground) {
+ renderArtboardBackground(state, gl, dimensions, Boolean(_options.showCheckerboard), false);
+ }
+ renderOnionSkins(state, gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, null);
+
+ const tree = buildLayerTree(layers);
+ renderNodeList(
+ state,
+ gl,
+ tree,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ null,
+ 0,
+ 1.0
+ );
+ }
+
+ // Prune mask textures belonging to deleted layers
+ if (state.maskTextureCache.size > layers.length) {
+ for (const cachedLayerId of Array.from(state.maskTextureCache.keys())) {
+ if (!layerVis.has(cachedLayerId)) {
+ const entry = state.maskTextureCache.get(cachedLayerId);
+ if (entry) gl.deleteTexture(entry.texture);
+ state.maskTextureCache.delete(cachedLayerId);
+ state.maskInvalidationEpochs.delete(cachedLayerId);
+ }
+ }
+ }
+
+ // Clean up stale textures if fallback pool exceeded limit
+ if (state.texturePool.length > MAX_TEXTURE_POOL_SIZE) {
+ evictStaleTextures(state);
+ }
+}
diff --git a/src/utils/compositor/shaders/blendModesGlsl.ts b/src/utils/compositor/shaders/blendModesGlsl.ts
new file mode 100644
index 0000000..a8d5dbb
--- /dev/null
+++ b/src/utils/compositor/shaders/blendModesGlsl.ts
@@ -0,0 +1,102 @@
+/**
+ * Shared GLSL ES 3.00 blend mode routines for all WebGL2 compositor fragment shaders.
+ * Implements all 28 Ink Studio / Photoshop / CSP blend modes (codes 0..27):
+ * 0: normal 10: difference 20: hard-mix
+ * 1: multiply 11: exclusion 21: subtract
+ * 2: screen 12: pass-through 22: darker-color
+ * 3: overlay 13: linear-burn 23: lighter-color
+ * 4: darken 14: add-glow 24: hue
+ * 5: lighten 15: color-dodge-glow 25: saturation
+ * 6: color-dodge 16: divide 26: color
+ * 7: color-burn 17: vivid-light 27: luminosity
+ * 8: hard-light 18: linear-light
+ * 9: soft-light 19: pin-light
+ */
+export function buildBlendModeGlsl(suffix: string = ''): string {
+ return `
+float blendLum${suffix}(vec3 c) {
+ return 0.3 * c.r + 0.59 * c.g + 0.11 * c.b;
+}
+
+vec3 clipColor${suffix}(vec3 c) {
+ float l = clamp(blendLum${suffix}(c), 0.0, 1.0);
+ float n = min(min(c.r, c.g), c.b);
+ float x = max(max(c.r, c.g), c.b);
+ if (n < 0.0) {
+ c = l + ((c - l) * l) / max(0.0001, l - n);
+ }
+ if (x > 1.0) {
+ c = l + ((c - l) * (1.0 - l)) / max(0.0001, x - l);
+ }
+ return clamp(c, 0.0, 1.0);
+}
+
+vec3 setLum${suffix}(vec3 c, float l) {
+ float d = l - blendLum${suffix}(c);
+ return clipColor${suffix}(c + vec3(d));
+}
+
+float blendSat${suffix}(vec3 c) {
+ return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b);
+}
+
+vec3 setSat${suffix}(vec3 c, float s) {
+ float cMin = min(min(c.r, c.g), c.b);
+ float cMax = max(max(c.r, c.g), c.b);
+ float delta = cMax - cMin;
+ if (delta <= 0.0001) {
+ return vec3(0.0);
+ }
+ return ((c - cMin) * s) / delta;
+}
+
+float blendChannel${suffix}(float b, float s, int mode) {
+ if (mode == 1) return b * s; // multiply
+ if (mode == 2) return b + s - b * s; // screen
+ if (mode == 3) return b < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // overlay
+ if (mode == 4) return min(b, s); // darken
+ if (mode == 5) return max(b, s); // lighten
+ if (mode == 6) return b <= 0.0 ? 0.0 : (s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s))); // color-dodge
+ if (mode == 7) return b >= 1.0 ? 1.0 : (s <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - b) / max(0.0001, s))); // color-burn
+ if (mode == 8) return s < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // hard-light
+ if (mode == 9) { // soft-light (W3C / Photoshop)
+ float d = b <= 0.25 ? (((16.0 * b - 12.0) * b + 4.0) * b) : sqrt(max(0.0, b));
+ return s <= 0.5 ? (b - (1.0 - 2.0 * s) * b * (1.0 - b)) : (b + (2.0 * s - 1.0) * (d - b));
+ }
+ if (mode == 10) return abs(b - s); // difference
+ if (mode == 11) return b + s - 2.0 * b * s; // exclusion
+ if (mode == 13) return max(0.0, b + s - 1.0); // linear-burn
+ if (mode == 14) return min(1.0, b + s); // add-glow
+ if (mode == 15) return s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s)); // color-dodge-glow
+ if (mode == 16) return s <= 0.0001 ? 1.0 : clamp(b / s, 0.0, 1.0); // divide
+ if (mode == 17) { // vivid-light
+ if (s <= 0.5) {
+ float s2 = 2.0 * s;
+ return s2 <= 0.0 ? 0.0 : (b >= 1.0 ? 1.0 : 1.0 - min(1.0, (1.0 - b) / max(0.0001, s2)));
+ } else {
+ float s2 = 2.0 * (s - 0.5);
+ return s2 >= 1.0 ? 1.0 : (b <= 0.0 ? 0.0 : min(1.0, b / max(0.0001, 1.0 - s2)));
+ }
+ }
+ if (mode == 18) return clamp(b + 2.0 * s - 1.0, 0.0, 1.0); // linear-light
+ if (mode == 19) return s <= 0.5 ? min(b, 2.0 * s) : max(b, 2.0 * (s - 0.5)); // pin-light
+ if (mode == 20) return step(1.0, b + s); // hard-mix
+ if (mode == 21) return max(0.0, b - s); // subtract
+ return s;
+}
+
+vec3 evaluateBlendMode${suffix}(vec3 Cb, vec3 Cs, int mode) {
+ if (mode == 22) return blendLum${suffix}(Cs) < blendLum${suffix}(Cb) ? Cs : Cb; // darker-color
+ if (mode == 23) return blendLum${suffix}(Cs) > blendLum${suffix}(Cb) ? Cs : Cb; // lighter-color
+ if (mode == 24) return setLum${suffix}(setSat${suffix}(Cs, blendSat${suffix}(Cb)), blendLum${suffix}(Cb)); // hue
+ if (mode == 25) return setLum${suffix}(setSat${suffix}(Cb, blendSat${suffix}(Cs)), blendLum${suffix}(Cb)); // saturation
+ if (mode == 26) return setLum${suffix}(Cs, blendLum${suffix}(Cb)); // color
+ if (mode == 27) return setLum${suffix}(Cb, blendLum${suffix}(Cs)); // luminosity
+ return vec3(
+ blendChannel${suffix}(Cb.r, Cs.r, mode),
+ blendChannel${suffix}(Cb.g, Cs.g, mode),
+ blendChannel${suffix}(Cb.b, Cs.b, mode)
+ );
+}
+`;
+}
diff --git a/src/utils/compositor/shaders/coreShaders.ts b/src/utils/compositor/shaders/coreShaders.ts
new file mode 100644
index 0000000..26a7798
--- /dev/null
+++ b/src/utils/compositor/shaders/coreShaders.ts
@@ -0,0 +1,382 @@
+import { buildBlendModeGlsl } from './blendModesGlsl';
+
+// Document-Space Solid Polygon Shaders for Frame Border Folder Stencil Clipping & Borders
+export const FRAME_POLY_VERTEX_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 a_docPos;
+uniform vec2 u_docDimensions;
+uniform vec2 u_viewportSize;
+uniform vec2 u_pan;
+uniform float u_zoom;
+uniform float u_rotationRad;
+uniform vec2 u_flip;
+uniform float u_dpr;
+
+void main() {
+ vec2 centered = (a_docPos - u_docDimensions * 0.5) * u_flip;
+ float cosR = cos(u_rotationRad);
+ float sinR = sin(u_rotationRad);
+ vec2 rotated = vec2(
+ centered.x * cosR - centered.y * sinR,
+ centered.x * sinR + centered.y * cosR
+ );
+ vec2 screenPos = (u_pan + rotated * u_zoom) * u_dpr;
+ vec2 clipPos = vec2(
+ (2.0 * screenPos.x / u_viewportSize.x) - 1.0,
+ 1.0 - (2.0 * screenPos.y / u_viewportSize.y)
+ );
+ gl_Position = vec4(clipPos, 0.0, 1.0);
+}
+`;
+
+export const FRAME_POLY_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+uniform vec4 u_color;
+out vec4 fragColor;
+
+void main() {
+ fragColor = vec4(u_color.rgb * u_color.a, u_color.a);
+}
+`;
+
+// Fullscreen blit for isolated folder compositing
+export const FOLDER_BLIT_VERTEX_SHADER = `#version 300 es
+precision highp float;
+in vec2 a_quadPos; // [0, 1] x [0, 1]
+out vec2 v_uv;
+void main() {
+ v_uv = a_quadPos;
+ gl_Position = vec4(a_quadPos.x * 2.0 - 1.0, a_quadPos.y * 2.0 - 1.0, 0.0, 1.0);
+}
+`;
+
+export const FOLDER_BLIT_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+in vec2 v_uv;
+uniform sampler2D u_blitTexture;
+uniform sampler2D u_backdropTexture;
+uniform int u_hasBackdrop;
+uniform int u_blendMode;
+uniform float u_blitOpacity;
+out vec4 fragColor;
+
+${buildBlendModeGlsl('Folder')}
+
+void main() {
+ vec4 srcPremul = texture(u_blitTexture, v_uv);
+ float srcA = srcPremul.a * u_blitOpacity;
+ if (srcA < 0.002) {
+ discard;
+ }
+ vec3 Cs = srcPremul.a > 0.001 ? clamp(srcPremul.rgb / srcPremul.a, 0.0, 1.0) : vec3(0.0);
+ if (u_hasBackdrop == 1 && u_blendMode != 0 && u_blendMode != 12) {
+ vec4 dstPremul = texture(u_backdropTexture, v_uv);
+ vec3 Cb = dstPremul.a > 0.001 ? clamp(dstPremul.rgb / dstPremul.a, 0.0, 1.0) : vec3(1.0);
+ vec3 blended = evaluateBlendModeFolder(Cb, Cs, u_blendMode);
+ Cs = mix(Cs, blended, dstPremul.a);
+ }
+ fragColor = vec4(Cs * srcA, srcA);
+}
+`;
+
+// Vertex Shader: Affine transformation in document space mapped to WebGL clip space
+export const COMPOSITOR_VERTEX_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 a_quadPos; // [0, 1] x [0, 1]
+uniform vec2 u_tileOrigin; // tile position in document space
+uniform vec2 u_tileSize; // tile or quad size in document space
+uniform vec2 u_docDimensions; // canvas width, height
+uniform vec2 u_viewportSize; // viewport width, height
+uniform vec2 u_pan;
+uniform float u_zoom;
+uniform float u_rotationRad;
+uniform vec2 u_flip;
+uniform float u_dpr;
+
+out vec2 v_texCoord;
+out vec2 v_docCoord;
+
+void main() {
+ v_texCoord = a_quadPos;
+
+ // Position within document space
+ vec2 docPos = u_tileOrigin + a_quadPos * u_tileSize;
+ v_docCoord = docPos;
+
+ // Center document around (0, 0) and apply non-destructive view flip
+ vec2 centered = (docPos - u_docDimensions * 0.5) * u_flip;
+
+ // Rotate
+ float cosR = cos(u_rotationRad);
+ float sinR = sin(u_rotationRad);
+ vec2 rotated = vec2(
+ centered.x * cosR - centered.y * sinR,
+ centered.x * sinR + centered.y * cosR
+ );
+
+ // Scale and translate: convert CSS screen coordinates to physical device pixels
+ vec2 screenPos = (u_pan + rotated * u_zoom) * u_dpr;
+
+ // Convert physical device pixels to WebGL clip coordinates [-1, 1]
+ vec2 clipPos = vec2(
+ (2.0 * screenPos.x / u_viewportSize.x) - 1.0,
+ 1.0 - (2.0 * screenPos.y / u_viewportSize.y)
+ );
+
+ gl_Position = vec4(clipPos, 0.0, 1.0);
+}
+`;
+
+// Fragment Shader: Layer Blending, Screentones with Anti-Moiré, and Layer Color Tinting
+export const COMPOSITOR_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+in vec2 v_docCoord;
+
+uniform sampler2D u_tileTexture;
+uniform sampler2D u_backdropTexture;
+uniform int u_hasBackdrop;
+uniform vec2 u_viewportSize;
+uniform float u_layerOpacity;
+uniform int u_blendMode;
+
+// Background Uniforms
+uniform int u_isBackground;
+uniform int u_showCheckerboard;
+
+// Screentone Uniforms
+uniform int u_toneEnabled;
+uniform float u_toneFrequency;
+uniform float u_toneAngleRad;
+uniform float u_toneDpi;
+uniform int u_toneDotShape;
+uniform float u_toneDensity;
+uniform int u_toneDensityType;
+uniform float u_zoom;
+
+// Layer Tint Uniforms
+uniform int u_layerColorEnabled;
+uniform vec3 u_layerColor;
+uniform vec3 u_layerSubColor;
+
+// Layer Mask Uniforms
+uniform vec2 u_docDimensions;
+uniform sampler2D u_maskTexture;
+uniform int u_maskEnabled;
+
+// CSP Expression Color Uniforms (0: color, 1: gray, 2: monochrome)
+uniform int u_expressionMode;
+uniform float u_monoThreshold;
+uniform int u_monoExpressBlack;
+uniform int u_monoExpressWhite;
+
+out vec4 fragColor;
+
+float fractVal(float x) {
+ return x - floor(x);
+}
+
+${buildBlendModeGlsl()}
+
+vec4 evaluateScreentone(vec4 srcColor, vec2 docCoord) {
+ if (srcColor.a < 0.0039) {
+ return vec4(0.0);
+ }
+
+ float density;
+ if (u_toneDensityType == 0) {
+ // Specified density
+ density = clamp(u_toneDensity * srcColor.a, 0.0, 1.0);
+ } else {
+ // Luminance
+ float lum = dot(srcColor.rgb, vec3(0.299, 0.587, 0.114));
+ density = clamp((1.0 - lum) * srcColor.a, 0.0, 1.0);
+ }
+
+ if (density <= 0.001) return vec4(0.0);
+ if (density >= 0.999) return vec4(0.0, 0.0, 0.0, 1.0);
+
+ float cellSize = max(3.5, u_toneDpi / max(1.0, u_toneFrequency));
+ float cosA = cos(u_toneAngleRad);
+ float sinA = sin(u_toneAngleRad);
+
+ float xr = docCoord.x * cosA - docCoord.y * sinA;
+ float yr = docCoord.x * sinA + docCoord.y * cosA;
+
+ float u = fractVal(xr / cellSize) - 0.5;
+ float v = fractVal(yr / cellSize) - 0.5;
+
+ float spot;
+ if (u_toneDotShape == 2) {
+ // Line
+ spot = 1.0 - 2.0 * abs(u);
+ } else if (u_toneDotShape == 3) {
+ // Diamond
+ spot = 1.0 - (abs(u) + abs(v));
+ } else {
+ // Euclidean circle
+ float absU = abs(u);
+ float absV = abs(v);
+ if (absU + absV <= 0.5) {
+ spot = 1.0 - 2.0 * (u * u + v * v);
+ } else {
+ float uc = absU - 0.5;
+ float vc = absV - 0.5;
+ spot = 2.0 * (uc * uc + vc * vc);
+ }
+ }
+
+ float diff = spot - (1.0 - density);
+ float halfSpan = min(0.25, 0.75 / cellSize);
+ float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);
+ vec4 halftoneColor = vec4(0.0, 0.0, 0.0, coverage);
+
+ // Anti-moiré smoothstep crossfading
+ float moireBlend = smoothstep(0.35, 0.95, u_zoom);
+ vec4 contColor = vec4(0.0, 0.0, 0.0, density);
+ return mix(contColor, halftoneColor, moireBlend);
+}
+
+vec4 applyLayerTint(vec4 color) {
+ if (u_layerColorEnabled == 0) return color;
+ float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));
+ vec3 tinted = mix(u_layerColor, u_layerSubColor, lum);
+ return vec4(tinted, color.a);
+}
+
+void main() {
+ if (u_isBackground == 1) {
+ vec2 outsideDoc = max(vec2(0.0) - v_docCoord, v_docCoord - u_docDimensions);
+ if (outsideDoc.x > 0.0 || outsideDoc.y > 0.0) {
+ float safeZoom = max(0.01, u_zoom);
+ vec2 outsidePx = outsideDoc * safeZoom;
+ float borderDist = max(outsidePx.x, outsidePx.y);
+ if (borderDist <= 1.0) {
+ fragColor = vec4(0.086, 0.086, 0.086, 1.0);
+ return;
+ }
+ vec2 shadowCoord = v_docCoord - vec2(0.0, 10.0 / safeZoom);
+ vec2 shadowOutside = max(vec2(0.0) - shadowCoord, shadowCoord - u_docDimensions);
+ float shadowDist = length(shadowOutside * safeZoom);
+ float shadowA = 0.55 * exp(-shadowDist * shadowDist / 520.0) * smoothstep(48.0, 0.0, shadowDist);
+ if (shadowA < 0.002) {
+ discard;
+ }
+ fragColor = vec4(0.0, 0.0, 0.0, shadowA);
+ return;
+ }
+ if (u_showCheckerboard == 1) {
+ vec2 checkCoord = floor(v_docCoord / 16.0);
+ float check = mod(checkCoord.x + checkCoord.y, 2.0);
+ vec3 checkColor = check > 0.5 ? vec3(0.157, 0.157, 0.157) : vec3(0.125, 0.125, 0.125);
+ fragColor = vec4(checkColor, 1.0);
+ } else {
+ fragColor = vec4(1.0, 1.0, 1.0, 1.0);
+ }
+ return;
+ }
+
+ vec4 rawTex = texture(u_tileTexture, v_texCoord);
+
+ if (rawTex.a < 0.002) {
+ discard;
+ }
+
+ vec4 texColor = vec4(clamp(rawTex.rgb / rawTex.a, 0.0, 1.0), rawTex.a);
+ vec4 finalColor = texColor;
+
+ if (u_expressionMode == 1) {
+ float gLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
+ finalColor.rgb = vec3(gLum);
+ } else if (u_expressionMode == 2) {
+ float mLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
+ float monoAlpha = u_zoom >= 0.99 ? step(0.5, finalColor.a) : finalColor.a;
+ if (mLum < u_monoThreshold) {
+ if (u_monoExpressBlack == 1) {
+ finalColor = vec4(0.0, 0.0, 0.0, monoAlpha);
+ } else {
+ discard;
+ }
+ } else {
+ if (u_monoExpressWhite == 1) {
+ finalColor = vec4(1.0, 1.0, 1.0, monoAlpha);
+ } else {
+ discard;
+ }
+ }
+ }
+
+ if (u_toneEnabled == 1) {
+ finalColor = evaluateScreentone(finalColor, v_docCoord);
+ }
+
+ if (u_layerColorEnabled == 1) {
+ finalColor = applyLayerTint(finalColor);
+ }
+
+ if (u_maskEnabled == 1) {
+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);
+ vec4 maskPixel = texture(u_maskTexture, maskCoord);
+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
+ finalColor.a *= maskLum;
+ }
+
+ finalColor.a *= u_layerOpacity;
+
+ if (finalColor.a < 0.002) {
+ discard;
+ }
+
+ if (u_hasBackdrop == 1 && u_blendMode != 0 && u_blendMode != 12) {
+ vec2 screenUV = clamp(gl_FragCoord.xy / max(vec2(1.0), u_viewportSize), 0.0, 1.0);
+ vec4 dstPremul = texture(u_backdropTexture, screenUV);
+ vec3 Cb = dstPremul.a > 0.001 ? clamp(dstPremul.rgb / dstPremul.a, 0.0, 1.0) : vec3(1.0);
+ vec3 Cs = clamp(finalColor.rgb, 0.0, 1.0);
+ vec3 blended = evaluateBlendMode(Cb, Cs, u_blendMode);
+ finalColor.rgb = mix(Cs, blended, dstPremul.a);
+ }
+
+ fragColor = vec4(finalColor.rgb * finalColor.a, finalColor.a);
+}
+`;
+
+// Viewport-Space Draft Vertex Shader: Maps a viewport-sized Canvas2D draft overlay 1:1 to screen
+// while reconstructing exact document coordinates for screentone & layer mask evaluation in-stack.
+export const VIEWPORT_DRAFT_VERTEX_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 a_quadPos; // [0, 1] x [0, 1] (0,0 = top-left of viewport)
+uniform vec2 u_docDimensions;
+uniform vec2 u_viewportSize;
+uniform vec2 u_pan;
+uniform float u_zoom;
+uniform float u_rotationRad;
+uniform vec2 u_flip;
+uniform float u_dpr;
+
+out vec2 v_texCoord;
+out vec2 v_docCoord;
+
+void main() {
+ v_texCoord = a_quadPos;
+
+ vec2 clipPos = vec2(a_quadPos.x * 2.0 - 1.0, 1.0 - a_quadPos.y * 2.0);
+ vec2 screenPos = a_quadPos * u_viewportSize;
+ vec2 cssScreen = screenPos / max(0.0001, u_dpr);
+ vec2 unscaled = (cssScreen - u_pan) / max(0.0001, u_zoom);
+
+ float cosR = cos(u_rotationRad);
+ float sinR = sin(u_rotationRad);
+ vec2 unrotated = vec2(
+ unscaled.x * cosR + unscaled.y * sinR,
+ -unscaled.x * sinR + unscaled.y * cosR
+ );
+
+ v_docCoord = unrotated * u_flip + u_docDimensions * 0.5;
+ gl_Position = vec4(clipPos, 0.0, 1.0);
+}
+`;
diff --git a/src/utils/compositor/shaders/effectShaders.ts b/src/utils/compositor/shaders/effectShaders.ts
new file mode 100644
index 0000000..26003cf
--- /dev/null
+++ b/src/utils/compositor/shaders/effectShaders.ts
@@ -0,0 +1,307 @@
+import { LayerStyles } from '../../../types/editor';
+
+// Fragment Shader: Non-Destructive Adjustment Layers with Real-Time LUT Transform
+export const ADJUSTMENT_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+in vec2 v_docCoord;
+
+uniform sampler2D u_snapshotTexture;
+uniform sampler2D u_lutTexture;
+uniform int u_adjMode; // 0: per-channel LUT (Curves/Levels), 1: luminance mapping (Gradient Map)
+uniform float u_layerOpacity;
+uniform int u_maskEnabled;
+uniform sampler2D u_maskTexture;
+uniform vec2 u_docDimensions;
+uniform vec2 u_viewportSize;
+
+out vec4 fragColor;
+
+void main() {
+ vec2 screenUV = gl_FragCoord.xy / u_viewportSize;
+ vec4 baseColor = texture(u_snapshotTexture, screenUV);
+
+ if (baseColor.a < 0.001) {
+ discard;
+ }
+
+ vec3 unPremult = baseColor.rgb / max(0.001, baseColor.a);
+ vec3 adjusted;
+
+ if (u_adjMode == 1) {
+ // Gradient map: map luminance to LUT
+ float lum = clamp(dot(unPremult, vec3(0.299, 0.587, 0.114)), 0.0, 1.0);
+ adjusted = texture(u_lutTexture, vec2(lum, 0.5)).rgb;
+ } else {
+ // Curves / Levels / Color Balance
+ float r = texture(u_lutTexture, vec2(clamp(unPremult.r, 0.0, 1.0), 0.5)).r;
+ float g = texture(u_lutTexture, vec2(clamp(unPremult.g, 0.0, 1.0), 0.5)).g;
+ float b = texture(u_lutTexture, vec2(clamp(unPremult.b, 0.0, 1.0), 0.5)).b;
+ adjusted = vec3(r, g, b);
+ }
+
+ float maskFactor = u_layerOpacity;
+ if (u_maskEnabled == 1) {
+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);
+ vec4 maskPixel = texture(u_maskTexture, maskCoord);
+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
+ maskFactor *= maskLum;
+ }
+
+ vec3 finalRgb = mix(unPremult, adjusted, maskFactor);
+ fragColor = vec4(finalRgb * baseColor.a, baseColor.a);
+}
+`;
+
+export function hasActiveLayerStyles(styles?: LayerStyles): boolean {
+ if (!styles) return false;
+ const hasStroke = Boolean(styles.stroke?.enabled && styles.stroke.size > 0 && styles.stroke.opacity > 0);
+ const hasShadow = Boolean(styles.dropShadow?.enabled && styles.dropShadow.opacity > 0);
+ const hasGlow = Boolean(styles.outerGlow?.enabled && styles.outerGlow.opacity > 0);
+ return hasStroke || hasShadow || hasGlow;
+}
+
+// Vertex Shader: Fullscreen quad for Layer Styles post-processing
+export const LAYER_STYLES_VERTEX_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 a_quadPos; // [0, 1] x [0, 1]
+out vec2 v_uv;
+
+void main() {
+ v_uv = a_quadPos;
+ gl_Position = vec4(a_quadPos.x * 2.0 - 1.0, a_quadPos.y * 2.0 - 1.0, 0.0, 1.0);
+}
+`;
+
+// Fragment Shader: Real-Time Non-Destructive Stroke, Outer Glow, and Drop Shadow
+export const LAYER_STYLES_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 v_uv;
+
+uniform sampler2D u_layerTexture;
+uniform vec2 u_viewportSize;
+uniform float u_layerOpacity;
+
+// Stroke Uniforms
+uniform int u_strokeEnabled;
+uniform float u_strokeSize; // in physical screen pixels
+uniform vec4 u_strokeColor; // rgba (includes stroke opacity)
+uniform int u_strokePosition; // 0: outside, 1: inside, 2: center
+
+// Outer Glow Uniforms
+uniform int u_glowEnabled;
+uniform vec4 u_glowColor; // rgba (includes glow opacity)
+uniform float u_glowBlur; // in physical screen pixels
+uniform float u_glowSpread; // 0.0 to 1.0
+
+// Drop Shadow Uniforms
+uniform int u_shadowEnabled;
+uniform vec4 u_shadowColor; // rgba (includes shadow opacity)
+uniform vec2 u_shadowOffset; // in physical screen pixels (dx, dy)
+uniform float u_shadowBlur; // in physical screen pixels
+uniform float u_shadowSpread; // 0.0 to 1.0
+
+out vec4 fragColor;
+
+// 16 Poisson disk sample offsets
+const vec2 POISSON_KERNEL[16] = vec2[](
+ vec2(-0.326212, -0.405805),
+ vec2(-0.840144, -0.073580),
+ vec2(-0.695914, 0.457137),
+ vec2(-0.203345, 0.620716),
+ vec2( 0.962340, -0.194983),
+ vec2( 0.473434, -0.480026),
+ vec2( 0.519456, 0.767022),
+ vec2( 0.185461, -0.893124),
+ vec2( 0.507431, 0.064425),
+ vec2( 0.896420, 0.412458),
+ vec2(-0.321940, -0.932615),
+ vec2(-0.791559, -0.597705),
+ vec2(-0.504245, -0.007671),
+ vec2( 0.052445, 0.375489),
+ vec2( 0.284245, -0.052445),
+ vec2(-0.052445, -0.284245)
+);
+
+float computeStrokeCoverage(vec2 uv, float centerAlpha, float R, int position, vec2 texel) {
+ if (R <= 0.0) return 0.0;
+
+ // Outside stroke
+ if (position == 0) {
+ if (centerAlpha >= 0.99) return 0.0;
+ float minInsideDist = R + 1.0;
+ for (int i = 0; i < 16; i++) {
+ float ang = float(i) * 0.39269908;
+ vec2 dir = vec2(cos(ang), sin(ang));
+ for (int j = 1; j <= 4; j++) {
+ float dist = R * (float(j) / 4.0);
+ vec2 sUv = uv + dir * (dist * texel);
+ if (texture(u_layerTexture, sUv).a > 0.5) {
+ if (dist < minInsideDist) minInsideDist = dist;
+ break;
+ }
+ }
+ }
+ if (minInsideDist <= R) {
+ return clamp(R - minInsideDist + 1.0, 0.0, 1.0) * (1.0 - centerAlpha);
+ }
+ return 0.0;
+ }
+
+ // Inside stroke
+ if (position == 1) {
+ if (centerAlpha < 0.01) return 0.0;
+ float minOutsideDist = R + 1.0;
+ for (int i = 0; i < 16; i++) {
+ float ang = float(i) * 0.39269908;
+ vec2 dir = vec2(cos(ang), sin(ang));
+ for (int j = 1; j <= 4; j++) {
+ float dist = R * (float(j) / 4.0);
+ vec2 sUv = uv + dir * (dist * texel);
+ if (texture(u_layerTexture, sUv).a < 0.5) {
+ if (dist < minOutsideDist) minOutsideDist = dist;
+ break;
+ }
+ }
+ }
+ if (minOutsideDist <= R) {
+ return clamp(R - minOutsideDist + 1.0, 0.0, 1.0) * centerAlpha;
+ }
+ return 0.0;
+ }
+
+ // Center stroke (half outside, half inside)
+ float halfR = max(0.5, R * 0.5);
+ if (centerAlpha < 0.5) {
+ float minInsideDist = halfR + 1.0;
+ for (int i = 0; i < 16; i++) {
+ float ang = float(i) * 0.39269908;
+ vec2 dir = vec2(cos(ang), sin(ang));
+ for (int j = 1; j <= 4; j++) {
+ float dist = halfR * (float(j) / 4.0);
+ vec2 sUv = uv + dir * (dist * texel);
+ if (texture(u_layerTexture, sUv).a >= 0.5) {
+ if (dist < minInsideDist) minInsideDist = dist;
+ break;
+ }
+ }
+ }
+ if (minInsideDist <= halfR) {
+ return clamp(halfR - minInsideDist + 1.0, 0.0, 1.0);
+ }
+ return 0.0;
+ } else {
+ float minOutsideDist = halfR + 1.0;
+ for (int i = 0; i < 16; i++) {
+ float ang = float(i) * 0.39269908;
+ vec2 dir = vec2(cos(ang), sin(ang));
+ for (int j = 1; j <= 4; j++) {
+ float dist = halfR * (float(j) / 4.0);
+ vec2 sUv = uv + dir * (dist * texel);
+ if (texture(u_layerTexture, sUv).a < 0.5) {
+ if (dist < minOutsideDist) minOutsideDist = dist;
+ break;
+ }
+ }
+ }
+ if (minOutsideDist <= halfR) {
+ return clamp(halfR - minOutsideDist + 1.0, 0.0, 1.0);
+ }
+ return 0.0;
+ }
+}
+
+void main() {
+ vec2 texel = 1.0 / u_viewportSize;
+ vec4 centerSample = texture(u_layerTexture, v_uv);
+ float centerAlpha = centerSample.a;
+
+ // 1. Drop Shadow Pass
+ float shadowAlpha = 0.0;
+ if (u_shadowEnabled == 1) {
+ vec2 shadowUV = v_uv - u_shadowOffset * texel;
+ if (u_shadowBlur <= 0.5) {
+ shadowAlpha = texture(u_layerTexture, shadowUV).a;
+ } else {
+ float rad = max(1.0, u_shadowBlur);
+ float accum = 0.0;
+ for (int k = 0; k < 16; k++) {
+ vec2 sUv = shadowUV + POISSON_KERNEL[k] * (rad * texel);
+ accum += texture(u_layerTexture, sUv).a;
+ }
+ accum /= 16.0;
+ float spreadFactor = max(0.01, 1.0 - u_shadowSpread * 0.95);
+ shadowAlpha = clamp(accum / spreadFactor, 0.0, 1.0);
+ }
+ shadowAlpha *= u_shadowColor.a;
+ }
+
+ // 2. Outer Glow Pass
+ float glowAlpha = 0.0;
+ if (u_glowEnabled == 1 && centerAlpha < 0.99) {
+ float rad = max(1.0, u_glowBlur);
+ float accum = 0.0;
+ for (int k = 0; k < 16; k++) {
+ vec2 sUv = v_uv + POISSON_KERNEL[k] * (rad * texel);
+ accum += texture(u_layerTexture, sUv).a;
+ }
+ accum /= 16.0;
+ float spreadFactor = max(0.01, 1.0 - u_glowSpread * 0.95);
+ float glowVal = clamp(accum / spreadFactor, 0.0, 1.0);
+ glowAlpha = glowVal * (1.0 - centerAlpha) * u_glowColor.a;
+ }
+
+ // 3. Stroke Pass
+ float strokeCov = 0.0;
+ if (u_strokeEnabled == 1) {
+ strokeCov = computeStrokeCoverage(v_uv, centerAlpha, u_strokeSize, u_strokePosition, texel);
+ }
+
+ // Composite layers in standard Photoshop order: Drop Shadow -> Outer Glow -> Outside Stroke -> Layer Body -> Inside Stroke
+ vec4 composite = vec4(0.0);
+
+ // Drop Shadow
+ if (u_shadowEnabled == 1 && shadowAlpha > 0.001) {
+ composite = vec4(u_shadowColor.rgb * shadowAlpha, shadowAlpha);
+ }
+
+ // Outer Glow
+ if (u_glowEnabled == 1 && glowAlpha > 0.001) {
+ vec4 glow = vec4(u_glowColor.rgb * glowAlpha, glowAlpha);
+ composite = glow + composite * (1.0 - glow.a);
+ }
+
+ // Outside / Outer Center Stroke
+ bool isOutsideOrCenter = (u_strokePosition == 0 || (u_strokePosition == 2 && centerAlpha < 0.5));
+ if (u_strokeEnabled == 1 && isOutsideOrCenter && strokeCov > 0.001) {
+ float sA = strokeCov * u_strokeColor.a;
+ vec4 strk = vec4(u_strokeColor.rgb * sA, sA);
+ composite = strk + composite * (1.0 - strk.a);
+ }
+
+ // Layer Content
+ if (centerSample.a > 0.001) {
+ composite = centerSample + composite * (1.0 - centerSample.a);
+ }
+
+ // Inside / Inner Center Stroke
+ bool isInsideOrCenter = (u_strokePosition == 1 || (u_strokePosition == 2 && centerAlpha >= 0.5));
+ if (u_strokeEnabled == 1 && isInsideOrCenter && strokeCov > 0.001) {
+ float sA = strokeCov * u_strokeColor.a;
+ vec4 strk = vec4(u_strokeColor.rgb * sA, sA);
+ composite = strk + composite * (1.0 - strk.a);
+ }
+
+ // Overall Layer Opacity
+ composite *= u_layerOpacity;
+
+ if (composite.a < 0.002) {
+ discard;
+ }
+
+ fragColor = composite;
+}
+`;
diff --git a/src/utils/compositor/shaders/instancedShaders.ts b/src/utils/compositor/shaders/instancedShaders.ts
new file mode 100644
index 0000000..54a7e4f
--- /dev/null
+++ b/src/utils/compositor/shaders/instancedShaders.ts
@@ -0,0 +1,223 @@
+import { buildBlendModeGlsl } from './blendModesGlsl';
+
+// Instanced Vertex Shader: Batched tile rendering via TEXTURE_2D_ARRAY + drawArraysInstanced
+export const COMPOSITOR_INSTANCED_VERTEX_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 a_quadPos; // [0, 1] x [0, 1]
+in vec3 a_instanceData; // xy = tileOrigin in document space, z = TEXTURE_2D_ARRAY slice index
+uniform vec2 u_tileSize; // tile size in document space (TILE_SIZE << lod)
+uniform vec2 u_docDimensions;
+uniform vec2 u_viewportSize;
+uniform vec2 u_pan;
+uniform float u_zoom;
+uniform float u_rotationRad;
+uniform vec2 u_flip;
+uniform float u_dpr;
+
+out vec2 v_texCoord;
+out vec2 v_docCoord;
+flat out float v_sliceIndex;
+
+void main() {
+ v_texCoord = a_quadPos;
+ v_sliceIndex = a_instanceData.z;
+
+ vec2 docPos = a_instanceData.xy + a_quadPos * u_tileSize;
+ v_docCoord = docPos;
+
+ vec2 centered = (docPos - u_docDimensions * 0.5) * u_flip;
+
+ float cosR = cos(u_rotationRad);
+ float sinR = sin(u_rotationRad);
+ vec2 rotated = vec2(
+ centered.x * cosR - centered.y * sinR,
+ centered.x * sinR + centered.y * cosR
+ );
+
+ vec2 screenPos = (u_pan + rotated * u_zoom) * u_dpr;
+
+ vec2 clipPos = vec2(
+ (2.0 * screenPos.x / u_viewportSize.x) - 1.0,
+ 1.0 - (2.0 * screenPos.y / u_viewportSize.y)
+ );
+
+ gl_Position = vec4(clipPos, 0.0, 1.0);
+}
+`;
+
+// Instanced Fragment Shader: Samples TEXTURE_2D_ARRAY slice for batched single-draw-call layer rendering
+export const COMPOSITOR_INSTANCED_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+precision highp sampler2DArray;
+
+in vec2 v_texCoord;
+in vec2 v_docCoord;
+flat in float v_sliceIndex;
+
+uniform sampler2DArray u_tileArrayTexture;
+uniform sampler2D u_backdropTexture;
+uniform int u_hasBackdrop;
+uniform vec2 u_viewportSize;
+uniform float u_layerOpacity;
+uniform int u_blendMode;
+
+// Screentone Uniforms
+uniform int u_toneEnabled;
+uniform float u_toneFrequency;
+uniform float u_toneAngleRad;
+uniform float u_toneDpi;
+uniform int u_toneDotShape;
+uniform float u_toneDensity;
+uniform int u_toneDensityType;
+uniform float u_zoom;
+
+// Layer Tint Uniforms
+uniform int u_layerColorEnabled;
+uniform vec3 u_layerColor;
+uniform vec3 u_layerSubColor;
+
+// Layer Mask Uniforms
+uniform vec2 u_docDimensions;
+uniform sampler2D u_maskTexture;
+uniform int u_maskEnabled;
+
+// CSP Expression Color Uniforms (0: color, 1: gray, 2: monochrome)
+uniform int u_expressionMode;
+uniform float u_monoThreshold;
+uniform int u_monoExpressBlack;
+uniform int u_monoExpressWhite;
+
+out vec4 fragColor;
+
+float fractVal(float x) {
+ return x - floor(x);
+}
+
+${buildBlendModeGlsl()}
+
+vec4 evaluateScreentone(vec4 srcColor, vec2 docCoord) {
+ if (srcColor.a < 0.0039) {
+ return vec4(0.0);
+ }
+
+ float density;
+ if (u_toneDensityType == 0) {
+ density = clamp(u_toneDensity * srcColor.a, 0.0, 1.0);
+ } else {
+ float lum = dot(srcColor.rgb, vec3(0.299, 0.587, 0.114));
+ density = clamp((1.0 - lum) * srcColor.a, 0.0, 1.0);
+ }
+
+ if (density <= 0.001) return vec4(0.0);
+ if (density >= 0.999) return vec4(0.0, 0.0, 0.0, 1.0);
+
+ float cellSize = max(3.5, u_toneDpi / max(1.0, u_toneFrequency));
+ float cosA = cos(u_toneAngleRad);
+ float sinA = sin(u_toneAngleRad);
+
+ float xr = docCoord.x * cosA - docCoord.y * sinA;
+ float yr = docCoord.x * sinA + docCoord.y * cosA;
+
+ float u = fractVal(xr / cellSize) - 0.5;
+ float v = fractVal(yr / cellSize) - 0.5;
+
+ float spot;
+ if (u_toneDotShape == 2) {
+ spot = 1.0 - 2.0 * abs(u);
+ } else if (u_toneDotShape == 3) {
+ spot = 1.0 - (abs(u) + abs(v));
+ } else {
+ float absU = abs(u);
+ float absV = abs(v);
+ if (absU + absV <= 0.5) {
+ spot = 1.0 - 2.0 * (u * u + v * v);
+ } else {
+ float uc = absU - 0.5;
+ float vc = absV - 0.5;
+ spot = 2.0 * (uc * uc + vc * vc);
+ }
+ }
+
+ float diff = spot - (1.0 - density);
+ float halfSpan = min(0.25, 0.75 / cellSize);
+ float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);
+ vec4 halftoneColor = vec4(0.0, 0.0, 0.0, coverage);
+
+ float moireBlend = smoothstep(0.35, 0.95, u_zoom);
+ vec4 contColor = vec4(0.0, 0.0, 0.0, density);
+ return mix(contColor, halftoneColor, moireBlend);
+}
+
+vec4 applyLayerTint(vec4 color) {
+ if (u_layerColorEnabled == 0) return color;
+ float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));
+ vec3 tinted = mix(u_layerColor, u_layerSubColor, lum);
+ return vec4(tinted, color.a);
+}
+
+void main() {
+ // Single hardware TMU fetch on premultiplied RGBA8 TEXTURE_2D_ARRAY
+ vec4 rawTex = texture(u_tileArrayTexture, vec3(v_texCoord, v_sliceIndex));
+
+ if (rawTex.a < 0.002) {
+ discard;
+ }
+
+ vec4 texColor = vec4(clamp(rawTex.rgb / rawTex.a, 0.0, 1.0), rawTex.a);
+ vec4 finalColor = texColor;
+
+ if (u_expressionMode == 1) {
+ float gLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
+ finalColor.rgb = vec3(gLum);
+ } else if (u_expressionMode == 2) {
+ float mLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
+ float monoAlpha = u_zoom >= 0.99 ? step(0.5, finalColor.a) : finalColor.a;
+ if (mLum < u_monoThreshold) {
+ if (u_monoExpressBlack == 1) {
+ finalColor = vec4(0.0, 0.0, 0.0, monoAlpha);
+ } else {
+ discard;
+ }
+ } else {
+ if (u_monoExpressWhite == 1) {
+ finalColor = vec4(1.0, 1.0, 1.0, monoAlpha);
+ } else {
+ discard;
+ }
+ }
+ }
+
+ if (u_toneEnabled == 1) {
+ finalColor = evaluateScreentone(finalColor, v_docCoord);
+ }
+
+ if (u_layerColorEnabled == 1) {
+ finalColor = applyLayerTint(finalColor);
+ }
+
+ if (u_maskEnabled == 1) {
+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);
+ vec4 maskPixel = texture(u_maskTexture, maskCoord);
+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
+ finalColor.a *= maskLum;
+ }
+
+ finalColor.a *= u_layerOpacity;
+
+ if (finalColor.a < 0.002) {
+ discard;
+ }
+
+ if (u_hasBackdrop == 1 && u_blendMode != 0 && u_blendMode != 12) {
+ vec2 screenUV = clamp(gl_FragCoord.xy / max(vec2(1.0), u_viewportSize), 0.0, 1.0);
+ vec4 dstPremul = texture(u_backdropTexture, screenUV);
+ vec3 Cb = dstPremul.a > 0.001 ? clamp(dstPremul.rgb / dstPremul.a, 0.0, 1.0) : vec3(1.0);
+ vec3 Cs = clamp(finalColor.rgb, 0.0, 1.0);
+ vec3 blended = evaluateBlendMode(Cb, Cs, u_blendMode);
+ finalColor.rgb = mix(Cs, blended, dstPremul.a);
+ }
+
+ fragColor = vec4(finalColor.rgb * finalColor.a, finalColor.a);
+}
+`;
diff --git a/src/utils/compositor/shaders/softProofShaders.ts b/src/utils/compositor/shaders/softProofShaders.ts
new file mode 100644
index 0000000..7e15f2e
--- /dev/null
+++ b/src/utils/compositor/shaders/softProofShaders.ts
@@ -0,0 +1,203 @@
+// Soft Proofing and Gamut Warning Post-Processing Shaders
+export const SOFT_PROOF_VERTEX_SHADER = `#version 300 es
+precision highp float;
+in vec2 a_quadPos; // [0, 1] x [0, 1]
+out vec2 v_uv;
+void main() {
+ v_uv = a_quadPos;
+ gl_Position = vec4(a_quadPos.x * 2.0 - 1.0, a_quadPos.y * 2.0 - 1.0, 0.0, 1.0);
+}
+`;
+
+export const SOFT_PROOF_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 v_uv;
+uniform sampler2D u_sceneTexture;
+uniform int u_standard; // 0: japan-color-2001, 1: us-web-coated-swop, 2: iso-coated-v2
+uniform int u_proofEnabled; // 1 or 0
+uniform int u_gamutWarning; // 1 or 0
+uniform vec3 u_gamutWarningColor;
+
+out vec4 fragColor;
+
+// sRGB to Linear RGB
+vec3 srgbToLinear(vec3 c) {
+ return mix(
+ c / 12.92,
+ pow((c + 0.055) / 1.055, vec3(2.4)),
+ step(vec3(0.04045), c)
+ );
+}
+
+// Linear RGB to sRGB
+vec3 linearToSrgb(vec3 c) {
+ c = clamp(c, 0.0, 1.0);
+ return mix(
+ c * 12.92,
+ 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055,
+ step(vec3(0.0031308), c)
+ );
+}
+
+// Linear sRGB to CIE XYZ (D65)
+vec3 linearToXyz(vec3 rgb) {
+ return vec3(
+ dot(rgb, vec3(0.4124564, 0.3575761, 0.1804375)),
+ dot(rgb, vec3(0.2126729, 0.7151522, 0.0721750)),
+ dot(rgb, vec3(0.0193339, 0.1191920, 0.9503041))
+ );
+}
+
+// CIE XYZ (D65) to CIE Lab
+float fLab(float t) {
+ const float delta = 6.0 / 29.0;
+ const float delta3 = delta * delta * delta;
+ return (t > delta3) ? pow(t, 1.0 / 3.0) : (t / (3.0 * delta * delta) + 4.0 / 29.0);
+}
+
+vec3 xyzToLab(vec3 xyz) {
+ vec3 white = vec3(0.95047, 1.0, 1.08883);
+ vec3 v = xyz / white;
+ float fx = fLab(v.x);
+ float fy = fLab(v.y);
+ float fz = fLab(v.z);
+ return vec3(
+ 116.0 * fy - 16.0,
+ 500.0 * (fx - fy),
+ 200.0 * (fy - fz)
+ );
+}
+
+vec3 srgbToLab(vec3 srgb) {
+ vec3 lin = srgbToLinear(clamp(srgb, 0.0, 1.0));
+ vec3 xyz = linearToXyz(lin);
+ return xyzToLab(xyz);
+}
+
+// CMYK soft-proofing simulation polynomial
+vec3 simulateCmyk(vec3 srgb, int standard) {
+ vec3 linRgb = srgbToLinear(clamp(srgb, 0.0, 1.0));
+ float c0 = 1.0 - linRgb.r;
+ float m0 = 1.0 - linRgb.g;
+ float y0 = 1.0 - linRgb.b;
+
+ // Standard 0: Japan Color 2001 (high saturation, clean cyans, TAC ~350%)
+ // Standard 1: US Web Coated (SWOP) (warm stock, heavy black, lower gamut, TAC ~300%)
+ // Standard 2: ISO Coated v2 (FOGRA39) (balanced European inks, TAC ~330%)
+ float tacLimit = 3.5;
+ float tvi = 0.14;
+ float gcrExp = 1.4;
+ float ucrFactor = 0.80;
+
+ vec3 densC = vec3(1.42, 0.17, 0.07);
+ vec3 densM = vec3(0.06, 1.35, 0.15);
+ vec3 densY = vec3(0.02, 0.04, 1.25);
+ vec3 densK = vec3(1.80, 1.80, 1.78);
+ vec3 paperReflect = vec3(0.96, 0.96, 0.97);
+
+ if (standard == 1) {
+ tacLimit = 3.0;
+ tvi = 0.20;
+ gcrExp = 1.15;
+ ucrFactor = 0.90;
+ densC = vec3(1.28, 0.24, 0.14);
+ densM = vec3(0.08, 1.22, 0.22);
+ densY = vec3(0.03, 0.07, 1.15);
+ densK = vec3(1.65, 1.65, 1.62);
+ paperReflect = vec3(0.94, 0.93, 0.88);
+ } else if (standard == 2) {
+ tacLimit = 3.3;
+ tvi = 0.16;
+ gcrExp = 1.3;
+ ucrFactor = 0.85;
+ densC = vec3(1.36, 0.19, 0.09);
+ densM = vec3(0.07, 1.30, 0.17);
+ densY = vec3(0.02, 0.05, 1.20);
+ densK = vec3(1.72, 1.72, 1.70);
+ paperReflect = vec3(0.95, 0.95, 0.94);
+ }
+
+ // Black generation (GCR)
+ float k0 = min(c0, min(m0, y0));
+ float k = pow(k0, gcrExp);
+
+ // Under Color Removal
+ float denom = max(0.001, 1.0 - k * 0.35);
+ float c1 = clamp((c0 - k * ucrFactor) / denom, 0.0, 1.0);
+ float m1 = clamp((m0 - k * ucrFactor) / denom, 0.0, 1.0);
+ float y1 = clamp((y0 - k * ucrFactor) / denom, 0.0, 1.0);
+
+ // Apply TAC limit
+ float totalInk = c1 + m1 + y1 + k;
+ if (totalInk > tacLimit) {
+ float scale = (tacLimit - k) / max(0.001, totalInk - k);
+ c1 *= scale;
+ m1 *= scale;
+ y1 *= scale;
+ }
+
+ // Tone Value Increase (dot gain)
+ c1 += 4.0 * tvi * c1 * (1.0 - c1);
+ m1 += 4.0 * tvi * m1 * (1.0 - m1);
+ y1 += 4.0 * tvi * y1 * (1.0 - y1);
+ k += 4.0 * tvi * k * (1.0 - k);
+
+ c1 = clamp(c1, 0.0, 1.0);
+ m1 = clamp(m1, 0.0, 1.0);
+ y1 = clamp(y1, 0.0, 1.0);
+ k = clamp(k, 0.0, 1.0);
+
+ // Inter-ink trapping
+ float cmTrap = c1 * m1 * 0.12;
+ float cyTrap = c1 * y1 * 0.10;
+ float myTrap = m1 * y1 * 0.10;
+
+ vec3 totalDensity = c1 * densC + m1 * densM + y1 * densY + k * densK
+ - cmTrap * (densC + densM) * 0.2
+ - cyTrap * (densC + densY) * 0.2
+ - myTrap * (densM + densY) * 0.2;
+
+ // Subtractive reflectance with paper tint and gloss minimum clamp
+ vec3 reflectance = paperReflect * exp(-totalDensity * 2.302585);
+ reflectance += vec3(0.012);
+
+ return linearToSrgb(reflectance);
+}
+
+void main() {
+ vec4 sceneColor = texture(u_sceneTexture, v_uv);
+
+ if (sceneColor.a < 0.002) {
+ fragColor = sceneColor;
+ return;
+ }
+
+ // Unpremultiply alpha for true color evaluation
+ vec3 rgb = sceneColor.rgb / sceneColor.a;
+
+ // Soft proof simulation
+ vec3 proofRgb = simulateCmyk(rgb, u_standard);
+
+ // Gamut evaluation in CIE Lab space
+ vec3 labOrig = srgbToLab(rgb);
+ vec3 labProof = srgbToLab(proofRgb);
+
+ // Delta-E (CIE76): normalized scale where 100 Lab units = 1.0 (deltaE = norm / 100.0)
+ vec3 dLab = labOrig - labProof;
+ float deltaE = length(dLab) / 100.0;
+
+ bool isOutOfGamut = (deltaE > 0.05);
+
+ vec3 outRgb = rgb;
+ if (u_proofEnabled == 1) {
+ outRgb = proofRgb;
+ }
+
+ if (u_gamutWarning == 1 && isOutOfGamut) {
+ outRgb = u_gamutWarningColor;
+ }
+
+ fragColor = vec4(outRgb * sceneColor.a, sceneColor.a);
+}
+`;
diff --git a/src/utils/compositor/stackCache.ts b/src/utils/compositor/stackCache.ts
new file mode 100644
index 0000000..6530c56
--- /dev/null
+++ b/src/utils/compositor/stackCache.ts
@@ -0,0 +1,162 @@
+import { LayerItem } from '../../types/editor';
+import { hasActiveLayerStyles } from './shaders/effectShaders';
+import { partitionLayerStack } from './layerTree';
+import {
+ CompositingUnit,
+ LayerStackCacheEvaluation,
+ LayerStackCacheInput,
+ LayerStackCacheTrackerLike,
+ LayerTreeNode,
+} from './types';
+
+export type { LayerStackCacheInput, LayerStackCacheEvaluation };
+
+function serializeLayerNodeSignature(
+ node: LayerTreeNode,
+ inheritedOpacity: number,
+ getLayerContentVersion: (layerId: string) => number,
+ getMaskInvalidationEpoch?: (layerId: string) => number
+): string {
+ const l = node.layer;
+ const contentVer = getLayerContentVersion(l.id);
+ const maskEpoch = getMaskInvalidationEpoch ? getMaskInvalidationEpoch(l.id) : 0;
+ const stylesSig = hasActiveLayerStyles(l.styles) ? JSON.stringify(l.styles) : '';
+ const adjSig = l.type === 'adjustment' && l.adjustmentData ? JSON.stringify(l.adjustmentData) : '';
+ const toneSig = l.toneEnabled
+ ? `1:${l.toneFrequency ?? 60}:${l.toneAngle ?? 45}:${l.toneDotShape ?? ''}:${l.toneDensity ?? 40}:${l.toneDensityType ?? ''}`
+ : '0';
+ const tintSig = l.layerColorEnabled
+ ? `1:${l.layerColor ?? ''}:${l.layerSubColor ?? ''}`
+ : '0';
+ const maskSig = l.maskCanvas && l.maskEnabled !== false
+ ? `1:${l.maskVersion ?? 0}:${maskEpoch}:${l.maskCanvas.width}x${l.maskCanvas.height}`
+ : '0';
+ const exprSig = `${l.expressionColor ?? 'color'}:${l.monoThreshold ?? 128}:${l.monoExpressBlack !== false ? 1 : 0}:${l.monoExpressWhite !== false ? 1 : 0}`;
+ const frameSig = l.type === 'frame-folder' && l.comicFrames ? JSON.stringify(l.comicFrames) : '';
+
+ let sig = `${l.id}|${l.type}|${l.visible ? 1 : 0}|${l.opacity}|${inheritedOpacity}|${l.blendMode}|${l.clipped ? 1 : 0}|v:${contentVer}|m:${maskSig}|t:${toneSig}|c:${tintSig}|e:${exprSig}|s:${stylesSig}|a:${adjSig}|f:${frameSig}`;
+
+ if (node.children.length > 0) {
+ const childSigs: string[] = [];
+ for (const child of node.children) {
+ if (!child.layer.visible || child.layer.opacity <= 0.001) continue;
+ childSigs.push(
+ serializeLayerNodeSignature(child, 1.0, getLayerContentVersion, getMaskInvalidationEpoch)
+ );
+ }
+ sig += `[${childSigs.join(',')}]`;
+ }
+
+ return sig;
+}
+
+function serializeUnitSignature(
+ unit: CompositingUnit,
+ getLayerContentVersion: (layerId: string) => number,
+ getMaskInvalidationEpoch?: (layerId: string) => number
+): string {
+ let sig = serializeLayerNodeSignature(
+ unit.group.baseNode,
+ unit.inheritedOpacity,
+ getLayerContentVersion,
+ getMaskInvalidationEpoch
+ );
+ if (unit.group.clippedNodes.length > 0) {
+ const clippedSigs: string[] = [];
+ for (const cn of unit.group.clippedNodes) {
+ if (!cn.layer.visible || cn.layer.opacity <= 0.001 || cn.layer.type === 'folder') continue;
+ clippedSigs.push(
+ serializeLayerNodeSignature(cn, unit.inheritedOpacity, getLayerContentVersion, getMaskInvalidationEpoch)
+ );
+ }
+ if (clippedSigs.length > 0) {
+ sig += `{clip:${clippedSigs.join(';')}}`;
+ }
+ }
+ return sig;
+}
+
+/**
+ * Pure invalidation tracker for the Baked Layer Stack Cache (`belowActiveCacheFbo` & `aboveActiveCacheFbo`).
+ * Determines independently whether the lower or upper cached FBO needs rebuilding.
+ */
+export class LayerStackCacheTracker implements LayerStackCacheTrackerLike {
+ private lastBelowSignature: string | null = null;
+ private lastAboveSignature: string | null = null;
+
+ public evaluate(input: LayerStackCacheInput): LayerStackCacheEvaluation {
+ const partition = partitionLayerStack(input.layers, input.activeLayerId);
+
+ const { transform, dimensions } = input;
+ const viewportSig =
+ `${input.viewportW}x${input.viewportH}@${input.dpr}|` +
+ `${dimensions.width}x${dimensions.height}@${dimensions.dpi ?? 600}|` +
+ `${transform.pan.x},${transform.pan.y},${transform.zoom},${transform.rotation},` +
+ `${transform.flipX ? 1 : 0},${transform.flipY ? 1 : 0}|g:${input.gridId ?? 0}|ep:${input.gridEpoch ?? 0}`;
+
+ // Onion skin frames are baked into the below cache right after the artboard background
+ let onionSig = '';
+ if (input.onionSkinFrames && input.onionSkinFrames.length > 0) {
+ const layerMap = new Map<string, LayerItem>();
+ for (const l of input.layers) layerMap.set(l.id, l);
+ const parts: string[] = [];
+ for (const frame of input.onionSkinFrames) {
+ const target = layerMap.get(frame.layerId);
+ if (target && target.visible) {
+ parts.push(
+ `${frame.layerId}:${frame.tint}:${frame.opacity}:v${input.getLayerContentVersion(frame.layerId)}`
+ );
+ }
+ }
+ onionSig = parts.join(',');
+ }
+
+ const modeTag = input.colorMode ?? 'color';
+ const belowUnitSigs = partition.belowUnits.map((u) =>
+ serializeUnitSignature(u, input.getLayerContentVersion, input.getMaskInvalidationEpoch)
+ );
+ const belowSignature = `${viewportSig}|cm:${modeTag}|cb:${input.showCheckerboard ? 1 : 0}|tb:${input.transparentBackground ? 1 : 0}|os:${onionSig}|below:[${belowUnitSigs.join('||')}]`;
+
+ let aboveSignature = '';
+ if (partition.aboveCachedUnits.length > 0) {
+ const aboveUnitSigs = partition.aboveCachedUnits.map((u) =>
+ serializeUnitSignature(u, input.getLayerContentVersion, input.getMaskInvalidationEpoch)
+ );
+ aboveSignature = `${viewportSig}|cm:${modeTag}|strat:${partition.aboveStrategy}:${partition.aboveCacheBlendMode}|above:[${aboveUnitSigs.join('||')}]`;
+ }
+
+ const belowDirty = belowSignature !== this.lastBelowSignature;
+ const aboveDirty =
+ partition.aboveCachedUnits.length > 0 && aboveSignature !== this.lastAboveSignature;
+
+ return {
+ partition,
+ belowSignature,
+ aboveSignature,
+ belowDirty,
+ aboveDirty,
+ };
+ }
+
+ public commit(belowSignature: string, aboveSignature: string): void {
+ this.lastBelowSignature = belowSignature;
+ this.lastAboveSignature = aboveSignature;
+ }
+
+ public invalidateAll(): void {
+ this.lastBelowSignature = null;
+ this.lastAboveSignature = null;
+ }
+
+ public invalidateBelow(): void {
+ this.lastBelowSignature = null;
+ }
+
+ public invalidateAbove(): void {
+ this.lastAboveSignature = null;
+ }
+
+ public getLastSignatures(): { below: string | null; above: string | null } {
+ return { below: this.lastBelowSignature, above: this.lastAboveSignature };
+ }
+}
diff --git a/src/utils/compositor/tileDraw.ts b/src/utils/compositor/tileDraw.ts
new file mode 100644
index 0000000..35d4d77
--- /dev/null
+++ b/src/utils/compositor/tileDraw.ts
@@ -0,0 +1,326 @@
+import { CanvasDimensions, LayerItem } from '../../types/editor';
+import { SparseTileGrid, TILE_SIZE, TileBuffer } from '../tileEngine';
+import { applyLayerUniforms, restoreStandardProgram, syncFrameUniforms } from './layerUniforms';
+import { getOrUploadArrayTileSlice, getTileTexture } from './tileTexturePool';
+import { CompositorState } from './types';
+
+/**
+ * Fallback per-tile TEXTURE_2D draw loop when visible tile count exceeds TEXTURE_2D_ARRAY pool capacity.
+ */
+export function drawTilesFallback2D(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ visibleTiles: TileBuffer[],
+ grid: SparseTileGrid,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ lodTileDocSize: number,
+ effectiveOpacity: number,
+ modeCode: number,
+ backdropTex: WebGLTexture | null,
+ maskTex: WebGLTexture | null
+): void {
+ if (!state.stdLocs) return;
+ restoreStandardProgram(state, gl);
+ syncFrameUniforms(state, gl, state.stdLocs);
+ gl.uniform1i(state.uTileTextureLoc, 0);
+ gl.uniform1i(state.uIsBackgroundLoc, 0);
+ applyLayerUniforms(
+ state,
+ gl,
+ state.stdLocs,
+ layer,
+ dimensions,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+ gl.uniform2f(state.uTileSizeLoc, lodTileDocSize, lodTileDocSize);
+
+ for (const tile of visibleTiles) {
+ const tex = getTileTexture(state, tile, grid);
+ if (!tex) continue;
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ gl.uniform2f(state.uTileOriginLoc, tile.tileX * lodTileDocSize, tile.tileY * lodTileDocSize);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ }
+}
+
+/**
+ * Unified tile draw path used by both normal layers and isolated live Eraser/Alpha-Lock FBOs.
+ * Batches via TEXTURE_2D_ARRAY + drawArraysInstanced and orphans instanceBuffer via STREAM_DRAW
+ * to prevent ANGLE/D3D11 instance attribute read-after-write hazards across consecutive draws.
+ */
+export function drawVisibleTiles(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ visibleTiles: TileBuffer[],
+ grid: SparseTileGrid,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ lodTileDocSize: number,
+ effectiveOpacity: number,
+ modeCode: number,
+ backdropTex: WebGLTexture | null,
+ maskTex: WebGLTexture | null
+): void {
+ const canBatch =
+ visibleTiles.length > 0 &&
+ state.instancedProgram !== null &&
+ state.instancedLocs !== null &&
+ state.tileArrayTexture !== null &&
+ state.instanceBuffer !== null &&
+ visibleTiles.length <= state.arrayPoolCapacity;
+
+ if (
+ canBatch &&
+ state.instancedProgram &&
+ state.instancedLocs &&
+ state.tileArrayTexture &&
+ state.instanceBuffer
+ ) {
+ const batchTick = ++state.arrayBatchCounter;
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, state.tileArrayTexture);
+
+ const desiredTier = state.currentZoom < 0.99 ? 0 : state.currentZoom < 2.0 ? 1 : 2;
+ if (state.arrayPoolFilterTier !== desiredTier) {
+ const filter = desiredTier <= 1 ? gl.LINEAR : gl.NEAREST;
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, filter);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, filter);
+ state.arrayPoolFilterTier = desiredTier;
+ }
+
+ let instanceCount = 0;
+ let overflowed = false;
+ for (let i = 0; i < visibleTiles.length; i++) {
+ const tile = visibleTiles[i];
+ const sliceIdx = getOrUploadArrayTileSlice(state, gl, tile, grid, batchTick);
+ if (sliceIdx < 0) {
+ overflowed = true;
+ break;
+ }
+ const off = instanceCount * 3;
+ state.instanceFloatScratch[off] = tile.tileX * lodTileDocSize;
+ state.instanceFloatScratch[off + 1] = tile.tileY * lodTileDocSize;
+ state.instanceFloatScratch[off + 2] = sliceIdx;
+ instanceCount++;
+ }
+
+ if (!overflowed && instanceCount > 0) {
+ gl.useProgram(state.instancedProgram);
+ syncFrameUniforms(state, gl, state.instancedLocs);
+ gl.uniform2f(state.uInstTileSizeLoc, lodTileDocSize, lodTileDocSize);
+ gl.uniform1i(state.uInstTileArrayLoc, 0);
+ applyLayerUniforms(
+ state,
+ gl,
+ state.instancedLocs,
+ layer,
+ dimensions,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, state.tileArrayTexture);
+
+ if (state.instancedVao) {
+ gl.bindVertexArray(state.instancedVao);
+ } else {
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.quadBuffer);
+ if (state.aInstQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aInstQuadPosLoc);
+ gl.vertexAttribPointer(state.aInstQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ gl.vertexAttribDivisor(state.aInstQuadPosLoc, 0);
+ }
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.instanceBuffer);
+ if (state.aInstDataLoc >= 0) {
+ gl.enableVertexAttribArray(state.aInstDataLoc);
+ gl.vertexAttribPointer(state.aInstDataLoc, 3, gl.FLOAT, false, 0, 0);
+ gl.vertexAttribDivisor(state.aInstDataLoc, 1);
+ }
+ }
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.instanceBuffer);
+ gl.bufferData(
+ gl.ARRAY_BUFFER,
+ state.instanceFloatScratch.subarray(0, instanceCount * 3),
+ gl.STREAM_DRAW
+ );
+ gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, instanceCount);
+
+ if (state.instancedVao) {
+ gl.bindVertexArray(null);
+ } else if (state.aInstDataLoc >= 0) {
+ gl.vertexAttribDivisor(state.aInstDataLoc, 0);
+ gl.disableVertexAttribArray(state.aInstDataLoc);
+ }
+ restoreStandardProgram(state, gl);
+ return;
+ }
+ }
+
+ drawTilesFallback2D(
+ state,
+ gl,
+ visibleTiles,
+ grid,
+ layer,
+ dimensions,
+ lodTileDocSize,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+}
+
+/**
+ * Uploads and renders the active draft canvas in-stack for the active layer.
+ * Supports both viewport-space overlays (from CanvasArea) and document-space draft canvases.
+ */
+export function renderActiveDraftForLayer(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ draftCanvas: HTMLCanvasElement,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ effectiveOpacity: number,
+ modeCode: number,
+ backdropTex: WebGLTexture | null,
+ maskTex: WebGLTexture | null,
+ draftVersion?: number,
+ draftSpace: 'document' | 'viewport' = 'document',
+ isDestinationOutMask: boolean = false
+): void {
+ if (draftCanvas.width <= 0 || draftCanvas.height <= 0) return;
+ if ((draftCanvas as any).__draftHasContent === false) return;
+ if (!state.draftTexture) {
+ state.draftTexture = gl.createTexture();
+ }
+ if (!state.draftTexture) return;
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, state.draftTexture);
+
+ const ver = draftVersion ?? -1;
+ const hasGenerateMipmap = typeof gl.generateMipmap === 'function';
+ const needsMipmap = hasGenerateMipmap && draftSpace === 'document' && state.currentZoom < 0.99;
+ const sizeChanged =
+ state.draftTexWidth !== draftCanvas.width || state.draftTexHeight !== draftCanvas.height;
+
+ if (ver === -1 || ver !== state.lastDraftVersion || sizeChanged) {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(
+ gl.TEXTURE_2D,
+ gl.TEXTURE_MIN_FILTER,
+ needsMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
+ );
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ if (!sizeChanged && state.draftTexWidth > 0 && typeof gl.texSubImage2D === 'function') {
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
+ } else {
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
+ }
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ if (needsMipmap) {
+ gl.generateMipmap(gl.TEXTURE_2D);
+ state.draftHasMipmap = true;
+ } else {
+ state.draftHasMipmap = false;
+ }
+ state.draftTexWidth = draftCanvas.width;
+ state.draftTexHeight = draftCanvas.height;
+ state.lastDraftVersion = ver;
+ } else {
+ if (needsMipmap && !state.draftHasMipmap) {
+ gl.generateMipmap(gl.TEXTURE_2D);
+ state.draftHasMipmap = true;
+ }
+ gl.texParameteri(
+ gl.TEXTURE_2D,
+ gl.TEXTURE_MIN_FILTER,
+ needsMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
+ );
+ }
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, state.currentZoom >= 2.0 ? gl.NEAREST : gl.LINEAR);
+
+ let effectiveDraftLayer: LayerItem =
+ state.currentOptions?.activeDraftMonochrome && layer.expressionColor !== 'monochrome'
+ ? { ...layer, expressionColor: 'monochrome' }
+ : layer;
+
+ if (isDestinationOutMask) {
+ // Destination-out draft is a pure alpha eraser mask; never modulate it by screentone, tint, or mono ink-channel exclusions
+ effectiveDraftLayer = {
+ ...effectiveDraftLayer,
+ toneEnabled: false,
+ layerColorEnabled: false,
+ monoExpressBlack: true,
+ monoExpressWhite: true,
+ };
+ }
+
+ if (draftSpace === 'viewport' && state.viewportDraftProgram && state.viewportDraftLocs) {
+ gl.useProgram(state.viewportDraftProgram);
+ syncFrameUniforms(state, gl, state.viewportDraftLocs);
+ gl.uniform1i(state.uViewportDraftTileTexLoc, 0);
+ gl.uniform1i(state.uViewportDraftIsBgLoc, 0);
+ applyLayerUniforms(
+ state,
+ gl,
+ state.viewportDraftLocs,
+ effectiveDraftLayer,
+ dimensions,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.quadBuffer);
+ if (state.aViewportDraftQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aViewportDraftQuadPosLoc);
+ gl.vertexAttribPointer(state.aViewportDraftQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, state.draftTexture);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ restoreStandardProgram(state, gl);
+ } else if (state.stdLocs) {
+ const docRect = state.currentOptions?.activeDraftDirtyRect;
+ const originX = docRect ? docRect.x : 0;
+ const originY = docRect ? docRect.y : 0;
+ const spanW = docRect ? docRect.width : dimensions.width;
+ const spanH = docRect ? docRect.height : dimensions.height;
+
+ restoreStandardProgram(state, gl);
+ syncFrameUniforms(state, gl, state.stdLocs);
+ gl.uniform1i(state.uTileTextureLoc, 0);
+ gl.uniform1i(state.uIsBackgroundLoc, 0);
+ applyLayerUniforms(
+ state,
+ gl,
+ state.stdLocs,
+ effectiveDraftLayer,
+ dimensions,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, state.draftTexture);
+ gl.uniform2f(state.uTileOriginLoc, originX, originY);
+ gl.uniform2f(state.uTileSizeLoc, spanW, spanH);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ gl.uniform2f(state.uTileSizeLoc, TILE_SIZE, TILE_SIZE);
+ }
+}
diff --git a/src/utils/compositor/tileTexturePool.ts b/src/utils/compositor/tileTexturePool.ts
new file mode 100644
index 0000000..b6c28ff
--- /dev/null
+++ b/src/utils/compositor/tileTexturePool.ts
@@ -0,0 +1,301 @@
+import { LayerItem } from '../../types/editor';
+import { SparseTileGrid, TILE_SIZE, TileBuffer, getTileKey } from '../tileEngine';
+import { premultiplyTileBytes } from './bounds';
+import { CompositorState, MAX_TEXTURE_POOL_SIZE } from './types';
+
+/**
+ * Explicitly invalidate a cached layer mask texture (or all masks if layerId omitted).
+ */
+export function invalidateMaskTexture(state: CompositorState, layerId?: string): void {
+ const nextEpoch = ++state.globalMaskEpochCounter;
+ if (layerId) {
+ const item = state.maskTextureCache.get(layerId);
+ if (item) item.version = -1;
+ state.maskInvalidationEpochs.set(layerId, nextEpoch);
+ } else {
+ for (const [id, item] of state.maskTextureCache.entries()) {
+ item.version = -1;
+ state.maskInvalidationEpochs.set(id, nextEpoch);
+ }
+ state.stackCache.invalidateAll();
+ }
+}
+
+/**
+ * Explicitly invalidate and clear all cached tile textures in both TEXTURE_2D and TEXTURE_2D_ARRAY pools.
+ */
+export function invalidateTileTextures(state: CompositorState): void {
+ if (state.gl) {
+ for (const slot of state.texturePool) {
+ state.gl.deleteTexture(slot.texture);
+ }
+ }
+ state.texturePool = [];
+ state.activePoolByKey.clear();
+ state.freeArraySlots = [];
+ for (let i = state.arrayPoolSlots.length - 1; i >= 0; i--) {
+ const slot = state.arrayPoolSlots[i];
+ slot.currentKey = null;
+ slot.version = -1;
+ slot.lastUsed = 0;
+ slot.lastBatchTick = 0;
+ state.freeArraySlots.push(slot);
+ }
+ state.arrayPoolByKey.clear();
+ state.stackCache.invalidateAll();
+}
+
+/**
+ * Allocates or updates a slice inside the TEXTURE_2D_ARRAY pool.
+ * Never evicts slices pinned by the current batchTick.
+ */
+export function getOrUploadArrayTileSlice(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ tile: TileBuffer,
+ grid: SparseTileGrid,
+ batchTick: number
+): number {
+ const gridId = typeof grid.getGridId === 'function' ? grid.getGridId() : 0;
+ const key = `${gridId}:${getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0)}`;
+ const accessTick = ++state.arrayAccessCounter;
+ let slot = state.arrayPoolByKey.get(key);
+
+ if (slot) {
+ // O(1) LRU promotion via JS Map insertion order
+ state.arrayPoolByKey.delete(key);
+ state.arrayPoolByKey.set(key, slot);
+ } else {
+ if (state.freeArraySlots.length > 0) {
+ slot = state.freeArraySlots.pop()!;
+ } else {
+ // Evict oldest unpinned slot from front of Map (O(1) amortized)
+ for (const candidate of state.arrayPoolByKey.values()) {
+ if (candidate.lastBatchTick !== batchTick) {
+ slot = candidate;
+ break;
+ }
+ }
+ if (!slot) return -1;
+ if (slot.currentKey) {
+ state.arrayPoolByKey.delete(slot.currentKey);
+ }
+ }
+ slot.currentKey = key;
+ slot.version = -1;
+ state.arrayPoolByKey.set(key, slot);
+ }
+
+ slot.lastUsed = accessTick;
+ slot.lastBatchTick = batchTick;
+
+ if (slot.version !== tile.version) {
+ const rgbaData = grid.getTileAsRGBA(tile);
+ const srcBytes =
+ rgbaData instanceof Uint8Array
+ ? rgbaData
+ : new Uint8Array(rgbaData.buffer, rgbaData.byteOffset, rgbaData.byteLength);
+
+ // Premultiply once on upload into reusable scratch buffer (TileBuffer remains straight-alpha;
+ // UNPACK_PREMULTIPLY_ALPHA_WEBGL stays false for WebGL2 spec compliance on texSubImage3D).
+ const uploadBytes = premultiplyTileBytes(srcBytes, tile, state.uploadPremulScratch);
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texSubImage3D(
+ gl.TEXTURE_2D_ARRAY,
+ 0,
+ 0,
+ 0,
+ slot.sliceIndex,
+ TILE_SIZE,
+ TILE_SIZE,
+ 1,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uploadBytes
+ );
+
+ slot.version = tile.version;
+ }
+
+ return slot.sliceIndex;
+}
+
+/**
+ * Get or upload a WebGLTexture from the fallback TEXTURE_2D pool with adaptive zoom filtering.
+ * Uses gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true) directly — zero CPU premultiply loop!
+ */
+export function getTileTexture(
+ state: CompositorState,
+ tile: TileBuffer,
+ grid: SparseTileGrid
+): WebGLTexture | null {
+ if (!state.gl) return null;
+ const gl = state.gl;
+ const gridId = typeof grid.getGridId === 'function' ? grid.getGridId() : 0;
+ const key = `${gridId}:${getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0)}`;
+ const accessTick = ++state.textureAccessCounter;
+
+ let slot = state.activePoolByKey.get(key);
+
+ if (slot) {
+ // O(1) LRU promotion via JS Map insertion order
+ state.activePoolByKey.delete(key);
+ state.activePoolByKey.set(key, slot);
+ } else {
+ if (state.texturePool.length < MAX_TEXTURE_POOL_SIZE) {
+ const tex = gl.createTexture();
+ if (!tex) return null;
+ slot = {
+ texture: tex,
+ currentKey: key,
+ version: -1,
+ lastUsed: accessTick,
+ filterTier: -1,
+ hasStorage: false,
+ hasMipmap: false,
+ };
+ state.texturePool.push(slot);
+ state.activePoolByKey.set(key, slot);
+ } else {
+ // O(1) LRU eviction from front of activePoolByKey Map
+ const oldestEntry = state.activePoolByKey.entries().next();
+ if (!oldestEntry.done) {
+ slot = oldestEntry.value[1];
+ state.activePoolByKey.delete(oldestEntry.value[0]);
+ } else {
+ slot = state.texturePool[0];
+ }
+ slot.currentKey = key;
+ slot.version = -1;
+ slot.lastUsed = accessTick;
+ slot.filterTier = -1;
+ slot.hasMipmap = false;
+ state.activePoolByKey.set(key, slot);
+ }
+ }
+
+ slot.lastUsed = accessTick;
+ const desiredTier = state.currentZoom < 0.99 ? 0 : state.currentZoom < 2.0 ? 1 : 2;
+
+ // Re-upload if version changed (direct GPU unpack premultiplication, zero JS pixel loop)
+ if (slot.version !== tile.version) {
+ gl.bindTexture(gl.TEXTURE_2D, slot.texture);
+
+ const rgbaData = grid.getTileAsRGBA(tile);
+ const srcBytes =
+ rgbaData instanceof Uint8Array
+ ? rgbaData
+ : new Uint8Array(rgbaData.buffer, rgbaData.byteOffset, rgbaData.byteLength);
+
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ if (slot.hasStorage && typeof gl.texSubImage2D === 'function') {
+ gl.texSubImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ 0,
+ 0,
+ TILE_SIZE,
+ TILE_SIZE,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ srcBytes
+ );
+ } else {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ TILE_SIZE,
+ TILE_SIZE,
+ 0,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ srcBytes
+ );
+ slot.hasStorage = true;
+ }
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+
+ slot.hasMipmap = false;
+ slot.version = tile.version;
+ slot.filterTier = -1; // Force filter parameter refresh
+ }
+
+ if (slot.filterTier !== desiredTier) {
+ gl.bindTexture(gl.TEXTURE_2D, slot.texture);
+ if (desiredTier <= 1) {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ } else {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ }
+ slot.filterTier = desiredTier;
+ }
+
+ return slot.texture;
+}
+
+/**
+ * Get or upload a WebGLTexture for a layer's mask canvas with dirty-version caching.
+ */
+export function getMaskTexture(state: CompositorState, layer: LayerItem): WebGLTexture | null {
+ if (!state.gl || !layer.maskCanvas) return null;
+ const gl = state.gl;
+ let cached = state.maskTextureCache.get(layer.id);
+ const currentVersion = layer.maskVersion ?? 0;
+ const maskW = layer.maskCanvas.width;
+ const maskH = layer.maskCanvas.height;
+
+ if (!cached) {
+ const tex = gl.createTexture();
+ if (!tex) return null;
+ cached = { texture: tex, version: -1, width: 0, height: 0 };
+ state.maskTextureCache.set(layer.id, cached);
+ }
+
+ if (cached.version !== currentVersion || cached.width !== maskW || cached.height !== maskH) {
+ gl.bindTexture(gl.TEXTURE_2D, cached.texture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ layer.maskCanvas
+ );
+
+ cached.version = currentVersion;
+ cached.width = maskW;
+ cached.height = maskH;
+ }
+
+ return cached.texture;
+}
+
+/**
+ * Evict least recently used tile textures when texture pool exceeds threshold.
+ */
+export function evictStaleTextures(state: CompositorState): void {
+ if (!state.gl || state.texturePool.length <= MAX_TEXTURE_POOL_SIZE) return;
+ state.texturePool.sort((a, b) => a.lastUsed - b.lastUsed);
+ while (state.texturePool.length > MAX_TEXTURE_POOL_SIZE) {
+ const slot = state.texturePool.shift();
+ if (slot) {
+ if (slot.currentKey) state.activePoolByKey.delete(slot.currentKey);
+ state.gl.deleteTexture(slot.texture);
+ }
+ }
+}
diff --git a/src/utils/compositor/types.ts b/src/utils/compositor/types.ts
new file mode 100644
index 0000000..25420d5
--- /dev/null
+++ b/src/utils/compositor/types.ts
@@ -0,0 +1,398 @@
+import {
+ LayerItem,
+ CanvasDimensions,
+ BlendMode,
+ CanvasColorMode,
+ SoftProofSettings,
+} from '../../types/editor';
+import { SparseTileGrid } from '../tileEngine';
+
+export const DEFAULT_ARRAY_POOL_LAYERS = 512;
+export const MAX_TEXTURE_POOL_SIZE = 2048;
+
+export interface ViewportTransform {
+ pan: { x: number; y: number };
+ zoom: number;
+ rotation: number; // in degrees
+ flipX?: boolean;
+ flipY?: boolean;
+}
+
+export const BLEND_MODE_MAP: Record<BlendMode, number> = {
+ normal: 0,
+ multiply: 1,
+ screen: 2,
+ overlay: 3,
+ darken: 4,
+ lighten: 5,
+ 'color-dodge': 6,
+ 'color-burn': 7,
+ 'hard-light': 8,
+ 'soft-light': 9,
+ difference: 10,
+ exclusion: 11,
+ 'pass-through': 12,
+ 'linear-burn': 13,
+ 'add-glow': 14,
+ 'color-dodge-glow': 15,
+ divide: 16,
+ 'vivid-light': 17,
+ 'linear-light': 18,
+ 'pin-light': 19,
+ 'hard-mix': 20,
+ subtract: 21,
+ 'darker-color': 22,
+ 'lighter-color': 23,
+ hue: 24,
+ saturation: 25,
+ color: 26,
+ luminosity: 27,
+};
+
+export interface LayerTreeNode {
+ layer: LayerItem;
+ children: LayerTreeNode[];
+}
+
+export interface TreeNodeRenderGroup {
+ baseNode: LayerTreeNode;
+ clippedNodes: LayerTreeNode[];
+}
+
+export interface LayerRenderGroup {
+ baseLayer: LayerItem;
+ clippedLayers: LayerItem[];
+}
+
+export interface OnionSkinCompositorFrame {
+ layerId: string;
+ tint: string;
+ opacity: number;
+}
+
+export interface CompositorOptions {
+ dimensions: CanvasDimensions;
+ colorMode?: CanvasColorMode;
+ showCheckerboard?: boolean;
+ transparentBackground?: boolean;
+ bypassStackCache?: boolean;
+ devicePixelRatio?: number;
+ onionSkinFrames?: OnionSkinCompositorFrame[];
+ softProof?: SoftProofSettings;
+ // Active layer identifier for Baked Layer Stack Cache partitioning (below / active / above)
+ activeLayerId?: string | null;
+ // WYSIWYG In-Stack Live Stroke Compositing
+ activeDraftCanvas?: HTMLCanvasElement | null;
+ activeDraftLayerId?: string | null;
+ activeDraftDirtyRect?: { x: number; y: number; width: number; height: number } | null;
+ activeDraftVersion?: number;
+ activeDraftSpace?: 'document' | 'viewport';
+ activeDraftOpacity?: number;
+ activeDraftMonochrome?: boolean;
+}
+
+export interface CompositingUnit {
+ /** Base node and its clipped siblings at this compositing level */
+ group: TreeNodeRenderGroup;
+ /** Accumulated opacity from enclosing pass-through folders */
+ inheritedOpacity: number;
+ /** All layer IDs contained in this unit (base, clipped siblings, and folder descendants) */
+ containedLayerIds: Set<string>;
+}
+
+export type AboveSliceStrategy = 'empty' | 'baked-normal' | 'baked-single-blend' | 'mixed';
+
+export interface LayerStackPartition {
+ /** Units strictly below the active unit (always safe to bake into belowActiveCacheFbo) */
+ belowUnits: CompositingUnit[];
+ /** The active unit containing activeLayerId, or null if none/hidden */
+ activeUnit: CompositingUnit | null;
+ /** Units above active that must render dynamically (non-associative blend modes / adjustments) */
+ aboveDynamicUnits: CompositingUnit[];
+ /** Units above activeDynamicUnits that can be baked into aboveActiveCacheFbo */
+ aboveCachedUnits: CompositingUnit[];
+ /** How aboveActiveCacheFbo should be composited over (below + active + aboveDynamic) */
+ aboveStrategy: AboveSliceStrategy;
+ /** Blend mode for aboveActiveCacheFbo when aboveStrategy === 'baked-single-blend' */
+ aboveCacheBlendMode: BlendMode;
+}
+
+export interface LayerStackCacheInput {
+ layers: LayerItem[];
+ activeLayerId?: string | null;
+ viewportW: number;
+ viewportH: number;
+ dpr: number;
+ dimensions: CanvasDimensions;
+ transform: ViewportTransform;
+ showCheckerboard?: boolean;
+ transparentBackground?: boolean;
+ colorMode?: CanvasColorMode;
+ onionSkinFrames?: OnionSkinCompositorFrame[];
+ getLayerContentVersion: (layerId: string) => number;
+ getMaskInvalidationEpoch?: (layerId: string) => number;
+ gridEpoch?: number;
+ gridId?: number;
+}
+
+export interface LayerStackCacheEvaluation {
+ partition: LayerStackPartition;
+ belowSignature: string;
+ aboveSignature: string;
+ belowDirty: boolean;
+ aboveDirty: boolean;
+}
+
+export interface LayerStackCacheTrackerLike {
+ evaluate(input: LayerStackCacheInput): LayerStackCacheEvaluation;
+ commit(belowSignature: string, aboveSignature: string): void;
+ invalidateAll(): void;
+ invalidateBelow(): void;
+ invalidateAbove(): void;
+ getLastSignatures(): { below: string | null; above: string | null };
+}
+
+export interface FboSurface {
+ fbo: WebGLFramebuffer;
+ texture: WebGLTexture;
+ stencilRb: WebGLRenderbuffer | null;
+ width: number;
+ height: number;
+}
+
+export interface PingPongTarget {
+ surfaces: [FboSurface, FboSurface];
+ activeIndex: 0 | 1;
+}
+
+export interface LayerUniformLocs {
+ uDocDimensions: WebGLUniformLocation | null;
+ uViewportSize: WebGLUniformLocation | null;
+ uPan: WebGLUniformLocation | null;
+ uZoom: WebGLUniformLocation | null;
+ uRotationRad: WebGLUniformLocation | null;
+ uFlip: WebGLUniformLocation | null;
+ uDpr: WebGLUniformLocation | null;
+ uBackdropTexture: WebGLUniformLocation | null;
+ uHasBackdrop: WebGLUniformLocation | null;
+ uLayerOpacity: WebGLUniformLocation | null;
+ uBlendMode: WebGLUniformLocation | null;
+ uToneEnabled: WebGLUniformLocation | null;
+ uToneFrequency: WebGLUniformLocation | null;
+ uToneAngleRad: WebGLUniformLocation | null;
+ uToneDpi: WebGLUniformLocation | null;
+ uToneDotShape: WebGLUniformLocation | null;
+ uToneDensity: WebGLUniformLocation | null;
+ uToneDensityType: WebGLUniformLocation | null;
+ uLayerColorEnabled: WebGLUniformLocation | null;
+ uLayerColor: WebGLUniformLocation | null;
+ uLayerSubColor: WebGLUniformLocation | null;
+ uMaskTexture: WebGLUniformLocation | null;
+ uMaskEnabled: WebGLUniformLocation | null;
+ uExpressionMode: WebGLUniformLocation | null;
+ uMonoThreshold: WebGLUniformLocation | null;
+ uMonoExpressBlack: WebGLUniformLocation | null;
+ uMonoExpressWhite: WebGLUniformLocation | null;
+}
+
+export interface ArrayPoolSlot {
+ sliceIndex: number;
+ currentKey: string | null;
+ version: number;
+ lastUsed: number;
+ lastBatchTick: number;
+}
+
+export interface Texture2DPoolSlot {
+ texture: WebGLTexture;
+ currentKey: string | null;
+ version: number;
+ lastUsed: number;
+ filterTier?: number;
+ hasStorage?: boolean;
+ hasMipmap?: boolean;
+}
+
+export interface MaskTextureCacheEntry {
+ texture: WebGLTexture;
+ version: number;
+ width: number;
+ height: number;
+}
+
+export interface FrameState {
+ viewportW: number;
+ viewportH: number;
+ dpr: number;
+ dimensions: CanvasDimensions;
+ transform: ViewportTransform;
+ rotRad: number;
+}
+
+export interface DocumentBounds {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+}
+
+export interface CompositorState {
+ canvas: HTMLCanvasElement;
+ gl: WebGL2RenderingContext | null;
+ program: WebGLProgram | null;
+ quadBuffer: WebGLBuffer | null;
+
+ // Standard compositor uniform locations
+ uTileOriginLoc: WebGLUniformLocation | null;
+ uTileSizeLoc: WebGLUniformLocation | null;
+ uIsBackgroundLoc: WebGLUniformLocation | null;
+ uShowCheckerboardLoc: WebGLUniformLocation | null;
+ uTileTextureLoc: WebGLUniformLocation | null;
+ stdLocs: LayerUniformLocs | null;
+
+ // Instanced TEXTURE_2D_ARRAY batching program, VAO, buffer, & pool
+ instancedProgram: WebGLProgram | null;
+ instancedLocs: LayerUniformLocs | null;
+ uInstTileSizeLoc: WebGLUniformLocation | null;
+ uInstTileArrayLoc: WebGLUniformLocation | null;
+ aInstQuadPosLoc: number;
+ aInstDataLoc: number;
+ instancedVao: WebGLVertexArrayObject | null;
+ instanceBuffer: WebGLBuffer | null;
+ instanceFloatScratch: Float32Array;
+ tileArrayTexture: WebGLTexture | null;
+ arrayPoolCapacity: number;
+ arrayPoolFilterTier: number;
+ arrayPoolSlots: ArrayPoolSlot[];
+ freeArraySlots: ArrayPoolSlot[];
+ arrayPoolByKey: Map<string, ArrayPoolSlot>;
+ arrayAccessCounter: number;
+ arrayBatchCounter: number;
+ uploadPremulScratch: Uint8Array;
+ readonly preserveDrawingBuffer: boolean;
+
+ // Viewport-space draft stroke program (reuses COMPOSITOR_FRAGMENT_SHADER)
+ viewportDraftProgram: WebGLProgram | null;
+ viewportDraftLocs: LayerUniformLocs | null;
+ uViewportDraftTileTexLoc: WebGLUniformLocation | null;
+ uViewportDraftIsBgLoc: WebGLUniformLocation | null;
+ aViewportDraftQuadPosLoc: number;
+
+ // Cached attribute locations
+ aQuadPosLoc: number;
+ aStylesQuadPosLoc: number;
+ aBlitQuadPosLoc: number;
+ aProofQuadPosLoc: number;
+ contextLost: boolean;
+ onContextLostHandler: ((e: Event) => void) | null;
+ onContextRestoredHandler: (() => void) | null;
+
+ // Mask version-tracked cache & invalidation epochs
+ maskTextureCache: Map<string, MaskTextureCacheEntry>;
+ maskInvalidationEpochs: Map<string, number>;
+ globalMaskEpochCounter: number;
+
+ // Live in-stack draft stroke texture cache
+ draftTexture: WebGLTexture | null;
+ draftTexWidth: number;
+ draftTexHeight: number;
+ draftHasMipmap: boolean;
+ lastDraftVersion: number;
+ currentOptions: CompositorOptions | null;
+ currentZoom: number;
+ currentFrameState: FrameState | null;
+
+ // Adjustment program & uniforms
+ adjProgram: WebGLProgram | null;
+ uAdjTileOriginLoc: WebGLUniformLocation | null;
+ uAdjTileSizeLoc: WebGLUniformLocation | null;
+ uAdjDocDimensionsLoc: WebGLUniformLocation | null;
+ uAdjViewportSizeLoc: WebGLUniformLocation | null;
+ uAdjPanLoc: WebGLUniformLocation | null;
+ uAdjZoomLoc: WebGLUniformLocation | null;
+ uAdjRotationRadLoc: WebGLUniformLocation | null;
+ uAdjFlipLoc: WebGLUniformLocation | null;
+ uAdjDprLoc: WebGLUniformLocation | null;
+ uAdjSnapshotLoc: WebGLUniformLocation | null;
+ uAdjLutLoc: WebGLUniformLocation | null;
+ uAdjModeLoc: WebGLUniformLocation | null;
+ uAdjOpacityLoc: WebGLUniformLocation | null;
+ uAdjMaskEnabledLoc: WebGLUniformLocation | null;
+ uAdjMaskTextureLoc: WebGLUniformLocation | null;
+
+ lutTexture: WebGLTexture | null;
+ lastLutKey: string;
+ lastLutAdjMode: number;
+
+ // Layer Styles program, FBO & uniforms
+ stylesProgram: WebGLProgram | null;
+ stylesQuadBuffer: WebGLBuffer | null;
+ layerFbo: WebGLFramebuffer | null;
+ layerTexture: WebGLTexture | null;
+ layerFboWidth: number;
+ layerFboHeight: number;
+ layerStylesOutFbo: FboSurface | null;
+
+ uStylesLayerTextureLoc: WebGLUniformLocation | null;
+ uStylesViewportSizeLoc: WebGLUniformLocation | null;
+ uStylesLayerOpacityLoc: WebGLUniformLocation | null;
+ uStylesStrokeEnabledLoc: WebGLUniformLocation | null;
+ uStylesStrokeSizeLoc: WebGLUniformLocation | null;
+ uStylesStrokeColorLoc: WebGLUniformLocation | null;
+ uStylesStrokePositionLoc: WebGLUniformLocation | null;
+ uStylesGlowEnabledLoc: WebGLUniformLocation | null;
+ uStylesGlowColorLoc: WebGLUniformLocation | null;
+ uStylesGlowBlurLoc: WebGLUniformLocation | null;
+ uStylesGlowSpreadLoc: WebGLUniformLocation | null;
+ uStylesShadowEnabledLoc: WebGLUniformLocation | null;
+ uStylesShadowColorLoc: WebGLUniformLocation | null;
+ uStylesShadowOffsetLoc: WebGLUniformLocation | null;
+ uStylesShadowBlurLoc: WebGLUniformLocation | null;
+ uStylesShadowSpreadLoc: WebGLUniformLocation | null;
+
+ // Folder / Cache blit program & uniforms
+ blitProgram: WebGLProgram | null;
+ uBlitTextureLoc: WebGLUniformLocation | null;
+ uBlitBackdropTextureLoc: WebGLUniformLocation | null;
+ uBlitHasBackdropLoc: WebGLUniformLocation | null;
+ uBlitBlendModeLoc: WebGLUniformLocation | null;
+ uBlitOpacityLoc: WebGLUniformLocation | null;
+
+ // Frame Border Folder polygon program & dynamic vertex buffer
+ framePolyProgram: WebGLProgram | null;
+ framePolyBuffer: WebGLBuffer | null;
+ aFramePolyDocPosLoc: number;
+ uFramePolyDocDimensionsLoc: WebGLUniformLocation | null;
+ uFramePolyViewportSizeLoc: WebGLUniformLocation | null;
+ uFramePolyPanLoc: WebGLUniformLocation | null;
+ uFramePolyZoomLoc: WebGLUniformLocation | null;
+ uFramePolyRotationRadLoc: WebGLUniformLocation | null;
+ uFramePolyFlipLoc: WebGLUniformLocation | null;
+ uFramePolyDprLoc: WebGLUniformLocation | null;
+ uFramePolyColorLoc: WebGLUniformLocation | null;
+
+ // Ping-Pong FBOs
+ scenePingPong: PingPongTarget | null;
+ folderPingPongs: PingPongTarget[];
+
+ // Baked Layer Stack Cache FBOs
+ belowActiveCacheFbo: FboSurface | null;
+ aboveActiveCacheFbo: FboSurface | null;
+ stackCache: LayerStackCacheTrackerLike;
+ stackCacheStats: { belowRebuilds: number; aboveRebuilds: number; cacheHits: number };
+
+ // Soft proofing program & uniforms
+ softProofProgram: WebGLProgram | null;
+ uProofSceneTextureLoc: WebGLUniformLocation | null;
+ uProofStandardLoc: WebGLUniformLocation | null;
+ uProofEnabledLoc: WebGLUniformLocation | null;
+ uProofGamutWarningLoc: WebGLUniformLocation | null;
+ uProofGamutWarningColorLoc: WebGLUniformLocation | null;
+
+ // Pre-allocated WebGL2 Texture2D Pool (overflow fallback for TEXTURE_2D_ARRAY)
+ textureAccessCounter: number;
+ texturePool: Texture2DPoolSlot[];
+ activePoolByKey: Map<string, Texture2DPoolSlot>;
+ fallbackTileCanvas: HTMLCanvasElement | null;
+ lastRenderedGrid: SparseTileGrid | null;
+}
diff --git a/src/utils/compositor/unitRenderer.ts b/src/utils/compositor/unitRenderer.ts
new file mode 100644
index 0000000..2481291
--- /dev/null
+++ b/src/utils/compositor/unitRenderer.ts
@@ -0,0 +1,436 @@
+import { BlendMode, CanvasDimensions, isFolderLikeLayer } from '../../types/editor';
+import { buildFrameBorderTriangles, triangulatePolygon } from '../frameEngine';
+import { SparseTileGrid } from '../tileEngine';
+import { parseHexColor } from './bounds';
+import {
+ blitFolderTexture,
+ drawFramePolygonTriangles,
+ renderAdjustmentLayer,
+} from './effectsPass';
+import { ensureFolderPingPong } from './fboManager';
+import { renderLayerWithStyles, renderSingleLayer } from './layerRenderer';
+import { flattenLayerTreeToUnits } from './layerTree';
+import { hasActiveLayerStyles } from './shaders/effectShaders';
+import {
+ CompositingUnit,
+ CompositorState,
+ DocumentBounds,
+ LayerTreeNode,
+ PingPongTarget,
+ ViewportTransform,
+} from './types';
+
+/**
+ * Renders a single atomic CompositingUnit (an isolated folder, adjustment layer, or base + clipped group)
+ * into the active Ping-Pong target.
+ */
+export function renderCompositingUnit(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ unit: CompositingUnit,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ frustum: DocumentBounds,
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ dpr: number,
+ target: PingPongTarget | null,
+ depth: number,
+ overrideRootBlendNormal: boolean
+): void {
+ const group = unit.group;
+ const baseNode = group.baseNode;
+ const baseLayer = overrideRootBlendNormal
+ ? { ...baseNode.layer, blendMode: 'normal' as BlendMode }
+ : baseNode.layer;
+
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001) {
+ return;
+ }
+
+ if (baseLayer.type === 'frame-folder') {
+ const folderTarget = ensureFolderPingPong(state, gl, depth, viewportW, viewportH);
+ if (!folderTarget) return;
+
+ const frames = (baseLayer.comicFrames || []).filter((f) => f.polygon.length >= 3);
+
+ // 1. Render nested child layers into folderTarget.surfaces[0] cleanly (no stencil conflict with child clipping masks)
+ folderTarget.activeIndex = 0;
+ const childSurf = folderTarget.surfaces[0];
+ gl.bindFramebuffer(gl.FRAMEBUFFER, childSurf.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ if (baseNode.children.length > 0) {
+ renderNodeList(
+ state,
+ gl,
+ baseNode.children,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ folderTarget,
+ depth + 1,
+ 1.0
+ );
+ }
+
+ const renderedChildrenTex = folderTarget.surfaces[folderTarget.activeIndex].texture;
+ const outIdx: 0 | 1 = folderTarget.activeIndex === 0 ? 1 : 0;
+ const outSurf = folderTarget.surfaces[outIdx];
+
+ gl.bindFramebuffer(gl.FRAMEBUFFER, outSurf.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ const shouldClip = frames.length > 0 && frames.some((f) => f.clipChildren !== false);
+
+ if (frames.length > 0 && state.framePolyProgram && state.framePolyBuffer) {
+ // 2. Write frame polygon interiors into stencil buffer (and optional background fill)
+ if (shouldClip) {
+ gl.enable(gl.STENCIL_TEST);
+ gl.stencilMask(0xFF);
+ gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
+ }
+
+ for (const frame of frames) {
+ const fillVerts = triangulatePolygon(frame.polygon);
+ if (fillVerts.length < 6) continue;
+ const doFill = frame.fillBackground !== false;
+ if (!doFill) {
+ gl.colorMask(false, false, false, false);
+ }
+ const [fr, fg, fb] = parseHexColor(frame.fillColor || '#ffffff');
+ drawFramePolygonTriangles(
+ state,
+ gl,
+ fillVerts,
+ fr,
+ fg,
+ fb,
+ 1.0,
+ dimensions,
+ viewportW,
+ viewportH,
+ transform,
+ dpr
+ );
+ if (!doFill) {
+ gl.colorMask(true, true, true, true);
+ }
+ }
+
+ // 3. Blit rendered children strictly inside stencil == 1
+ if (shouldClip) {
+ gl.stencilMask(0x00);
+ gl.stencilFunc(gl.EQUAL, 1, 0xFF);
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
+ }
+
+ blitFolderTexture(
+ state,
+ gl,
+ renderedChildrenTex,
+ 'normal',
+ 1.0,
+ viewportW,
+ viewportH,
+ null,
+ shouldClip
+ );
+
+ gl.stencilMask(0xFF);
+ gl.disable(gl.STENCIL_TEST);
+
+ // 4. Draw crisp frame borders ON TOP of clipped folder contents
+ for (const frame of frames) {
+ const borderVerts = buildFrameBorderTriangles(frame.polygon, frame.borderWidth || 3);
+ if (borderVerts.length < 6) continue;
+ const [sr, sg, sb] = parseHexColor(frame.strokeColor || '#000000');
+ drawFramePolygonTriangles(
+ state,
+ gl,
+ borderVerts,
+ sr,
+ sg,
+ sb,
+ 1.0,
+ dimensions,
+ viewportW,
+ viewportH,
+ transform,
+ dpr
+ );
+ }
+
+ folderTarget.activeIndex = outIdx;
+ }
+
+ // 5. Composite finished frame folder onto parent framebuffer
+ const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+
+ const folderBlend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;
+ blitFolderTexture(
+ state,
+ gl,
+ folderTarget.surfaces[folderTarget.activeIndex].texture,
+ folderBlend,
+ baseLayer.opacity * unit.inheritedOpacity,
+ viewportW,
+ viewportH,
+ target,
+ false
+ );
+ return;
+ }
+
+ if (baseLayer.type === 'folder') {
+ const folderTarget = ensureFolderPingPong(state, gl, depth, viewportW, viewportH);
+ if (!folderTarget) return;
+
+ folderTarget.activeIndex = 0;
+ const folderSurf = folderTarget.surfaces[0];
+ gl.bindFramebuffer(gl.FRAMEBUFFER, folderSurf.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ renderNodeList(
+ state,
+ gl,
+ baseNode.children,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ folderTarget,
+ depth + 1,
+ 1.0
+ );
+
+ // Restore parent target framebuffer and blit isolated folder result
+ const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+
+ blitFolderTexture(
+ state,
+ gl,
+ folderTarget.surfaces[folderTarget.activeIndex].texture,
+ baseLayer.blendMode,
+ baseLayer.opacity * unit.inheritedOpacity,
+ viewportW,
+ viewportH,
+ target,
+ false
+ );
+ return;
+ }
+
+ const activeClippedLayers = group.clippedNodes
+ .map((n) => n.layer)
+ .filter((cl) => cl.visible && cl.opacity > 0.001 && !isFolderLikeLayer(cl));
+
+ const baseEffectiveOpacity = unit.inheritedOpacity;
+
+ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
+ renderAdjustmentLayer(
+ state,
+ gl,
+ baseLayer,
+ transform,
+ dimensions,
+ viewportW,
+ viewportH,
+ dpr,
+ baseEffectiveOpacity,
+ target,
+ false
+ );
+ return;
+ }
+
+ const baseHasStyles = hasActiveLayerStyles(baseLayer.styles);
+
+ if (activeClippedLayers.length > 0) {
+ // Record base layer silhouette in stencil buffer of the current Ping-Pong surface
+ gl.enable(gl.STENCIL_TEST);
+ gl.clear(gl.STENCIL_BUFFER_BIT);
+ gl.stencilMask(0xFF);
+ gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
+
+ if (baseHasStyles) {
+ // Record base layer silhouette in stencil without writing colors
+ gl.colorMask(false, false, false, false);
+ renderSingleLayer(
+ state,
+ gl,
+ { ...baseLayer, blendMode: 'normal' },
+ dimensions,
+ grid,
+ frustum,
+ baseEffectiveOpacity,
+ target,
+ true
+ );
+ gl.colorMask(true, true, true, true);
+
+ // Draw base layer with styles (do not overwrite stencil with shadow/glow)
+ gl.stencilMask(0x00);
+ renderLayerWithStyles(
+ state,
+ gl,
+ baseLayer,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ baseEffectiveOpacity,
+ target,
+ true
+ );
+ gl.stencilMask(0xFF);
+ } else {
+ renderSingleLayer(
+ state,
+ gl,
+ baseLayer,
+ dimensions,
+ grid,
+ frustum,
+ baseEffectiveOpacity,
+ target,
+ true
+ );
+ }
+
+ // Render clipped layers: only draw over opaque pixels of base layer (stencil == 1)
+ gl.stencilMask(0x00);
+ gl.stencilFunc(gl.EQUAL, 1, 0xFF);
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
+
+ for (const clippedLayer of activeClippedLayers) {
+ if (hasActiveLayerStyles(clippedLayer.styles)) {
+ renderLayerWithStyles(
+ state,
+ gl,
+ clippedLayer,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ baseEffectiveOpacity,
+ target,
+ true
+ );
+ } else {
+ renderSingleLayer(
+ state,
+ gl,
+ clippedLayer,
+ dimensions,
+ grid,
+ frustum,
+ baseEffectiveOpacity,
+ target,
+ true
+ );
+ }
+ }
+
+ gl.stencilMask(0xFF);
+ gl.disable(gl.STENCIL_TEST);
+ } else {
+ gl.disable(gl.STENCIL_TEST);
+ if (baseHasStyles) {
+ renderLayerWithStyles(
+ state,
+ gl,
+ baseLayer,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ baseEffectiveOpacity,
+ target,
+ false
+ );
+ } else {
+ renderSingleLayer(
+ state,
+ gl,
+ baseLayer,
+ dimensions,
+ grid,
+ frustum,
+ baseEffectiveOpacity,
+ target,
+ false
+ );
+ }
+ }
+}
+
+/**
+ * Recursively composite a layer hierarchy, supporting folder pass-through and isolated offscreen rendering.
+ */
+export function renderNodeList(
+ state: CompositorState,
+ gl: WebGL2RenderingContext,
+ nodes: LayerTreeNode[],
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ frustum: DocumentBounds,
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ dpr: number,
+ target: PingPongTarget | null,
+ depth: number,
+ inheritedOpacity: number
+): void {
+ const units = flattenLayerTreeToUnits(nodes, inheritedOpacity);
+ for (const unit of units) {
+ renderCompositingUnit(
+ state,
+ gl,
+ unit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ target,
+ depth,
+ false
+ );
+ }
+}
diff --git a/src/utils/cspParser.ts b/src/utils/cspParser.ts
index 0b2f5d6..e4a71d8 100644
--- a/src/utils/cspParser.ts
+++ b/src/utils/cspParser.ts
@@ -1,25 +1,12 @@
-import initSqlJs, { Database, SqlValue } from 'sql.js';
-import { Unzlib, inflateSync } from 'fflate';
-import {
- BlendMode,
- CanvasColorMode,
- LayerItem,
- LoadedDocument,
-} from '../types/editor';
-import { createCanvasThumbnail } from './canvasUtils';
+import { Unzlib, inflateSync } from 'fflate';
+import { BlendMode, LoadedDocument } from '../types/editor';
+import { isNativeRustAvailable, parseClipNative } from './nativeBackend';
import { SparseTileGrid, TILE_SIZE, TILE_PIXELS } from './tileEngine';
const MAX_CANVAS_DIM = 32768;
const MAX_BLOCKS_PER_LAYER = 16384; // 128x128 tiles = 32768x32768 px
const MAX_COMPRESSED_TILE_BYTES = 2 * 1024 * 1024;
const MAX_DECOMPRESSED_TILE_BYTES = 2 * 1024 * 1024;
-const MAX_FOLDER_DEPTH = 64;
-const MAX_LAYERS = 4096;
-
-const SQLITE_SIG = new Uint8Array([
- 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
- 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
-]);
function encodeUtf16BeTagged(ascii: string): Uint8Array {
const out = new Uint8Array(4 + ascii.length * 2);
@@ -37,21 +24,6 @@ const TAG_BLOCK_END = encodeUtf16BeTagged('BlockDataEndChunk');
const TAG_PARAMETER = encodeUtf16BeTagged('Parameter');
const TAG_INIT_COLOR = encodeUtf16BeTagged('InitColor');
-let sqlJsPromise: Promise<Awaited<ReturnType<typeof initSqlJs>>> | null = null;
-
-async function getSql() {
- if (!sqlJsPromise) {
- const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
- sqlJsPromise = initSqlJs(
- isBrowser ? { locateFile: () => '/sql-wasm.wasm' } : undefined
- ).catch((err) => {
- sqlJsPromise = null;
- throw err;
- });
- }
- return await sqlJsPromise;
-}
-
/**
* Maps Clip Studio Paint LayerComposite integer to Ink Studio BlendMode.
* Reference: CSP internal composite mode enum (0..36).
@@ -69,9 +41,9 @@ export function mapCspBlendMode(val: number): BlendMode {
case 4:
return 'linear-burn';
case 5:
- return 'difference'; // Subtract
+ return 'subtract'; // Subtract
case 6:
- return 'darken'; // Darker Color
+ return 'darker-color'; // Darker Color
case 7:
return 'lighten';
case 8:
@@ -85,21 +57,33 @@ export function mapCspBlendMode(val: number): BlendMode {
case 12:
return 'add-glow'; // Add (Glow)
case 13:
- return 'lighten'; // Lighter Color
+ return 'lighter-color'; // Lighter Color
case 14:
return 'overlay';
case 15:
return 'soft-light';
case 16:
- case 17: // Vivid Light
- case 18: // Linear Light
- case 19: // Pin Light
- case 20: // Hard Mix
return 'hard-light';
+ case 17:
+ return 'vivid-light'; // Vivid Light
+ case 18:
+ return 'linear-light'; // Linear Light
+ case 19:
+ return 'pin-light'; // Pin Light
+ case 20:
+ return 'hard-mix'; // Hard Mix
case 21:
return 'difference';
case 22:
return 'exclusion';
+ case 23:
+ return 'hue';
+ case 24:
+ return 'saturation';
+ case 25:
+ return 'color';
+ case 26:
+ return 'luminosity';
case 30:
return 'pass-through'; // Through (folder)
case 36:
@@ -232,16 +216,6 @@ export function parseCspChunks(buffer: Uint8Array): CspChunk[] {
return chunks;
}
-function findSqliteData(chunks: CspChunk[], rawBuffer: Uint8Array): Uint8Array | null {
- const sqliChunk = chunks.find((c) => c.name === 'SQLi');
- if (sqliChunk) {
- const idx = indexOfBytes(sqliChunk.data, SQLITE_SIG, 0);
- if (idx >= 0) return sqliChunk.data.subarray(idx);
- }
- const idx = indexOfBytes(rawBuffer, SQLITE_SIG, 0);
- return idx >= 0 ? rawBuffer.subarray(idx) : null;
-}
-
/**
* Extracts CHNKExta external payloads keyed by external ID (e.g. "extrnlid...").
*/
@@ -743,885 +717,20 @@ export function decodeCspTileToRgba(
return false;
}
-/**
- * Unpacks a single 256x256 mask tile into 65536 grayscale bytes (0 = hidden, 255 = revealed).
- */
-function decodeCspTileToMaskValues(raw: Uint8Array, outMask: Uint8Array): boolean {
- if (raw.byteLength >= TILE_PIXELS) {
- outMask.set(raw.subarray(0, TILE_PIXELS));
- return true;
- }
- if (raw.byteLength >= 8192) {
- for (let byteIdx = 0; byteIdx < 8192; byteIdx++) {
- const b = raw[byteIdx];
- const baseP = byteIdx << 3;
- for (let bit = 0; bit < 8; bit++) {
- outMask[baseP + bit] = (b & (1 << (7 - bit))) !== 0 ? 255 : 0;
- }
- }
- return true;
- }
- return false;
-}
-
-/**
- * Writes a clipped tile rectangle into SparseTileGrid without allocating a full-document canvas.
- */
-function writeClippedTileToGrid(
- tileGrid: SparseTileGrid,
- layerId: string,
- tileRgba: Uint8ClampedArray,
- tileDocX: number,
- tileDocY: number,
- maxBitmapW: number,
- maxBitmapH: number,
- offsetX: number,
- offsetY: number,
- docWidth: number,
- docHeight: number
-): void {
- const validRight = Math.min(docWidth, offsetX + maxBitmapW);
- const validBottom = Math.min(docHeight, offsetY + maxBitmapH);
-
- const srcX0 = Math.max(0, -tileDocX);
- const srcY0 = Math.max(0, -tileDocY);
- const srcX1 = Math.min(TILE_SIZE, validRight - tileDocX);
- const srcY1 = Math.min(TILE_SIZE, validBottom - tileDocY);
- if (srcX0 >= srcX1 || srcY0 >= srcY1) return;
-
- if (srcX0 === 0 && srcY0 === 0 && srcX1 === TILE_SIZE && srcY1 === TILE_SIZE) {
- tileGrid.writeImageData(
- layerId,
- { data: tileRgba, width: TILE_SIZE, height: TILE_SIZE },
- tileDocX,
- tileDocY,
- 'color-32bit',
- true
- );
- return;
- }
-
- const cw = srcX1 - srcX0;
- const ch = srcY1 - srcY0;
- const cropped = new Uint8ClampedArray(cw * ch * 4);
- const rowBytes = cw * 4;
- for (let row = 0; row < ch; row++) {
- const srcOff = ((srcY0 + row) * TILE_SIZE + srcX0) * 4;
- cropped.set(tileRgba.subarray(srcOff, srcOff + rowBytes), row * rowBytes);
- }
- tileGrid.writeImageData(
- layerId,
- { data: cropped, width: cw, height: ch },
- tileDocX + srcX0,
- tileDocY + srcY0,
- 'color-32bit',
- true
- );
-}
-
-/**
- * Decodes a CSP mask offscreen into an Ink Studio maskCanvas (grayscale RGB, alpha=255).
- */
-function buildMaskCanvasFromOffscreen(
- offscreen: OffscreenRecord,
- extaChunks: Map<string, Uint8Array>,
- maskOffsetX: number,
- maskOffsetY: number,
- docWidth: number,
- docHeight: number,
- maskScratch: Uint8Array
-): HTMLCanvasElement | undefined {
- if (typeof document === 'undefined') return undefined;
-
- const attr = parseOffscreenAttribute(offscreen.attribute, docWidth, docHeight);
- const defaultVal = attr.defaultFill !== 0 ? 255 : 0;
-
- const maskCanvas = document.createElement('canvas');
- maskCanvas.width = docWidth;
- maskCanvas.height = docHeight;
- const mCtx = maskCanvas.getContext('2d', { willReadFrequently: true });
- if (!mCtx) return undefined;
-
- const outImg = mCtx.createImageData(docWidth, docHeight);
- const out = outImg.data;
- for (let i = 0; i < out.length; i += 4) {
- out[i] = defaultVal;
- out[i + 1] = defaultVal;
- out[i + 2] = defaultVal;
- out[i + 3] = 255;
- }
-
- const payload = offscreen.blockDataId ? extaChunks.get(offscreen.blockDataId) : undefined;
- if (payload) {
- const totalBlocks = attr.blockGridWidth * attr.blockGridHeight;
- const tiles = parseBlockDataPayload(payload, totalBlocks);
- for (const [blockIdx, raw] of tiles.entries()) {
- if (!decodeCspTileToMaskValues(raw, maskScratch)) continue;
- const col = blockIdx % attr.blockGridWidth;
- const row = Math.floor(blockIdx / attr.blockGridWidth);
- const tileDocX = col * TILE_SIZE + maskOffsetX;
- const tileDocY = row * TILE_SIZE + maskOffsetY;
-
- const x0 = Math.max(0, -tileDocX);
- const y0 = Math.max(0, -tileDocY);
- const x1 = Math.min(TILE_SIZE, docWidth - tileDocX, attr.bitmapWidth - col * TILE_SIZE);
- const y1 = Math.min(TILE_SIZE, docHeight - tileDocY, attr.bitmapHeight - row * TILE_SIZE);
- if (x0 >= x1 || y0 >= y1) continue;
-
- for (let sy = y0; sy < y1; sy++) {
- const dy = tileDocY + sy;
- const srcRow = sy * TILE_SIZE;
- const dstRow = dy * docWidth;
- for (let sx = x0; sx < x1; sx++) {
- const v = maskScratch[srcRow + sx];
- const di = (dstRow + tileDocX + sx) << 2;
- out[di] = v;
- out[di + 1] = v;
- out[di + 2] = v;
- out[di + 3] = 255;
- }
- }
- }
- }
-
- mCtx.putImageData(outImg, 0, 0);
- return maskCanvas;
-}
-
-type SqlRow = Record<string, SqlValue>;
-
-function getTableNames(db: Database): Set<string> {
- const names = new Set<string>();
- try {
- const res = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
- if (res.length > 0) {
- for (const row of res[0].values) {
- if (typeof row[0] === 'string') names.add(row[0]);
- }
- }
- } catch {
- // ignore
- }
- return names;
-}
-
-function queryTable(db: Database, tables: Set<string>, tableName: string): SqlRow[] {
- if (!tables.has(tableName)) return [];
- try {
- const res = db.exec(`SELECT * FROM "${tableName.replace(/"/g, '""')}"`);
- if (res.length === 0) return [];
- const { columns, values } = res[0];
- const out: SqlRow[] = new Array(values.length);
- for (let i = 0; i < values.length; i++) {
- const obj: SqlRow = {};
- const row = values[i];
- for (let c = 0; c < columns.length; c++) {
- obj[columns[c]] = row[c];
- }
- out[i] = obj;
- }
- return out;
- } catch {
- return [];
- }
-}
-
-function getNum(row: SqlRow, keys: string[], fallback: number): number {
- for (const k of keys) {
- const v = row[k];
- if (typeof v === 'number' && Number.isFinite(v)) return v;
- }
- return fallback;
-}
-
-function getOptNum(row: SqlRow, keys: string[]): number | null {
- for (const k of keys) {
- const v = row[k];
- if (typeof v === 'number' && Number.isFinite(v)) return v;
- }
- return null;
-}
-
-const utf8Decoder = new TextDecoder('utf-8', { fatal: false });
-
-function getStr(row: SqlRow, keys: string[], fallback: string): string {
- for (const k of keys) {
- const v = row[k];
- if (typeof v === 'string' && v.length > 0) return v.replace(/\0+$/, '');
- if (v instanceof Uint8Array && v.byteLength > 0) {
- const decoded = utf8Decoder.decode(v).replace(/\0+$/, '');
- if (decoded.length > 0) return decoded;
- }
- }
- return fallback;
-}
-
-function getBytes(row: SqlRow, keys: string[]): Uint8Array | null {
- for (const k of keys) {
- const v = row[k];
- if (v instanceof Uint8Array && v.byteLength > 0) return v;
- }
- return null;
-}
-
-function rgbToHex(r: number, g: number, b: number): string {
- const clamp = (n: number) => Math.max(0, Math.min(255, Math.round(n)));
- return (
- '#' +
- ((1 << 24) | (clamp(r) << 16) | (clamp(g) << 8) | clamp(b))
- .toString(16)
- .slice(1)
- );
-}
-
-function normalizeColorChannel(v: number): number {
- if (v <= 255) return Math.max(0, Math.round(v));
- if (v <= 65535) return (v >> 8) & 0xff;
- return (v >>> 24) & 0xff;
-}
-
-function bytesToPngDataUrl(bytes: Uint8Array): string | undefined {
- if (bytes.byteLength < 8) return undefined;
- // Detect PNG or JPEG magic
- const isPng =
- bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47;
- const isJpeg = bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
- if (!isPng && !isJpeg) return undefined;
- const mime = isPng ? 'image/png' : 'image/jpeg';
- if (typeof btoa === 'function') {
- let bin = '';
- const step = 0x8000;
- for (let i = 0; i < bytes.byteLength; i += step) {
- bin += String.fromCharCode(...bytes.subarray(i, Math.min(bytes.byteLength, i + step)));
- }
- return `data:${mime};base64,${btoa(bin)}`;
- }
- return undefined;
-}
-
-function decodeImageBytesToTileGrid(
- bytes: Uint8Array,
- tileGrid: SparseTileGrid,
- layerId: string,
- width: number,
- height: number
-): Promise<boolean> {
- if (typeof document === 'undefined' || typeof Image === 'undefined' || typeof URL === 'undefined') {
- return Promise.resolve(false);
- }
- return new Promise((resolve) => {
- const copy = new Uint8Array(bytes.byteLength);
- copy.set(bytes);
- const blob = new Blob([copy]);
- const url = URL.createObjectURL(blob);
- const img = new Image();
-
- img.onload = () => {
- URL.revokeObjectURL(url);
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (ctx) {
- ctx.drawImage(img, 0, 0, width, height);
- tileGrid.ingestCanvas(layerId, canvas, 'color-32bit');
- }
- canvas.width = 0;
- canvas.height = 0;
- resolve(Boolean(ctx));
- };
-
- img.onerror = () => {
- URL.revokeObjectURL(url);
- resolve(false);
- };
-
- img.src = url;
- });
-}
-
-interface OffscreenRecord {
- mainId: number;
- layerId: number;
- blockDataId: string;
- attribute: Uint8Array | null;
-}
-
-interface MipmapInfoRecord {
- mainId: number;
- offscreenId: number;
- thisScale: number;
- nextIndex: number;
-}
-
-/**
- * Extracts Paper / Solid Color fill hex if the layer row or associated fill tables specify one.
- */
-function extractSolidFillColor(
- layerRow: SqlRow,
- attr: ParsedOffscreenAttribute | null,
- fillByLayerId: Map<number, string>,
- isBottomMost: boolean
-): string | null {
- const mainId = getNum(layerRow, ['MainId'], -1);
- if (fillByLayerId.has(mainId)) {
- return fillByLayerId.get(mainId)!;
- }
-
- // Check explicit fill color columns on Layer (present in some CSP versions)
- const r = getOptNum(layerRow, ['LayerFillRed', 'FillColorRed', 'PaperRed']);
- const g = getOptNum(layerRow, ['LayerFillGreen', 'FillColorGreen', 'PaperGreen']);
- const b = getOptNum(layerRow, ['LayerFillBlue', 'FillColorBlue', 'PaperBlue']);
- if (r !== null && g !== null && b !== null) {
- return rgbToHex(normalizeColorChannel(r), normalizeColorChannel(g), normalizeColorChannel(b));
- }
-
- // Check packed ARGB/RGB color integer on Paper/Fill layers
- const packedColor = getOptNum(layerRow, ['LayerFillColor', 'SolidColor', 'PaperColor']);
- if (packedColor !== null && packedColor !== 0) {
- return rgbToHex((packedColor >>> 16) & 0xff, (packedColor >>> 8) & 0xff, packedColor & 0xff);
- }
-
- // Check Offscreen Attribute InitColor (opaque)
- if (attr?.initColor && attr.initColor[3] > 0) {
- return rgbToHex(attr.initColor[0], attr.initColor[1], attr.initColor[2]);
- }
-
- // CSP Paper layer heuristic: bottom-most layer named Paper / 用紙 or defaultFill=1 with no tiles
- const name = getStr(layerRow, ['LayerName'], '').trim().toLowerCase();
- const isPaperName = name === 'paper' || name === '用紙' || name === 'papier' || name === 'papel';
- const layerType = getNum(layerRow, ['LayerType'], -1);
- // CSP Paper layer frequently has LayerType = 1 with no offscreen, or specific fill type, or defaultFill = 1
- if (isPaperName || (isBottomMost && attr?.defaultFill === 1) || layerType === 1280) {
- return '#ffffff';
- }
-
- return null;
-}
-
/**
* Main parser for Clip Studio Paint (.clip / .csp / .lip) files.
- * Decodes full layer hierarchy, folders, raster/vector/text cached bitmaps,
- * layer masks, blend modes, opacity, clipping, locks, and paper fills
- * directly into a SparseTileGrid-backed LoadedDocument.
+ * Delegates SQLite extraction and Rayon-parallel tile decoding to the native Rust backend
+ * (zero WASM sql.js dependency on the JS main thread).
*/
export async function parseCspFile(
buffer: ArrayBuffer,
fileName: string,
targetGrid?: SparseTileGrid
): Promise<LoadedDocument> {
- const bytes = new Uint8Array(buffer);
- const chunks = parseCspChunks(bytes);
- const sqliteData = findSqliteData(chunks, bytes);
-
- if (!sqliteData) {
- throw new Error('Could not find SQLite database metadata within Clip Studio Paint file.');
- }
-
- const SQL = await getSql();
- // sql.js requires a standalone Uint8Array copy when given a subarray view
- const dbBytes =
- sqliteData.byteOffset === 0 && sqliteData.byteLength === sqliteData.buffer.byteLength
- ? sqliteData
- : sqliteData.slice();
- const db: Database = new SQL.Database(dbBytes);
-
- try {
- const tables = getTableNames(db);
-
- // 1. Canvas metadata
- let width = 1440;
- let height = 900;
- let dpi = 300;
- let rootFolderId: number | null = null;
- const colorMode: CanvasColorMode = 'color';
-
- const canvasRows = queryTable(db, tables, 'Canvas');
- if (canvasRows.length > 0) {
- const c = canvasRows[0];
- const w = getNum(c, ['CanvasWidth'], 1440);
- const h = getNum(c, ['CanvasHeight'], 900);
- width = Math.max(1, Math.min(MAX_CANVAS_DIM, Math.round(w)));
- height = Math.max(1, Math.min(MAX_CANVAS_DIM, Math.round(h)));
- const res = getNum(c, ['CanvasResolution', 'CanvasDpi'], 300);
- dpi = Math.max(1, Math.min(2400, Math.round(res)));
- rootFolderId = getOptNum(c, ['CanvasRootFolder']);
- }
-
- // 2. Preview image bytes (for recent-doc thumbnail & last-resort fallback)
- let previewBytes: Uint8Array | null = null;
- const previewRows = queryTable(db, tables, 'CanvasPreview');
- if (previewRows.length > 0) {
- previewBytes = getBytes(previewRows[0], ['ImageData']);
- }
- const previewDataUrl = previewBytes ? bytesToPngDataUrl(previewBytes) : undefined;
-
- // 3. External CHNKExta map
- const extaChunks = extractExtaChunks(chunks);
-
- // 4. Build Mipmap -> MipmapInfo -> Offscreen lookup tables
- const mipmapBaseInfoById = new Map<number, number>();
- for (const row of queryTable(db, tables, 'Mipmap')) {
- const id = getNum(row, ['MainId'], -1);
- const baseInfo = getNum(row, ['BaseMipmapInfo'], 0);
- if (id >= 0 && baseInfo > 0) {
- mipmapBaseInfoById.set(id, baseInfo);
- }
- }
-
- const mipmapInfoById = new Map<number, MipmapInfoRecord>();
- const mipmapInfoTable = tables.has('MipmapInfo')
- ? 'MipmapInfo'
- : tables.has('MipmapStoring')
- ? 'MipmapStoring'
- : '';
- if (mipmapInfoTable) {
- for (const row of queryTable(db, tables, mipmapInfoTable)) {
- const mainId = getNum(row, ['MainId'], -1);
- const offscreenId = getNum(row, ['Offscreen'], 0);
- const thisScale = getNum(row, ['ThisScale'], 1);
- const nextIndex = getNum(row, ['NextIndex'], 0);
- if (mainId >= 0) {
- mipmapInfoById.set(mainId, { mainId, offscreenId, thisScale, nextIndex });
- }
- }
- }
-
- const offscreenById = new Map<number, OffscreenRecord>();
- const offscreensByLayerId = new Map<number, OffscreenRecord[]>();
- for (const row of queryTable(db, tables, 'Offscreen')) {
- const mainId = getNum(row, ['MainId'], -1);
- const layerId = getNum(row, ['LayerId'], -1);
- const blockDataId = getStr(row, ['BlockData'], '');
- const attribute = getBytes(row, ['Attribute']);
- if (mainId < 0) continue;
- const rec: OffscreenRecord = { mainId, layerId, blockDataId, attribute };
- offscreenById.set(mainId, rec);
- if (layerId >= 0) {
- let list = offscreensByLayerId.get(layerId);
- if (!list) {
- list = [];
- offscreensByLayerId.set(layerId, list);
- }
- list.push(rec);
- }
- }
-
- // Optional solid-color / paper fill tables (CSP stores Paper/Fill color in Fill / SolidColor / Paper when present)
- const fillByLayerId = new Map<number, string>();
- for (const fillTable of ['SolidColor', 'FillLayer', 'Paper', 'Fill']) {
- for (const row of queryTable(db, tables, fillTable)) {
- const lid = getNum(row, ['LayerId', 'MainId'], -1);
- if (lid < 0) continue;
- const r = getOptNum(row, ['Red', 'ColorRed', 'FillRed', 'R']);
- const g = getOptNum(row, ['Green', 'ColorGreen', 'FillGreen', 'G']);
- const b = getOptNum(row, ['Blue', 'ColorBlue', 'FillBlue', 'B']);
- if (r !== null && g !== null && b !== null) {
- fillByLayerId.set(
- lid,
- rgbToHex(normalizeColorChannel(r), normalizeColorChannel(g), normalizeColorChannel(b))
- );
- }
- }
- }
-
- const resolveMipmapToOffscreen = (mipmapId: number): OffscreenRecord | null => {
- if (mipmapId <= 0) return null;
- let infoId = mipmapBaseInfoById.get(mipmapId);
- if (!infoId) return null;
-
- let best: OffscreenRecord | null = null;
- const seen = new Set<number>();
- while (infoId && infoId > 0 && !seen.has(infoId)) {
- seen.add(infoId);
- const info = mipmapInfoById.get(infoId);
- if (!info) break;
- const off = offscreenById.get(info.offscreenId) ?? null;
- if (off) {
- if (Math.abs(info.thisScale - 1) < 0.001) return off;
- if (!best) best = off;
- }
- infoId = info.nextIndex;
- }
- return best;
- };
-
- // 5. Query Layer table and reconstruct full tree
- const layerRows = queryTable(db, tables, 'Layer');
- const layerRowById = new Map<number, SqlRow>();
- const referencedAsMaskOffscreen = new Set<number>();
-
- for (const row of layerRows) {
- const mainId = getNum(row, ['MainId'], -1);
- if (mainId < 0) continue;
- layerRowById.set(mainId, row);
- const maskMipmapId = getNum(row, ['LayerLayerMaskMipmap', 'LayerMaskMipmap'], 0);
- const maskOff = resolveMipmapToOffscreen(maskMipmapId);
- if (maskOff) referencedAsMaskOffscreen.add(maskOff.mainId);
- }
-
- // Collect ordered siblings (bottom-to-top in CSP) from a parent folder
- const collectChildrenBottomToTop = (
- firstChildId: number,
- visitedNodes: Set<number>
- ): SqlRow[] => {
- const list: SqlRow[] = [];
- let curId = firstChildId;
- while (curId > 0 && !visitedNodes.has(curId) && list.length < MAX_LAYERS) {
- const row = layerRowById.get(curId);
- if (!row) break;
- visitedNodes.add(curId);
- list.push(row);
- curId = getNum(row, ['LayerNextIndex'], 0);
- }
- return list;
- };
-
- const tileGrid = targetGrid ?? new SparseTileGrid();
- const layers: LayerItem[] = [];
- const tileRgbaScratch = new Uint8ClampedArray(TILE_PIXELS * 4);
- const maskTileScratch = new Uint8Array(TILE_PIXELS);
- const runStamp = Date.now();
- let seq = 0;
- let decodedAnyPixels = false;
-
- const resolveLayerRenderOffscreen = (row: SqlRow, mainId: number): OffscreenRecord | null => {
- const renderMipmapId = getNum(row, ['LayerRenderMipmap'], 0);
- const fromMipmap = resolveMipmapToOffscreen(renderMipmapId);
- if (fromMipmap) return fromMipmap;
-
- const directOffId = getNum(row, ['LayerRenderOffscreen'], 0);
- if (directOffId > 0 && offscreenById.has(directOffId)) {
- return offscreenById.get(directOffId)!;
- }
-
- // Fallback: pick largest non-mask offscreen associated with this LayerId
- const candidates = offscreensByLayerId.get(mainId);
- if (!candidates || candidates.length === 0) return null;
- let best: OffscreenRecord | null = null;
- let bestArea = -1;
- for (const c of candidates) {
- if (referencedAsMaskOffscreen.has(c.mainId)) continue;
- if (!c.blockDataId || !extaChunks.has(c.blockDataId)) continue;
- const a = parseOffscreenAttribute(c.attribute, width, height);
- const area = a.bitmapWidth * a.bitmapHeight;
- if (area > bestArea) {
- bestArea = area;
- best = c;
- }
- }
- return best;
- };
-
- const emitLayerNode = (
- row: SqlRow,
- parentId: string | null,
- visitedNodes: Set<number>,
- depth: number,
- isBottomMostRoot: boolean,
- parentOffsetX: number,
- parentOffsetY: number
- ): void => {
- if (depth > MAX_FOLDER_DEPTH || layers.length >= MAX_LAYERS) return;
-
- const mainId = getNum(row, ['MainId'], seq + 1);
- const name = getStr(row, ['LayerName'], `Layer ${mainId}`);
- const layerFolder = getOptNum(row, ['LayerFolder']);
- const firstChildId = getNum(row, ['LayerFirstChildIndex'], 0);
- const layerType = getNum(row, ['LayerType'], 1);
- const compositeVal = getNum(row, ['LayerComposite'], 0);
- const rawOpacity = getNum(row, ['LayerOpacity'], 256);
- const visibilityVal = getNum(row, ['LayerVisibility'], 1);
- const lockVal = getNum(row, ['LayerLock'], 0);
- const clipVal = getNum(row, ['LayerClip'], 0);
- const layerSelect = getOptNum(row, ['LayerSelect']);
-
- // CSP accumulates folder LayerOffsetX/Y onto all descendants, and adds
- // per-offscreen origin offsets (LayerRenderOffscrOffsetX/Y, LayerMaskOffscrOffsetX/Y).
- const baseOffsetX = parentOffsetX + getNum(row, ['LayerOffsetX', 'LayerMoveOffsetX'], 0);
- const baseOffsetY = parentOffsetY + getNum(row, ['LayerOffsetY', 'LayerMoveOffsetY'], 0);
- const offsetX = Math.round(
- baseOffsetX + getNum(row, ['LayerRenderOffscrOffsetX', 'LayerRenderOffsetX'], 0)
- );
- const offsetY = Math.round(
- baseOffsetY + getNum(row, ['LayerRenderOffscrOffsetY', 'LayerRenderOffsetY'], 0)
- );
- const maskOffsetX = Math.round(
- baseOffsetX +
- getNum(row, ['LayerMaskOffsetX'], 0) +
- getNum(row, ['LayerMaskOffscrOffsetX'], 0)
- );
- const maskOffsetY = Math.round(
- baseOffsetY +
- getNum(row, ['LayerMaskOffsetY'], 0) +
- getNum(row, ['LayerMaskOffscrOffsetY'], 0)
- );
-
- const hasRenderOffscreen = Boolean(resolveLayerRenderOffscreen(row, mainId));
- const isFolder =
- (layerFolder !== null && layerFolder !== 0) ||
- firstChildId > 0 ||
- (layerFolder === null && layerType === 0 && !hasRenderOffscreen);
-
- seq += 1;
- const id = `csp-${isFolder ? 'folder' : 'layer'}-${mainId}-${runStamp}-${seq}`;
- const blendMode = mapCspBlendMode(compositeVal);
- // CSP stores opacity in [0..256] (256 = 100%)
- const opacity = Math.max(0, Math.min(1, rawOpacity / 256));
- const visible = (visibilityVal & 1) !== 0;
- const locked = (lockVal & 1) !== 0;
- const alphaLocked =
- (lockVal & 16) !== 0 || getNum(row, ['LayerLockTransparentPixel', 'LayerAlphaLock'], 0) !== 0;
- const clipped = clipVal !== 0;
-
- // Optional layer mask
- const maskMipmapId = getNum(row, ['LayerLayerMaskMipmap', 'LayerMaskMipmap'], 0);
- const maskOffscreen = resolveMipmapToOffscreen(maskMipmapId);
- let maskFields: Pick<
- LayerItem,
- 'maskCanvas' | 'maskEnabled' | 'maskLinked' | 'maskVersion' | 'maskThumbnailUrl'
- > = {};
- if (maskOffscreen) {
- const maskCanvas = buildMaskCanvasFromOffscreen(
- maskOffscreen,
- extaChunks,
- maskOffsetX,
- maskOffsetY,
- width,
- height,
- maskTileScratch
- );
- // CSP exact bitflags: LayerVisibility & 2 = mask enabled; LayerSelect & 256 = mask linked
- const maskEnabled =
- row['LayerVisibility'] !== undefined ? (visibilityVal & 2) !== 0 : true;
- const maskLinked = layerSelect !== null ? (layerSelect & 256) !== 0 : true;
- maskFields = {
- maskCanvas,
- maskEnabled,
- maskLinked,
- maskVersion: 1,
- maskThumbnailUrl: maskCanvas ? createCanvasThumbnail(maskCanvas, false) : undefined,
- };
- }
-
- if (isFolder) {
- const collapsed = layerFolder !== null ? (layerFolder & 16) !== 0 : false;
- layers.push({
- id,
- name,
- type: 'folder',
- visible,
- opacity,
- blendMode,
- locked,
- alphaLocked,
- clipped,
- collapsed,
- parentId,
- ...maskFields,
- });
-
- if (firstChildId > 0) {
- const childrenBottomToTop = collectChildrenBottomToTop(firstChildId, visitedNodes);
- // Reverse bottom-to-top into Ink Studio's top-to-bottom stack order
- for (let i = childrenBottomToTop.length - 1; i >= 0; i--) {
- emitLayerNode(
- childrenBottomToTop[i],
- id,
- visitedNodes,
- depth + 1,
- false,
- baseOffsetX,
- baseOffsetY
- );
- }
- }
- return;
- }
-
- // Editable raster layer (including cached raster render of vector/text/balloon/tone/3D layers)
- tileGrid.setLayerFormat(id, 'color-32bit');
- tileGrid.markLayerIngested(id);
-
- const offscreen = resolveLayerRenderOffscreen(row, mainId);
- const attr = offscreen ? parseOffscreenAttribute(offscreen.attribute, width, height) : null;
- let layerHasPixels = false;
-
- if (offscreen && offscreen.blockDataId && extaChunks.has(offscreen.blockDataId)) {
- const payload = extaChunks.get(offscreen.blockDataId)!;
- const resolvedAttr = attr!;
- const expectedBlocks = resolvedAttr.blockGridWidth * resolvedAttr.blockGridHeight;
- const decodedTiles = parseBlockDataPayload(payload, expectedBlocks);
-
- for (const [blockIdx, rawTile] of decodedTiles.entries()) {
- if (decodeCspTileToRgba(rawTile, tileRgbaScratch, resolvedAttr)) {
- const col = blockIdx % resolvedAttr.blockGridWidth;
- const rowIdx = Math.floor(blockIdx / resolvedAttr.blockGridWidth);
- const tileDocX = col * TILE_SIZE + offsetX;
- const tileDocY = rowIdx * TILE_SIZE + offsetY;
- writeClippedTileToGrid(
- tileGrid,
- id,
- tileRgbaScratch,
- tileDocX,
- tileDocY,
- resolvedAttr.bitmapWidth,
- resolvedAttr.bitmapHeight,
- offsetX,
- offsetY,
- width,
- height
- );
- layerHasPixels = true;
- decodedAnyPixels = true;
- }
- }
- }
-
- // Handle Paper / Solid Color Fill layers (no raster tiles, solid fill color)
- if (!layerHasPixels) {
- const fillHex = extractSolidFillColor(row, attr, fillByLayerId, isBottomMostRoot);
- if (fillHex) {
- tileGrid.fillLayerSolidColor(id, width, height, fillHex, 'color-32bit');
- layerHasPixels = true;
- decodedAnyPixels = true;
- }
- }
-
- const thumb = createCanvasThumbnail(
- { grid: tileGrid, layerId: id, dimensions: { width, height } },
- true
- );
-
- layers.push({
- id,
- name,
- type: 'raster',
- visible,
- opacity,
- blendMode,
- locked,
- alphaLocked,
- clipped,
- parentId,
- thumbnailUrl: thumb,
- ...maskFields,
- });
- };
-
- // Determine root container and traverse hierarchy
- const visited = new Set<number>();
- let rootRow: SqlRow | undefined;
-
- if (rootFolderId !== null && layerRowById.has(rootFolderId)) {
- rootRow = layerRowById.get(rootFolderId);
- } else {
- // Heuristic: find an unreferenced root folder that has children
- const referenced = new Set<number>();
- for (const row of layerRows) {
- const nextId = getNum(row, ['LayerNextIndex'], 0);
- const childId = getNum(row, ['LayerFirstChildIndex'], 0);
- if (nextId > 0) referenced.add(nextId);
- if (childId > 0) referenced.add(childId);
- }
- for (const row of layerRows) {
- const id = getNum(row, ['MainId'], -1);
- const childId = getNum(row, ['LayerFirstChildIndex'], 0);
- if (id >= 0 && childId > 0 && !referenced.has(id)) {
- rootRow = row;
- break;
- }
- }
- }
-
- if (rootRow) {
- const rootMainId = getNum(rootRow, ['MainId'], -1);
- if (rootMainId >= 0) visited.add(rootMainId);
- const rootOffsetX = getNum(rootRow, ['LayerOffsetX', 'LayerMoveOffsetX'], 0);
- const rootOffsetY = getNum(rootRow, ['LayerOffsetY', 'LayerMoveOffsetY'], 0);
- const firstChild = getNum(rootRow, ['LayerFirstChildIndex'], 0);
- if (firstChild > 0) {
- const topLevelBottomToTop = collectChildrenBottomToTop(firstChild, visited);
- for (let i = topLevelBottomToTop.length - 1; i >= 0; i--) {
- emitLayerNode(
- topLevelBottomToTop[i],
- null,
- visited,
- 0,
- i === 0,
- rootOffsetX,
- rootOffsetY
- );
- }
- }
- }
-
- // Fallback: if linked-list traversal yielded nothing (minimal/legacy schema), emit flat Layer rows
- if (layers.length === 0 && layerRows.length > 0) {
- for (let i = layerRows.length - 1; i >= 0; i--) {
- const row = layerRows[i];
- const mid = getNum(row, ['MainId'], -1);
- if (rootFolderId !== null && mid === rootFolderId) continue;
- emitLayerNode(row, null, visited, 0, i === 0, 0, 0);
- }
- }
-
- // Last-resort fallback: ONLY if zero raster pixels were decoded from any layer AND preview exists
- if (!decodedAnyPixels && previewBytes && previewBytes.byteLength > 0) {
- const bgId = `csp-preview-base-${runStamp}`;
- const loaded = await decodeImageBytesToTileGrid(previewBytes, tileGrid, bgId, width, height);
- if (loaded) {
- const thumb = createCanvasThumbnail(
- { grid: tileGrid, layerId: bgId, dimensions: { width, height } },
- false
- );
- layers.push({
- id: bgId,
- name: 'CSP Composite Preview',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: false,
- alphaLocked: false,
- clipped: false,
- parentId: null,
- thumbnailUrl: thumb,
- });
- }
- }
-
- // Guarantee at least one editable layer
- if (layers.length === 0) {
- const fallbackId = `layer-${runStamp}`;
- tileGrid.fillLayerSolidWhite(fallbackId, width, height, 'color-32bit');
- layers.push({
- id: fallbackId,
- name: 'Layer 1',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: false,
- alphaLocked: false,
- clipped: false,
- parentId: null,
- thumbnailUrl: createCanvasThumbnail(
- { grid: tileGrid, layerId: fallbackId, dimensions: { width, height } },
- false
- ),
- });
- }
-
- return {
- name: fileName.replace(/\.[^/.]+$/, ''),
- dimensions: { width, height, dpi },
- colorMode,
- layers,
- tileGrid,
- previewDataUrl,
- };
- } finally {
- db.close();
+ if (!isNativeRustAvailable()) {
+ throw new Error(
+ 'Parsing .clip/.csp files requires the native desktop Rust backend (WASM sql.js was removed).'
+ );
}
+ return await parseClipNative(buffer, fileName, targetGrid);
}
diff --git a/src/utils/documentStore.ts b/src/utils/documentStore.ts
index e6314fe..0bfad0f 100644
--- a/src/utils/documentStore.ts
+++ b/src/utils/documentStore.ts
@@ -13,7 +13,6 @@ import {
IScratchDiskDriver,
createDefaultScratchDiskDriver,
globalTileGrid,
- releaseTemporaryCanvas,
} from './tileEngine';
import { UndoCacheManager, MAX_RAM_UNDO_STEPS } from './undoCache';
@@ -30,8 +29,6 @@ export class TileGridSession {
public readonly undoCache: UndoCacheManager;
public history: HistoryItem[] = [];
public historyIndex: number = -1;
- public readonly layerCanvases: Map<string, HTMLCanvasElement> = new Map();
- public readonly layerSourceCanvases: Map<string, HTMLCanvasElement> = new Map();
public lastAccessedAt: number;
public isActive: boolean = false;
private disposed: boolean = false;
@@ -64,34 +61,9 @@ export class TileGridSession {
}
/**
- * Releases any transiently materialized display canvases (safe because SparseTileGrid
- * is the authoritative pixel store; source canvases for non-destructive effects are preserved).
- */
- public releaseTransientDisplayCanvases(): number {
- let released = 0;
- for (const [layerId, canvas] of Array.from(this.layerCanvases.entries())) {
- if (this.layerSourceCanvases.has(layerId)) continue;
- releaseTemporaryCanvas(canvas);
- this.layerCanvases.delete(layerId);
- released++;
- }
- return released;
- }
-
- /**
- * Releases a single layer's tiles and any temporary/source canvases.
+ * Releases a single layer's tiles.
*/
public clearLayerResources(layerId: string): void {
- const display = this.layerCanvases.get(layerId);
- if (display) {
- releaseTemporaryCanvas(display);
- this.layerCanvases.delete(layerId);
- }
- const source = this.layerSourceCanvases.get(layerId);
- if (source) {
- releaseTemporaryCanvas(source);
- this.layerSourceCanvases.delete(layerId);
- }
this.tileGrid.clearLayer(layerId);
}
@@ -105,23 +77,13 @@ export class TileGridSession {
}
/**
- * Permanently disposes all tiles, scratch disk state, undo cache, and canvases for this tab.
+ * Permanently disposes all tiles, scratch disk state, and undo cache for this tab.
*/
public async dispose(): Promise<void> {
if (this.disposed) return;
this.disposed = true;
this.isActive = false;
- for (const canvas of this.layerCanvases.values()) {
- releaseTemporaryCanvas(canvas);
- }
- this.layerCanvases.clear();
-
- for (const canvas of this.layerSourceCanvases.values()) {
- releaseTemporaryCanvas(canvas);
- }
- this.layerSourceCanvases.clear();
-
this.history = [];
this.historyIndex = -1;
@@ -205,7 +167,6 @@ export class DocumentStore {
if (prevSession && !prevSession.isDisposed()) {
prevSession.isActive = false;
prevSession.touch();
- prevSession.releaseTransientDisplayCanvases();
if (this.offloadInactiveUndoOnSwitch) {
void prevSession.undoCache.offloadAllToDisk(prevSession.history).catch(() => {});
}
diff --git a/src/utils/filterEngine.ts b/src/utils/filterEngine.ts
index 2d88a09..173b5a9 100644
--- a/src/utils/filterEngine.ts
+++ b/src/utils/filterEngine.ts
@@ -1,4 +1,16 @@
-import { FilterType } from '../types/editor';
+import { CanvasDimensions, CanvasSelection, DirtyRect, FilterType, TileDelta } from '../types/editor';
+import { applyFilterNative, isNativeRustAvailable } from './nativeBackend';
+import {
+ BYTES_32BIT,
+ SparseTileGrid,
+ TILE_SIZE,
+ TileFormat,
+ getTileKey,
+ pixelToTileCoord,
+ unpack1BitToRGBA,
+ unpack8BitToRGBA,
+} from './tileEngine';
+import { createSelectionMask } from './tonalEngine';
export interface GaussianBlurParams {
radius: number; // Blur radius in pixels (1 to 100)
@@ -689,3 +701,370 @@ export function applyFilterToCanvas(
return true;
}
+function makeImageDataBuffer(data: Uint8ClampedArray, width: number, height: number): ImageData {
+ if (typeof ImageData !== 'undefined') {
+ return new ImageData(new Uint8ClampedArray(data), width, height);
+ }
+ return { data: new Uint8ClampedArray(data), width, height } as ImageData;
+}
+
+/**
+ * Tile-native convolution filter processor: runs in halo-padded chunks strictly over
+ * the populated tile bounds of `layerId` (expanded by filter kernel halo).
+ * Seamless across chunk boundaries; zero full-document canvas/ImageData allocation.
+ */
+export function applyFilterToTileGrid(params: {
+ grid: SparseTileGrid;
+ layerId: string;
+ dimensions: CanvasDimensions;
+ type: FilterType;
+ filterParams: any;
+ targetFormat: TileFormat;
+ selection?: CanvasSelection | null;
+}): { dirtyRect: DirtyRect | null; tileDeltas: TileDelta[] } {
+ const { grid, layerId, dimensions, type, filterParams, targetFormat, selection } = params;
+ const docW = dimensions.width;
+ const docH = dimensions.height;
+ if (docW <= 0 || docH <= 0 || !grid.hasLayerTiles(layerId)) {
+ return { dirtyRect: null, tileDeltas: [] };
+ }
+
+ const tileBounds = grid.getLayerTileBounds(layerId, dimensions);
+ if (!tileBounds) return { dirtyRect: null, tileDeltas: [] };
+
+ let halo = 0;
+ if (type === 'gaussian-blur') {
+ halo = Math.min(256, Math.ceil((filterParams?.radius || 5) * 3) + 4);
+ } else if (type === 'unsharp-mask') {
+ halo = Math.min(256, Math.ceil((filterParams?.radius || 2) * 3) + 4);
+ } else if (type === 'motion-blur') {
+ halo = Math.min(256, Math.ceil((filterParams?.distance || 15) * 0.6) + 4);
+ }
+
+ let minX = Math.max(0, tileBounds.x - halo);
+ let minY = Math.max(0, tileBounds.y - halo);
+ let maxX = Math.min(docW, tileBounds.x + tileBounds.width + halo);
+ let maxY = Math.min(docH, tileBounds.y + tileBounds.height + halo);
+
+ if (selection) {
+ const sb = selection.bounds;
+ minX = Math.max(minX, Math.floor(sb.x));
+ minY = Math.max(minY, Math.floor(sb.y));
+ maxX = Math.min(maxX, Math.ceil(sb.x + sb.width));
+ maxY = Math.min(maxY, Math.ceil(sb.y + sb.height));
+ }
+
+ if (maxX <= minX || maxY <= minY) return { dirtyRect: null, tileDeltas: [] };
+
+ const dirtyRect: DirtyRect = { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
+
+ // Freeze pre-filter tile snapshot for both halo-consistent reads and undo deltas
+ const beforeSnapshot = grid.snapshotTilesInRect(layerId, dirtyRect);
+ // Also ensure halo-border source tiles outside dirtyRect are readable without mutation
+ const readRect: DirtyRect = {
+ x: Math.max(0, minX - halo),
+ y: Math.max(0, minY - halo),
+ width: Math.min(docW, maxX + halo) - Math.max(0, minX - halo),
+ height: Math.min(docH, maxY + halo) - Math.max(0, minY - halo),
+ };
+ const sourceSnap = grid.snapshotTilesInRect(layerId, readRect);
+
+ const scratch = new Uint8ClampedArray(BYTES_32BIT);
+ const readFromSourceSnap = (rx: number, ry: number, rw: number, rh: number): Uint8ClampedArray => {
+ const out = new Uint8ClampedArray(rw * rh * 4);
+ const tx0 = pixelToTileCoord(rx, 0);
+ const ty0 = pixelToTileCoord(ry, 0);
+ const tx1 = pixelToTileCoord(rx + rw - 1, 0);
+ const ty1 = pixelToTileCoord(ry + rh - 1, 0);
+
+ for (let ty = ty0; ty <= ty1; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ for (let tx = tx0; tx <= tx1; tx++) {
+ const entry = sourceSnap.get(getTileKey(layerId, tx, ty, 0));
+ if (!entry || !entry.data) continue;
+ let rgba: Uint8ClampedArray;
+ if (entry.format === 'color-32bit') {
+ rgba = new Uint8ClampedArray(entry.data.buffer, entry.data.byteOffset, BYTES_32BIT);
+ } else if (entry.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(entry.data, scratch);
+ rgba = scratch;
+ } else {
+ unpack8BitToRGBA(entry.data, scratch);
+ rgba = scratch;
+ }
+ const tileDocX = tx * TILE_SIZE;
+ const ix0 = Math.max(rx, tileDocX);
+ const iy0 = Math.max(ry, tileDocY);
+ const ix1 = Math.min(rx + rw, tileDocX + TILE_SIZE);
+ const iy1 = Math.min(ry + rh, tileDocY + TILE_SIZE);
+ const copyW = ix1 - ix0;
+ if (copyW <= 0 || iy1 <= iy0) continue;
+ for (let py = iy0; py < iy1; py++) {
+ const sOff = ((py - tileDocY) * TILE_SIZE + (ix0 - tileDocX)) << 2;
+ const dOff = ((py - ry) * rw + (ix0 - rx)) << 2;
+ out.set(rgba.subarray(sOff, sOff + (copyW << 2)), dOff);
+ }
+ }
+ }
+ return out;
+ };
+
+ const selMask = selection ? createSelectionMask(selection, docW, docH) : null;
+ const CHUNK = 512;
+
+ for (let cy = minY; cy < maxY; cy += CHUNK) {
+ const ch = Math.min(CHUNK, maxY - cy);
+ for (let cx = minX; cx < maxX; cx += CHUNK) {
+ const cw = Math.min(CHUNK, maxX - cx);
+
+ const padLeft = Math.min(halo, cx);
+ const padTop = Math.min(halo, cy);
+ const padRight = Math.min(halo, docW - (cx + cw));
+ const padBottom = Math.min(halo, docH - (cy + ch));
+
+ const px = cx - padLeft;
+ const py = cy - padTop;
+ const pw = cw + padLeft + padRight;
+ const ph = ch + padTop + padBottom;
+
+ const srcPixels = readFromSourceSnap(px, py, pw, ph);
+ // Skip completely empty padded chunks
+ let hasAny = false;
+ for (let i = 3; i < srcPixels.length; i += 4) {
+ if (srcPixels[i] !== 0) {
+ hasAny = true;
+ break;
+ }
+ }
+ if (!hasAny) continue;
+
+ const chunkParams =
+ type === 'film-grain'
+ ? { ...filterParams, seed: ((filterParams?.seed || 1337) ^ ((cx * 73856093) ^ (cy * 19349663))) | 0 }
+ : filterParams;
+
+ const filtered = applyFilter(makeImageDataBuffer(srcPixels, pw, ph), type, chunkParams);
+ const outChunk = new Uint8ClampedArray(cw * ch * 4);
+
+ for (let ly = 0; ly < ch; ly++) {
+ const gy = cy + ly;
+ const srcRowOff = ((ly + padTop) * pw + padLeft) * 4;
+ const dstRowOff = ly * cw * 4;
+ if (!selMask) {
+ outChunk.set(filtered.data.subarray(srcRowOff, srcRowOff + cw * 4), dstRowOff);
+ } else {
+ const selRow = gy * docW;
+ for (let lx = 0; lx < cw; lx++) {
+ const gx = cx + lx;
+ const m = selMask[selRow + gx];
+ const sIdx = srcRowOff + lx * 4;
+ const dIdx = dstRowOff + lx * 4;
+ if (m === 0) {
+ outChunk[dIdx] = srcPixels[sIdx];
+ outChunk[dIdx + 1] = srcPixels[sIdx + 1];
+ outChunk[dIdx + 2] = srcPixels[sIdx + 2];
+ outChunk[dIdx + 3] = srcPixels[sIdx + 3];
+ } else if (m === 255 || m === 1) {
+ outChunk[dIdx] = filtered.data[sIdx];
+ outChunk[dIdx + 1] = filtered.data[sIdx + 1];
+ outChunk[dIdx + 2] = filtered.data[sIdx + 2];
+ outChunk[dIdx + 3] = filtered.data[sIdx + 3];
+ } else {
+ const a = m / 255;
+ const inv = 1 - a;
+ outChunk[dIdx] = Math.round(srcPixels[sIdx] * inv + filtered.data[sIdx] * a);
+ outChunk[dIdx + 1] = Math.round(srcPixels[sIdx + 1] * inv + filtered.data[sIdx + 1] * a);
+ outChunk[dIdx + 2] = Math.round(srcPixels[sIdx + 2] * inv + filtered.data[sIdx + 2] * a);
+ outChunk[dIdx + 3] = Math.round(srcPixels[sIdx + 3] * inv + filtered.data[sIdx + 3] * a);
+ }
+ }
+ }
+ }
+
+ grid.writeImageData(layerId, { data: outChunk, width: cw, height: ch }, cx, cy, targetFormat, true);
+ }
+ }
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId, dirtyRect);
+ grid.notifyChange(true);
+ return { dirtyRect, tileDeltas };
+}
+
+/**
+ * Async tile-native filter processor: offloads heavy convolution math to the parallel
+ * Rust Rayon backend when running in Tauri, falling back to sync JS on Web/Vitest.
+ */
+export async function applyFilterToTileGridAsync(params: {
+ grid: SparseTileGrid;
+ layerId: string;
+ dimensions: CanvasDimensions;
+ type: FilterType;
+ filterParams: any;
+ targetFormat: TileFormat;
+ selection?: CanvasSelection | null;
+}): Promise<{ dirtyRect: DirtyRect | null; tileDeltas: TileDelta[] }> {
+ if (!isNativeRustAvailable()) {
+ return applyFilterToTileGrid(params);
+ }
+
+ const { grid, layerId, dimensions, type, filterParams, targetFormat, selection } = params;
+ const docW = dimensions.width;
+ const docH = dimensions.height;
+ if (docW <= 0 || docH <= 0 || !grid.hasLayerTiles(layerId)) {
+ return { dirtyRect: null, tileDeltas: [] };
+ }
+
+ const tileBounds = grid.getLayerTileBounds(layerId, dimensions);
+ if (!tileBounds) return { dirtyRect: null, tileDeltas: [] };
+
+ let halo = 0;
+ if (type === 'gaussian-blur') {
+ halo = Math.min(256, Math.ceil((filterParams?.radius || 5) * 3) + 4);
+ } else if (type === 'unsharp-mask') {
+ halo = Math.min(256, Math.ceil((filterParams?.radius || 2) * 3) + 4);
+ } else if (type === 'motion-blur') {
+ halo = Math.min(256, Math.ceil((filterParams?.distance || 15) * 0.6) + 4);
+ }
+
+ let minX = Math.max(0, tileBounds.x - halo);
+ let minY = Math.max(0, tileBounds.y - halo);
+ let maxX = Math.min(docW, tileBounds.x + tileBounds.width + halo);
+ let maxY = Math.min(docH, tileBounds.y + tileBounds.height + halo);
+
+ if (selection) {
+ const sb = selection.bounds;
+ minX = Math.max(minX, Math.floor(sb.x));
+ minY = Math.max(minY, Math.floor(sb.y));
+ maxX = Math.min(maxX, Math.ceil(sb.x + sb.width));
+ maxY = Math.min(maxY, Math.ceil(sb.y + sb.height));
+ }
+ if (maxX <= minX || maxY <= minY) return { dirtyRect: null, tileDeltas: [] };
+
+ const dirtyRect: DirtyRect = { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
+ const beforeSnapshot = grid.snapshotTilesInRect(layerId, dirtyRect);
+ const readRect: DirtyRect = {
+ x: Math.max(0, minX - halo),
+ y: Math.max(0, minY - halo),
+ width: Math.min(docW, maxX + halo) - Math.max(0, minX - halo),
+ height: Math.min(docH, maxY + halo) - Math.max(0, minY - halo),
+ };
+ const sourceSnap = grid.snapshotTilesInRect(layerId, readRect);
+ const scratch = new Uint8ClampedArray(BYTES_32BIT);
+
+ const readFromSourceSnap = (rx: number, ry: number, rw: number, rh: number): Uint8ClampedArray => {
+ const out = new Uint8ClampedArray(rw * rh * 4);
+ const tx0 = pixelToTileCoord(rx, 0);
+ const ty0 = pixelToTileCoord(ry, 0);
+ const tx1 = pixelToTileCoord(rx + rw - 1, 0);
+ const ty1 = pixelToTileCoord(ry + rh - 1, 0);
+ for (let ty = ty0; ty <= ty1; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ for (let tx = tx0; tx <= tx1; tx++) {
+ const entry = sourceSnap.get(getTileKey(layerId, tx, ty, 0));
+ if (!entry || !entry.data) continue;
+ let rgba: Uint8ClampedArray;
+ if (entry.format === 'color-32bit') {
+ rgba = new Uint8ClampedArray(entry.data.buffer, entry.data.byteOffset, BYTES_32BIT);
+ } else if (entry.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(entry.data, scratch);
+ rgba = scratch;
+ } else {
+ unpack8BitToRGBA(entry.data, scratch);
+ rgba = scratch;
+ }
+ const tileDocX = tx * TILE_SIZE;
+ const ix0 = Math.max(rx, tileDocX);
+ const iy0 = Math.max(ry, tileDocY);
+ const ix1 = Math.min(rx + rw, tileDocX + TILE_SIZE);
+ const iy1 = Math.min(ry + rh, tileDocY + TILE_SIZE);
+ const copyW = ix1 - ix0;
+ if (copyW <= 0 || iy1 <= iy0) continue;
+ for (let py = iy0; py < iy1; py++) {
+ const sOff = ((py - tileDocY) * TILE_SIZE + (ix0 - tileDocX)) << 2;
+ const dOff = ((py - ry) * rw + (ix0 - rx)) << 2;
+ out.set(rgba.subarray(sOff, sOff + (copyW << 2)), dOff);
+ }
+ }
+ }
+ return out;
+ };
+
+ const selMask = selection ? createSelectionMask(selection, docW, docH) : null;
+ // Larger chunks in Rust (1024x1024) minimize IPC roundtrips while Rayon saturates CPU cores
+ const CHUNK = 1024;
+
+ for (let cy = minY; cy < maxY; cy += CHUNK) {
+ const ch = Math.min(CHUNK, maxY - cy);
+ for (let cx = minX; cx < maxX; cx += CHUNK) {
+ const cw = Math.min(CHUNK, maxX - cx);
+ const padLeft = Math.min(halo, cx);
+ const padTop = Math.min(halo, cy);
+ const padRight = Math.min(halo, docW - (cx + cw));
+ const padBottom = Math.min(halo, docH - (cy + ch));
+ const px = cx - padLeft;
+ const py = cy - padTop;
+ const pw = cw + padLeft + padRight;
+ const ph = ch + padTop + padBottom;
+
+ const srcPixels = readFromSourceSnap(px, py, pw, ph);
+ let hasAny = false;
+ for (let i = 3; i < srcPixels.length; i += 4) {
+ if (srcPixels[i] !== 0) {
+ hasAny = true;
+ break;
+ }
+ }
+ if (!hasAny) continue;
+
+ const chunkParams =
+ type === 'film-grain'
+ ? { ...filterParams, seed: ((filterParams?.seed || 1337) ^ ((cx * 73856093) ^ (cy * 19349663))) >>> 0 }
+ : (filterParams ?? {});
+
+ const filteredData = await applyFilterNative(srcPixels, pw, ph, type, chunkParams);
+ const outChunk = new Uint8ClampedArray(cw * ch * 4);
+
+ for (let ly = 0; ly < ch; ly++) {
+ const gy = cy + ly;
+ const srcRowOff = ((ly + padTop) * pw + padLeft) * 4;
+ const dstRowOff = ly * cw * 4;
+ if (!selMask) {
+ outChunk.set(filteredData.subarray(srcRowOff, srcRowOff + cw * 4), dstRowOff);
+ } else {
+ const selRow = gy * docW;
+ for (let lx = 0; lx < cw; lx++) {
+ const gx = cx + lx;
+ const m = selMask[selRow + gx];
+ const sIdx = srcRowOff + lx * 4;
+ const dIdx = dstRowOff + lx * 4;
+ if (m === 0) {
+ outChunk[dIdx] = srcPixels[sIdx];
+ outChunk[dIdx + 1] = srcPixels[sIdx + 1];
+ outChunk[dIdx + 2] = srcPixels[sIdx + 2];
+ outChunk[dIdx + 3] = srcPixels[sIdx + 3];
+ } else if (m === 255 || m === 1) {
+ outChunk[dIdx] = filteredData[sIdx];
+ outChunk[dIdx + 1] = filteredData[sIdx + 1];
+ outChunk[dIdx + 2] = filteredData[sIdx + 2];
+ outChunk[dIdx + 3] = filteredData[sIdx + 3];
+ } else {
+ const a = m / 255;
+ const inv = 1 - a;
+ outChunk[dIdx] = Math.round(srcPixels[sIdx] * inv + filteredData[sIdx] * a);
+ outChunk[dIdx + 1] = Math.round(srcPixels[sIdx + 1] * inv + filteredData[sIdx + 1] * a);
+ outChunk[dIdx + 2] = Math.round(srcPixels[sIdx + 2] * inv + filteredData[sIdx + 2] * a);
+ outChunk[dIdx + 3] = Math.round(srcPixels[sIdx + 3] * inv + filteredData[sIdx + 3] * a);
+ }
+ }
+ }
+ }
+
+ grid.writeImageData(layerId, { data: outChunk, width: cw, height: ch }, cx, cy, targetFormat, true);
+ }
+ }
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId, dirtyRect);
+ grid.notifyChange(true);
+ return { dirtyRect, tileDeltas };
+}
+
diff --git a/src/utils/floodFill.ts b/src/utils/floodFill.ts
index 39204f0..227a3b2 100644
--- a/src/utils/floodFill.ts
+++ b/src/utils/floodFill.ts
@@ -1,5 +1,17 @@
-import { LayerItem, CanvasDimensions, DirtyRect } from '../types/editor';
+import { LayerItem, CanvasDimensions, DirtyRect, TileDelta } from '../types/editor';
import { getCanvasCompositeOperation } from './canvasUtils';
+import {
+ BYTES_32BIT,
+ SparseTileGrid,
+ TILE_PIXELS,
+ TILE_SIZE,
+ TileFormat,
+ TileSnapshotEntry,
+ pixelToTileCoord,
+ releaseTemporaryCanvas,
+} from './tileEngine';
+import { documentStore } from './documentStore';
+import { floodFillNative, isNativeRustAvailable } from './nativeBackend';
/**
* Parses color string (hex #RRGGBB, #RGB, or rgba) to [r, g, b, a (0-255)].
@@ -49,9 +61,6 @@ export interface FloodFillOptions {
selectionMask?: Uint8Array | null;
}
-import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';
-import { documentStore } from './documentStore';
-
/**
* Creates a flat composite canvas of all visible layers.
* Reads directly from SparseTileGrid when a layer has no materialized backing canvas.
@@ -605,3 +614,709 @@ export function executeLassoFill(
return { dirtyRect, modified: true };
}
+
+/**
+ * Lazily composites a single 256x256 reference tile across a list of layers in SparseTileGrid.
+ * Returns null when all contributing layers are empty at (tx, ty).
+ */
+export function buildCompositedReferenceTile(
+ grid: SparseTileGrid,
+ refLayers: LayerItem[],
+ tx: number,
+ ty: number
+): Uint8ClampedArray | null {
+ let out: Uint8ClampedArray | null = null;
+ for (let i = refLayers.length - 1; i >= 0; i--) {
+ const layer = refLayers[i];
+ if (layer.type === 'folder' || layer.type === 'frame-folder' || !layer.visible) continue;
+ const tile = grid.getTile(layer.id, tx, ty, 0);
+ if (!tile || !tile.data) continue;
+ const src = grid.getTileAsRGBA(tile);
+ const layerAlpha = layer.opacity ?? 1.0;
+ if (layerAlpha <= 0.001) continue;
+
+ if (!out) {
+ out = new Uint8ClampedArray(BYTES_32BIT);
+ if (layerAlpha >= 0.999) {
+ out.set(src);
+ } else {
+ for (let p = 0; p < BYTES_32BIT; p += 4) {
+ out[p] = src[p];
+ out[p + 1] = src[p + 1];
+ out[p + 2] = src[p + 2];
+ out[p + 3] = Math.round(src[p + 3] * layerAlpha);
+ }
+ }
+ } else {
+ for (let p = 0; p < BYTES_32BIT; p += 4) {
+ const sa = src[p + 3];
+ if (sa === 0) continue;
+ const sA = (sa / 255) * layerAlpha;
+ const dA = out[p + 3] / 255;
+ const outA = sA + dA * (1 - sA);
+ if (outA > 0) {
+ const invOut = 1 / outA;
+ const invSA = 1 - sA;
+ out[p] = Math.round((src[p] * sA + out[p] * dA * invSA) * invOut);
+ out[p + 1] = Math.round((src[p + 1] * sA + out[p + 1] * dA * invSA) * invOut);
+ out[p + 2] = Math.round((src[p + 2] * sA + out[p + 2] * dA * invSA) * invOut);
+ out[p + 3] = Math.round(outA * 255);
+ }
+ }
+ }
+ }
+ return out;
+}
+
+const FLOOD_TILE_STRIDE = 65536;
+const FLOOD_TILE_BIAS = 32768;
+function packFloodTileKey(tx: number, ty: number): number {
+ return (ty + FLOOD_TILE_BIAS) * FLOOD_TILE_STRIDE + (tx + FLOOD_TILE_BIAS);
+}
+
+/**
+ * Tile-native scanline flood fill operating directly on SparseTileGrid.
+ * Peak memory is proportional to visited tiles only (zero full-canvas materialization).
+ */
+export function executeFloodFillOnTileGrid(params: {
+ grid: SparseTileGrid;
+ targetLayerId: string;
+ layers: LayerItem[];
+ dimensions: CanvasDimensions;
+ startX: number;
+ startY: number;
+ fillColorHex: string;
+ tolerance: number;
+ referMode: 'active' | 'refer-all' | 'refer-reference';
+ targetFormat?: TileFormat;
+ options?: FloodFillOptions;
+}): { dirtyRect: DirtyRect | null; modified: boolean; tileDeltas: TileDelta[] } {
+ const {
+ grid,
+ targetLayerId,
+ layers,
+ dimensions,
+ startX,
+ startY,
+ fillColorHex,
+ tolerance,
+ referMode,
+ options,
+ } = params;
+ const width = dimensions.width;
+ const height = dimensions.height;
+ if (width <= 0 || height <= 0) return { dirtyRect: null, modified: false, tileDeltas: [] };
+
+ const px = Math.floor(startX);
+ const py = Math.floor(startY);
+ if (px < 0 || px >= width || py < 0 || py >= height) {
+ return { dirtyRect: null, modified: false, tileDeltas: [] };
+ }
+
+ const selectionMask = options?.selectionMask ?? null;
+ const totalPixels = width * height;
+ if (selectionMask && selectionMask.length === totalPixels && selectionMask[py * width + px] === 0) {
+ return { dirtyRect: null, modified: false, tileDeltas: [] };
+ }
+
+ // Determine reference layers for lazy tile compositing
+ let refLayers: LayerItem[] | null = null;
+ if (referMode === 'refer-reference') {
+ const refs = layers.filter((l) => l.visible && l.isReference && l.type !== 'folder' && l.type !== 'frame-folder');
+ refLayers = refs.length > 0 ? refs : layers.filter((l) => l.visible && l.type !== 'folder' && l.type !== 'frame-folder');
+ } else if (referMode === 'refer-all') {
+ refLayers = layers.filter((l) => l.visible && l.type !== 'folder' && l.type !== 'frame-folder');
+ }
+
+ const refTileCache = new Map<number, Uint8ClampedArray | null>();
+ const getRefTile = (tx: number, ty: number): Uint8ClampedArray | null => {
+ const key = packFloodTileKey(tx, ty);
+ let cached = refTileCache.get(key);
+ if (cached !== undefined) return cached;
+ if (refLayers) {
+ cached = buildCompositedReferenceTile(grid, refLayers, tx, ty);
+ } else {
+ const tile = grid.getTile(targetLayerId, tx, ty, 0);
+ cached = tile && tile.data ? new Uint8ClampedArray(grid.getTileAsRGBA(tile)) : null;
+ }
+ refTileCache.set(key, cached);
+ return cached;
+ };
+
+ const getRefPixel = (x: number, y: number, out: [number, number, number, number]): void => {
+ const tile = getRefTile(x >> 8, y >> 8);
+ if (!tile) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ return;
+ }
+ const off = (((y & 255) << 8) | (x & 255)) << 2;
+ out[0] = tile[off];
+ out[1] = tile[off + 1];
+ out[2] = tile[off + 2];
+ out[3] = tile[off + 3];
+ };
+
+ const [fillR, fillG, fillB, fillA] = parseColorToRgba(fillColorHex);
+ const seedPx: [number, number, number, number] = [0, 0, 0, 0];
+ getRefPixel(px, py, seedPx);
+ const [seedR, seedG, seedB, seedA] = seedPx;
+
+ const closeGap = Math.max(0, Math.min(20, Math.round(options?.closeGap ?? 0)));
+ const areaScale = Math.max(-20, Math.min(20, Math.round(options?.areaScale ?? 0)));
+ const antiAlias = options?.antiAlias ?? false;
+
+ if (
+ referMode === 'active' &&
+ areaScale === 0 &&
+ Math.abs(seedR - fillR) <= 2 &&
+ Math.abs(seedG - fillG) <= 2 &&
+ Math.abs(seedB - fillB) <= 2 &&
+ Math.abs(seedA - fillA) <= 2
+ ) {
+ return { dirtyRect: null, modified: false, tileDeltas: [] };
+ }
+
+ const maxToleranceDistance = (tolerance / 100) * 255;
+
+ // Lazy per-tile barrier cache when closeGap > 0 (padded morphological closing across tile boundaries)
+ const barrierTileCache = closeGap > 0 ? new Map<number, Uint8Array>() : null;
+ const closingRadius = closeGap > 0 ? Math.max(1, Math.ceil(closeGap / 2)) : 0;
+
+ const getBarrierTile = (tx: number, ty: number): Uint8Array => {
+ const key = packFloodTileKey(tx, ty);
+ let cached = barrierTileCache!.get(key);
+ if (cached) return cached;
+
+ const r = closingRadius;
+ const padSize = TILE_SIZE + r * 2;
+ const raw = new Uint8Array(padSize * padSize);
+ const originX = tx * TILE_SIZE - r;
+ const originY = ty * TILE_SIZE - r;
+ const tmp: [number, number, number, number] = [0, 0, 0, 0];
+
+ for (let ly = 0; ly < padSize; ly++) {
+ const gy = originY + ly;
+ const row = ly * padSize;
+ for (let lx = 0; lx < padSize; lx++) {
+ const gx = originX + lx;
+ if (gx < 0 || gx >= width || gy < 0 || gy >= height) {
+ raw[row + lx] = 1;
+ continue;
+ }
+ getRefPixel(gx, gy, tmp);
+ const diff =
+ (Math.abs(tmp[0] - seedR) +
+ Math.abs(tmp[1] - seedG) +
+ Math.abs(tmp[2] - seedB) +
+ Math.abs(tmp[3] - seedA)) /
+ 4;
+ if (diff > maxToleranceDistance) raw[row + lx] = 1;
+ }
+ }
+
+ const dilated = dilateBinaryMask(raw, padSize, padSize, r);
+ const closed = erodeBinaryMask(dilated, padSize, padSize, r);
+ cached = new Uint8Array(TILE_PIXELS);
+ for (let ly = 0; ly < TILE_SIZE; ly++) {
+ const srcRow = (ly + r) * padSize + r;
+ const dstRow = ly * TILE_SIZE;
+ for (let lx = 0; lx < TILE_SIZE; lx++) {
+ cached[dstRow + lx] = raw[srcRow + lx] || closed[srcRow + lx] ? 1 : 0;
+ }
+ }
+ // Never block the seed pixel if it wasn't originally a barrier
+ if ((px >> 8) === tx && (py >> 8) === ty) {
+ const slx = px & 255;
+ const sly = py & 255;
+ cached[sly * TILE_SIZE + slx] = raw[(sly + r) * padSize + (slx + r)];
+ }
+ barrierTileCache!.set(key, cached);
+ return cached;
+ };
+
+ // Sparse visited bitmask per 256x256 tile
+ const visitedTiles = new Map<number, Uint8Array>();
+ const isVisited = (x: number, y: number): boolean => {
+ const arr = visitedTiles.get(packFloodTileKey(x >> 8, y >> 8));
+ if (!arr) return false;
+ return arr[((y & 255) << 8) | (x & 255)] !== 0;
+ };
+ const setVisited = (x: number, y: number): void => {
+ const key = packFloodTileKey(x >> 8, y >> 8);
+ let arr = visitedTiles.get(key);
+ if (!arr) {
+ arr = new Uint8Array(TILE_PIXELS);
+ visitedTiles.set(key, arr);
+ }
+ arr[((y & 255) << 8) | (x & 255)] = 1;
+ };
+
+ const sampleTmp: [number, number, number, number] = [0, 0, 0, 0];
+ const matchesSeed = (x: number, y: number): boolean => {
+ if (selectionMask && selectionMask.length === totalPixels && selectionMask[y * width + x] === 0) {
+ return false;
+ }
+ if (barrierTileCache) {
+ const bt = getBarrierTile(x >> 8, y >> 8);
+ return bt[((y & 255) << 8) | (x & 255)] === 0;
+ }
+ getRefPixel(x, y, sampleTmp);
+ const diff =
+ (Math.abs(sampleTmp[0] - seedR) +
+ Math.abs(sampleTmp[1] - seedG) +
+ Math.abs(sampleTmp[2] - seedB) +
+ Math.abs(sampleTmp[3] - seedA)) /
+ 4;
+ return diff <= maxToleranceDistance;
+ };
+
+ const stackX: number[] = [px];
+ const stackY: number[] = [py];
+
+ let minX = px;
+ let maxX = px;
+ let minY = py;
+ let maxY = py;
+
+ while (stackX.length > 0) {
+ const curX = stackX.pop()!;
+ const curY = stackY.pop()!;
+ if (isVisited(curX, curY)) continue;
+
+ let x1 = curX;
+ while (x1 >= 0 && matchesSeed(x1, curY) && !isVisited(x1, curY)) {
+ x1--;
+ }
+ x1++;
+
+ let x2 = curX;
+ while (x2 < width && matchesSeed(x2, curY) && !isVisited(x2, curY)) {
+ x2++;
+ }
+ x2--;
+
+ if (x1 > x2) continue;
+
+ if (x1 < minX) minX = x1;
+ if (x2 > maxX) maxX = x2;
+ if (curY < minY) minY = curY;
+ if (curY > maxY) maxY = curY;
+
+ let spanAbove = false;
+ let spanBelow = false;
+
+ for (let x = x1; x <= x2; x++) {
+ setVisited(x, curY);
+
+ if (curY > 0) {
+ const aboveVisited = isVisited(x, curY - 1);
+ const aboveMatch = matchesSeed(x, curY - 1);
+ if (!spanAbove && aboveMatch && !aboveVisited) {
+ stackX.push(x);
+ stackY.push(curY - 1);
+ spanAbove = true;
+ } else if (spanAbove && (!aboveMatch || aboveVisited)) {
+ spanAbove = false;
+ }
+ }
+
+ if (curY < height - 1) {
+ const belowVisited = isVisited(x, curY + 1);
+ const belowMatch = matchesSeed(x, curY + 1);
+ if (!spanBelow && belowMatch && !belowVisited) {
+ stackX.push(x);
+ stackY.push(curY + 1);
+ spanBelow = true;
+ } else if (spanBelow && (!belowMatch || belowVisited)) {
+ spanBelow = false;
+ }
+ }
+ }
+ }
+
+ // Optional Area Scaling operated strictly on the tight filled bounding box (not full 600 DPI doc)
+ if (areaScale > 0) {
+ const getLineStrength = (x: number, y: number): number => {
+ getRefPixel(x, y, sampleTmp);
+ const a = sampleTmp[3] / 255;
+ const luma = (0.299 * sampleTmp[0] + 0.587 * sampleTmp[1] + 0.114 * sampleTmp[2]) / 255;
+ return a * (1.0 - luma * 0.85);
+ };
+
+ let frontier: number[] = [];
+ for (let y = minY; y <= maxY; y++) {
+ for (let x = minX; x <= maxX; x++) {
+ if (!isVisited(x, y)) continue;
+ if (
+ (x > 0 && !isVisited(x - 1, y)) ||
+ (x < width - 1 && !isVisited(x + 1, y)) ||
+ (y > 0 && !isVisited(x, y - 1)) ||
+ (y < height - 1 && !isVisited(x, y + 1))
+ ) {
+ frontier.push(x, y);
+ }
+ }
+ }
+
+ const dxDirs = [-1, 1, 0, 0];
+ const dyDirs = [0, 0, -1, 1];
+ for (let step = 0; step < areaScale && frontier.length > 0; step++) {
+ const nextFrontier: number[] = [];
+ for (let i = 0; i < frontier.length; i += 2) {
+ const cx = frontier[i];
+ const cy = frontier[i + 1];
+ const curStrength = getLineStrength(cx, cy);
+ for (let d = 0; d < 4; d++) {
+ const nx = cx + dxDirs[d];
+ const ny = cy + dyDirs[d];
+ if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue;
+ if (isVisited(nx, ny)) continue;
+ const nStrength = getLineStrength(nx, ny);
+ if (curStrength > 0.55 && nStrength < curStrength - 0.05) continue;
+ setVisited(nx, ny);
+ nextFrontier.push(nx, ny);
+ if (nx < minX) minX = nx;
+ if (nx > maxX) maxX = nx;
+ if (ny < minY) minY = ny;
+ if (ny > maxY) maxY = ny;
+ }
+ }
+ frontier = nextFrontier;
+ }
+ } else if (areaScale < 0) {
+ const bw = maxX - minX + 1;
+ const bh = maxY - minY + 1;
+ const localMask = new Uint8Array(bw * bh);
+ for (let y = minY; y <= maxY; y++) {
+ for (let x = minX; x <= maxX; x++) {
+ if (isVisited(x, y)) localMask[(y - minY) * bw + (x - minX)] = 1;
+ }
+ }
+ const eroded = erodeBinaryMask(localMask, bw, bh, Math.abs(areaScale));
+ visitedTiles.clear();
+ for (let ly = 0; ly < bh; ly++) {
+ for (let lx = 0; lx < bw; lx++) {
+ if (eroded[ly * bw + lx]) setVisited(minX + lx, minY + ly);
+ }
+ }
+ }
+
+ if (antiAlias) {
+ minX = Math.max(0, minX - 1);
+ minY = Math.max(0, minY - 1);
+ maxX = Math.min(width - 1, maxX + 1);
+ maxY = Math.min(height - 1, maxY + 1);
+ }
+
+ const targetFormat = params.targetFormat ?? grid.getLayerFormat(targetLayerId);
+ const beforeSnapshot = new Map<string, TileSnapshotEntry>();
+
+ const minTx = pixelToTileCoord(minX, 0);
+ const minTy = pixelToTileCoord(minY, 0);
+ const maxTx = pixelToTileCoord(maxX, 0);
+ const maxTy = pixelToTileCoord(maxY, 0);
+
+ const workBuf = new Uint8ClampedArray(BYTES_32BIT);
+
+ for (let ty = minTy; ty <= maxTy; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const startLY = Math.max(0, minY - tileDocY);
+ const endLY = Math.min(TILE_SIZE, maxY - tileDocY + 1);
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+ const startLX = Math.max(0, minX - tileDocX);
+ const endLX = Math.min(TILE_SIZE, maxX - tileDocX + 1);
+
+ const tileVisited = visitedTiles.get(packFloodTileKey(tx, ty));
+ if (!tileVisited && !antiAlias) continue;
+
+ const existingTile = grid.getTile(targetLayerId, tx, ty, 0);
+ if (existingTile && existingTile.data) {
+ workBuf.set(grid.getTileAsRGBA(existingTile));
+ } else {
+ workBuf.fill(0);
+ }
+
+ let tileChanged = false;
+ for (let ly = startLY; ly < endLY; ly++) {
+ const gy = tileDocY + ly;
+ const rowOff = ly * TILE_SIZE;
+ const selRow = gy * width;
+ for (let lx = startLX; lx < endLX; lx++) {
+ const gx = tileDocX + lx;
+ if (selectionMask && selectionMask.length === totalPixels && selectionMask[selRow + gx] === 0) {
+ continue;
+ }
+ const filled = tileVisited ? tileVisited[rowOff + lx] !== 0 : false;
+ if (filled) {
+ const off = (rowOff + lx) << 2;
+ workBuf[off] = fillR;
+ workBuf[off + 1] = fillG;
+ workBuf[off + 2] = fillB;
+ workBuf[off + 3] = fillA;
+ tileChanged = true;
+ } else if (antiAlias) {
+ let filledNeighbors = 0;
+ if (gx > 0 && isVisited(gx - 1, gy)) filledNeighbors++;
+ if (gx < width - 1 && isVisited(gx + 1, gy)) filledNeighbors++;
+ if (gy > 0 && isVisited(gx, gy - 1)) filledNeighbors++;
+ if (gy < height - 1 && isVisited(gx, gy + 1)) filledNeighbors++;
+ if (filledNeighbors >= 2) {
+ const off = (rowOff + lx) << 2;
+ const blendAlpha = (filledNeighbors / 4) * (fillA / 255) * 0.5;
+ const dstA = workBuf[off + 3] / 255;
+ const outA = blendAlpha + dstA * (1 - blendAlpha);
+ if (outA > 0) {
+ workBuf[off] = Math.round((fillR * blendAlpha + workBuf[off] * dstA * (1 - blendAlpha)) / outA);
+ workBuf[off + 1] = Math.round((fillG * blendAlpha + workBuf[off + 1] * dstA * (1 - blendAlpha)) / outA);
+ workBuf[off + 2] = Math.round((fillB * blendAlpha + workBuf[off + 2] * dstA * (1 - blendAlpha)) / outA);
+ workBuf[off + 3] = Math.round(outA * 255);
+ tileChanged = true;
+ }
+ }
+ }
+ }
+ }
+
+ if (tileChanged) {
+ grid.snapshotSingleTileInto(targetLayerId, tx, ty, beforeSnapshot);
+ grid.writeImageData(
+ targetLayerId,
+ { data: workBuf, width: TILE_SIZE, height: TILE_SIZE },
+ tileDocX,
+ tileDocY,
+ targetFormat,
+ true
+ );
+ }
+ }
+ }
+
+ const dirtyRect: DirtyRect = {
+ x: minX,
+ y: minY,
+ width: Math.max(1, maxX - minX + 1),
+ height: Math.max(1, maxY - minY + 1),
+ };
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, targetLayerId, dirtyRect);
+ grid.notifyChange(true);
+ return { dirtyRect, modified: tileDeltas.length > 0, tileDeltas };
+}
+
+/**
+ * Tile-native freehand lasso fill: rasterizes the polygon in bounded 512x512 chunks
+ * directly into SparseTileGrid tiles (zero full-canvas allocation).
+ */
+export function executeLassoFillOnTileGrid(params: {
+ grid: SparseTileGrid;
+ targetLayerId: string;
+ dimensions: CanvasDimensions;
+ polygon: Array<{ x: number; y: number }>;
+ fillColorHex: string;
+ targetFormat?: TileFormat;
+ alphaLocked?: boolean;
+}): { dirtyRect: DirtyRect | null; modified: boolean; tileDeltas: TileDelta[] } {
+ const { grid, targetLayerId, dimensions, polygon, fillColorHex, alphaLocked = false } = params;
+ if (polygon.length < 3 || typeof document === 'undefined') {
+ return { dirtyRect: null, modified: false, tileDeltas: [] };
+ }
+
+ let minX = polygon[0].x;
+ let maxX = polygon[0].x;
+ let minY = polygon[0].y;
+ let maxY = polygon[0].y;
+ for (const pt of polygon) {
+ if (pt.x < minX) minX = pt.x;
+ if (pt.x > maxX) maxX = pt.x;
+ if (pt.y < minY) minY = pt.y;
+ if (pt.y > maxY) maxY = pt.y;
+ }
+
+ const rx = Math.max(0, Math.floor(minX));
+ const ry = Math.max(0, Math.floor(minY));
+ const rx1 = Math.min(dimensions.width, Math.ceil(maxX));
+ const ry1 = Math.min(dimensions.height, Math.ceil(maxY));
+ const rw = rx1 - rx;
+ const rh = ry1 - ry;
+ if (rw <= 0 || rh <= 0) return { dirtyRect: null, modified: false, tileDeltas: [] };
+
+ const targetFormat = params.targetFormat ?? grid.getLayerFormat(targetLayerId);
+ const beforeSnapshot = new Map<string, TileSnapshotEntry>();
+ const CHUNK = 512;
+ const chunkCanvas = document.createElement('canvas');
+ chunkCanvas.width = Math.min(CHUNK, rw);
+ chunkCanvas.height = Math.min(CHUNK, rh);
+ const cCtx = chunkCanvas.getContext('2d', { willReadFrequently: true });
+ if (!cCtx) {
+ releaseTemporaryCanvas(chunkCanvas);
+ return { dirtyRect: null, modified: false, tileDeltas: [] };
+ }
+
+ try {
+ for (let cy = ry; cy < ry1; cy += CHUNK) {
+ const ch = Math.min(CHUNK, ry1 - cy);
+ for (let cx = rx; cx < rx1; cx += CHUNK) {
+ const cw = Math.min(CHUNK, rx1 - cx);
+ if (chunkCanvas.width !== cw) chunkCanvas.width = cw;
+ if (chunkCanvas.height !== ch) chunkCanvas.height = ch;
+
+ cCtx.clearRect(0, 0, cw, ch);
+ cCtx.save();
+ cCtx.translate(-cx, -cy);
+ cCtx.fillStyle = fillColorHex;
+ cCtx.beginPath();
+ cCtx.moveTo(polygon[0].x, polygon[0].y);
+ for (let i = 1; i < polygon.length; i++) {
+ cCtx.lineTo(polygon[i].x, polygon[i].y);
+ }
+ cCtx.closePath();
+ cCtx.fill();
+ cCtx.restore();
+
+ const img = cCtx.getImageData(0, 0, cw, ch);
+ grid.compositeStrokeToTiles({
+ layerId: targetLayerId,
+ strokeData: img,
+ destX: cx,
+ destY: cy,
+ format: targetFormat,
+ compositeOp: alphaLocked ? 'source-atop' : 'source-over',
+ opacity: 1.0,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+ }
+ } finally {
+ releaseTemporaryCanvas(chunkCanvas);
+ }
+
+ const dirtyRect: DirtyRect = { x: rx, y: ry, width: rw, height: rh };
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, targetLayerId, dirtyRect);
+ grid.notifyChange(true);
+ return { dirtyRect, modified: tileDeltas.length > 0, tileDeltas };
+}
+
+/**
+ * Async tile-native flood fill: dispatches Close Gap + Area Scale + scanline fill
+ * to the parallel Rust Rayon backend when running in Tauri, returning only the
+ * modified dirtyRect pixels over raw binary IPC.
+ */
+export async function executeFloodFillOnTileGridAsync(params: {
+ grid: SparseTileGrid;
+ targetLayerId: string;
+ layers: LayerItem[];
+ dimensions: CanvasDimensions;
+ startX: number;
+ startY: number;
+ fillColorHex: string;
+ tolerance: number;
+ referMode: 'active' | 'refer-all' | 'refer-reference';
+ targetFormat?: TileFormat;
+ options?: FloodFillOptions;
+}): Promise<{ dirtyRect: DirtyRect | null; modified: boolean; tileDeltas: TileDelta[] }> {
+ if (!isNativeRustAvailable()) {
+ return executeFloodFillOnTileGrid(params);
+ }
+
+ const {
+ grid,
+ targetLayerId,
+ layers,
+ dimensions,
+ startX,
+ startY,
+ fillColorHex,
+ tolerance,
+ referMode,
+ options,
+ } = params;
+
+ const width = dimensions.width;
+ const height = dimensions.height;
+ if (width <= 0 || height <= 0) return { dirtyRect: null, modified: false, tileDeltas: [] };
+ // Guard against extreme canvases exceeding native 256MB raster IPC cap (~8192x8192 RGBA)
+ if (width * height * 4 > 128 * 1024 * 1024) {
+ return executeFloodFillOnTileGrid(params);
+ }
+
+ const px = Math.floor(startX);
+ const py = Math.floor(startY);
+ if (px < 0 || px >= width || py < 0 || py >= height) {
+ return { dirtyRect: null, modified: false, tileDeltas: [] };
+ }
+
+ const targetRgba = grid.readImageData(targetLayerId, 0, 0, width, height).data;
+ let refRgba: Uint8ClampedArray = targetRgba;
+
+ if (referMode !== 'active') {
+ const refLayers =
+ referMode === 'refer-reference'
+ ? (() => {
+ const r = layers.filter(
+ (l) => l.visible && l.isReference && l.type !== 'folder' && l.type !== 'frame-folder'
+ );
+ return r.length > 0
+ ? r
+ : layers.filter((l) => l.visible && l.type !== 'folder' && l.type !== 'frame-folder');
+ })()
+ : layers.filter((l) => l.visible && l.type !== 'folder' && l.type !== 'frame-folder');
+
+ const comp = new Uint8ClampedArray(width * height * 4);
+ const tilesX = Math.ceil(width / TILE_SIZE);
+ const tilesY = Math.ceil(height / TILE_SIZE);
+ for (let ty = 0; ty < tilesY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const copyH = Math.min(TILE_SIZE, height - tileDocY);
+ for (let tx = 0; tx < tilesX; tx++) {
+ const cTile = buildCompositedReferenceTile(grid, refLayers, tx, ty);
+ if (!cTile) continue;
+ const tileDocX = tx * TILE_SIZE;
+ const copyW = Math.min(TILE_SIZE, width - tileDocX);
+ const rowBytes = copyW * 4;
+ for (let row = 0; row < copyH; row++) {
+ const sOff = row * TILE_SIZE * 4;
+ const dOff = ((tileDocY + row) * width + tileDocX) * 4;
+ comp.set(cTile.subarray(sOff, sOff + rowBytes), dOff);
+ }
+ }
+ }
+ refRgba = comp;
+ }
+
+ const res = await floodFillNative({
+ refRgba,
+ targetRgba: referMode === 'active' ? null : targetRgba,
+ selectionMask: options?.selectionMask ?? null,
+ width,
+ height,
+ startX: px,
+ startY: py,
+ fillRgba: parseColorToRgba(fillColorHex),
+ tolerance,
+ closeGap: Math.max(0, Math.min(20, Math.round(options?.closeGap ?? 0))),
+ areaScale: Math.max(-20, Math.min(20, Math.round(options?.areaScale ?? 0))),
+ antiAlias: options?.antiAlias ?? false,
+ });
+
+ if (!res.modified || !res.dirtyRect || !res.dirtyRgba) {
+ return { dirtyRect: null, modified: false, tileDeltas: [] };
+ }
+
+ const targetFormat = params.targetFormat ?? grid.getLayerFormat(targetLayerId);
+ const beforeSnapshot = grid.snapshotTilesInRect(targetLayerId, res.dirtyRect);
+ grid.writeImageData(
+ targetLayerId,
+ { data: res.dirtyRgba, width: res.dirtyRect.width, height: res.dirtyRect.height },
+ res.dirtyRect.x,
+ res.dirtyRect.y,
+ targetFormat,
+ true
+ );
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, targetLayerId, res.dirtyRect);
+ grid.notifyChange(true);
+ return { dirtyRect: res.dirtyRect, modified: tileDeltas.length > 0, tileDeltas };
+}
diff --git a/src/utils/imageLoader.ts b/src/utils/imageLoader.ts
index 2f35011..ccfd38b 100644
--- a/src/utils/imageLoader.ts
+++ b/src/utils/imageLoader.ts
@@ -1,9 +1,8 @@
-import { LoadedDocument, LayerItem, CanvasColorMode, isFolderLikeLayer } from '../types/editor';
-import { createCanvasThumbnail } from './canvasUtils';
+import { LoadedDocument, LayerItem, CanvasColorMode } from '../types/editor';
import { renderVectorLayer } from './vectorEngine';
import { renderBalloonLayerData, renderTextLayerData } from './vectorLayerRenderer';
-import { parseSoraProject } from './saveManager';
-import { releaseTemporaryCanvas } from './tileEngine';
+import { PRIMARY_PROJECT_EXTENSION, parseInkProject } from './saveManager';
+import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';
/**
* Loads standard raster/vector image formats (.png, .jpg, .jpeg, .webp, .bmp, .gif, .svg).
@@ -19,30 +18,23 @@ export async function loadStandardImage(file: File): Promise<LoadedDocument> {
const height = img.naturalHeight || 900;
const layerId = `layer-${Date.now()}`;
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d');
+ const bgId = `layer-bg-${Date.now()}`;
+ const grid = new SparseTileGrid();
+
+ const tempCanvas = document.createElement('canvas');
+ tempCanvas.width = width;
+ tempCanvas.height = height;
+ const ctx = tempCanvas.getContext('2d');
if (ctx) {
ctx.drawImage(img, 0, 0);
}
+ grid.ingestCanvas(layerId, tempCanvas, 'color-32bit');
+ releaseTemporaryCanvas(tempCanvas);
- const bgId = `layer-bg-${Date.now()}`;
- const bgCanvas = document.createElement('canvas');
- bgCanvas.width = width;
- bgCanvas.height = height;
- const bgCtx = bgCanvas.getContext('2d');
- if (bgCtx) {
- bgCtx.fillStyle = '#ffffff';
- bgCtx.fillRect(0, 0, width, height);
- }
-
- const layerCanvases = new Map<string, HTMLCanvasElement>();
- layerCanvases.set(layerId, canvas);
- layerCanvases.set(bgId, bgCanvas);
+ grid.fillLayerSolidWhite(bgId, width, height, 'color-32bit');
- const thumb = createCanvasThumbnail(canvas, false);
- const bgThumb = createCanvasThumbnail(bgCanvas, false);
+ const thumb = grid.generateThumbnail(layerId, 64, 64, { width, height }, true);
+ const bgThumb = grid.generateThumbnail(bgId, 64, 64, { width, height }, false);
const layers: LayerItem[] = [
{
@@ -74,7 +66,7 @@ export async function loadStandardImage(file: File): Promise<LoadedDocument> {
dimensions: { width, height, dpi: 600 },
colorMode: 'color' as CanvasColorMode,
layers,
- layerCanvases,
+ tileGrid: grid,
});
};
@@ -88,10 +80,12 @@ export async function loadStandardImage(file: File): Promise<LoadedDocument> {
}
/**
- * Universal file opener detecting file extension and loading image, PSD, or CSP files.
+ * Universal file opener detecting file extension and loading native `.ink`, legacy `.sora`
+ * (via read-only migrator), PSD, CSP, or standard image files.
*/
export async function openFile(file: File): Promise<LoadedDocument> {
- const ext = file.name.slice(file.name.lastIndexOf('.')).toLowerCase();
+ const dot = file.name.lastIndexOf('.');
+ const ext = dot >= 0 ? file.name.slice(dot).toLowerCase() : '';
if (ext === '.psd' || ext === '.psb') {
const { parsePsdFile } = await import('./psdParser');
@@ -105,156 +99,63 @@ export async function openFile(file: File): Promise<LoadedDocument> {
return await parseCspFile(buffer, file.name);
}
- if (ext === '.ink' || ext === '.sora' || ext === '.json') {
- try {
- const buffer = await file.arrayBuffer();
- const project = await parseSoraProject(buffer);
- if (project.layers && Array.isArray(project.layers)) {
- const width = project.dimensions.width;
- const height = project.dimensions.height;
- const dpi = project.dimensions.dpi || 300;
- const colorMode: CanvasColorMode = project.colorMode || 'color';
- const layers: LayerItem[] = project.layers;
-
- // Fast native binary v2 path: tiles are already populated directly into SparseTileGrid
- if (project.format === 'v2' && project.tileGrid) {
- const grid = project.tileGrid;
- if (typeof document !== 'undefined') {
- for (const layer of layers) {
- if (grid.hasLayerTiles(layer.id)) continue;
- if (layer.type === 'text' && layer.textData) {
- const temp = document.createElement('canvas');
- temp.width = width;
- temp.height = height;
- const ctx = temp.getContext('2d');
- if (ctx) renderTextLayerData(ctx, layer.textData);
- grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
- releaseTemporaryCanvas(temp);
- } else if (layer.type === 'balloon' && layer.balloonData) {
- const temp = document.createElement('canvas');
- temp.width = width;
- temp.height = height;
- const ctx = temp.getContext('2d');
- if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
- grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
- releaseTemporaryCanvas(temp);
- } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
- const temp = document.createElement('canvas');
- temp.width = width;
- temp.height = height;
- const ctx = temp.getContext('2d');
- if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
- grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
- releaseTemporaryCanvas(temp);
- }
- }
- }
-
- return {
- name: project.name || file.name.replace(/\.[^/.]+$/, ''),
- dimensions: { width, height, dpi },
- colorMode,
- layers,
- tileGrid: grid,
- perspectiveRuler: project.perspectiveRuler ?? null,
- animationTimeline: project.animationTimeline ?? null,
- timelapse: project.timelapse ?? null,
- previewDataUrl: project.previewDataUrl,
- };
+ if (ext === PRIMARY_PROJECT_EXTENSION) {
+ const buffer = await file.arrayBuffer();
+ const project = await parseInkProject(buffer);
+ const { width, height } = project.dimensions;
+ const dpi = project.dimensions.dpi || 300;
+ const colorMode: CanvasColorMode = project.colorMode || 'color';
+ const layers = project.layers;
+ const grid = project.tileGrid;
+
+ if (typeof document !== 'undefined') {
+ for (const layer of layers) {
+ if (grid.hasLayerTiles(layer.id)) continue;
+ if (layer.type === 'text' && layer.textData) {
+ const temp = document.createElement('canvas');
+ temp.width = width;
+ temp.height = height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderTextLayerData(ctx, layer.textData);
+ grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
+ releaseTemporaryCanvas(temp);
+ } else if (layer.type === 'balloon' && layer.balloonData) {
+ const temp = document.createElement('canvas');
+ temp.width = width;
+ temp.height = height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
+ grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
+ releaseTemporaryCanvas(temp);
+ } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
+ const temp = document.createElement('canvas');
+ temp.width = width;
+ temp.height = height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
+ grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
+ releaseTemporaryCanvas(temp);
}
-
- // Legacy v1.2 JSON path: reconstruct canvases from base64 PNG data URLs
- const layerCanvases = new Map<string, HTMLCanvasElement>();
-
- const loadPromises = layers.map((layer) => {
- const tasks: Promise<void>[] = [];
-
- // Reconstruct maskCanvas if saved in project.masks
- const maskDataUrl = project.masks?.[layer.id];
- if (maskDataUrl) {
- tasks.push(
- new Promise<void>((resolve) => {
- const mCanvas = document.createElement('canvas');
- mCanvas.width = width;
- mCanvas.height = height;
- const mImg = new Image();
- mImg.onload = () => {
- mCanvas.getContext('2d')?.drawImage(mImg, 0, 0);
- layer.maskCanvas = mCanvas;
- layer.maskVersion = (layer.maskVersion || 0) + 1;
- resolve();
- };
- mImg.onerror = () => resolve();
- mImg.src = maskDataUrl;
- })
- );
- }
-
- if (!isFolderLikeLayer(layer) && layer.type !== 'adjustment') {
- tasks.push(
- new Promise<void>((resolve) => {
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
-
- // Always re-render non-destructive text/balloon from crisp vector data when available
- if (layer.type === 'text' && layer.textData) {
- const ctx = canvas.getContext('2d');
- if (ctx) renderTextLayerData(ctx, layer.textData);
- layerCanvases.set(layer.id, canvas);
- resolve();
- return;
- }
- if (layer.type === 'balloon' && layer.balloonData) {
- const ctx = canvas.getContext('2d');
- if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
- layerCanvases.set(layer.id, canvas);
- resolve();
- return;
- }
-
- const dataUrl = project.canvases?.[layer.id];
- if (dataUrl) {
- const img = new Image();
- img.onload = () => {
- const ctx = canvas.getContext('2d');
- ctx?.drawImage(img, 0, 0);
- layerCanvases.set(layer.id, canvas);
- resolve();
- };
- img.onerror = () => {
- layerCanvases.set(layer.id, canvas);
- resolve();
- };
- img.src = dataUrl;
- } else {
- if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
- const ctx = canvas.getContext('2d');
- if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
- }
- layerCanvases.set(layer.id, canvas);
- resolve();
- }
- })
- );
- }
-
- return Promise.all(tasks).then(() => {});
- });
-
- await Promise.all(loadPromises);
-
- return {
- name: project.name || file.name.replace(/\.[^/.]+$/, ''),
- dimensions: { width, height, dpi },
- colorMode,
- layers,
- layerCanvases,
- };
}
- } catch (err) {
- console.warn('Failed to parse .sora project, falling back to image loader:', err);
}
+
+ return {
+ name: project.name || file.name.replace(/\.[^/.]+$/, ''),
+ dimensions: { width, height, dpi },
+ colorMode,
+ layers,
+ tileGrid: grid,
+ perspectiveRuler: project.perspectiveRuler ?? null,
+ animationTimeline: project.animationTimeline ?? null,
+ timelapse: project.timelapse ?? null,
+ previewDataUrl: project.previewDataUrl,
+ };
+ }
+
+ // Legacy `.sora` files are routed exclusively to the read-only migrator
+ if (ext === '.sora') {
+ const { migrateLegacySoraFile } = await import('./legacySoraMigrator');
+ return await migrateLegacySoraFile(file);
}
// Common image extensions: .png, .jpg, .jpeg, .webp, .bmp, .gif, .svg
diff --git a/src/utils/inkbBrushFormat.ts b/src/utils/inkbBrushFormat.ts
index d54cfcc..3623616 100644
--- a/src/utils/inkbBrushFormat.ts
+++ b/src/utils/inkbBrushFormat.ts
@@ -1,5 +1,6 @@
import { zipSync, unzipSync, strToU8, strFromU8 } from 'fflate';
import {
+ ALL_BLEND_MODES,
BlendMode,
BrushDynamics,
BrushSettings,
@@ -53,25 +54,7 @@ const VALID_TEXTURE_MODES = new Set<CspPaperTextureMode>([
'overlay',
'outline',
]);
-const VALID_BLEND_MODES = new Set<BlendMode>([
- 'normal',
- 'multiply',
- 'screen',
- 'overlay',
- 'darken',
- 'lighten',
- 'color-dodge',
- 'color-burn',
- 'hard-light',
- 'soft-light',
- 'difference',
- 'exclusion',
- 'pass-through',
- 'linear-burn',
- 'add-glow',
- 'color-dodge-glow',
- 'divide',
-]);
+const VALID_BLEND_MODES = new Set<BlendMode>(ALL_BLEND_MODES);
interface InkbArchivePayload {
format: typeof INKB_FORMAT;
diff --git a/src/utils/legacySoraMigrator.ts b/src/utils/legacySoraMigrator.ts
new file mode 100644
index 0000000..19af20f
--- /dev/null
+++ b/src/utils/legacySoraMigrator.ts
@@ -0,0 +1,303 @@
+import {
+ CanvasColorMode,
+ CanvasDimensions,
+ LayerItem,
+ LoadedDocument,
+ isFolderLikeLayer,
+} from '../types/editor';
+import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';
+import { renderVectorLayer } from './vectorEngine';
+import { renderBalloonLayerData, renderTextLayerData } from './vectorLayerRenderer';
+import {
+ MAX_DOCUMENT_DIM,
+ ParsedInkProject,
+ SaveProgress,
+ isInkProjectBytes,
+ sanitizeJsonLayer,
+} from './saveManager/types';
+import { extractZipPreview, parseInkZipBytes } from './saveManager/inkParse';
+
+/**
+ * Read-only migrator for legacy `.sora` project files (v1 JSON and v2 binary/wrapped containers).
+ * Never writes `.sora`; callers save migrated documents in the primary `.ink` format.
+ */
+export const LEGACY_SORA_EXTENSION = '.sora';
+
+export interface LegacySoraV1Project {
+ format: 'sora-v1';
+ app: string;
+ version: string;
+ name: string;
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: LayerItem[];
+ canvases: Record<string, string>;
+ masks: Record<string, string>;
+}
+
+export type MigratedSoraProject =
+ | (ParsedInkProject & { migratedFrom: 'sora-v2' })
+ | (LegacySoraV1Project & { migratedFrom: 'sora-v1' });
+
+export function isLegacySoraExtension(filenameOrPath: string): boolean {
+ const dot = filenameOrPath.lastIndexOf('.');
+ return dot > 0 && filenameOrPath.slice(dot).toLowerCase() === LEGACY_SORA_EXTENSION;
+}
+
+/**
+ * Detects the legacy 8-byte `SORA\x00\x02` binary wrapper prefix.
+ */
+export function hasLegacySoraHeader(input: Uint8Array | ArrayBuffer): boolean {
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
+ return (
+ bytes.byteLength >= 8 &&
+ bytes[0] === 0x53 &&
+ bytes[1] === 0x4f &&
+ bytes[2] === 0x52 &&
+ bytes[3] === 0x41 &&
+ bytes[4] === 0x00 &&
+ bytes[5] === 0x02
+ );
+}
+
+/**
+ * Strips the optional 8-byte `SORA\x00\x02` header prefix from legacy v2 containers.
+ */
+export function unwrapLegacySoraBytes(bytes: Uint8Array): Uint8Array {
+ return hasLegacySoraHeader(bytes) ? bytes.subarray(8) : bytes;
+}
+
+/**
+ * Checks whether binary input is a legacy `.sora` v2 archive (raw ZIP or `SORA\x00\x02`-prefixed ZIP).
+ */
+export function isLegacySoraV2Bytes(input: Uint8Array | ArrayBuffer): boolean {
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
+ if (hasLegacySoraHeader(bytes)) return true;
+ return isInkProjectBytes(bytes);
+}
+
+/**
+ * Extracts `preview.png` from a legacy `.sora` v2 file without decompressing tile payloads.
+ */
+export function extractLegacySoraPreview(input: ArrayBuffer | Uint8Array): Uint8Array | null {
+ const raw = input instanceof Uint8Array ? input : new Uint8Array(input);
+ if (!isLegacySoraV2Bytes(raw)) return null;
+ return extractZipPreview(unwrapLegacySoraBytes(raw));
+}
+
+/**
+ * Pure read-only parser for legacy `.sora` v1.x JSON payloads.
+ */
+export function parseLegacySoraV1Json(jsonText: string): LegacySoraV1Project {
+ const cleanText = jsonText.charCodeAt(0) === 0xfeff ? jsonText.slice(1) : jsonText;
+ const parsed = JSON.parse(cleanText);
+ if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.layers)) {
+ throw new Error('Invalid legacy .sora project payload: missing layers array');
+ }
+ const layers = parsed.layers.map((l: any) => sanitizeJsonLayer(l));
+ return {
+ format: 'sora-v1',
+ app: typeof parsed.app === 'string' ? parsed.app : 'Ink Studio',
+ version: typeof parsed.version === 'string' ? parsed.version : '1.0',
+ name: typeof parsed.name === 'string' ? parsed.name : 'Untitled',
+ dimensions: {
+ width: Math.max(1, Math.min(MAX_DOCUMENT_DIM, Number(parsed.dimensions?.width) || 1440)),
+ height: Math.max(1, Math.min(MAX_DOCUMENT_DIM, Number(parsed.dimensions?.height) || 900)),
+ dpi: Number(parsed.dimensions?.dpi) || 300,
+ },
+ colorMode: parsed.colorMode || 'color',
+ layers,
+ canvases: parsed.canvases && typeof parsed.canvases === 'object' ? parsed.canvases : {},
+ masks: parsed.masks && typeof parsed.masks === 'object' ? parsed.masks : {},
+ };
+}
+
+/**
+ * Read-only migration parser for legacy `.sora` payloads (both v2 binary and v1 JSON).
+ */
+export async function migrateLegacySoraBytes(
+ input: ArrayBuffer | Uint8Array | string,
+ options?: { onProgress?: (progress: SaveProgress) => void }
+): Promise<MigratedSoraProject> {
+ if (typeof input === 'string') {
+ const v1 = parseLegacySoraV1Json(input);
+ return { ...v1, migratedFrom: 'sora-v1' };
+ }
+
+ const rawBytes = input instanceof Uint8Array ? input : new Uint8Array(input);
+ if (isLegacySoraV2Bytes(rawBytes)) {
+ const zipBytes = unwrapLegacySoraBytes(rawBytes);
+ const parsed = await parseInkZipBytes(zipBytes, {
+ onProgress: options?.onProgress,
+ containerLabel: 'legacy .sora',
+ });
+ return { ...parsed, migratedFrom: 'sora-v2' };
+ }
+
+ const text = new TextDecoder('utf-8').decode(rawBytes);
+ const v1 = parseLegacySoraV1Json(text);
+ return { ...v1, migratedFrom: 'sora-v1' };
+}
+
+function hydrateMissingVectorLayers(
+ grid: SparseTileGrid,
+ layers: LayerItem[],
+ width: number,
+ height: number
+): void {
+ if (typeof document === 'undefined') return;
+ for (const layer of layers) {
+ if (grid.hasLayerTiles(layer.id)) continue;
+ if (layer.type === 'text' && layer.textData) {
+ const temp = document.createElement('canvas');
+ temp.width = width;
+ temp.height = height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderTextLayerData(ctx, layer.textData);
+ grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
+ releaseTemporaryCanvas(temp);
+ } else if (layer.type === 'balloon' && layer.balloonData) {
+ const temp = document.createElement('canvas');
+ temp.width = width;
+ temp.height = height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
+ grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
+ releaseTemporaryCanvas(temp);
+ } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
+ const temp = document.createElement('canvas');
+ temp.width = width;
+ temp.height = height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
+ grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
+ releaseTemporaryCanvas(temp);
+ }
+ }
+}
+
+/**
+ * Loads a legacy `.sora` file in read-only mode and converts it into an in-memory `LoadedDocument`.
+ */
+export async function migrateLegacySoraFile(file: File): Promise<LoadedDocument> {
+ const buffer = await file.arrayBuffer();
+ const migrated = await migrateLegacySoraBytes(buffer);
+ const width = migrated.dimensions.width;
+ const height = migrated.dimensions.height;
+ const dpi = migrated.dimensions.dpi || 300;
+ const colorMode: CanvasColorMode = migrated.colorMode || 'color';
+ const layers = migrated.layers;
+ const fallbackName = file.name.replace(/\.[^/.]+$/, '');
+
+ if (migrated.migratedFrom === 'sora-v2') {
+ hydrateMissingVectorLayers(migrated.tileGrid, layers, width, height);
+ return {
+ name: migrated.name || fallbackName,
+ dimensions: { width, height, dpi },
+ colorMode,
+ layers,
+ tileGrid: migrated.tileGrid,
+ perspectiveRuler: migrated.perspectiveRuler ?? null,
+ animationTimeline: migrated.animationTimeline ?? null,
+ timelapse: migrated.timelapse ?? null,
+ previewDataUrl: migrated.previewDataUrl,
+ };
+ }
+
+ // Legacy v1 JSON: ingest base64 canvas/mask PNGs into SparseTileGrid
+ const grid = new SparseTileGrid();
+ if (typeof document !== 'undefined') {
+ const loadPromises = layers.map((layer) => {
+ const tasks: Promise<void>[] = [];
+
+ const maskDataUrl = migrated.masks[layer.id];
+ if (maskDataUrl) {
+ tasks.push(
+ new Promise<void>((resolve) => {
+ const mCanvas = document.createElement('canvas');
+ mCanvas.width = width;
+ mCanvas.height = height;
+ const mImg = new Image();
+ mImg.onload = () => {
+ mCanvas.getContext('2d')?.drawImage(mImg, 0, 0);
+ layer.maskCanvas = mCanvas;
+ layer.maskVersion = (layer.maskVersion || 0) + 1;
+ resolve();
+ };
+ mImg.onerror = () => resolve();
+ mImg.src = maskDataUrl;
+ })
+ );
+ }
+
+ if (!isFolderLikeLayer(layer) && layer.type !== 'adjustment') {
+ tasks.push(
+ new Promise<void>((resolve) => {
+ const fmt =
+ layer.expressionColor === 'monochrome'
+ ? 'monochrome-1bit'
+ : layer.expressionColor === 'gray'
+ ? 'grayscale-8bit'
+ : 'color-32bit';
+
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+
+ const finishIngest = () => {
+ grid.ingestCanvas(layer.id, canvas, fmt);
+ releaseTemporaryCanvas(canvas);
+ resolve();
+ };
+
+ if (layer.type === 'text' && layer.textData) {
+ const ctx = canvas.getContext('2d');
+ if (ctx) renderTextLayerData(ctx, layer.textData);
+ finishIngest();
+ return;
+ }
+ if (layer.type === 'balloon' && layer.balloonData) {
+ const ctx = canvas.getContext('2d');
+ if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
+ finishIngest();
+ return;
+ }
+
+ const dataUrl = migrated.canvases[layer.id];
+ if (dataUrl) {
+ const img = new Image();
+ img.onload = () => {
+ canvas.getContext('2d')?.drawImage(img, 0, 0);
+ finishIngest();
+ };
+ img.onerror = () => {
+ releaseTemporaryCanvas(canvas);
+ resolve();
+ };
+ img.src = dataUrl;
+ } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
+ const ctx = canvas.getContext('2d');
+ if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
+ finishIngest();
+ } else {
+ releaseTemporaryCanvas(canvas);
+ resolve();
+ }
+ })
+ );
+ }
+
+ return Promise.all(tasks).then(() => {});
+ });
+
+ await Promise.all(loadPromises);
+ }
+
+ return {
+ name: migrated.name || fallbackName,
+ dimensions: { width, height, dpi },
+ colorMode,
+ layers,
+ tileGrid: grid,
+ };
+}
diff --git a/src/utils/liquifyEngine.ts b/src/utils/liquifyEngine.ts
index 7ab1f93..c43eaf6 100644
--- a/src/utils/liquifyEngine.ts
+++ b/src/utils/liquifyEngine.ts
@@ -1,4 +1,16 @@
-import { CanvasSelection, LayerItem, isFolderLikeLayer } from '../types/editor';
+import { CanvasDimensions, CanvasSelection, LayerItem, isFolderLikeLayer } from '../types/editor';
+import { isNativeRustAvailable, liquifyStepNative } from './nativeBackend';
+import {
+ BYTES_32BIT,
+ SparseTileGrid,
+ TILE_SIZE,
+ TileFormat,
+ TileSnapshotEntry,
+ getTileKey,
+ pixelToTileCoord,
+ unpack1BitToRGBA,
+ unpack8BitToRGBA,
+} from './tileEngine';
export type LiquifyMode =
| 'push'
@@ -653,3 +665,390 @@ export function resolveLiquifyTargetLayers(
return layers.filter(isEditableRaster);
}
+
+export interface TileGridLiquifyStepParams {
+ grid: SparseTileGrid;
+ layerId: string;
+ dimensions: CanvasDimensions;
+ targetFormat: TileFormat;
+ cx: number;
+ cy: number;
+ prevX: number;
+ prevY: number;
+ settings: LiquifySettings;
+ pressure?: number;
+ beforeTileSnapshot: Map<string, TileSnapshotEntry>;
+ selectionMask?: Uint8Array | null;
+}
+
+/**
+ * Tile-native liquify step: reads ONLY the brush ROI from SparseTileGrid,
+ * lazily snapshots touched tiles before first mutation, performs bilinear displacement
+ * (or reconstructs from beforeTileSnapshot), and writes ONLY the ROI back to tiles.
+ * Zero full-document HTMLCanvasElement allocation.
+ */
+export function applyLiquifyStepOnTileGrid(params: TileGridLiquifyStepParams): DirtyRect | null {
+ const {
+ grid,
+ layerId,
+ dimensions,
+ targetFormat,
+ cx,
+ cy,
+ prevX,
+ prevY,
+ settings,
+ pressure = 1.0,
+ beforeTileSnapshot,
+ selectionMask,
+ } = params;
+
+ const width = dimensions.width;
+ const height = dimensions.height;
+ if (width <= 0 || height <= 0) return null;
+
+ const radius = Math.max(2, Math.round(settings.size / 2));
+ const radiusSq = radius * radius;
+ const pad = Math.min(32, Math.max(4, Math.ceil(radius * 0.2)));
+ const minX = Math.max(0, Math.floor(cx - radius - pad));
+ const minY = Math.max(0, Math.floor(cy - radius - pad));
+ const maxX = Math.min(width, Math.ceil(cx + radius + pad));
+ const maxY = Math.min(height, Math.ceil(cy + radius + pad));
+
+ const roiW = maxX - minX;
+ const roiH = maxY - minY;
+ if (roiW <= 0 || roiH <= 0) return null;
+
+ const vx = cx - prevX;
+ const vy = cy - prevY;
+ const vLen = Math.hypot(vx, vy);
+ let ux = 0;
+ let uy = 0;
+ if (vLen > 0.0001) {
+ ux = vx / vLen;
+ uy = vy / vLen;
+ }
+
+ const mode = settings.mode;
+ const isPushMode = mode === 'push' || mode === 'push-left' || mode === 'push-right';
+ if (isPushMode && vLen < 0.0001) return null;
+
+ const minTx = pixelToTileCoord(minX, 0);
+ const minTy = pixelToTileCoord(minY, 0);
+ const maxTx = pixelToTileCoord(maxX - 1, 0);
+ const maxTy = pixelToTileCoord(maxY - 1, 0);
+
+ // Skip completely empty ROI (unless reconstructing from a non-empty snapshot)
+ let hasAnyPixel = false;
+ for (let ty = minTy; ty <= maxTy && !hasAnyPixel; ty++) {
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ if (grid.hasTile(layerId, tx, ty, 0)) {
+ hasAnyPixel = true;
+ break;
+ }
+ if (mode === 'reconstruct') {
+ const snap = beforeTileSnapshot.get(getTileKey(layerId, tx, ty, 0));
+ if (snap && snap.data) {
+ hasAnyPixel = true;
+ break;
+ }
+ }
+ }
+ }
+ if (!hasAnyPixel) return null;
+
+ // Snapshot untouched tiles overlapping this ROI lazily before mutating
+ for (let ty = minTy; ty <= maxTy; ty++) {
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ grid.snapshotSingleTileInto(layerId, tx, ty, beforeTileSnapshot);
+ }
+ }
+
+ const srcBuf = grid.readImageData(layerId, minX, minY, roiW, roiH);
+ const src = srcBuf.data;
+ const dst = new Uint8ClampedArray(src);
+
+ const hardnessFactor = Math.max(0, Math.min(1, settings.hardness / 100));
+ const effectivePressure = settings.usePressure ? Math.max(0.1, pressure) : 1.0;
+ const strengthFactor = (settings.strength / 100) * effectivePressure;
+ const twirlBaseAngle = (mode === 'twirl-cw' ? 1 : -1) * (strengthFactor * 0.45);
+
+ // Lazy unpacked cache of initial pre-stroke tiles when in reconstruct mode
+ let initRoiData: Uint8ClampedArray | null = null;
+ if (mode === 'reconstruct') {
+ initRoiData = new Uint8ClampedArray(roiW * roiH * 4);
+ const scratch = new Uint8ClampedArray(BYTES_32BIT);
+ for (let ty = minTy; ty <= maxTy; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ const snap = beforeTileSnapshot.get(getTileKey(layerId, tx, ty, 0));
+ if (!snap || !snap.data) continue;
+ let tileRgba: Uint8ClampedArray;
+ if (snap.format === 'color-32bit') {
+ tileRgba = new Uint8ClampedArray(snap.data.buffer, snap.data.byteOffset, BYTES_32BIT);
+ } else if (snap.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(snap.data, scratch);
+ tileRgba = scratch;
+ } else {
+ unpack8BitToRGBA(snap.data, scratch);
+ tileRgba = scratch;
+ }
+ const tileDocX = tx * TILE_SIZE;
+ const interX0 = Math.max(minX, tileDocX);
+ const interY0 = Math.max(minY, tileDocY);
+ const interX1 = Math.min(maxX, tileDocX + TILE_SIZE);
+ const interY1 = Math.min(maxY, tileDocY + TILE_SIZE);
+ const copyW = interX1 - interX0;
+ if (copyW <= 0 || interY1 <= interY0) continue;
+ for (let py = interY0; py < interY1; py++) {
+ const sOff = ((py - tileDocY) * TILE_SIZE + (interX0 - tileDocX)) << 2;
+ const dOff = ((py - minY) * roiW + (interX0 - minX)) << 2;
+ initRoiData.set(tileRgba.subarray(sOff, sOff + (copyW << 2)), dOff);
+ }
+ }
+ }
+ }
+
+ for (let ry = 0; ry < roiH; ry++) {
+ const py = minY + ry;
+ const dy = py - cy;
+ const rowOffset = ry * roiW * 4;
+
+ for (let rx = 0; rx < roiW; rx++) {
+ const px = minX + rx;
+ const dx = px - cx;
+ const distSq = dx * dx + dy * dy;
+ if (distSq >= radiusSq) continue;
+ if (selectionMask && selectionMask[py * width + px] === 0) continue;
+
+ const dist = Math.sqrt(distSq);
+ const weight = computeFalloffWeight(dist, radius, hardnessFactor);
+ if (weight <= 0) continue;
+
+ const dstIdx = rowOffset + rx * 4;
+
+ if (mode === 'reconstruct') {
+ if (!initRoiData) continue;
+ const alpha = Math.min(1, strengthFactor * weight * 0.35);
+ dst[dstIdx] = Math.round(dst[dstIdx] * (1 - alpha) + initRoiData[dstIdx] * alpha);
+ dst[dstIdx + 1] = Math.round(dst[dstIdx + 1] * (1 - alpha) + initRoiData[dstIdx + 1] * alpha);
+ dst[dstIdx + 2] = Math.round(dst[dstIdx + 2] * (1 - alpha) + initRoiData[dstIdx + 2] * alpha);
+ dst[dstIdx + 3] = Math.round(dst[dstIdx + 3] * (1 - alpha) + initRoiData[dstIdx + 3] * alpha);
+ continue;
+ }
+
+ let srcCanvasX = px;
+ let srcCanvasY = py;
+ if (mode === 'push') {
+ const pushAmount = vLen * strengthFactor * weight;
+ srcCanvasX = px - ux * pushAmount;
+ srcCanvasY = py - uy * pushAmount;
+ } else if (mode === 'push-left') {
+ const pushAmount = Math.max(1.5, vLen) * strengthFactor * weight;
+ srcCanvasX = px + uy * pushAmount;
+ srcCanvasY = py - ux * pushAmount;
+ } else if (mode === 'push-right') {
+ const pushAmount = Math.max(1.5, vLen) * strengthFactor * weight;
+ srcCanvasX = px - uy * pushAmount;
+ srcCanvasY = py + ux * pushAmount;
+ } else if (mode === 'expand') {
+ const factor = strengthFactor * weight * 0.3;
+ srcCanvasX = cx + dx * (1 - factor);
+ srcCanvasY = cy + dy * (1 - factor);
+ } else if (mode === 'pinch') {
+ const factor = strengthFactor * weight * 0.3;
+ srcCanvasX = cx + dx * (1 + factor);
+ srcCanvasY = cy + dy * (1 + factor);
+ } else if (mode === 'twirl-cw' || mode === 'twirl-ccw') {
+ const theta = twirlBaseAngle * weight;
+ const cosT = Math.cos(theta);
+ const sinT = Math.sin(theta);
+ srcCanvasX = cx + dx * cosT + dy * sinT;
+ srcCanvasY = cy - dx * sinT + dy * cosT;
+ }
+
+ const localSx = Math.max(0, Math.min(roiW - 1.0001, srcCanvasX - minX));
+ const localSy = Math.max(0, Math.min(roiH - 1.0001, srcCanvasY - minY));
+ const x0 = Math.floor(localSx);
+ const y0 = Math.floor(localSy);
+ const x1 = Math.min(roiW - 1, x0 + 1);
+ const y1 = Math.min(roiH - 1, y0 + 1);
+ const fx = localSx - x0;
+ const fy = localSy - y0;
+
+ const w00 = (1 - fx) * (1 - fy);
+ const w10 = fx * (1 - fy);
+ const w01 = (1 - fx) * fy;
+ const w11 = fx * fy;
+
+ const i00 = (y0 * roiW + x0) * 4;
+ const i10 = (y0 * roiW + x1) * 4;
+ const i01 = (y1 * roiW + x0) * 4;
+ const i11 = (y1 * roiW + x1) * 4;
+
+ dst[dstIdx] = Math.round(w00 * src[i00] + w10 * src[i10] + w01 * src[i01] + w11 * src[i11]);
+ dst[dstIdx + 1] = Math.round(w00 * src[i00 + 1] + w10 * src[i10 + 1] + w01 * src[i01 + 1] + w11 * src[i11 + 1]);
+ dst[dstIdx + 2] = Math.round(w00 * src[i00 + 2] + w10 * src[i10 + 2] + w01 * src[i01 + 2] + w11 * src[i11 + 2]);
+ dst[dstIdx + 3] = Math.round(w00 * src[i00 + 3] + w10 * src[i10 + 3] + w01 * src[i01 + 3] + w11 * src[i11 + 3]);
+ }
+ }
+
+ grid.writeImageData(layerId, { data: dst, width: roiW, height: roiH }, minX, minY, targetFormat, true);
+ return { x: minX, y: minY, width: roiW, height: roiH };
+}
+
+/**
+ * Async tile-native liquify step: offloads ROI bilinear displacement to the
+ * Rayon-parallel Rust backend when running in Tauri, falling back to sync JS on Web/Vitest.
+ */
+export async function applyLiquifyStepOnTileGridAsync(
+ params: TileGridLiquifyStepParams
+): Promise<DirtyRect | null> {
+ if (!isNativeRustAvailable()) {
+ return applyLiquifyStepOnTileGrid(params);
+ }
+
+ const {
+ grid,
+ layerId,
+ dimensions,
+ targetFormat,
+ cx,
+ cy,
+ prevX,
+ prevY,
+ settings,
+ pressure = 1.0,
+ beforeTileSnapshot,
+ selectionMask,
+ } = params;
+
+ const width = dimensions.width;
+ const height = dimensions.height;
+ if (width <= 0 || height <= 0) return null;
+
+ const radius = Math.max(2, Math.round(settings.size / 2));
+ const pad = Math.min(32, Math.max(4, Math.ceil(radius * 0.2)));
+ const minX = Math.max(0, Math.floor(cx - radius - pad));
+ const minY = Math.max(0, Math.floor(cy - radius - pad));
+ const maxX = Math.min(width, Math.ceil(cx + radius + pad));
+ const maxY = Math.min(height, Math.ceil(cy + radius + pad));
+
+ const roiW = maxX - minX;
+ const roiH = maxY - minY;
+ if (roiW <= 0 || roiH <= 0) return null;
+
+ const vx = cx - prevX;
+ const vy = cy - prevY;
+ const vLen = Math.hypot(vx, vy);
+ let ux = 0;
+ let uy = 0;
+ if (vLen > 0.0001) {
+ ux = vx / vLen;
+ uy = vy / vLen;
+ }
+
+ const mode = settings.mode;
+ const isPushMode = mode === 'push' || mode === 'push-left' || mode === 'push-right';
+ if (isPushMode && vLen < 0.0001) return null;
+
+ const minTx = pixelToTileCoord(minX, 0);
+ const minTy = pixelToTileCoord(minY, 0);
+ const maxTx = pixelToTileCoord(maxX - 1, 0);
+ const maxTy = pixelToTileCoord(maxY - 1, 0);
+
+ let hasAnyPixel = false;
+ for (let ty = minTy; ty <= maxTy && !hasAnyPixel; ty++) {
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ if (grid.hasTile(layerId, tx, ty, 0)) {
+ hasAnyPixel = true;
+ break;
+ }
+ if (mode === 'reconstruct') {
+ const snap = beforeTileSnapshot.get(getTileKey(layerId, tx, ty, 0));
+ if (snap && snap.data) {
+ hasAnyPixel = true;
+ break;
+ }
+ }
+ }
+ }
+ if (!hasAnyPixel) return null;
+
+ for (let ty = minTy; ty <= maxTy; ty++) {
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ grid.snapshotSingleTileInto(layerId, tx, ty, beforeTileSnapshot);
+ }
+ }
+
+ const srcBuf = grid.readImageData(layerId, minX, minY, roiW, roiH);
+ const hardnessFactor = Math.max(0, Math.min(1, settings.hardness / 100));
+ const effectivePressure = settings.usePressure ? Math.max(0.1, pressure) : 1.0;
+ const strengthFactor = (settings.strength / 100) * effectivePressure;
+
+ let initRoiData: Uint8ClampedArray | null = null;
+ if (mode === 'reconstruct') {
+ initRoiData = new Uint8ClampedArray(roiW * roiH * 4);
+ const scratch = new Uint8ClampedArray(BYTES_32BIT);
+ for (let ty = minTy; ty <= maxTy; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ const snap = beforeTileSnapshot.get(getTileKey(layerId, tx, ty, 0));
+ if (!snap || !snap.data) continue;
+ let tileRgba: Uint8ClampedArray;
+ if (snap.format === 'color-32bit') {
+ tileRgba = new Uint8ClampedArray(snap.data.buffer, snap.data.byteOffset, BYTES_32BIT);
+ } else if (snap.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(snap.data, scratch);
+ tileRgba = scratch;
+ } else {
+ unpack8BitToRGBA(snap.data, scratch);
+ tileRgba = scratch;
+ }
+ const tileDocX = tx * TILE_SIZE;
+ const interX0 = Math.max(minX, tileDocX);
+ const interY0 = Math.max(minY, tileDocY);
+ const interX1 = Math.min(maxX, tileDocX + TILE_SIZE);
+ const interY1 = Math.min(maxY, tileDocY + TILE_SIZE);
+ const copyW = interX1 - interX0;
+ if (copyW <= 0 || interY1 <= interY0) continue;
+ for (let py = interY0; py < interY1; py++) {
+ const sOff = ((py - tileDocY) * TILE_SIZE + (interX0 - tileDocX)) << 2;
+ const dOff = ((py - minY) * roiW + (interX0 - minX)) << 2;
+ initRoiData.set(tileRgba.subarray(sOff, sOff + (copyW << 2)), dOff);
+ }
+ }
+ }
+ }
+
+ let selMaskRoi: Uint8Array | null = null;
+ if (selectionMask) {
+ selMaskRoi = new Uint8Array(roiW * roiH);
+ for (let ry = 0; ry < roiH; ry++) {
+ const sOff = (minY + ry) * width + minX;
+ selMaskRoi.set(selectionMask.subarray(sOff, sOff + roiW), ry * roiW);
+ }
+ }
+
+ const dst = await liquifyStepNative({
+ srcRoi: srcBuf.data,
+ initRoi: initRoiData,
+ selMaskRoi,
+ roiW,
+ roiH,
+ minX,
+ minY,
+ cx,
+ cy,
+ ux,
+ uy,
+ vLen,
+ radius,
+ hardness: hardnessFactor,
+ strength: strengthFactor,
+ mode,
+ });
+
+ grid.writeImageData(layerId, { data: dst, width: roiW, height: roiH }, minX, minY, targetFormat, true);
+ return { x: minX, y: minY, width: roiW, height: roiH };
+}
diff --git a/src/utils/lz4.ts b/src/utils/lz4.ts
new file mode 100644
index 0000000..eb41c39
--- /dev/null
+++ b/src/utils/lz4.ts
@@ -0,0 +1,302 @@
+/**
+ * Zero-dependency standard LZ4 raw block compressor and strictly bounds-checked decompressor.
+ * Used for BINARY_TILE raster synchronization across Tauri desktop and WebSocket browser guests.
+ */
+
+const HASH_LOG = 14;
+const HASH_SIZE = 1 << HASH_LOG;
+const HASH_SHIFT = 32 - HASH_LOG;
+const HASH_MULT = 2654435761; // Knuth multiplicative hash (standard LZ4)
+const MIN_MATCH = 4;
+const MF_LIMIT = 12;
+const LAST_LITERALS = 5;
+const MAX_DISTANCE = 65535;
+const DEFAULT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024; // 4 MB safety ceiling
+
+// Reusable hash table to avoid per-tile GC churn on the hot path
+const sharedHashTable = new Int32Array(HASH_SIZE);
+
+export function lz4CompressBound(inputLength: number): number {
+ return inputLength + ((inputLength / 255) | 0) + 16;
+}
+
+/**
+ * Compresses raw bytes into a standard LZ4 block (without prepended size header).
+ */
+export function lz4CompressBlock(src: Uint8Array): Uint8Array {
+ const srcLen = src.byteLength;
+ if (srcLen === 0) return new Uint8Array(0);
+
+ const dst = new Uint8Array(lz4CompressBound(srcLen));
+ let op = 0;
+
+ if (srcLen < MF_LIMIT + 1) {
+ op = emitLastLiterals(src, 0, srcLen, dst, op);
+ return dst.subarray(0, op);
+ }
+
+ sharedHashTable.fill(-1);
+
+ const mflimit = srcLen - MF_LIMIT;
+ const matchLimit = srcLen - LAST_LITERALS;
+ let anchor = 0;
+ let ip = 0;
+
+ while (ip <= mflimit) {
+ // Search for a 4-byte match using step acceleration on incompressible spans
+ let ref = -1;
+ let forwardIp = ip;
+ let step = 1;
+ let searchMatchNb = 1 << 6;
+
+ while (true) {
+ ip = forwardIp;
+ forwardIp += step;
+ step = searchMatchNb++ >> 6;
+
+ if (forwardIp > mflimit) {
+ op = emitLastLiterals(src, anchor, srcLen - anchor, dst, op);
+ return dst.subarray(0, op);
+ }
+
+ const seq =
+ src[ip] |
+ (src[ip + 1] << 8) |
+ (src[ip + 2] << 16) |
+ (src[ip + 3] << 24);
+ const h = Math.imul(seq, HASH_MULT) >>> HASH_SHIFT;
+ ref = sharedHashTable[h];
+ sharedHashTable[h] = ip;
+
+ if (
+ ref >= 0 &&
+ ip - ref <= MAX_DISTANCE &&
+ src[ref] === src[ip] &&
+ src[ref + 1] === src[ip + 1] &&
+ src[ref + 2] === src[ip + 2] &&
+ src[ref + 3] === src[ip + 3]
+ ) {
+ break;
+ }
+ }
+
+ // Catch up backwards if previous bytes also match
+ while (ip > anchor && ref > 0 && src[ip - 1] === src[ref - 1]) {
+ ip--;
+ ref--;
+ }
+
+ // Emit token + literal length + literals
+ const litLen = ip - anchor;
+ let tokenPos = op++;
+ if (litLen >= 15) {
+ dst[tokenPos] = 0xf0;
+ let rem = litLen - 15;
+ while (rem >= 255) {
+ dst[op++] = 255;
+ rem -= 255;
+ }
+ dst[op++] = rem;
+ } else {
+ dst[tokenPos] = litLen << 4;
+ }
+
+ if (litLen > 0) {
+ dst.set(src.subarray(anchor, ip), op);
+ op += litLen;
+ }
+
+ // Emit match sequence(s)
+ while (true) {
+ const offset = ip - ref;
+ dst[op++] = offset & 0xff;
+ dst[op++] = (offset >>> 8) & 0xff;
+
+ ip += MIN_MATCH;
+ ref += MIN_MATCH;
+ const matchStart = ip;
+ while (ip < matchLimit && src[ip] === src[ref]) {
+ ip++;
+ ref++;
+ }
+
+ const matchCode = ip - matchStart;
+ if (matchCode >= 15) {
+ dst[tokenPos] |= 0x0f;
+ let rem = matchCode - 15;
+ while (rem >= 255) {
+ dst[op++] = 255;
+ rem -= 255;
+ }
+ dst[op++] = rem;
+ } else {
+ dst[tokenPos] |= matchCode;
+ }
+
+ anchor = ip;
+
+ if (ip > mflimit) {
+ op = emitLastLiterals(src, anchor, srcLen - anchor, dst, op);
+ return dst.subarray(0, op);
+ }
+
+ // Update hash at ip - 2
+ const prevIdx = ip - 2;
+ const prevSeq =
+ src[prevIdx] |
+ (src[prevIdx + 1] << 8) |
+ (src[prevIdx + 2] << 16) |
+ (src[prevIdx + 3] << 24);
+ sharedHashTable[Math.imul(prevSeq, HASH_MULT) >>> HASH_SHIFT] = prevIdx;
+
+ // Test immediate next position for chained match
+ const nextSeq =
+ src[ip] |
+ (src[ip + 1] << 8) |
+ (src[ip + 2] << 16) |
+ (src[ip + 3] << 24);
+ const nextH = Math.imul(nextSeq, HASH_MULT) >>> HASH_SHIFT;
+ ref = sharedHashTable[nextH];
+ sharedHashTable[nextH] = ip;
+
+ if (
+ ref >= 0 &&
+ ip - ref <= MAX_DISTANCE &&
+ src[ref] === src[ip] &&
+ src[ref + 1] === src[ip + 1] &&
+ src[ref + 2] === src[ip + 2] &&
+ src[ref + 3] === src[ip + 3]
+ ) {
+ tokenPos = op++;
+ dst[tokenPos] = 0;
+ continue;
+ }
+
+ ip++;
+ break;
+ }
+ }
+
+ op = emitLastLiterals(src, anchor, srcLen - anchor, dst, op);
+ return dst.subarray(0, op);
+}
+
+function emitLastLiterals(
+ src: Uint8Array,
+ anchor: number,
+ litLen: number,
+ dst: Uint8Array,
+ op: number
+): number {
+ if (litLen >= 15) {
+ dst[op++] = 0xf0;
+ let rem = litLen - 15;
+ while (rem >= 255) {
+ dst[op++] = 255;
+ rem -= 255;
+ }
+ dst[op++] = rem;
+ } else {
+ dst[op++] = litLen << 4;
+ }
+ if (litLen > 0) {
+ dst.set(src.subarray(anchor, anchor + litLen), op);
+ op += litLen;
+ }
+ return op;
+}
+
+/**
+ * Strictly bounds-checked LZ4 raw block decompressor.
+ * Returns null on any corrupt, truncated, or out-of-bounds input (guards against LZ4 bombs).
+ */
+export function lz4DecompressBlock(
+ src: Uint8Array,
+ uncompressedLength: number,
+ maxOutputBytes: number = DEFAULT_MAX_OUTPUT_BYTES
+): Uint8Array | null {
+ if (
+ !Number.isInteger(uncompressedLength) ||
+ uncompressedLength < 0 ||
+ uncompressedLength > maxOutputBytes
+ ) {
+ return null;
+ }
+ if (uncompressedLength === 0) {
+ return src.byteLength === 0 ? new Uint8Array(0) : null;
+ }
+
+ const srcLen = src.byteLength;
+ if (srcLen === 0) return null;
+
+ const dst = new Uint8Array(uncompressedLength);
+ let ip = 0;
+ let op = 0;
+
+ while (ip < srcLen) {
+ const token = src[ip++];
+
+ // 1. Literal length
+ let litLen = token >>> 4;
+ if (litLen === 15) {
+ let s: number;
+ do {
+ if (ip >= srcLen) return null;
+ s = src[ip++];
+ litLen += s;
+ if (op + litLen > uncompressedLength) return null;
+ } while (s === 255);
+ }
+
+ if (ip + litLen > srcLen || op + litLen > uncompressedLength) {
+ return null;
+ }
+ if (litLen > 0) {
+ dst.set(src.subarray(ip, ip + litLen), op);
+ ip += litLen;
+ op += litLen;
+ }
+
+ // End of block: last sequence has no offset/match
+ if (ip === srcLen) {
+ break;
+ }
+
+ // 2. Match offset (uint16 LE)
+ if (ip + 2 > srcLen) return null;
+ const offset = src[ip] | (src[ip + 1] << 8);
+ ip += 2;
+ if (offset === 0 || offset > op) {
+ return null;
+ }
+
+ // 3. Match length
+ let matchLen = (token & 0x0f) + MIN_MATCH;
+ if ((token & 0x0f) === 15) {
+ let s: number;
+ do {
+ if (ip >= srcLen) return null;
+ s = src[ip++];
+ matchLen += s;
+ if (op + matchLen > uncompressedLength) return null;
+ } while (s === 255);
+ }
+
+ if (op + matchLen > uncompressedLength) {
+ return null;
+ }
+
+ // Copy match (supports overlapping copies such as offset=1 or offset=4 RGBA solid runs)
+ let ref = op - offset;
+ if (offset >= matchLen) {
+ dst.set(dst.subarray(ref, ref + matchLen), op);
+ op += matchLen;
+ } else {
+ for (let i = 0; i < matchLen; i++) {
+ dst[op++] = dst[ref++];
+ }
+ }
+ }
+
+ return op === uncompressedLength ? dst : null;
+}
diff --git a/src/utils/nativeBackend.ts b/src/utils/nativeBackend.ts
new file mode 100644
index 0000000..1ea15c8
--- /dev/null
+++ b/src/utils/nativeBackend.ts
@@ -0,0 +1,703 @@
+/**
+ * Raw-binary Tauri v2 IPC bridge to the Rust backend (src-tauri/src/lib.rs).
+ * Zero JSON pixel encoding: all buffers cross IPC as raw Uint8Array / ArrayBuffer frames.
+ */
+
+import { BlendMode, CanvasColorMode, DirtyRect, FilterType, LayerItem, LoadedDocument } from '../types/editor';
+import { createCanvasThumbnail } from './canvasUtils';
+import { lz4DecompressBlock } from './lz4';
+import { BYTES_32BIT, SparseTileGrid } from './tileEngine';
+import { isTauriEnvironment } from './tileEngine/scratchDriver';
+import type { LiquifyMode } from './liquifyEngine';
+
+type TauriInvoke = typeof import('@tauri-apps/api/core').invoke;
+
+let cachedInvokePromise: Promise<TauriInvoke> | null = null;
+
+export function isNativeRustAvailable(): boolean {
+ return isTauriEnvironment();
+}
+
+function getInvoke(): Promise<TauriInvoke> {
+ if (!cachedInvokePromise) {
+ cachedInvokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);
+ }
+ return cachedInvokePromise;
+}
+
+function toUint8Array(raw: ArrayBuffer | Uint8Array | number[]): Uint8Array {
+ if (raw instanceof Uint8Array) return raw;
+ if (raw instanceof ArrayBuffer) return new Uint8Array(raw);
+ return new Uint8Array(raw);
+}
+
+// ---------------------------------------------------------------------------
+// Shared INKD binary document hydrator (.clip and .psd/.psb)
+// ---------------------------------------------------------------------------
+
+interface WirePreviewRef {
+ offset: number;
+ len: number;
+ mime: string;
+}
+
+interface WireTileRef {
+ tx: number;
+ ty: number;
+ codec: number;
+ offset: number;
+ len: number;
+}
+
+interface WireMaskRef {
+ enabled: boolean;
+ linked: boolean;
+ defaultColor: number;
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ codec: number;
+ offset: number;
+ len: number;
+}
+
+interface WireLayerMeta {
+ id: string;
+ name: string;
+ type: 'raster' | 'folder';
+ visible: boolean;
+ opacity: number;
+ blendMode: BlendMode;
+ locked: boolean;
+ alphaLocked: boolean;
+ clipped: boolean;
+ collapsed: boolean;
+ parentId: string | null;
+ solidFillHex: string | null;
+ tiles: WireTileRef[];
+ mask: WireMaskRef | null;
+}
+
+interface WireDocumentMeta {
+ width: number;
+ height: number;
+ dpi: number;
+ colorMode: CanvasColorMode;
+ preview: WirePreviewRef | null;
+ layers: WireLayerMeta[];
+}
+
+const utf8Decoder = new TextDecoder('utf-8');
+
+function bytesToDataUrl(bytes: Uint8Array, mime: string): string | undefined {
+ if (typeof btoa !== 'function' || bytes.byteLength === 0) return undefined;
+ let bin = '';
+ const step = 0x8000;
+ for (let i = 0; i < bytes.byteLength; i += step) {
+ bin += String.fromCharCode(...bytes.subarray(i, Math.min(bytes.byteLength, i + step)));
+ }
+ return `data:${mime};base64,${btoa(bin)}`;
+}
+
+function decodeMaskCanvas(
+ maskRef: WireMaskRef,
+ blobSection: Uint8Array
+): Pick<LayerItem, 'maskCanvas' | 'maskEnabled' | 'maskLinked' | 'maskVersion' | 'maskThumbnailUrl'> {
+ const base = {
+ maskEnabled: maskRef.enabled,
+ maskLinked: maskRef.linked,
+ maskVersion: 1,
+ };
+ if (typeof document === 'undefined') return base;
+
+ const expectedLen = maskRef.width * maskRef.height;
+ const payload = blobSection.subarray(maskRef.offset, maskRef.offset + maskRef.len);
+ const gray =
+ maskRef.codec === 2
+ ? lz4DecompressBlock(payload, expectedLen, expectedLen)
+ : payload.byteLength === expectedLen
+ ? payload
+ : null;
+ if (!gray) return base;
+
+ const canvas = document.createElement('canvas');
+ canvas.width = maskRef.width;
+ canvas.height = maskRef.height;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return base;
+
+ const img = ctx.createImageData(maskRef.width, maskRef.height);
+ const out = img.data;
+ for (let i = 0; i < expectedLen; i++) {
+ const v = gray[i];
+ const di = i << 2;
+ out[di] = v;
+ out[di + 1] = v;
+ out[di + 2] = v;
+ out[di + 3] = 255;
+ }
+ ctx.putImageData(img, 0, 0);
+
+ return {
+ ...base,
+ maskCanvas: canvas,
+ maskThumbnailUrl: createCanvasThumbnail(canvas, false),
+ };
+}
+
+/**
+ * Hydrates a Rust `INKD` binary response directly into a SparseTileGrid-backed LoadedDocument.
+ */
+export function hydrateParsedDocumentBinary(
+ wire: Uint8Array,
+ fileName: string,
+ targetGrid?: SparseTileGrid
+): LoadedDocument {
+ if (
+ wire.byteLength < 12 ||
+ wire[0] !== 0x49 ||
+ wire[1] !== 0x4e ||
+ wire[2] !== 0x4b ||
+ wire[3] !== 0x44
+ ) {
+ throw new Error('Invalid INKD binary document response from Rust backend');
+ }
+ const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
+ const metaLen = view.getUint32(8, true);
+ if (12 + metaLen > wire.byteLength) {
+ throw new Error('Truncated INKD metadata header');
+ }
+ const meta: WireDocumentMeta = JSON.parse(
+ utf8Decoder.decode(wire.subarray(12, 12 + metaLen))
+ );
+ const blobSection = wire.subarray(12 + metaLen);
+
+ const width = meta.width || 1440;
+ const height = meta.height || 900;
+ const dpi = meta.dpi || 300;
+ const colorMode: CanvasColorMode = meta.colorMode === 'grayscale' ? 'grayscale' : 'color';
+ const tileGrid = targetGrid ?? new SparseTileGrid();
+ const stamp = Date.now();
+ const idMap = new Map<string, string>();
+ const layers: LayerItem[] = [];
+
+ for (const wl of meta.layers) {
+ const uniqueId = `${wl.id}-${stamp}`;
+ idMap.set(wl.id, uniqueId);
+ }
+
+ for (const wl of meta.layers) {
+ const id = idMap.get(wl.id)!;
+ const parentId = wl.parentId ? (idMap.get(wl.parentId) ?? null) : null;
+ const maskFields = wl.mask ? decodeMaskCanvas(wl.mask, blobSection) : {};
+
+ if (wl.type === 'folder') {
+ layers.push({
+ id,
+ name: wl.name,
+ type: 'folder',
+ visible: wl.visible,
+ opacity: wl.opacity,
+ blendMode: wl.blendMode,
+ locked: wl.locked,
+ alphaLocked: wl.alphaLocked,
+ clipped: wl.clipped,
+ collapsed: wl.collapsed,
+ parentId,
+ ...maskFields,
+ });
+ continue;
+ }
+
+ tileGrid.setLayerFormat(id, 'color-32bit');
+ tileGrid.markLayerIngested(id);
+
+ if (wl.tiles.length > 0) {
+ for (const t of wl.tiles) {
+ const payload = blobSection.subarray(t.offset, t.offset + t.len);
+ let rgba: Uint8Array | null;
+ if (t.codec === 2) {
+ rgba = lz4DecompressBlock(payload, BYTES_32BIT, BYTES_32BIT);
+ } else if (t.codec === 1 && payload.byteLength === BYTES_32BIT) {
+ rgba = payload.slice();
+ } else {
+ rgba = null;
+ }
+ if (rgba) {
+ tileGrid.setTile(id, t.tx, t.ty, {
+ layerId: id,
+ tileX: t.tx,
+ tileY: t.ty,
+ format: 'color-32bit',
+ data: rgba,
+ dirty: true,
+ version: 1,
+ isPagedToDisk: false,
+ lastAccessTimestamp: stamp,
+ lod: 0,
+ });
+ }
+ }
+ } else if (wl.solidFillHex) {
+ tileGrid.fillLayerSolidColor(id, width, height, wl.solidFillHex, 'color-32bit');
+ }
+
+ const thumb = createCanvasThumbnail(
+ { grid: tileGrid, layerId: id, dimensions: { width, height } },
+ true
+ );
+
+ layers.push({
+ id,
+ name: wl.name,
+ type: 'raster',
+ visible: wl.visible,
+ opacity: wl.opacity,
+ blendMode: wl.blendMode,
+ locked: wl.locked,
+ alphaLocked: wl.alphaLocked,
+ clipped: wl.clipped,
+ parentId,
+ thumbnailUrl: thumb,
+ ...maskFields,
+ });
+ }
+
+ if (layers.length === 0) {
+ const id = `layer-${stamp}`;
+ tileGrid.fillLayerSolidWhite(id, width, height, 'color-32bit');
+ const thumb = createCanvasThumbnail(
+ { grid: tileGrid, layerId: id, dimensions: { width, height } },
+ false
+ );
+ layers.push({
+ id,
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ alphaLocked: false,
+ clipped: false,
+ parentId: null,
+ thumbnailUrl: thumb,
+ });
+ }
+
+ const previewDataUrl = meta.preview
+ ? bytesToDataUrl(
+ blobSection.subarray(meta.preview.offset, meta.preview.offset + meta.preview.len),
+ meta.preview.mime
+ )
+ : undefined;
+
+ return {
+ name: fileName.replace(/\.[^/.]+$/, ''),
+ dimensions: { width, height, dpi },
+ colorMode,
+ layers,
+ tileGrid,
+ previewDataUrl,
+ };
+}
+
+export async function parseClipNative(
+ buffer: ArrayBuffer | Uint8Array,
+ fileName: string,
+ targetGrid?: SparseTileGrid
+): Promise<LoadedDocument> {
+ const invoke = await getInvoke();
+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('parse_clip_file', bytes);
+ return hydrateParsedDocumentBinary(toUint8Array(raw), fileName, targetGrid);
+}
+
+export async function parsePsdNative(
+ buffer: ArrayBuffer | Uint8Array,
+ fileName: string,
+ targetGrid?: SparseTileGrid
+): Promise<LoadedDocument> {
+ const invoke = await getInvoke();
+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('parse_psd_file', bytes);
+ return hydrateParsedDocumentBinary(toUint8Array(raw), fileName, targetGrid);
+}
+
+export interface NativeSutExtract {
+ nodeName: string | null;
+ variantId: number | null;
+ variantValues: Map<string, unknown>;
+ materials: Array<{
+ pwId: string;
+ originalPath: string;
+ catalogPath: string;
+ fileData: Uint8Array;
+ }>;
+}
+
+export async function parseSutSqliteNative(bytes: Uint8Array): Promise<NativeSutExtract> {
+ const invoke = await getInvoke();
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('parse_sut_sqlite', bytes);
+ const wire = toUint8Array(raw);
+ if (
+ wire.byteLength < 8 ||
+ wire[0] !== 0x53 ||
+ wire[1] !== 0x55 ||
+ wire[2] !== 0x54 ||
+ wire[3] !== 0x44
+ ) {
+ throw new Error('Invalid SUTD binary response from Rust backend');
+ }
+ const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
+ const metaLen = view.getUint32(4, true);
+ const meta = JSON.parse(utf8Decoder.decode(wire.subarray(8, 8 + metaLen))) as {
+ nodeName: string | null;
+ variantId: number | null;
+ variantScalars: Record<string, unknown>;
+ variantBlobs: Record<string, { offset: number; len: number }>;
+ materials: Array<{
+ pwId: string;
+ originalPath: string;
+ catalogPath: string;
+ fileDataOffset: number;
+ fileDataLen: number;
+ }>;
+ };
+ const blobs = wire.subarray(8 + metaLen);
+ const variantValues = new Map<string, unknown>();
+ for (const [k, v] of Object.entries(meta.variantScalars)) {
+ variantValues.set(k.toLowerCase(), v);
+ }
+ for (const [k, ref] of Object.entries(meta.variantBlobs)) {
+ variantValues.set(k.toLowerCase(), blobs.subarray(ref.offset, ref.offset + ref.len));
+ }
+ const materials = meta.materials.map((m) => ({
+ pwId: m.pwId,
+ originalPath: m.originalPath,
+ catalogPath: m.catalogPath,
+ fileData: blobs.subarray(m.fileDataOffset, m.fileDataOffset + m.fileDataLen),
+ }));
+ return {
+ nodeName: meta.nodeName,
+ variantId: meta.variantId,
+ variantValues,
+ materials,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Native Parallel Raster Ops (Filters, FloodFill, Liquify, Tile Compression)
+// ---------------------------------------------------------------------------
+
+export async function applyFilterNative(
+ rgba: Uint8ClampedArray | Uint8Array,
+ width: number,
+ height: number,
+ type: FilterType,
+ params: Record<string, unknown>
+): Promise<Uint8ClampedArray> {
+ const invoke = await getInvoke();
+ let pA = 0;
+ let pB = 0;
+ let pC = 0;
+ let pD = 0;
+ if (type === 'gaussian-blur') {
+ pA = Number(params?.radius ?? 5);
+ } else if (type === 'motion-blur') {
+ pA = Number(params?.distance ?? 15);
+ pB = Number(params?.angle ?? 0);
+ } else if (type === 'unsharp-mask') {
+ pA = Number(params?.radius ?? 2);
+ pB = Number(params?.amount ?? 1.5);
+ pC = Number(params?.threshold ?? 0);
+ } else if (type === 'film-grain') {
+ pA = Number(params?.intensity ?? 25);
+ pB = Number(params?.size ?? 1);
+ pC = (params?.monochromatic ?? true) ? 1 : 0;
+ pD = Number(params?.seed ?? 1337) >>> 0;
+ }
+
+ const body =
+ rgba instanceof Uint8Array
+ ? rgba
+ : new Uint8Array(rgba.buffer, rgba.byteOffset, rgba.byteLength);
+
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('native_apply_filter', body, {
+ headers: {
+ 'x-filter-type': encodeURIComponent(type),
+ 'x-width': String(width),
+ 'x-height': String(height),
+ 'x-param-a': String(pA),
+ 'x-param-b': String(pB),
+ 'x-param-c': String(pC),
+ 'x-param-d': String(pD),
+ },
+ });
+ const bytes = toUint8Array(raw);
+ return new Uint8ClampedArray(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+}
+
+export async function floodFillNative(params: {
+ refRgba: Uint8ClampedArray | Uint8Array;
+ targetRgba?: Uint8ClampedArray | Uint8Array | null;
+ selectionMask?: Uint8Array | null;
+ width: number;
+ height: number;
+ startX: number;
+ startY: number;
+ fillRgba: [number, number, number, number];
+ tolerance: number;
+ closeGap: number;
+ areaScale: number;
+ antiAlias: boolean;
+}): Promise<{ modified: boolean; dirtyRect: DirtyRect | null; dirtyRgba: Uint8ClampedArray | null }> {
+ const invoke = await getInvoke();
+ const sameSurface = !params.targetRgba || params.targetRgba === params.refRgba;
+ const hasMask = Boolean(params.selectionMask && params.selectionMask.byteLength === params.width * params.height);
+
+ const refView = new Uint8Array(
+ params.refRgba.buffer,
+ params.refRgba.byteOffset,
+ params.refRgba.byteLength
+ );
+ let body: Uint8Array;
+ if (sameSurface && !hasMask) {
+ body = refView;
+ } else {
+ const total =
+ refView.byteLength +
+ (sameSurface ? 0 : params.targetRgba!.byteLength) +
+ (hasMask ? params.selectionMask!.byteLength : 0);
+ body = new Uint8Array(total);
+ let off = 0;
+ body.set(refView, off);
+ off += refView.byteLength;
+ if (!sameSurface) {
+ const tgt = params.targetRgba!;
+ body.set(new Uint8Array(tgt.buffer, tgt.byteOffset, tgt.byteLength), off);
+ off += tgt.byteLength;
+ }
+ if (hasMask) {
+ body.set(params.selectionMask!, off);
+ }
+ }
+
+ const [r, g, b, a] = params.fillRgba;
+ const packedColor = (((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | (a & 0xff)) >>> 0;
+
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('native_flood_fill', body, {
+ headers: {
+ 'x-width': String(params.width),
+ 'x-height': String(params.height),
+ 'x-start-x': String(Math.floor(params.startX)),
+ 'x-start-y': String(Math.floor(params.startY)),
+ 'x-fill-rgba': String(packedColor),
+ 'x-tolerance': String(params.tolerance),
+ 'x-close-gap': String(params.closeGap),
+ 'x-area-scale': String(params.areaScale),
+ 'x-anti-alias': params.antiAlias ? '1' : '0',
+ 'x-same-surface': sameSurface ? '1' : '0',
+ 'x-has-mask': hasMask ? '1' : '0',
+ },
+ });
+
+ const resp = toUint8Array(raw);
+ if (resp.byteLength < 17 || resp[0] === 0) {
+ return { modified: false, dirtyRect: null, dirtyRgba: null };
+ }
+ const view = new DataView(resp.buffer, resp.byteOffset, resp.byteLength);
+ const x = view.getInt32(1, true);
+ const y = view.getInt32(5, true);
+ const width = view.getInt32(9, true);
+ const height = view.getInt32(13, true);
+ const pixels = resp.subarray(17);
+ return {
+ modified: true,
+ dirtyRect: { x, y, width, height },
+ dirtyRgba: new Uint8ClampedArray(pixels.buffer, pixels.byteOffset, pixels.byteLength),
+ };
+}
+
+const LIQUIFY_MODE_CODE: Record<LiquifyMode, number> = {
+ push: 0,
+ 'push-left': 1,
+ 'push-right': 2,
+ expand: 3,
+ pinch: 4,
+ 'twirl-cw': 5,
+ 'twirl-ccw': 6,
+ reconstruct: 7,
+};
+
+export async function liquifyStepNative(params: {
+ srcRoi: Uint8ClampedArray | Uint8Array;
+ initRoi?: Uint8ClampedArray | Uint8Array | null;
+ selMaskRoi?: Uint8Array | null;
+ roiW: number;
+ roiH: number;
+ minX: number;
+ minY: number;
+ cx: number;
+ cy: number;
+ ux: number;
+ uy: number;
+ vLen: number;
+ radius: number;
+ hardness: number;
+ strength: number;
+ mode: LiquifyMode;
+}): Promise<Uint8ClampedArray> {
+ const invoke = await getInvoke();
+ const hasInit = Boolean(params.initRoi);
+ const hasMask = Boolean(params.selMaskRoi);
+ const srcView = new Uint8Array(
+ params.srcRoi.buffer,
+ params.srcRoi.byteOffset,
+ params.srcRoi.byteLength
+ );
+
+ let body: Uint8Array;
+ if (!hasInit && !hasMask) {
+ body = srcView;
+ } else {
+ const total =
+ srcView.byteLength +
+ (hasInit ? params.initRoi!.byteLength : 0) +
+ (hasMask ? params.selMaskRoi!.byteLength : 0);
+ body = new Uint8Array(total);
+ let off = 0;
+ body.set(srcView, off);
+ off += srcView.byteLength;
+ if (hasInit) {
+ const init = params.initRoi!;
+ body.set(new Uint8Array(init.buffer, init.byteOffset, init.byteLength), off);
+ off += init.byteLength;
+ }
+ if (hasMask) {
+ body.set(params.selMaskRoi!, off);
+ }
+ }
+
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('native_liquify_step', body, {
+ headers: {
+ 'x-roi-w': String(params.roiW),
+ 'x-roi-h': String(params.roiH),
+ 'x-min-x': String(params.minX),
+ 'x-min-y': String(params.minY),
+ 'x-cx': String(params.cx),
+ 'x-cy': String(params.cy),
+ 'x-ux': String(params.ux),
+ 'x-uy': String(params.uy),
+ 'x-vlen': String(params.vLen),
+ 'x-radius': String(params.radius),
+ 'x-hardness': String(params.hardness),
+ 'x-strength': String(params.strength),
+ 'x-mode': String(LIQUIFY_MODE_CODE[params.mode]),
+ 'x-has-init': hasInit ? '1' : '0',
+ 'x-has-mask': hasMask ? '1' : '0',
+ },
+ });
+
+ const out = toUint8Array(raw);
+ return new Uint8ClampedArray(out.buffer, out.byteOffset, out.byteLength);
+}
+
+export async function compressTilesLz4BatchNative(
+ tiles: Uint8Array[]
+): Promise<Array<{ codec: number; data: Uint8Array }>> {
+ const invoke = await getInvoke();
+ let total = 4;
+ for (const t of tiles) total += 4 + t.byteLength;
+ const req = new Uint8Array(total);
+ const view = new DataView(req.buffer);
+ view.setUint32(0, tiles.length, true);
+ let off = 4;
+ for (const t of tiles) {
+ view.setUint32(off, t.byteLength, true);
+ off += 4;
+ req.set(t, off);
+ off += t.byteLength;
+ }
+
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('native_compress_tiles_lz4', req);
+ const resp = toUint8Array(raw);
+ const rview = new DataView(resp.buffer, resp.byteOffset, resp.byteLength);
+ const count = rview.getUint32(0, true);
+ const out: Array<{ codec: number; data: Uint8Array }> = new Array(count);
+ let roff = 4;
+ for (let i = 0; i < count; i++) {
+ const codec = resp[roff];
+ const len = rview.getUint32(roff + 1, true);
+ roff += 5;
+ out[i] = { codec, data: resp.slice(roff, roff + len) };
+ roff += len;
+ }
+ return out;
+}
+
+export async function decompressTilesLz4BatchNative(
+ items: Array<{ codec: number; expectedLen: number; data: Uint8Array }>
+): Promise<Uint8Array[]> {
+ const invoke = await getInvoke();
+ let total = 4;
+ for (const it of items) total += 9 + it.data.byteLength;
+ const req = new Uint8Array(total);
+ const view = new DataView(req.buffer);
+ view.setUint32(0, items.length, true);
+ let off = 4;
+ for (const it of items) {
+ req[off] = it.codec;
+ view.setUint32(off + 1, it.expectedLen, true);
+ view.setUint32(off + 5, it.data.byteLength, true);
+ off += 9;
+ req.set(it.data, off);
+ off += it.data.byteLength;
+ }
+
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('native_decompress_tiles_lz4', req);
+ const resp = toUint8Array(raw);
+ const rview = new DataView(resp.buffer, resp.byteOffset, resp.byteLength);
+ const count = rview.getUint32(0, true);
+ const out: Uint8Array[] = new Array(count);
+ let roff = 4;
+ for (let i = 0; i < count; i++) {
+ const len = rview.getUint32(roff, true);
+ roff += 4;
+ out[i] = resp.slice(roff, roff + len);
+ roff += len;
+ }
+ return out;
+}
+
+export async function flateCompressNative(
+ op: 'deflate' | 'zlib',
+ data: Uint8Array,
+ level: number = 1
+): Promise<Uint8Array> {
+ const invoke = await getInvoke();
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('native_flate_compress', data, {
+ headers: {
+ 'x-op': op,
+ 'x-level': String(level),
+ },
+ });
+ return toUint8Array(raw);
+}
+
+export async function flateDecompressNative(
+ op: 'inflate' | 'unzlib',
+ data: Uint8Array,
+ maxOutputBytes?: number
+): Promise<Uint8Array> {
+ const invoke = await getInvoke();
+ const headers: Record<string, string> = { 'x-op': op };
+ if (maxOutputBytes !== undefined) {
+ headers['x-max-output-bytes'] = String(maxOutputBytes);
+ }
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('native_flate_decompress', data, {
+ headers,
+ });
+ return toUint8Array(raw);
+}
diff --git a/src/utils/nativeTabletInput.ts b/src/utils/nativeTabletInput.ts
new file mode 100644
index 0000000..4f7dc76
--- /dev/null
+++ b/src/utils/nativeTabletInput.ts
@@ -0,0 +1,173 @@
+/**
+ * Native low-latency Windows tablet input client (WinTab / Windows Ink API via Rust Channel).
+ * Replaces throttled browser PointerEvents on Tauri desktop while falling back cleanly on Web.
+ */
+
+import { isTauriEnvironment } from './tileEngine/scratchDriver';
+
+export type TabletInputMode = 'auto' | 'wintab' | 'windows-ink' | 'off';
+
+export interface NativeTabletStatus {
+ active: boolean;
+ backend: 'wintab' | 'windows-ink' | 'none';
+ wintabAvailable: boolean;
+ windowsInkAvailable: boolean;
+ deviceName: string | null;
+ maxPressure: number;
+}
+
+export interface NativeTabletSample {
+ clientX: number;
+ clientY: number;
+ pressure: number;
+ tiltX: number;
+ tiltY: number;
+ twist: number;
+ timestamp: number;
+ buttons: number; // bit 0=tip, 1=barrel1, 2=barrel2, 3=eraser
+ phase: 0 | 1 | 2 | 3 | 4; // 0=hover, 1=down, 2=move/drag, 3=up, 4=leave
+ backend: 1 | 2; // 1=wintab, 2=windows-ink
+}
+
+export type TabletSampleBatchListener = (samples: NativeTabletSample[]) => void;
+
+const SAMPLE_WIRE_BYTES = 36;
+const listeners = new Set<TabletSampleBatchListener>();
+let activeStatus: NativeTabletStatus = {
+ active: false,
+ backend: 'none',
+ wintabAvailable: false,
+ windowsInkAvailable: false,
+ deviceName: null,
+ maxPressure: 1024,
+};
+let lastPacketPerfMs = 0;
+let startPromise: Promise<NativeTabletStatus> | null = null;
+
+/**
+ * Unpacks a binary batch frame emitted by `src-tauri/src/tablet_input.rs`.
+ */
+export function unpackTabletSampleBatch(raw: ArrayBuffer | Uint8Array | number[]): NativeTabletSample[] {
+ const bytes =
+ raw instanceof Uint8Array
+ ? raw
+ : raw instanceof ArrayBuffer
+ ? new Uint8Array(raw)
+ : new Uint8Array(raw);
+
+ if (bytes.byteLength < 4) return [];
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const count = view.getUint32(0, true);
+ const maxCount = Math.floor((bytes.byteLength - 4) / SAMPLE_WIRE_BYTES);
+ const n = Math.min(count, maxCount);
+ const out: NativeTabletSample[] = new Array(n);
+
+ let off = 4;
+ for (let i = 0; i < n; i++) {
+ out[i] = {
+ clientX: view.getFloat32(off, true),
+ clientY: view.getFloat32(off + 4, true),
+ pressure: view.getFloat32(off + 8, true),
+ tiltX: view.getFloat32(off + 12, true),
+ tiltY: view.getFloat32(off + 16, true),
+ twist: view.getFloat32(off + 20, true),
+ timestamp: view.getFloat64(off + 24, true),
+ buttons: view.getUint16(off + 32, true),
+ phase: bytes[off + 34] as NativeTabletSample['phase'],
+ backend: bytes[off + 35] as NativeTabletSample['backend'],
+ };
+ off += SAMPLE_WIRE_BYTES;
+ }
+ return out;
+}
+
+/**
+ * Returns true if native WinTab / Windows Ink packets are currently active and recently received
+ * (used to suppress redundant DOM `pointerType === 'pen'` PointerEvents).
+ */
+export function isNativePenStreamActive(): boolean {
+ if (!activeStatus.active) return false;
+ const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ return now - lastPacketPerfMs < 250;
+}
+
+export function getCachedTabletStatus(): NativeTabletStatus {
+ return activeStatus;
+}
+
+export function subscribeNativeTablet(listener: TabletSampleBatchListener): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+export async function startNativeTablet(mode: TabletInputMode = 'auto'): Promise<NativeTabletStatus> {
+ if (!isTauriEnvironment()) {
+ return activeStatus;
+ }
+ if (mode === 'off') {
+ await stopNativeTablet();
+ return activeStatus;
+ }
+ if (startPromise) return startPromise;
+
+ startPromise = (async () => {
+ try {
+ const { invoke, Channel } = await import('@tauri-apps/api/core');
+ const channel = new Channel<ArrayBuffer | Uint8Array | number[]>();
+ channel.onmessage = (payload) => {
+ const batch = unpackTabletSampleBatch(payload);
+ if (batch.length === 0) return;
+ lastPacketPerfMs = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ for (const fn of listeners) {
+ fn(batch);
+ }
+ };
+
+ const status = await invoke<NativeTabletStatus>('tablet_start_input', {
+ mode,
+ onSamples: channel,
+ });
+ activeStatus = status;
+ return status;
+ } catch {
+ activeStatus = {
+ ...activeStatus,
+ active: false,
+ backend: 'none',
+ };
+ return activeStatus;
+ } finally {
+ startPromise = null;
+ }
+ })();
+
+ return startPromise;
+}
+
+export async function stopNativeTablet(): Promise<void> {
+ if (!isTauriEnvironment()) return;
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ await invoke('tablet_stop_input');
+ } catch {
+ // Ignore shutdown errors
+ }
+ activeStatus = {
+ ...activeStatus,
+ active: false,
+ backend: 'none',
+ };
+}
+
+export async function queryNativeTabletStatus(): Promise<NativeTabletStatus> {
+ if (!isTauriEnvironment()) return activeStatus;
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ activeStatus = await invoke<NativeTabletStatus>('tablet_get_status');
+ } catch {
+ // Ignore
+ }
+ return activeStatus;
+}
diff --git a/src/utils/pencilEngine.ts b/src/utils/pencilEngine.ts
deleted file mode 100644
index 790bc3d..0000000
--- a/src/utils/pencilEngine.ts
+++ /dev/null
@@ -1,592 +0,0 @@
-import { Point } from '../types/editor';
-import { getTintedMasterCanvas, drawSingleStamp, buildCubicArcLengthTable, getCubicPointAtArcLength } from './stampEngine';
-
-/**
- * Real Pencil Physics & Paper Grain Simulation Engine
- * Simulates authentic graphite marks on cold-press sketchbook paper,
- * modeled after physical graphite grades: F, HB, 2B, and 4B.
- */
-
-export type PencilGrade = 'pencil-f' | 'pencil-hb' | 'pencil-2b' | 'pencil-4b';
-
-export interface PencilGradeConfig {
- id: PencilGrade;
- name: string;
- gradeLabel: string;
- description: string;
- defaultSize: number;
- minSizeFactor: number;
- hardness: number; // 0.0 to 1.0 (firmness of the tip)
- flow: number; // 0.0 to 1.0 (graphite release rate)
- spacing: number; // step spacing along curve
- grain: number; // 0.0 to 1.0 (paper tooth visibility)
- particleDensity: number; // micro-graphite particles per stamp
- particleSize: number; // size of individual graphite flakes (px)
- thresholdBase: number; // base paper height threshold
- thresholdPressureSensitivity: number; // how much pressure lowers threshold
- graphiteColorHex: string; // default authentic graphite tone
-}
-
-export const PENCIL_CONFIGS: Record<PencilGrade, PencilGradeConfig> = {
- 'pencil-f': {
- id: 'pencil-f',
- name: 'Pencil (F)',
- gradeLabel: 'F',
- description: 'Firm & Fine Lead — crisp lineart, light construction & technical sketching',
- defaultSize: 2.5,
- minSizeFactor: 0.35,
- hardness: 0.85,
- flow: 0.55,
- spacing: 0.08,
- grain: 0.88,
- particleDensity: 8,
- particleSize: 1.0,
- thresholdBase: 135,
- thresholdPressureSensitivity: 60,
- graphiteColorHex: '#3a3d43',
- },
- 'pencil-hb': {
- id: 'pencil-hb',
- name: 'Pencil (HB)',
- gradeLabel: 'HB',
- description: 'Medium Classic — everyday sketching, drafting & line work',
- defaultSize: 3.2,
- minSizeFactor: 0.25,
- hardness: 0.75,
- flow: 0.65,
- spacing: 0.07,
- grain: 0.92,
- particleDensity: 11,
- particleSize: 1.15,
- thresholdBase: 120,
- thresholdPressureSensitivity: 70,
- graphiteColorHex: '#2d2f34',
- },
- 'pencil-2b': {
- id: 'pencil-2b',
- name: 'Pencil (2B)',
- gradeLabel: '2B',
- description: 'Soft & Black Sketching — rich graphite, dynamic pressure & natural shading tooth',
- defaultSize: 4.5,
- minSizeFactor: 0.20,
- hardness: 0.65,
- flow: 0.74,
- spacing: 0.06,
- grain: 0.95,
- particleDensity: 15,
- particleSize: 1.35,
- thresholdBase: 105,
- thresholdPressureSensitivity: 80,
- graphiteColorHex: '#222326',
- },
- 'pencil-4b': {
- id: 'pencil-4b',
- name: 'Pencil (4B)',
- gradeLabel: '4B',
- description: 'Extra Soft & Velvety Carbon — deep expressive darks, loose gestures & rich crumbly texture',
- defaultSize: 6.5,
- minSizeFactor: 0.15,
- hardness: 0.50,
- flow: 0.88,
- spacing: 0.05,
- grain: 1.0,
- particleDensity: 20,
- particleSize: 1.6,
- thresholdBase: 90,
- thresholdPressureSensitivity: 90,
- graphiteColorHex: '#141416',
- },
-};
-
-/**
- * 512x512 Seamless Procedural Paper Grain Texture
- * Precalculated at startup into a 1D Uint8Array for instant O(1) single-cycle lookups.
- * Models cold-press cotton sketchbook paper with micro-mineral tooth and intertwined cellulose fibers.
- */
-export const GRAIN_SIZE = 512;
-const GRAIN_MASK = GRAIN_SIZE - 1;
-export const paperGrainTable = new Uint8Array(GRAIN_SIZE * GRAIN_SIZE);
-
-// Deterministic fast PRNG for seamless texture synthesis
-function sfc32(a: number, b: number, c: number, d: number) {
- return function () {
- a |= 0;
- b |= 0;
- c |= 0;
- d |= 0;
- const t = (((a + b) | 0) + d) | 0;
- d = (d + 1) | 0;
- a = b ^ (b >>> 9);
- b = (c + (c << 3)) | 0;
- c = (c << 21) | (c >>> 11);
- c = (c + t) | 0;
- return (t >>> 0) / 4294967296;
- };
-}
-
-(function initPaperGrain() {
- const rand = sfc32(0x9e3779b9, 0x243f6a88, 0xb7e15162, 0x8aed2a6b);
-
- // Build tileable periodic value-noise grids for smooth multi-octave cold-press paper synthesis
- const makeGrid = (res: number) => {
- const g = new Float32Array(res * res);
- for (let i = 0; i < g.length; i++) g[i] = rand();
- return g;
- };
-
- const samplePeriodic = (grid: Float32Array, res: number, fx: number, fy: number): number => {
- const mask = res - 1;
- const x0 = Math.floor(fx);
- const y0 = Math.floor(fy);
- const tx = fx - x0;
- const ty = fy - y0;
- // Smooth cubic Hermite interpolation eliminates grid-aligned banding & blockiness
- const sx = tx * tx * (3 - 2 * tx);
- const sy = ty * ty * (3 - 2 * ty);
- const ix0 = x0 & mask;
- const iy0 = y0 & mask;
- const ix1 = (ix0 + 1) & mask;
- const iy1 = (iy0 + 1) & mask;
- const v00 = grid[iy0 * res + ix0];
- const v10 = grid[iy0 * res + ix1];
- const v01 = grid[iy1 * res + ix0];
- const v11 = grid[iy1 * res + ix1];
- const top = v00 + (v10 - v00) * sx;
- const bot = v01 + (v11 - v01) * sx;
- return top + (bot - top) * sy;
- };
-
- const gCoarse = makeGrid(64); // 8px cold-press paper hills/valleys
- const gMedium = makeGrid(128); // 4px primary cotton paper tooth
- const gFine = makeGrid(256); // 2px interwoven cellulose fibers
- const gMicro = makeGrid(512); // 1px mineral grit micro-tooth
-
- for (let y = 0; y < GRAIN_SIZE; y++) {
- const row = y * GRAIN_SIZE;
- for (let x = 0; x < GRAIN_SIZE; x++) {
- // Slight anisotropic weave warp for natural organic paper fibers
- const warpX = x + Math.sin(y * 0.09817477) * 1.4;
- const warpY = y + Math.cos(x * 0.09817477) * 1.4;
-
- const nCoarse = samplePeriodic(gCoarse, 64, x * 0.125, y * 0.125);
- const nMedium = samplePeriodic(gMedium, 128, warpX * 0.25, warpY * 0.25);
- const nFine = samplePeriodic(gFine, 256, warpX * 0.5, warpY * 0.5);
- const nMicro = gMicro[row + x];
-
- const combined = nCoarse * 0.28 + nMedium * 0.36 + nFine * 0.24 + nMicro * 0.12;
- // S-curve contrast shaping for crisp tooth peaks and realistic paper valleys
- const stretched = Math.max(0, Math.min(1, (combined - 0.18) / 0.64));
- const curved = Math.pow(stretched, 1.18);
- paperGrainTable[row + x] = Math.min(255, Math.max(0, Math.round(curved * 255)));
- }
- }
-})();
-
-/**
- * World-anchored paper grain elevation query at canvas coordinate (x, y).
- * Uses smooth sub-pixel bilinear interpolation across the 512x512 seamless paper grain table.
- * Returns number 0 to 255 representing paper tooth height.
- */
-export function getPaperGrain(x: number, y: number): number {
- const fx = Math.floor(x);
- const fy = Math.floor(y);
- const tx = x - fx;
- const ty = y - fy;
-
- const x0 = (fx & GRAIN_MASK) >>> 0;
- const y0 = (fy & GRAIN_MASK) >>> 0;
- const x1 = ((fx + 1) & GRAIN_MASK) >>> 0;
- const y1 = ((fy + 1) & GRAIN_MASK) >>> 0;
-
- const v00 = paperGrainTable[y0 * GRAIN_SIZE + x0];
- const v10 = paperGrainTable[y0 * GRAIN_SIZE + x1];
- const v01 = paperGrainTable[y1 * GRAIN_SIZE + x0];
- const v11 = paperGrainTable[y1 * GRAIN_SIZE + x1];
-
- const top = v00 + (v10 - v00) * tx;
- const bottom = v01 + (v11 - v01) * tx;
- return Math.round(top + (bottom - top) * ty);
-}
-
-/**
- * Converts a hex or rgb/rgba string into RGBA components [r, g, b, a].
- */
-export function parseRgba(colorStr: string): [number, number, number, number] {
- if (colorStr.startsWith('#')) {
- let hex = colorStr.slice(1);
- if (hex.length === 3) {
- hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
- }
- const num = parseInt(hex, 16);
- if (hex.length === 6) {
- return [(num >> 16) & 255, (num >> 8) & 255, num & 255, 1];
- } else if (hex.length === 8) {
- return [(num >> 24) & 255, (num >> 16) & 255, (num >> 8) & 255, (num & 255) / 255];
- }
- }
-
- const match = colorStr.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (match) {
- return [
- parseInt(match[1], 10),
- parseInt(match[2], 10),
- parseInt(match[3], 10),
- match[4] !== undefined ? parseFloat(match[4]) : 1,
- ];
- }
-
- return [30, 31, 34, 1]; // Fallback dark graphite
-}
-
-/**
- * Evaluates a quadratic Bézier curve at parameter t (0 <= t <= 1).
- */
-export function getQuadraticBezierPoint(
- p0: Point,
- control: Point,
- p2: Point,
- t: number
-): { x: number; y: number; width: number; pressure: number } {
- const invT = 1 - t;
- const invT2 = invT * invT;
- const t2 = t * t;
- const twoInvTT = 2 * invT * t;
-
- return {
- x: invT2 * p0.x + twoInvTT * control.x + t2 * p2.x,
- y: invT2 * p0.y + twoInvTT * control.y + t2 * p2.y,
- width: invT * p0.width + t * p2.width,
- pressure: invT * p0.pressure + t * p2.pressure,
- };
-}
-
-/**
- * Fast deterministic pseudo-random float generator in [0, 1).
- * Ensures graphite micro-flakes land on identical coordinates for live preview and committed strokes.
- */
-export function getPencilNoise(seed: number): number {
- let t = (seed + 0x6d2b79f5) | 0;
- t = Math.imul(t ^ (t >>> 15), t | 1);
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
-}
-
-/**
- * Evaluates a cubic Bézier point at parameter t (0 <= t <= 1).
- */
-export function getCubicBezierPoint(
- p0: Point,
- c1: Point,
- c2: Point,
- p3: Point,
- t: number
-): Point {
- const invT = 1.0 - t;
- const invT2 = invT * invT;
- const invT3 = invT2 * invT;
- const t2 = t * t;
- const t3 = t2 * t;
-
- return {
- x: invT3 * p0.x + 3.0 * invT2 * t * c1.x + 3.0 * invT * t2 * c2.x + t3 * p3.x,
- y: invT3 * p0.y + 3.0 * invT2 * t * c1.y + 3.0 * invT * t2 * c2.y + t3 * p3.y,
- pressure: invT * p0.pressure + t * p3.pressure,
- width: invT * p0.width + t * p3.width,
- tiltX: invT * (p0.tiltX ?? 0) + t * (p3.tiltX ?? 0),
- tiltY: invT * (p0.tiltY ?? 0) + t * (p3.tiltY ?? 0),
- twist: invT * (p0.twist ?? 0) + t * (p3.twist ?? 0),
- };
-}
-
-const graphiteMaskCache = new Map<PencilGrade, HTMLCanvasElement>();
-
-/**
- * Pre-renders and caches high-resolution graphite particle masks for each pencil grade.
- * Features microscopic graphite flake distribution and porous core voids.
- */
-export function getGraphiteTipMaster(grade: PencilGrade, color: string): HTMLCanvasElement {
- let maskCanvas = graphiteMaskCache.get(grade);
- if (!maskCanvas) {
- const config = PENCIL_CONFIGS[grade] || PENCIL_CONFIGS['pencil-2b'];
- const size = 64;
- maskCanvas = document.createElement('canvas');
- maskCanvas.width = size;
- maskCanvas.height = size;
- const ctx = maskCanvas.getContext('2d');
- if (ctx) {
- const imgData = ctx.createImageData(size, size);
- const data = imgData.data;
- const cx = size / 2;
- const cy = size / 2;
- const radius = size / 2 - 2; // 30px
- const rand = sfc32(0x9e3779b9, 0x243f6a88, 0xb7e15162, 0x8aed2a6b);
-
- for (let y = 0; y < size; y++) {
- const dy = y - cy + 0.5;
- const rowOffset = y * size * 4;
- for (let x = 0; x < size; x++) {
- const dx = x - cx + 0.5;
- const dist = Math.hypot(dx, dy);
- if (dist < radius) {
- const normDist = dist / radius;
- const coreFalloff = Math.pow(Math.max(0, 1.0 - normDist), config.hardness > 0.7 ? 0.65 : 1.2);
- // Graphite micro-flakes and porous grain voids
- const flakeNoise = rand();
- const microVoid = flakeNoise > (0.15 + (1 - config.grain) * 0.1) ? 1.0 : 0.25;
- const alpha = Math.min(1.0, coreFalloff * (0.65 + flakeNoise * 0.35) * microVoid);
-
- if (alpha > 0.005) {
- const idx = rowOffset + x * 4;
- data[idx] = 255;
- data[idx + 1] = 255;
- data[idx + 2] = 255;
- data[idx + 3] = Math.round(alpha * 255);
- }
- }
- }
- }
- ctx.putImageData(imgData, 0, 0);
- }
- graphiteMaskCache.set(grade, maskCanvas);
- }
-
- return getTintedMasterCanvas(maskCanvas, `pencil_${grade}`, color, 64, 64);
-}
-
-/**
- * Draws a real pencil mark along a cubic Bézier curve using arc-length stepping and paper tooth modulation.
- * Delivers authentic graphite tooth on cold-press paper at a locked 120 FPS without string allocations.
- */
-export function drawPencilCubicBezierSegment(
- ctx: CanvasRenderingContext2D,
- p0: Point,
- c1: Point,
- c2: Point,
- p3: Point,
- color: string,
- grade: PencilGrade = 'pencil-2b',
- userFlow: number = 0.75,
- grainIntensity: number = 1.0,
- _userHardness?: number,
- remainderDist: number = 0,
- alphaLocked: boolean = false,
- isTransparentInk: boolean = false,
- useTilt: boolean = true
-): number {
- const config = PENCIL_CONFIGS[grade] || PENCIL_CONFIGS['pencil-2b'];
- const arcTable = buildCubicArcLengthTable(p0, c1, c2, p3);
- const dist = arcTable.totalLength;
- if (dist < 0.1) return Math.max(0, remainderDist - dist);
-
- const graphiteMaster = getGraphiteTipMaster(grade, color);
- const isMonoCrisp = _userHardness !== undefined && _userHardness >= 0.99;
- const baseThreshold = config.thresholdBase;
- const sens = config.thresholdPressureSensitivity;
- const flow = isMonoCrisp ? 1.0 : userFlow * config.flow;
- const spacingRatio = config.spacing || 0.07;
-
- let currentDist = Math.max(0, remainderDist);
- while (currentDist <= dist) {
- const pt = getCubicPointAtArcLength(p0, c1, c2, p3, currentDist, arcTable);
- const pressure = Math.min(Math.max(pt.pressure || 0.5, 0.05), 1.0);
-
- const tiltX = useTilt ? (pt.tiltX ?? 0) : 0;
- const tiltY = useTilt ? (pt.tiltY ?? 0) : 0;
- const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
-
- const minStampW = isMonoCrisp ? 1.35 : 0.6;
- const curWidth = Math.max(minStampW, pt.width * (1.0 + tiltMagnitude * 2.2));
- const stepDist = Math.max(0.25, Math.min(1.8, Math.max(0.6, pt.width) * spacingRatio));
-
- const effThreshold = Math.max(
- 15,
- baseThreshold - pressure * sens + (1 - grainIntensity) * 40 - tiltMagnitude * 35
- );
-
- let stampW = curWidth;
- let stampH = curWidth;
- let stampAngle = 0;
- if (tiltMagnitude > 0.01) {
- const tiltAzimuth = Math.atan2(tiltY, tiltX);
- stampW = curWidth;
- stampH = curWidth * (1.0 + tiltMagnitude * 1.5);
- if (tiltMagnitude > 0.05) {
- stampAngle = tiltAzimuth;
- }
- }
- if (pt.twist) {
- stampAngle += (pt.twist * Math.PI) / 180;
- }
-
- // Multi-sample Quincunx grain integration for wider graphite leads (> 4px) to prevent whole-stamp blinking
- let paperHeight: number;
- if (curWidth > 4.0) {
- const off = curWidth * 0.25;
- paperHeight = (
- getPaperGrain(pt.x, pt.y) * 2 +
- getPaperGrain(pt.x - off, pt.y - off) +
- getPaperGrain(pt.x + off, pt.y - off) +
- getPaperGrain(pt.x - off, pt.y + off) +
- getPaperGrain(pt.x + off, pt.y + off)
- ) / 6;
- } else {
- paperHeight = getPaperGrain(pt.x, pt.y);
- }
-
- if (isMonoCrisp || paperHeight >= effThreshold) {
- const heightFactor = isMonoCrisp ? 1.0 : Math.min(1.0, (paperHeight - effThreshold + 25) / 55);
- const dabAlpha = isMonoCrisp
- ? 1.0
- : Math.min(
- 1.0,
- Math.max(0.04, flow * (0.35 + 0.65 * pressure) * heightFactor)
- );
-
- drawSingleStamp(
- ctx,
- graphiteMaster,
- pt.x,
- pt.y,
- stampW,
- stampH,
- stampAngle,
- dabAlpha,
- false,
- false,
- alphaLocked,
- isTransparentInk
- );
- } else if (pressure > 0.55) {
- // Firm pressure pushing into troughs
- const dabAlpha = Math.min(1.0, flow * 0.15 * pressure);
- drawSingleStamp(
- ctx,
- graphiteMaster,
- pt.x,
- pt.y,
- stampW,
- stampH,
- stampAngle,
- dabAlpha,
- false,
- false,
- alphaLocked,
- isTransparentInk
- );
- }
-
- currentDist += stepDist;
- }
-
- return Math.max(0, currentDist - dist);
-}
-
-/**
- * Draws a real pencil mark along a quadratic Bézier curve by elevating to cubic.
- */
-export function drawPencilBezierSegment(
- ctx: CanvasRenderingContext2D,
- start: Point,
- control: Point,
- end: Point,
- color: string,
- grade: PencilGrade = 'pencil-2b',
- userFlow: number = 0.75,
- grainIntensity: number = 1.0,
- userHardness?: number,
- alphaLocked: boolean = false,
- isTransparentInk: boolean = false
-) {
- const c1: Point = {
- x: start.x + (2.0 / 3.0) * (control.x - start.x),
- y: start.y + (2.0 / 3.0) * (control.y - start.y),
- pressure: start.pressure + (2.0 / 3.0) * (control.pressure - start.pressure),
- width: start.width + (2.0 / 3.0) * (control.width - start.width),
- tiltX: start.tiltX !== undefined && control.tiltX !== undefined ? start.tiltX + (2.0 / 3.0) * (control.tiltX - start.tiltX) : undefined,
- tiltY: start.tiltY !== undefined && control.tiltY !== undefined ? start.tiltY + (2.0 / 3.0) * (control.tiltY - start.tiltY) : undefined,
- twist: start.twist !== undefined && control.twist !== undefined ? start.twist + (2.0 / 3.0) * (control.twist - start.twist) : undefined,
- };
- const c2: Point = {
- x: end.x + (2.0 / 3.0) * (control.x - end.x),
- y: end.y + (2.0 / 3.0) * (control.y - end.y),
- pressure: end.pressure + (2.0 / 3.0) * (control.pressure - end.pressure),
- width: end.width + (2.0 / 3.0) * (control.width - end.width),
- tiltX: end.tiltX !== undefined && control.tiltX !== undefined ? end.tiltX + (2.0 / 3.0) * (control.tiltX - end.tiltX) : undefined,
- tiltY: end.tiltY !== undefined && control.tiltY !== undefined ? end.tiltY + (2.0 / 3.0) * (control.tiltY - end.tiltY) : undefined,
- twist: end.twist !== undefined && control.twist !== undefined ? end.twist + (2.0 / 3.0) * (control.twist - end.twist) : undefined,
- };
- drawPencilCubicBezierSegment(ctx, start, c1, c2, end, color, grade, userFlow, grainIntensity, userHardness, 0, alphaLocked, isTransparentInk);
-}
-
-/**
- * Draws a real pencil dot (e.g. single tap / initial contact).
- */
-export function drawPencilDot(
- ctx: CanvasRenderingContext2D,
- point: Point,
- color: string,
- grade: PencilGrade = 'pencil-2b',
- userFlow: number = 0.75,
- grainIntensity: number = 1.0,
- _userHardness?: number,
- alphaLocked: boolean = false,
- isTransparentInk: boolean = false
-) {
- const config = PENCIL_CONFIGS[grade] || PENCIL_CONFIGS['pencil-2b'];
- const graphiteMaster = getGraphiteTipMaster(grade, color);
- const isMonoCrisp = _userHardness !== undefined && _userHardness >= 0.99;
- const pressure = Math.min(Math.max(point.pressure || 0.5, 0.05), 1.0);
-
- const tiltX = point.tiltX ?? 0;
- const tiltY = point.tiltY ?? 0;
- const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
-
- const curWidth = Math.max(isMonoCrisp ? 1.35 : 0.6, point.width * (1.0 + tiltMagnitude * 2.2));
-
- const effThreshold = Math.max(
- 15,
- config.thresholdBase - pressure * config.thresholdPressureSensitivity + (1 - grainIntensity) * 40 - tiltMagnitude * 35
- );
-
- let stampW = curWidth;
- let stampH = curWidth;
- let stampAngle = 0;
- if (tiltMagnitude > 0.01) {
- const tiltAzimuth = Math.atan2(tiltY, tiltX);
- stampW = curWidth;
- stampH = curWidth * (1.0 + tiltMagnitude * 1.5);
- if (tiltMagnitude > 0.05) {
- stampAngle = tiltAzimuth;
- }
- }
- if (point.twist) {
- stampAngle += (point.twist * Math.PI) / 180;
- }
-
- const paperHeight = getPaperGrain(point.x, point.y);
- const heightFactor = isMonoCrisp
- ? 1.0
- : paperHeight >= effThreshold
- ? Math.min(1.0, (paperHeight - effThreshold + 25) / 55)
- : 0.15;
-
- const flow = isMonoCrisp ? 1.0 : userFlow * config.flow;
- const dabAlpha = isMonoCrisp ? 1.0 : Math.min(1.0, Math.max(0.05, flow * pressure * heightFactor));
-
- drawSingleStamp(
- ctx,
- graphiteMaster,
- point.x,
- point.y,
- stampW,
- stampH,
- stampAngle,
- dabAlpha,
- false,
- false,
- alphaLocked,
- isTransparentInk
- );
-}
diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.ts
index ed103df..940bcd1 100644
--- a/src/utils/presetBrushes.ts
+++ b/src/utils/presetBrushes.ts
@@ -4,7 +4,7 @@ import {
BrushSettings,
DEFAULT_BRUSH_DYNAMICS,
} from '../types/editor';
-import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/CspBrushEngine';
+import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/BrushEngine';
import {
generateRealGPenTip,
generateTexturedPenTip,
diff --git a/src/utils/pressureCurve.ts b/src/utils/pressureCurve.ts
index b41738c..c2a2ecd 100644
--- a/src/utils/pressureCurve.ts
+++ b/src/utils/pressureCurve.ts
@@ -4,7 +4,7 @@ import {
PressureCurvePreset,
PressureCurveSettings,
} from '../types/settings';
-import { evaluateFastSpline } from '../engine/CspBrushEngine';
+import { evaluateFastSpline } from '../engine/BrushEngine';
export { PRESSURE_CURVE_PRESETS };
diff --git a/src/utils/psdParser.ts b/src/utils/psdParser.ts
index 7441a9c..06c48d9 100644
--- a/src/utils/psdParser.ts
+++ b/src/utils/psdParser.ts
@@ -1,6 +1,7 @@
import { readPsd, initializeCanvas, Layer as PsdLayer, LayerMaskData, PixelData } from 'ag-psd';
import { BlendMode, CanvasColorMode, LayerItem, LoadedDocument } from '../types/editor';
import { createCanvasThumbnail } from './canvasUtils';
+import { isNativeRustAvailable, parsePsdNative } from './nativeBackend';
import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';
initializeCanvas(
@@ -31,11 +32,13 @@ export function mapPsdBlendMode(psdBlendMode?: string): BlendMode {
case 'overlay':
return 'overlay';
case 'darken':
- case 'darker color':
return 'darken';
+ case 'darker color':
+ return 'darker-color';
case 'lighten':
- case 'lighter color':
return 'lighten';
+ case 'lighter color':
+ return 'lighter-color';
case 'color dodge':
return 'color-dodge';
case 'linear dodge':
@@ -45,21 +48,34 @@ export function mapPsdBlendMode(psdBlendMode?: string): BlendMode {
case 'linear burn':
return 'linear-burn';
case 'hard light':
+ return 'hard-light';
case 'vivid light':
+ return 'vivid-light';
case 'linear light':
+ return 'linear-light';
case 'pin light':
+ return 'pin-light';
case 'hard mix':
- return 'hard-light';
+ return 'hard-mix';
case 'soft light':
return 'soft-light';
case 'difference':
+ return 'difference';
case 'subtract':
case 'subtraction':
- return 'difference';
+ return 'subtract';
case 'exclusion':
return 'exclusion';
case 'divide':
return 'divide';
+ case 'hue':
+ return 'hue';
+ case 'saturation':
+ return 'saturation';
+ case 'color':
+ return 'color';
+ case 'luminosity':
+ return 'luminosity';
case 'pass through':
return 'pass-through';
case 'normal':
@@ -230,6 +246,10 @@ export async function parsePsdFile(
fileName: string,
targetGrid?: SparseTileGrid
): Promise<LoadedDocument> {
+ if (isNativeRustAvailable()) {
+ return await parsePsdNative(buffer, fileName, targetGrid);
+ }
+
const psd = readPsd(buffer, {
skipLayerImageData: false,
skipCompositeImageData: true,
diff --git a/src/utils/saveManager.ts b/src/utils/saveManager.ts
index 2804e2a..c54b53a 100644
--- a/src/utils/saveManager.ts
+++ b/src/utils/saveManager.ts
@@ -1,2497 +1,49 @@
-import type {
- BlendMode as AgPsdBlendMode,
- Layer as AgPsdLayer,
- LayerMaskData as AgPsdMaskData,
-} from 'ag-psd';
-import { Zip, ZipDeflate, ZipPassThrough, unzipSync } from 'fflate';
-import {
- CanvasDimensions,
- LayerItem,
- CanvasColorMode,
- BlendMode,
- AnimationTimeline,
- SoraTimelapseMetadata,
- isFolderLikeLayer,
- hasTileBackedLayer,
-} from '../types/editor';
-import type { PerspectiveRuler } from '../types/perspective';
-import { getCanvasCompositeOperation } from './canvasUtils';
-import {
- buildLayerTree,
- groupTreeNodesForCompositing,
- LayerTreeNode,
- ViewportCompositor,
- ViewportTransform,
-} from './compositor';
-import { applyAdjustment } from './tonalEngine';
-import { applyMultiFrameClip, renderFrameBorder } from './frameEngine';
-import { renderVectorLayer } from './vectorEngine';
-import { renderBalloonLayerData, renderTextLayerData } from './vectorLayerRenderer';
-import { recoveryService } from '../services/recoveryService';
-import {
- SparseTileGrid,
- TILE_SIZE,
- TileBuffer,
- TileFormat,
- getTileByteSize,
- releaseTemporaryCanvas,
-} from './tileEngine';
-import { documentStore } from './documentStore';
-
-export interface SavedFileInfo {
- handle?: any; // FileSystemFileHandle
- name: string;
- extension: string;
- size?: number;
- previewDataUrl?: string;
-}
-
-export interface SaveProgress {
- phase: 'preparing' | 'preview' | 'tiles' | 'masks' | 'compositing' | 'encoding' | 'finalizing' | 'done';
- current: number;
- total: number;
- percent: number;
- message: string;
-}
-
-export interface SaveDocumentData {
- name: string;
- dimensions: CanvasDimensions;
- colorMode: CanvasColorMode;
- layers: LayerItem[];
- layerCanvasesMap: Map<string, HTMLCanvasElement>;
- tileGrid?: SparseTileGrid;
- getEffectiveOpacity: (layer: LayerItem) => number;
- isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
- tabId?: string;
- perspectiveRuler?: PerspectiveRuler | null;
- animationTimeline?: AnimationTimeline | null;
- timelapse?: SoraTimelapseMetadata | null;
- onProgress?: (progress: SaveProgress) => void;
- compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
-}
-
-export interface SoraV2Manifest {
- format: 'sora-v2';
- app: string;
- version: '2.0';
- tileSize: number;
- name: string;
- dimensions: CanvasDimensions;
- colorMode: CanvasColorMode;
- layers: Array<Omit<LayerItem, 'maskCanvas'>>;
- layerFormats: Record<string, TileFormat>;
- layerTileKeys: Record<string, string>;
- masksMeta: Record<string, { width: number; height: number; format: 'alpha-8bit' }>;
- perspectiveRuler?: PerspectiveRuler | null;
- animationTimeline?: AnimationTimeline | null;
- timelapse?: SoraTimelapseMetadata | null;
- preview: { path: string; width: number; height: number } | null;
- savedAt: number;
-}
-
-export interface ParsedSoraProject {
- format: 'v2' | 'v1';
- app: string;
- version: string;
- name: string;
- dimensions: CanvasDimensions;
- colorMode: CanvasColorMode;
- layers: LayerItem[];
- tileGrid?: SparseTileGrid;
- canvases: Record<string, string>;
- masks: Record<string, string>;
- masksBinary?: Map<string, { width: number; height: number; data: Uint8Array }>;
- perspectiveRuler?: PerspectiveRuler | null;
- animationTimeline?: AnimationTimeline | null;
- timelapse?: SoraTimelapseMetadata | null;
- previewBytes?: Uint8Array | null;
- previewDataUrl?: string;
-}
-
-export interface ExportImageOptions {
- format?: 'png' | 'jpg' | 'jpeg' | 'webp';
- quality?: number;
- fillWhiteBackground?: boolean;
- tileSize?: number;
- onProgress?: (progress: SaveProgress) => void;
-}
-
-export interface ExportImageResult {
- blob: Blob;
- mimeType: string;
- width: number;
- height: number;
- usedGpu: boolean;
-}
-
-export interface CompositeCanvasOptions {
- tileSize?: number;
- colorMode?: CanvasColorMode;
- onProgress?: (progress: SaveProgress) => void;
-}
-
-export const SORA_V2_DEFAULT_TILE_EXPORT_SIZE = 2048;
-
-const SORA_V2_FORMAT_TO_BYTE: Record<TileFormat, number> = {
- 'monochrome-1bit': 0,
- 'grayscale-8bit': 1,
- 'color-32bit': 2,
-};
-
-const SORA_V2_BYTE_TO_FORMAT: Record<number, TileFormat> = {
- 0: 'monochrome-1bit',
- 1: 'grayscale-8bit',
- 2: 'color-32bit',
-};
-
-const TILE_BINARY_HEADER_BYTES = 9; // [format:u8][version:u32 LE][dataLen:u32 LE]
-const MASK_BINARY_HEADER_BYTES = 8; // [width:u32 LE][height:u32 LE]
-const MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
-const MAX_DOCUMENT_DIM = 65536;
-const MAX_TILE_ENTRIES = 120000;
-const CHUNK_YIELD_INTERVAL = 8;
-const MAX_STYLE_MARGIN_PX = 256;
-const PREVIEW_MAX_DIM = 512;
-
-function yieldToMainThread(): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, 0));
-}
-
-const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
-
-function bytesToBase64(bytes: Uint8Array): string {
- if (typeof btoa === 'function') {
- const chunkSize = 0x8000;
- let binary = '';
- for (let i = 0; i < bytes.length; i += chunkSize) {
- const slice = bytes.subarray(i, Math.min(i + chunkSize, bytes.length));
- binary += String.fromCharCode(...slice);
- }
- return btoa(binary);
- }
- let out = '';
- for (let i = 0; i < bytes.length; i += 3) {
- const a = bytes[i];
- const b = i + 1 < bytes.length ? bytes[i + 1] : 0;
- const c = i + 2 < bytes.length ? bytes[i + 2] : 0;
- const triple = (a << 16) | (b << 8) | c;
- out += BASE64_ALPHABET[(triple >> 18) & 63];
- out += BASE64_ALPHABET[(triple >> 12) & 63];
- out += i + 1 < bytes.length ? BASE64_ALPHABET[(triple >> 6) & 63] : '=';
- out += i + 2 < bytes.length ? BASE64_ALPHABET[triple & 63] : '=';
- }
- return out;
-}
-
-function toPngDataUrl(bytes: Uint8Array | null | undefined): string | undefined {
- if (!bytes || bytes.byteLength === 0) return undefined;
- const b64 = bytesToBase64(bytes);
- return b64 ? `data:image/png;base64,${b64}` : undefined;
-}
-
-function toSafeZipKey(rawId: string, usedKeys: Set<string>): string {
- let base = rawId.replace(/[^a-zA-Z0-9._-]/g, '_');
- if (!base || base === '.' || base === '..') {
- base = 'layer';
- }
- // Prevent hidden or traversal-looking segments
- base = base.replace(/\.{2,}/g, '_');
- let candidate = base;
- let suffix = 1;
- while (usedKeys.has(candidate)) {
- candidate = `${base}_${suffix++}`;
- }
- usedKeys.add(candidate);
- return candidate;
-}
-
-function isSafeZipPath(path: string): boolean {
- if (!path || path.includes('\0') || path.includes('\\') || path.startsWith('/')) {
- return false;
- }
- const segments = path.split('/');
- for (const seg of segments) {
- if (!seg || seg === '.' || seg === '..') {
- return false;
- }
- }
- return true;
-}
-
-function sanitizeJsonLayer(raw: any): LayerItem {
- const clean: any = Object.create(null);
- for (const key of Object.keys(raw)) {
- if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
- clean[key] = raw[key];
- }
- const normalized: LayerItem = { ...clean };
- if (normalized.maskCanvas && typeof normalized.maskCanvas.getContext !== 'function') {
- normalized.maskCanvas = undefined;
- }
- return normalized;
-}
-
-/**
- * Checks whether binary input begins with `.sora` v2 container magic bytes:
- * - Standard ZIP local file header (`PK\x03\x04`) or empty ZIP (`PK\x05\x06`)
- * - Optional explicit `SORA\x00\x02` wrapper prefix
- */
-export function isSoraV2Bytes(input: Uint8Array | ArrayBuffer): boolean {
- const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
- if (bytes.byteLength < 4) return false;
- // PK\x03\x04 or PK\x05\x06 (ZIP container)
- if (
- bytes[0] === 0x50 &&
- bytes[1] === 0x4b &&
- ((bytes[2] === 0x03 && bytes[3] === 0x04) || (bytes[2] === 0x05 && bytes[3] === 0x06))
- ) {
- return true;
- }
- // Optional SORA\x00\x02 wrapper prefix
- if (
- bytes.byteLength >= 8 &&
- bytes[0] === 0x53 &&
- bytes[1] === 0x4f &&
- bytes[2] === 0x52 &&
- bytes[3] === 0x41 &&
- bytes[4] === 0x00 &&
- bytes[5] === 0x02
- ) {
- return true;
- }
- return false;
-}
-
-function unwrapZipPayload(bytes: Uint8Array): Uint8Array {
- if (
- bytes.byteLength >= 8 &&
- bytes[0] === 0x53 &&
- bytes[1] === 0x4f &&
- bytes[2] === 0x52 &&
- bytes[3] === 0x41 &&
- bytes[4] === 0x00 &&
- bytes[5] === 0x02
- ) {
- return bytes.subarray(8);
- }
- return bytes;
-}
-
-/**
- * Maps Ink Studio BlendMode to ag-psd BlendMode format.
- */
-export function toAgPsdBlendMode(mode: BlendMode): AgPsdBlendMode {
- switch (mode) {
- case 'color-dodge':
- case 'color-dodge-glow':
- return 'color dodge';
- case 'color-burn':
- return 'color burn';
- case 'linear-burn':
- return 'linear burn';
- case 'add-glow':
- return 'linear dodge';
- case 'hard-light':
- return 'hard light';
- case 'soft-light':
- return 'soft light';
- case 'divide':
- return 'divide';
- case 'pass-through':
- return 'pass through';
- case 'normal':
- case 'multiply':
- case 'screen':
- case 'overlay':
- case 'darken':
- case 'lighten':
- case 'difference':
- case 'exclusion':
- return mode;
- default:
- return 'normal';
- }
-}
-
-function extractLayerMaskForPsd(layer: LayerItem): AgPsdMaskData | undefined {
- const maskCanvas = layer.maskCanvas;
- if (!maskCanvas || maskCanvas.width <= 0 || maskCanvas.height <= 0) {
- return undefined;
- }
-
- const mw = maskCanvas.width;
- const mh = maskCanvas.height;
- const maskMeta: AgPsdMaskData = {
- top: 0,
- left: 0,
- bottom: mh,
- right: mw,
- defaultColor: 255,
- disabled: layer.maskEnabled === false,
- positionRelativeToLayer: layer.maskLinked === false,
- };
-
- const ctx = maskCanvas.getContext('2d', { willReadFrequently: true });
- if (ctx && typeof ctx.getImageData === 'function') {
- const src = ctx.getImageData(0, 0, mw, mh).data;
- const out = new Uint8ClampedArray(mw * mh * 4);
- for (let i = 0; i < src.length; i += 4) {
- const lum = Math.round(((0.299 * src[i] + 0.587 * src[i + 1] + 0.114 * src[i + 2]) * src[i + 3]) / 255);
- out[i] = lum;
- out[i + 1] = lum;
- out[i + 2] = lum;
- out[i + 3] = 255;
- }
- maskMeta.imageData = { data: out, width: mw, height: mh };
- } else {
- maskMeta.canvas = maskCanvas;
- }
-
- return maskMeta;
-}
-
-function attachRasterPixelsForPsd(
- target: AgPsdLayer,
- layer: LayerItem,
- dimensions: CanvasDimensions,
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
- tileGrid: SparseTileGrid | undefined,
- tempCanvases: HTMLCanvasElement[]
-): void {
- const isVectorText =
- (layer.type === 'text' && Boolean(layer.textData)) ||
- (layer.type === 'balloon' && Boolean(layer.balloonData));
-
- if (!isVectorText && !layerCanvasesMap.has(layer.id) && tileGrid && tileGrid.hasLayerTiles(layer.id)) {
- const tiles = tileGrid.getLayerTiles(layer.id, 0);
- if (tiles.length === 0) return;
-
- let minX = dimensions.width;
- let minY = dimensions.height;
- let maxX = 0;
- let maxY = 0;
- for (const tile of tiles) {
- const tx0 = tile.tileX * TILE_SIZE;
- const ty0 = tile.tileY * TILE_SIZE;
- if (tx0 < minX) minX = tx0;
- if (ty0 < minY) minY = ty0;
- if (tx0 + TILE_SIZE > maxX) maxX = tx0 + TILE_SIZE;
- if (ty0 + TILE_SIZE > maxY) maxY = ty0 + TILE_SIZE;
- }
- const left = Math.max(0, minX);
- const top = Math.max(0, minY);
- const right = Math.min(dimensions.width, maxX);
- const bottom = Math.min(dimensions.height, maxY);
- if (left < right && top < bottom) {
- const imgData = tileGrid.readImageData(layer.id, left, top, right - left, bottom - top);
- target.left = left;
- target.top = top;
- target.right = right;
- target.bottom = bottom;
- target.imageData = imgData;
- }
- return;
- }
-
- const acq = acquireLayerExportCanvas(layer, dimensions, layerCanvasesMap, tileGrid);
- if (!acq.canvas) return;
- if (acq.isTemporary) tempCanvases.push(acq.canvas);
-
- const w = acq.canvas.width;
- const h = acq.canvas.height;
- if (w <= 0 || h <= 0) return;
-
- const ctx = acq.canvas.getContext('2d', { willReadFrequently: true });
- if (ctx && typeof ctx.getImageData === 'function') {
- const imgData = ctx.getImageData(0, 0, w, h);
- target.left = 0;
- target.top = 0;
- target.right = w;
- target.bottom = h;
- target.imageData = { data: imgData.data, width: w, height: h };
- } else {
- target.canvas = acq.canvas;
- }
-}
-
-function buildPsdLayerTree(
- nodes: LayerTreeNode[],
- dimensions: CanvasDimensions,
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
- tileGrid: SparseTileGrid | undefined,
- tempCanvases: HTMLCanvasElement[]
-): AgPsdLayer[] {
- const result: AgPsdLayer[] = [];
-
- for (let i = nodes.length - 1; i >= 0; i--) {
- const node = nodes[i];
- const layer = node.layer;
- const isFolder = isFolderLikeLayer(layer);
- if (!isFolder && !hasTileBackedLayer(layer)) continue;
-
- const psdLayer: AgPsdLayer = {
- name: layer.name,
- hidden: !layer.visible,
- opacity: Math.max(0, Math.min(1, layer.opacity ?? 1)),
- blendMode: toAgPsdBlendMode(layer.blendMode),
- };
-
- if (layer.clipped) {
- psdLayer.clipping = true;
- }
-
- if (layer.alphaLocked || layer.locked) {
- psdLayer.protected = {
- transparency: Boolean(layer.alphaLocked),
- composite: Boolean(layer.locked),
- position: Boolean(layer.locked),
- };
- if (layer.alphaLocked) {
- psdLayer.transparencyProtected = true;
- }
- }
-
- const mask = extractLayerMaskForPsd(layer);
- if (mask) {
- psdLayer.mask = mask;
- }
-
- if (isFolder) {
- psdLayer.opened = !layer.collapsed;
- psdLayer.children = buildPsdLayerTree(
- node.children,
- dimensions,
- layerCanvasesMap,
- tileGrid,
- tempCanvases
- );
- } else {
- attachRasterPixelsForPsd(
- psdLayer,
- layer,
- dimensions,
- layerCanvasesMap,
- tileGrid,
- tempCanvases
- );
- }
-
- result.push(psdLayer);
- }
-
- return result;
-}
-
-/**
- * Resolves a layer's canvas from either the map or temporarily from SparseTileGrid.
- * Returns `{ canvas, isTemporary }` so caller immediately releases temporary canvases.
- */
-function acquireLayerExportCanvas(
- layer: LayerItem,
- dimensions: CanvasDimensions,
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
- tileGrid?: SparseTileGrid
-): { canvas: HTMLCanvasElement | null; isTemporary: boolean } {
- if (layer.type === 'text' && layer.textData && typeof document !== 'undefined') {
- const temp = document.createElement('canvas');
- temp.width = dimensions.width;
- temp.height = dimensions.height;
- const ctx = temp.getContext('2d');
- if (ctx) renderTextLayerData(ctx, layer.textData);
- return { canvas: temp, isTemporary: true };
- }
- if (layer.type === 'balloon' && layer.balloonData && typeof document !== 'undefined') {
- const temp = document.createElement('canvas');
- temp.width = dimensions.width;
- temp.height = dimensions.height;
- const ctx = temp.getContext('2d');
- if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
- return { canvas: temp, isTemporary: true };
- }
- const existing = layerCanvasesMap.get(layer.id);
- if (existing) {
- return { canvas: existing, isTemporary: false };
- }
- if (tileGrid && tileGrid.hasLayerTiles(layer.id)) {
- const temp = tileGrid.exportLayerToCanvas(layer.id, dimensions.width, dimensions.height);
- return { canvas: temp, isTemporary: true };
- }
- return { canvas: null, isTemporary: false };
-}
-
-// ============================================================================
-// Pixel-Accurate GPU Tiled Export Engine (ViewportCompositor FBO Pipeline)
-// ============================================================================
-
-/**
- * Computes the maximum pixel halo margin required around export tiles so GPU
- * Layer Styles (Stroke, Drop Shadow, Outer Glow) render seamlessly across tile seams.
- */
-export function computeMaxLayerStyleMargin(layers: LayerItem[]): number {
- let maxMargin = 0;
- for (const layer of layers) {
- if (!layer.visible || layer.opacity <= 0.001 || !layer.styles) continue;
- const { stroke, dropShadow, outerGlow } = layer.styles;
- if (stroke?.enabled && stroke.size > 0 && stroke.opacity > 0) {
- maxMargin = Math.max(maxMargin, Math.ceil(stroke.size) + 2);
- }
- if (dropShadow?.enabled && dropShadow.opacity > 0) {
- const extent = Math.ceil((dropShadow.distance || 0) + (dropShadow.blur || 0) * 1.5) + 2;
- maxMargin = Math.max(maxMargin, extent);
- }
- if (outerGlow?.enabled && outerGlow.opacity > 0 && outerGlow.blur > 0) {
- const extent = Math.ceil(outerGlow.blur * 1.5) + 2;
- maxMargin = Math.max(maxMargin, extent);
- }
- }
- return Math.min(MAX_STYLE_MARGIN_PX, Math.max(0, maxMargin));
-}
-
-function inferLayerTileFormat(layer: LayerItem): TileFormat {
- if (layer.expressionColor === 'monochrome') return 'monochrome-1bit';
- if (layer.expressionColor === 'gray') return 'grayscale-8bit';
- return 'color-32bit';
-}
-
-/**
- * Prepares a SparseTileGrid containing all visible tile-backed layers for GPU compositing.
- * Zero-copy fast path when `tileGrid` already holds all visible raster/vector/text/balloon layers.
- */
-function prepareExportTileGrid(
- dimensions: CanvasDimensions,
- layers: LayerItem[],
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
- tileGrid?: SparseTileGrid
-): { grid: SparseTileGrid; isTemporary: boolean } {
- const missingLayers: LayerItem[] = [];
-
- for (const layer of layers) {
- if (!layer.visible || layer.opacity <= 0.001) continue;
- if (!hasTileBackedLayer(layer)) continue;
- const hasTiles = Boolean(tileGrid && tileGrid.hasLayerTiles(layer.id));
- if (hasTiles) continue;
-
- const hasVectorSource =
- (layer.type === 'text' && Boolean(layer.textData)) ||
- (layer.type === 'balloon' && Boolean(layer.balloonData)) ||
- (layer.type === 'vector' && Boolean(layer.vectorStrokes && layer.vectorStrokes.length > 0));
- if (hasVectorSource || layerCanvasesMap.has(layer.id)) {
- missingLayers.push(layer);
- }
- }
-
- if (tileGrid && missingLayers.length === 0) {
- return { grid: tileGrid, isTemporary: false };
- }
-
- const tempGrid = new SparseTileGrid();
- if (tileGrid) {
- // Share existing TileBuffer references without duplicating pixel buffers
- for (const [layerId, fmt] of tileGrid.getAllLayerFormats().entries()) {
- tempGrid.setLayerFormat(layerId, fmt);
- }
- for (const tile of tileGrid.getAllTiles()) {
- if ((tile.lod ?? 0) === 0) {
- tempGrid.setTile(tile.layerId, tile.tileX, tile.tileY, tile);
- }
- }
- }
-
- if (typeof document !== 'undefined') {
- for (const layer of missingLayers) {
- const fmt = inferLayerTileFormat(layer);
- if (layer.type === 'text' && layer.textData) {
- const temp = document.createElement('canvas');
- temp.width = dimensions.width;
- temp.height = dimensions.height;
- const ctx = temp.getContext('2d');
- if (ctx) renderTextLayerData(ctx, layer.textData);
- tempGrid.ingestCanvas(layer.id, temp, fmt);
- releaseTemporaryCanvas(temp);
- } else if (layer.type === 'balloon' && layer.balloonData) {
- const temp = document.createElement('canvas');
- temp.width = dimensions.width;
- temp.height = dimensions.height;
- const ctx = temp.getContext('2d');
- if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
- tempGrid.ingestCanvas(layer.id, temp, fmt);
- releaseTemporaryCanvas(temp);
- } else {
- const existingCanvas = layerCanvasesMap.get(layer.id);
- if (existingCanvas) {
- tempGrid.ingestCanvas(layer.id, existingCanvas, fmt);
- } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
- const temp = document.createElement('canvas');
- temp.width = dimensions.width;
- temp.height = dimensions.height;
- const ctx = temp.getContext('2d');
- if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
- tempGrid.ingestCanvas(layer.id, temp, fmt);
- releaseTemporaryCanvas(temp);
- }
- }
- }
- }
-
- return { grid: tempGrid, isTemporary: true };
-}
-
-/**
- * Ensures any tiles paged out to SSD scratch disk for visible layers are hydrated in RAM
- * before GPU or CPU export begins.
- */
-async function hydratePagedTilesForLayers(
- tileGrid: SparseTileGrid | undefined,
- layers: LayerItem[],
- visibleOnly: boolean
-): Promise<void> {
- if (!tileGrid) return;
- const mm = tileGrid.getMemoryManager();
- if (!mm) return;
-
- for (const layer of layers) {
- if (visibleOnly && (!layer.visible || layer.opacity <= 0.001)) continue;
- if (!hasTileBackedLayer(layer)) continue;
- const tiles = tileGrid.getLayerTiles(layer.id, 0);
- for (const tile of tiles) {
- if (tile.data === null && tile.isPagedToDisk) {
- await mm.requestTileData(tile);
- }
- }
- }
-}
-
-export interface GpuTilePlanEntry {
- tileX: number;
- tileY: number;
- width: number;
- height: number;
- padLeft: number;
- padTop: number;
- padRight: number;
- padBottom: number;
- originX: number;
- originY: number;
- fboWidth: number;
- fboHeight: number;
-}
-
-/**
- * Pure geometry planner for tiled GPU FBO export with seam-free Layer Style halo padding.
- */
-export function buildGpuExportTilePlan(
- docWidth: number,
- docHeight: number,
- maxTileSize: number = SORA_V2_DEFAULT_TILE_EXPORT_SIZE,
- styleMargin: number = 0
-): { fboWidth: number; fboHeight: number; tiles: GpuTilePlanEntry[] } {
- const safeMaxTile = Math.max(256, Math.floor(maxTileSize));
- const clampedMargin = Math.max(0, Math.min(styleMargin, Math.floor((safeMaxTile - 256) / 2)));
- const innerStep = Math.max(256, safeMaxTile - clampedMargin * 2);
-
- const tiles: GpuTilePlanEntry[] = [];
- let maxFboW = 1;
- let maxFboH = 1;
-
- for (let tileY = 0; tileY < docHeight; tileY += innerStep) {
- const height = Math.min(innerStep, docHeight - tileY);
- const padTop = Math.min(clampedMargin, tileY);
- const padBottom = Math.min(clampedMargin, docHeight - (tileY + height));
- const fboHeight = height + padTop + padBottom;
- if (fboHeight > maxFboH) maxFboH = fboHeight;
-
- for (let tileX = 0; tileX < docWidth; tileX += innerStep) {
- const width = Math.min(innerStep, docWidth - tileX);
- const padLeft = Math.min(clampedMargin, tileX);
- const padRight = Math.min(clampedMargin, docWidth - (tileX + width));
- const fboWidth = width + padLeft + padRight;
- if (fboWidth > maxFboW) maxFboW = fboWidth;
-
- tiles.push({
- tileX,
- tileY,
- width,
- height,
- padLeft,
- padTop,
- padRight,
- padBottom,
- originX: tileX - padLeft,
- originY: tileY - padTop,
- fboWidth,
- fboHeight,
- });
- }
- }
-
- return { fboWidth: maxFboW, fboHeight: maxFboH, tiles };
-}
-
-function tryCompositeCanvasGpuSync(
- dimensions: CanvasDimensions,
- layers: LayerItem[],
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
- fillWhiteBackground: boolean,
- tileGrid?: SparseTileGrid,
- options?: CompositeCanvasOptions
-): HTMLCanvasElement | null {
- if (typeof document === 'undefined' || dimensions.width <= 0 || dimensions.height <= 0) {
- return null;
- }
-
- const probeCanvas = document.createElement('canvas');
- const requestedTileSize = options?.tileSize ?? SORA_V2_DEFAULT_TILE_EXPORT_SIZE;
- probeCanvas.width = Math.min(requestedTileSize, dimensions.width);
- probeCanvas.height = Math.min(requestedTileSize, dimensions.height);
-
- const compositor = new ViewportCompositor(probeCanvas, { preserveDrawingBuffer: true });
- if (!compositor.isReady()) {
- compositor.dispose();
- releaseTemporaryCanvas(probeCanvas);
- return null;
- }
-
- const prepared = prepareExportTileGrid(dimensions, layers, layerCanvasesMap, tileGrid);
- const exportCanvas = document.createElement('canvas');
- exportCanvas.width = dimensions.width;
- exportCanvas.height = dimensions.height;
- const dstCtx = exportCanvas.getContext('2d');
-
- try {
- if (!dstCtx) {
- return exportCanvas;
- }
-
- const maxGpuTile = Math.min(requestedTileSize, compositor.getMaxTextureSize());
- const styleMargin = computeMaxLayerStyleMargin(layers);
- const plan = buildGpuExportTilePlan(dimensions.width, dimensions.height, maxGpuTile, styleMargin);
-
- if (probeCanvas.width !== plan.fboWidth) probeCanvas.width = plan.fboWidth;
- if (probeCanvas.height !== plan.fboHeight) probeCanvas.height = plan.fboHeight;
-
- const total = plan.tiles.length;
- for (let i = 0; i < total; i++) {
- const entry = plan.tiles[i];
- const transform: ViewportTransform = {
- pan: {
- x: dimensions.width * 0.5 - entry.originX,
- y: dimensions.height * 0.5 - entry.originY,
- },
- zoom: 1.0,
- rotation: 0,
- flipX: false,
- flipY: false,
- };
-
- compositor.render(layers, transform, dimensions, prepared.grid, {
- dimensions,
- colorMode: options?.colorMode,
- showCheckerboard: false,
- transparentBackground: !fillWhiteBackground,
- bypassStackCache: true,
- devicePixelRatio: 1,
- });
-
- dstCtx.drawImage(
- probeCanvas,
- entry.padLeft,
- entry.padTop,
- entry.width,
- entry.height,
- entry.tileX,
- entry.tileY,
- entry.width,
- entry.height
- );
-
- if (options?.onProgress) {
- const done = i + 1;
- options.onProgress({
- phase: 'compositing',
- current: done,
- total,
- percent: Math.round((done / total) * 100),
- message: `Compositing GPU tile ${done}/${total}...`,
- });
- }
- }
-
- return exportCanvas;
- } catch (err) {
- console.warn('GPU tiled export failed, falling back to CPU compositor:', err);
- releaseTemporaryCanvas(exportCanvas);
- return null;
- } finally {
- compositor.dispose();
- releaseTemporaryCanvas(probeCanvas);
- if (prepared.isTemporary) {
- prepared.grid.clearAll();
- }
- }
-}
-
-/**
- * Asynchronous tiled GPU compositor with paged-tile hydration, progress reporting,
- * and event-loop yields between tiles. Falls back to CPU only when WebGL2 is unavailable.
- */
-export async function compositeCanvasAsync(
- dimensions: CanvasDimensions,
- layers: LayerItem[],
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
- getEffectiveOpacity: (layer: LayerItem) => number,
- isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
- fillWhiteBackground: boolean = false,
- tileGrid?: SparseTileGrid,
- options?: CompositeCanvasOptions
-): Promise<{ canvas: HTMLCanvasElement; usedGpu: boolean }> {
- await hydratePagedTilesForLayers(tileGrid, layers, true);
-
- if (typeof document !== 'undefined' && dimensions.width > 0 && dimensions.height > 0) {
- const requestedTileSize = options?.tileSize ?? SORA_V2_DEFAULT_TILE_EXPORT_SIZE;
- const probeCanvas = document.createElement('canvas');
- probeCanvas.width = Math.min(requestedTileSize, dimensions.width);
- probeCanvas.height = Math.min(requestedTileSize, dimensions.height);
-
- const compositor = new ViewportCompositor(probeCanvas, { preserveDrawingBuffer: true });
- if (compositor.isReady()) {
- const prepared = prepareExportTileGrid(dimensions, layers, layerCanvasesMap, tileGrid);
- const exportCanvas = document.createElement('canvas');
- exportCanvas.width = dimensions.width;
- exportCanvas.height = dimensions.height;
- const dstCtx = exportCanvas.getContext('2d');
-
- try {
- if (dstCtx) {
- const maxGpuTile = Math.min(requestedTileSize, compositor.getMaxTextureSize());
- const styleMargin = computeMaxLayerStyleMargin(layers);
- const plan = buildGpuExportTilePlan(dimensions.width, dimensions.height, maxGpuTile, styleMargin);
-
- if (probeCanvas.width !== plan.fboWidth) probeCanvas.width = plan.fboWidth;
- if (probeCanvas.height !== plan.fboHeight) probeCanvas.height = plan.fboHeight;
-
- const total = plan.tiles.length;
- for (let i = 0; i < total; i++) {
- const entry = plan.tiles[i];
- const transform: ViewportTransform = {
- pan: {
- x: dimensions.width * 0.5 - entry.originX,
- y: dimensions.height * 0.5 - entry.originY,
- },
- zoom: 1.0,
- rotation: 0,
- flipX: false,
- flipY: false,
- };
-
- compositor.render(layers, transform, dimensions, prepared.grid, {
- dimensions,
- colorMode: options?.colorMode,
- showCheckerboard: false,
- transparentBackground: !fillWhiteBackground,
- bypassStackCache: true,
- devicePixelRatio: 1,
- });
-
- dstCtx.drawImage(
- probeCanvas,
- entry.padLeft,
- entry.padTop,
- entry.width,
- entry.height,
- entry.tileX,
- entry.tileY,
- entry.width,
- entry.height
- );
-
- if (options?.onProgress) {
- const done = i + 1;
- options.onProgress({
- phase: 'compositing',
- current: done,
- total,
- percent: Math.round((done / total) * 85),
- message: `Compositing GPU tile ${done}/${total}...`,
- });
- }
-
- if (i + 1 < total) {
- await yieldToMainThread();
- }
- }
- }
- return { canvas: exportCanvas, usedGpu: true };
- } catch (err) {
- console.warn('Async GPU tiled export failed, falling back to CPU compositor:', err);
- releaseTemporaryCanvas(exportCanvas);
- } finally {
- compositor.dispose();
- releaseTemporaryCanvas(probeCanvas);
- if (prepared.isTemporary) {
- prepared.grid.clearAll();
- }
- }
- } else {
- compositor.dispose();
- releaseTemporaryCanvas(probeCanvas);
- }
- }
-
- const cpuCanvas = compositeCanvasCpuFallback(
- dimensions,
- layers,
- layerCanvasesMap,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- fillWhiteBackground,
- tileGrid
- );
- return { canvas: cpuCanvas, usedGpu: false };
-}
-
-/**
- * Creates a reusable GPU region renderer (with CPU fallback) for rendering arbitrary
- * document strips (e.g., tall 800x50,000px Webtoon chapter slices without allocating
- * a monolithic full-height canvas). Caller MUST call `dispose()` when done.
- */
-export function createDocumentRegionRenderer(
- dimensions: CanvasDimensions,
- layers: LayerItem[],
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
- getEffectiveOpacity: (layer: LayerItem) => number,
- isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
- tileGrid?: SparseTileGrid,
- options?: { colorMode?: CanvasColorMode; maxTileSize?: number }
-): {
- usedGpu: boolean;
- renderRegion: (
- x: number,
- y: number,
- width: number,
- height: number,
- targetCanvas: HTMLCanvasElement,
- fillWhiteBackground: boolean
- ) => void;
- dispose: () => void;
-} {
- const maxTileSize = options?.maxTileSize ?? SORA_V2_DEFAULT_TILE_EXPORT_SIZE;
- const styleMargin = computeMaxLayerStyleMargin(layers);
- const prepared = prepareExportTileGrid(dimensions, layers, layerCanvasesMap, tileGrid);
-
- let gpuCanvas: HTMLCanvasElement | null = null;
- let compositor: ViewportCompositor | null = null;
- let usedGpu = false;
- let cpuFullCache: HTMLCanvasElement | null = null;
- let cpuFullCacheWhite = false;
-
- if (typeof document !== 'undefined') {
- gpuCanvas = document.createElement('canvas');
- gpuCanvas.width = Math.min(maxTileSize, Math.max(1, dimensions.width));
- gpuCanvas.height = Math.min(maxTileSize, Math.max(1, dimensions.height));
- const candidate = new ViewportCompositor(gpuCanvas, { preserveDrawingBuffer: true });
- if (candidate.isReady()) {
- compositor = candidate;
- usedGpu = true;
- } else {
- candidate.dispose();
- releaseTemporaryCanvas(gpuCanvas);
- gpuCanvas = null;
- }
- }
-
- const renderRegion = (
- x: number,
- y: number,
- width: number,
- height: number,
- targetCanvas: HTMLCanvasElement,
- fillWhiteBackground: boolean
- ): void => {
- const dstCtx = targetCanvas.getContext('2d');
- if (!dstCtx || width <= 0 || height <= 0) return;
-
- if (fillWhiteBackground) {
- dstCtx.fillStyle = '#ffffff';
- dstCtx.fillRect(0, 0, width, height);
- } else {
- dstCtx.clearRect(0, 0, width, height);
- }
-
- if (compositor && gpuCanvas) {
- const maxGpuTile = Math.min(maxTileSize, compositor.getMaxTextureSize());
- const clampedMargin = Math.max(0, Math.min(styleMargin, Math.floor((maxGpuTile - 256) / 2)));
- const innerStep = Math.max(256, maxGpuTile - clampedMargin * 2);
-
- for (let sy = 0; sy < height; sy += innerStep) {
- const subH = Math.min(innerStep, height - sy);
- const docY = y + sy;
- const padTop = Math.min(clampedMargin, docY);
- const padBottom = Math.min(clampedMargin, Math.max(0, dimensions.height - (docY + subH)));
-
- for (let sx = 0; sx < width; sx += innerStep) {
- const subW = Math.min(innerStep, width - sx);
- const docX = x + sx;
- const padLeft = Math.min(clampedMargin, docX);
- const padRight = Math.min(clampedMargin, Math.max(0, dimensions.width - (docX + subW)));
-
- const fboW = subW + padLeft + padRight;
- const fboH = subH + padTop + padBottom;
- if (gpuCanvas.width < fboW) gpuCanvas.width = fboW;
- if (gpuCanvas.height < fboH) gpuCanvas.height = fboH;
-
- const transform: ViewportTransform = {
- pan: {
- x: dimensions.width * 0.5 - (docX - padLeft),
- y: dimensions.height * 0.5 - (docY - padTop),
- },
- zoom: 1.0,
- rotation: 0,
- flipX: false,
- flipY: false,
- };
-
- compositor.render(layers, transform, dimensions, prepared.grid, {
- dimensions,
- colorMode: options?.colorMode,
- showCheckerboard: false,
- transparentBackground: !fillWhiteBackground,
- bypassStackCache: true,
- devicePixelRatio: 1,
- });
-
- dstCtx.drawImage(gpuCanvas, padLeft, padTop, subW, subH, sx, sy, subW, subH);
- }
- }
- return;
- }
-
- // CPU fallback when WebGL2 is unavailable
- if (!cpuFullCache || cpuFullCacheWhite !== fillWhiteBackground) {
- if (cpuFullCache) releaseTemporaryCanvas(cpuFullCache);
- cpuFullCache = compositeCanvasCpuFallback(
- dimensions,
- layers,
- layerCanvasesMap,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- fillWhiteBackground,
- tileGrid
- );
- cpuFullCacheWhite = fillWhiteBackground;
- }
- dstCtx.drawImage(cpuFullCache, x, y, width, height, 0, 0, width, height);
- };
-
- const dispose = (): void => {
- if (compositor) {
- compositor.dispose();
- compositor = null;
- }
- if (gpuCanvas) {
- releaseTemporaryCanvas(gpuCanvas);
- gpuCanvas = null;
- }
- if (cpuFullCache) {
- releaseTemporaryCanvas(cpuFullCache);
- cpuFullCache = null;
- }
- if (prepared.isTemporary) {
- prepared.grid.clearAll();
- }
- };
-
- return { usedGpu, renderRegion, dispose };
-}
-
-/**
- * CPU 2D fallback compositor — used strictly when WebGL2 is unavailable.
- */
-export function compositeCanvasCpuFallback(
- dimensions: CanvasDimensions,
- layers: LayerItem[],
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
- getEffectiveOpacity: (layer: LayerItem) => number,
- isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
- fillWhiteBackground: boolean = false,
- tileGrid?: SparseTileGrid
-): HTMLCanvasElement {
- const exportCanvas = document.createElement('canvas');
- exportCanvas.width = dimensions.width;
- exportCanvas.height = dimensions.height;
- const ctx = exportCanvas.getContext('2d');
- if (!ctx) return exportCanvas;
-
- if (fillWhiteBackground) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, dimensions.width, dimensions.height);
- }
-
- const getMaskedLayerCanvas = (
- layer: LayerItem,
- srcCanvas: HTMLCanvasElement
- ): { canvas: HTMLCanvasElement; isTemporary: boolean } => {
- if (!layer.maskCanvas || layer.maskEnabled === false) {
- return { canvas: srcCanvas, isTemporary: false };
- }
- const masked = document.createElement('canvas');
- masked.width = dimensions.width;
- masked.height = dimensions.height;
- const mCtx = masked.getContext('2d');
- const maskCtx = layer.maskCanvas.getContext('2d', { willReadFrequently: true });
- if (!mCtx || !maskCtx) {
- releaseTemporaryCanvas(masked);
- return { canvas: srcCanvas, isTemporary: false };
- }
- mCtx.drawImage(srcCanvas, 0, 0);
- const imgData = mCtx.getImageData(0, 0, dimensions.width, dimensions.height);
- const maskData = maskCtx.getImageData(0, 0, dimensions.width, dimensions.height).data;
- const d = imgData.data;
- for (let i = 0; i < d.length; i += 4) {
- if (d[i + 3] === 0) continue;
- const maskLum = ((0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255) * (maskData[i + 3] / 255);
- d[i + 3] = Math.round(d[i + 3] * maskLum);
- }
- mCtx.putImageData(imgData, 0, 0);
- return { canvas: masked, isTemporary: true };
- };
-
- const renderTreeNodes = (
- targetCtx: CanvasRenderingContext2D,
- nodes: LayerTreeNode[],
- opacityMul: number
- ) => {
- const renderOrder = nodes.slice().reverse();
- const groups = groupTreeNodesForCompositing(renderOrder);
-
- for (const group of groups) {
- const baseNode = group.baseNode;
- const baseLayer = baseNode.layer;
- if (!baseLayer.visible || baseLayer.opacity <= 0.001) continue;
-
- if (baseLayer.type === 'frame-folder') {
- const folderAlpha = opacityMul * baseLayer.opacity;
- const frames = (baseLayer.comicFrames || []).filter((f) => f.polygon.length >= 3);
- const shouldClip = frames.length > 0 && frames.some((f) => f.clipChildren !== false);
- const folderCanvas = document.createElement('canvas');
- folderCanvas.width = dimensions.width;
- folderCanvas.height = dimensions.height;
- const fCtx = folderCanvas.getContext('2d');
- if (fCtx) {
- fCtx.save();
- if (shouldClip) {
- applyMultiFrameClip(fCtx, frames);
- }
- for (const frame of frames) {
- if (frame.fillBackground !== false) {
- fCtx.fillStyle = frame.fillColor || '#ffffff';
- fCtx.beginPath();
- fCtx.moveTo(frame.polygon[0].x, frame.polygon[0].y);
- for (let i = 1; i < frame.polygon.length; i++) {
- fCtx.lineTo(frame.polygon[i].x, frame.polygon[i].y);
- }
- fCtx.closePath();
- fCtx.fill();
- }
- }
- if (baseNode.children.length > 0) {
- renderTreeNodes(fCtx, baseNode.children, 1.0);
- }
- fCtx.restore();
- for (const frame of frames) {
- renderFrameBorder(fCtx, frame, false);
- }
- targetCtx.save();
- targetCtx.globalAlpha = Math.max(0, Math.min(1, folderAlpha));
- const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;
- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);
- targetCtx.drawImage(folderCanvas, 0, 0);
- targetCtx.restore();
- }
- releaseTemporaryCanvas(folderCanvas);
- continue;
- }
-
- if (baseLayer.type === 'folder') {
- const folderAlpha = opacityMul * baseLayer.opacity;
- if (baseLayer.blendMode === 'pass-through') {
- if (baseNode.children.length > 0) {
- renderTreeNodes(targetCtx, baseNode.children, folderAlpha);
- }
- } else {
- const folderCanvas = document.createElement('canvas');
- folderCanvas.width = dimensions.width;
- folderCanvas.height = dimensions.height;
- const fCtx = folderCanvas.getContext('2d');
- if (fCtx) {
- if (baseNode.children.length > 0) {
- renderTreeNodes(fCtx, baseNode.children, 1.0);
- }
- targetCtx.save();
- targetCtx.globalAlpha = Math.max(0, Math.min(1, folderAlpha));
- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
- targetCtx.drawImage(folderCanvas, 0, 0);
- targetCtx.restore();
- }
- releaseTemporaryCanvas(folderCanvas);
- }
- continue;
- }
-
- if (!isLayerEffectivelyVisible(baseLayer)) continue;
-
- if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
- const imgData = targetCtx.getImageData(0, 0, dimensions.width, dimensions.height);
- applyAdjustment(
- imgData,
- baseLayer.adjustmentData,
- baseLayer.maskEnabled !== false ? baseLayer.maskCanvas : undefined,
- baseLayer.opacity * opacityMul
- );
- targetCtx.putImageData(imgData, 0, 0);
- continue;
- }
-
- const baseAcq = acquireLayerExportCanvas(baseLayer, dimensions, layerCanvasesMap, tileGrid);
- if (!baseAcq.canvas) continue;
- const maskedBase = getMaskedLayerCanvas(baseLayer, baseAcq.canvas);
-
- const activeClipped = group.clippedNodes
- .map((n) => n.layer)
- .filter((cl) => !isFolderLikeLayer(cl) && cl.type !== 'adjustment' && cl.visible && cl.opacity > 0.001);
-
- if (activeClipped.length === 0) {
- targetCtx.save();
- targetCtx.globalAlpha = Math.max(0, Math.min(1, baseLayer.opacity * opacityMul));
- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
- targetCtx.drawImage(maskedBase.canvas, 0, 0);
- targetCtx.restore();
- } else {
- const groupCanvas = document.createElement('canvas');
- groupCanvas.width = dimensions.width;
- groupCanvas.height = dimensions.height;
- const gCtx = groupCanvas.getContext('2d');
- if (gCtx) {
- gCtx.save();
- gCtx.globalAlpha = Math.max(0, Math.min(1, baseLayer.opacity * opacityMul));
- gCtx.drawImage(maskedBase.canvas, 0, 0);
- gCtx.restore();
-
- for (const clipped of activeClipped) {
- const clipAcq = acquireLayerExportCanvas(clipped, dimensions, layerCanvasesMap, tileGrid);
- if (!clipAcq.canvas) continue;
- const maskedClip = getMaskedLayerCanvas(clipped, clipAcq.canvas);
-
- gCtx.save();
- gCtx.globalAlpha = Math.max(0, Math.min(1, clipped.opacity * opacityMul));
- gCtx.globalCompositeOperation = 'source-atop';
- gCtx.drawImage(maskedClip.canvas, 0, 0);
- gCtx.restore();
-
- if (maskedClip.isTemporary) releaseTemporaryCanvas(maskedClip.canvas);
- if (clipAcq.isTemporary) releaseTemporaryCanvas(clipAcq.canvas);
- }
-
- targetCtx.save();
- targetCtx.globalAlpha = 1.0;
- targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
- targetCtx.drawImage(groupCanvas, 0, 0);
- targetCtx.restore();
- }
- releaseTemporaryCanvas(groupCanvas);
- }
-
- if (maskedBase.isTemporary) releaseTemporaryCanvas(maskedBase.canvas);
- if (baseAcq.isTemporary) releaseTemporaryCanvas(baseAcq.canvas);
- }
- };
-
- const tree = buildLayerTree(layers);
- renderTreeNodes(ctx, tree, 1.0);
- void getEffectiveOpacity;
-
- return exportCanvas;
-}
-
-/**
- * Composites all visible layers using tiled offscreen WebGL2 rendering via `ViewportCompositor`
- * (preserving 100% of GPU blend modes, Layer Styles, Screentones, Layer Color Tint,
- * Expression Color, Frame Folders, and Adjustment Layers).
- * Falls back to 2D CPU compositing strictly when WebGL2 is unavailable.
- */
-export function compositeCanvas(
- dimensions: CanvasDimensions,
- layers: LayerItem[],
- layerCanvasesMap: Map<string, HTMLCanvasElement>,
- getEffectiveOpacity: (layer: LayerItem) => number,
- isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
- fillWhiteBackground: boolean = false,
- tileGrid?: SparseTileGrid,
- options?: CompositeCanvasOptions
-): HTMLCanvasElement {
- const gpuResult = tryCompositeCanvasGpuSync(
- dimensions,
- layers,
- layerCanvasesMap,
- fillWhiteBackground,
- tileGrid,
- options
- );
- if (gpuResult) {
- return gpuResult;
- }
-
- return compositeCanvasCpuFallback(
- dimensions,
- layers,
- layerCanvasesMap,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- fillWhiteBackground,
- tileGrid
- );
-}
-
-/**
- * Pixel-accurate tiled GPU image exporter (PNG / JPEG / WebP) with automatic
- * CPU fallback when WebGL2 is unavailable.
- */
-export async function exportImage(
- data: SaveDocumentData,
- options: ExportImageOptions = {}
-): Promise<ExportImageResult> {
- const format = options.format ?? 'png';
- const isJpeg = format === 'jpg' || format === 'jpeg';
- const isWebp = format === 'webp';
- const mimeType = isJpeg ? 'image/jpeg' : isWebp ? 'image/webp' : 'image/png';
- const quality = isJpeg || isWebp ? (options.quality ?? 0.92) : undefined;
- const fillWhite = options.fillWhiteBackground ?? isJpeg;
- const tileGrid =
- data.tileGrid ??
- (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : documentStore.getActiveTileGrid());
-
- const onProgress = options.onProgress ?? data.onProgress;
-
- const { canvas, usedGpu } = await compositeCanvasAsync(
- data.dimensions,
- data.layers,
- data.layerCanvasesMap,
- data.getEffectiveOpacity,
- data.isLayerEffectivelyVisible,
- fillWhite,
- tileGrid,
- {
- tileSize: options.tileSize ?? SORA_V2_DEFAULT_TILE_EXPORT_SIZE,
- colorMode: data.colorMode,
- onProgress,
- }
- );
-
- try {
- onProgress?.({
- phase: 'encoding',
- current: 1,
- total: 1,
- percent: 92,
- message: `Encoding ${format.toUpperCase()}...`,
- });
- const blob = await canvasToBlob(canvas, mimeType, quality);
- onProgress?.({
- phase: 'done',
- current: 1,
- total: 1,
- percent: 100,
- message: 'Export complete',
- });
- return {
- blob,
- mimeType,
- width: data.dimensions.width,
- height: data.dimensions.height,
- usedGpu,
- };
- } finally {
- releaseTemporaryCanvas(canvas);
- }
-}
-
-/**
- * Converts a canvas element into a Blob with the specified mime-type.
- */
-export function canvasToBlob(
- canvas: HTMLCanvasElement,
- mimeType: string = 'image/png',
- quality?: number
-): Promise<Blob> {
- return new Promise((resolve, reject) => {
- canvas.toBlob(
- (blob) => {
- if (blob) resolve(blob);
- else reject(new Error('Canvas toBlob failed'));
- },
- mimeType,
- quality
- );
- });
-}
-
-// ============================================================================
-// Binary `.sora` v2 Container (fflate ZIP) & Legacy v1.2 JSON Support
-// ============================================================================
-
-export interface SerializedSoraProject {
- app: string;
- version: string;
- name: string;
- dimensions: CanvasDimensions;
- colorMode: CanvasColorMode;
- layers: Array<Omit<LayerItem, 'maskCanvas'>>;
- canvases: Record<string, string>;
- masks: Record<string, string>;
-}
-
-/**
- * Legacy v1.2 JSON serializer — kept exported for backward compatibility and tests.
- */
-export function buildSoraProjectPayload(
- data: SaveDocumentData,
- tileGrid?: SparseTileGrid
-): SerializedSoraProject {
- const layerImages: Record<string, string> = {};
- const maskImages: Record<string, string> = {};
- const serializableLayers = data.layers.map((l) => {
- if (hasTileBackedLayer(l)) {
- const acq = acquireLayerExportCanvas(l, data.dimensions, data.layerCanvasesMap, tileGrid);
- if (acq.canvas && typeof acq.canvas.toDataURL === 'function') {
- layerImages[l.id] = acq.canvas.toDataURL('image/png');
- if (acq.isTemporary) releaseTemporaryCanvas(acq.canvas);
- }
- }
- if (l.maskCanvas && typeof l.maskCanvas.toDataURL === 'function') {
- maskImages[l.id] = l.maskCanvas.toDataURL('image/png');
- }
- const { maskCanvas: _mc, ...rest } = l;
- return rest;
- });
-
- return {
- app: 'Ink Studio',
- version: '1.2',
- name: data.name,
- dimensions: data.dimensions,
- colorMode: data.colorMode,
- layers: serializableLayers,
- canvases: layerImages,
- masks: maskImages,
- };
-}
-
-/**
- * Pure parser for legacy `.sora` / `.ink` v1.x JSON strings.
- */
-export function parseSoraProjectJson(jsonText: string): SerializedSoraProject {
- const cleanText = jsonText.charCodeAt(0) === 0xfeff ? jsonText.slice(1) : jsonText;
- const parsed = JSON.parse(cleanText);
- if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.layers)) {
- throw new Error('Invalid .sora project payload: missing layers array');
- }
- const layers = parsed.layers.map((l: any) => sanitizeJsonLayer(l));
- return {
- app: typeof parsed.app === 'string' ? parsed.app : 'Ink Studio',
- version: typeof parsed.version === 'string' ? parsed.version : '1.0',
- name: typeof parsed.name === 'string' ? parsed.name : 'Untitled',
- dimensions: {
- width: Math.max(1, Math.min(MAX_DOCUMENT_DIM, Number(parsed.dimensions?.width) || 1440)),
- height: Math.max(1, Math.min(MAX_DOCUMENT_DIM, Number(parsed.dimensions?.height) || 900)),
- dpi: Number(parsed.dimensions?.dpi) || 300,
- },
- colorMode: parsed.colorMode || 'color',
- layers,
- canvases: parsed.canvases && typeof parsed.canvases === 'object' ? parsed.canvases : {},
- masks: parsed.masks && typeof parsed.masks === 'object' ? parsed.masks : {},
- };
-}
-
-function encodeNativeTileRecord(tile: TileBuffer, rawBytes: Uint8Array): Uint8Array {
- const fmtByte = SORA_V2_FORMAT_TO_BYTE[tile.format] ?? 2;
- const out = new Uint8Array(TILE_BINARY_HEADER_BYTES + rawBytes.byteLength);
- const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
- view.setUint8(0, fmtByte);
- view.setUint32(1, tile.version >>> 0, true);
- view.setUint32(5, rawBytes.byteLength >>> 0, true);
- out.set(rawBytes, TILE_BINARY_HEADER_BYTES);
- return out;
-}
-
-function decodeNativeTileRecord(
- layerId: string,
- tileX: number,
- tileY: number,
- payload: Uint8Array
-): TileBuffer {
- if (payload.byteLength < TILE_BINARY_HEADER_BYTES) {
- throw new Error(`Corrupted .sora v2 tile (${layerId} ${tileX}_${tileY}): header truncated`);
- }
- const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
- const fmtByte = view.getUint8(0);
- const format = SORA_V2_BYTE_TO_FORMAT[fmtByte];
- if (!format) {
- throw new Error(`Corrupted .sora v2 tile (${layerId} ${tileX}_${tileY}): unknown format byte ${fmtByte}`);
- }
- const version = view.getUint32(1, true);
- const dataLen = view.getUint32(5, true);
- const expectedLen = getTileByteSize(format);
- if (dataLen !== expectedLen || payload.byteLength !== TILE_BINARY_HEADER_BYTES + expectedLen) {
- throw new Error(
- `Corrupted .sora v2 tile (${layerId} ${tileX}_${tileY}): length mismatch (expected ${expectedLen}, got ${dataLen}/${payload.byteLength - TILE_BINARY_HEADER_BYTES})`
- );
- }
- const data = new Uint8Array(expectedLen);
- data.set(payload.subarray(TILE_BINARY_HEADER_BYTES, TILE_BINARY_HEADER_BYTES + expectedLen));
- return {
- layerId,
- tileX,
- tileY,
- format,
- data,
- dirty: true,
- version: version || 1,
- isPagedToDisk: false,
- lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
- lod: 0,
- };
-}
-
-function encodeMaskBinary(maskCanvas: HTMLCanvasElement): { width: number; height: number; record: Uint8Array } | null {
- const w = maskCanvas.width;
- const h = maskCanvas.height;
- if (w <= 0 || h <= 0 || w > MAX_DOCUMENT_DIM || h > MAX_DOCUMENT_DIM) return null;
- const ctx = maskCanvas.getContext('2d', { willReadFrequently: true });
- if (!ctx || typeof ctx.getImageData !== 'function') return null;
-
- const src = ctx.getImageData(0, 0, w, h).data;
- const pixelCount = w * h;
- const record = new Uint8Array(MASK_BINARY_HEADER_BYTES + pixelCount);
- const view = new DataView(record.buffer, record.byteOffset, record.byteLength);
- view.setUint32(0, w >>> 0, true);
- view.setUint32(4, h >>> 0, true);
-
- for (let p = 0, i = 0; p < pixelCount; p++, i += 4) {
- record[MASK_BINARY_HEADER_BYTES + p] = Math.round(
- ((0.299 * src[i] + 0.587 * src[i + 1] + 0.114 * src[i + 2]) * src[i + 3]) / 255
- );
- }
- return { width: w, height: h, record };
-}
-
-function decodeMaskBinary(payload: Uint8Array): { width: number; height: number; data: Uint8Array } {
- if (payload.byteLength < MASK_BINARY_HEADER_BYTES) {
- throw new Error('Corrupted .sora v2 mask: header truncated');
- }
- const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
- const width = view.getUint32(0, true);
- const height = view.getUint32(4, true);
- if (width === 0 || height === 0 || width > MAX_DOCUMENT_DIM || height > MAX_DOCUMENT_DIM) {
- throw new Error(`Invalid .sora v2 mask dimensions: ${width}x${height}`);
- }
- const expectedPixels = width * height;
- if (payload.byteLength !== MASK_BINARY_HEADER_BYTES + expectedPixels) {
- throw new Error(
- `Corrupted .sora v2 mask: expected ${expectedPixels} bytes, got ${payload.byteLength - MASK_BINARY_HEADER_BYTES}`
- );
- }
- const data = new Uint8Array(expectedPixels);
- data.set(payload.subarray(MASK_BINARY_HEADER_BYTES));
- return { width, height, data };
-}
-
-function createMaskCanvasFromAlpha(width: number, height: number, alpha: Uint8Array): HTMLCanvasElement | undefined {
- if (typeof document === 'undefined') return undefined;
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d');
- if (!ctx || typeof ctx.putImageData !== 'function') return undefined;
-
- const rgba = new Uint8ClampedArray(width * height * 4);
- for (let p = 0, i = 0; p < alpha.length; p++, i += 4) {
- const v = alpha[p];
- rgba[i] = v;
- rgba[i + 1] = v;
- rgba[i + 2] = v;
- rgba[i + 3] = 255;
- }
- if (typeof ImageData !== 'undefined') {
- ctx.putImageData(new ImageData(rgba, width, height), 0, 0);
- } else if (typeof ctx.createImageData === 'function') {
- const imgData = ctx.createImageData(width, height);
- imgData.data.set(rgba);
- ctx.putImageData(imgData, 0, 0);
- }
- return canvas;
-}
-
-async function generatePreviewPng(
- data: SaveDocumentData,
- tileGrid: SparseTileGrid | undefined
-): Promise<{ bytes: Uint8Array; width: number; height: number } | null> {
- if (typeof document === 'undefined' || data.dimensions.width <= 0 || data.dimensions.height <= 0) {
- return null;
- }
- const scale = Math.min(1, PREVIEW_MAX_DIM / Math.max(data.dimensions.width, data.dimensions.height));
- const outW = Math.max(1, Math.round(data.dimensions.width * scale));
- const outH = Math.max(1, Math.round(data.dimensions.height * scale));
- const previewCanvas = document.createElement('canvas');
- previewCanvas.width = outW;
- previewCanvas.height = outH;
-
- if (typeof previewCanvas.toBlob !== 'function') {
- releaseTemporaryCanvas(previewCanvas);
- return null;
- }
-
- try {
- if (tileGrid) {
- ViewportCompositor.renderLowResPreview(previewCanvas, data.layers, data.dimensions, tileGrid, {
- showCheckerboard: false,
- });
- } else {
- const ctx = previewCanvas.getContext('2d');
- if (!ctx) return null;
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, outW, outH);
- for (let i = data.layers.length - 1; i >= 0; i--) {
- const layer = data.layers[i];
- if (!layer.visible || layer.opacity <= 0.001) continue;
- const src = data.layerCanvasesMap.get(layer.id);
- if (!src) continue;
- ctx.save();
- ctx.globalAlpha = Math.max(0, Math.min(1, layer.opacity));
- ctx.drawImage(src, 0, 0, outW, outH);
- ctx.restore();
- }
- }
-
- const blob = await canvasToBlob(previewCanvas, 'image/png');
- const buf = await blob.arrayBuffer();
- const bytes = new Uint8Array(buf);
- if (bytes.byteLength === 0) return null;
- return { bytes, width: outW, height: outH };
- } catch {
- return null;
- } finally {
- releaseTemporaryCanvas(previewCanvas);
- }
-}
-
-function concatUint8Arrays(chunks: Uint8Array[]): Uint8Array {
- let total = 0;
- for (const c of chunks) total += c.byteLength;
- const out = new Uint8Array(total);
- let offset = 0;
- for (const c of chunks) {
- out.set(c, offset);
- offset += c.byteLength;
- }
- return out;
-}
-
-/**
- * Serializes a document into the compact binary `.sora` v2 ZIP container:
- * - `manifest.json` (metadata: document, layers, folders, masks, vectors, text, balloons, perspective, animation, timelapse)
- * - `preview.png` (downscaled preview for Recent Documents)
- * - `tiles/<layerKey>/<tx>_<ty>.bin` (native 1-bit/8-bit/32-bit SparseTileGrid buffers, zero `toDataURL`, zero full-canvas assembly)
- * - `masks/<layerKey>.bin` (8-bit mask luminance buffers)
- *
- * Uses chunked non-blocking streaming compression via `fflate.Zip` with progress reporting.
- */
-export async function serializeSoraV2(
- data: SaveDocumentData,
- tileGrid?: SparseTileGrid
-): Promise<{
- bytes: Uint8Array;
- previewBytes: Uint8Array | null;
- previewDataUrl?: string;
- manifest: SoraV2Manifest;
-}> {
- const onProgress = data.onProgress;
- const tileCompressionLevel = data.compressionLevel ?? 3;
- const resolvedGrid =
- tileGrid ??
- data.tileGrid ??
- (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : undefined);
-
- onProgress?.({
- phase: 'preparing',
- current: 0,
- total: 1,
- percent: 2,
- message: 'Preparing project metadata...',
- });
-
- const usedKeys = new Set<string>();
- const layerTileKeys: Record<string, string> = {};
- const layerFormats: Record<string, TileFormat> = {};
- const masksMeta: Record<string, { width: number; height: number; format: 'alpha-8bit' }> = {};
- const encodedMasks: Array<{ path: string; record: Uint8Array }> = [];
-
- // Fallback temporary tile grid strictly for legacy layers only present in layerCanvasesMap
- let fallbackTempGrid: SparseTileGrid | null = null;
-
- type PendingTileSource = {
- path: string;
- tile: TileBuffer;
- sourceGrid: SparseTileGrid;
- };
- const pendingTiles: PendingTileSource[] = [];
-
- const serializableLayers: Array<Omit<LayerItem, 'maskCanvas'>> = [];
-
- for (const layer of data.layers) {
- const safeKey = toSafeZipKey(layer.id, usedKeys);
- layerTileKeys[layer.id] = safeKey;
-
- if (hasTileBackedLayer(layer)) {
- const gridHasTiles = Boolean(resolvedGrid && resolvedGrid.hasLayerTiles(layer.id));
- if (resolvedGrid && gridHasTiles) {
- const tiles = resolvedGrid.getLayerTiles(layer.id, 0);
- const fmt = tiles[0]?.format ?? resolvedGrid.getLayerFormat(layer.id);
- layerFormats[layer.id] = fmt;
- for (const tile of tiles) {
- pendingTiles.push({
- path: `tiles/${safeKey}/${tile.tileX}_${tile.tileY}.bin`,
- tile,
- sourceGrid: resolvedGrid,
- });
- }
- } else {
- const fmt = resolvedGrid?.getLayerFormat(layer.id) ?? inferLayerTileFormat(layer);
- layerFormats[layer.id] = fmt;
-
- // Legacy fallback when raster data exists only on layerCanvasesMap (no toDataURL!)
- const canvas = data.layerCanvasesMap.get(layer.id);
- if (canvas && canvas.width > 0 && canvas.height > 0) {
- if (!fallbackTempGrid) {
- fallbackTempGrid = new SparseTileGrid();
- }
- fallbackTempGrid.ingestCanvas(layer.id, canvas, fmt);
- const tiles = fallbackTempGrid.getLayerTiles(layer.id, 0);
- for (const tile of tiles) {
- pendingTiles.push({
- path: `tiles/${safeKey}/${tile.tileX}_${tile.tileY}.bin`,
- tile,
- sourceGrid: fallbackTempGrid,
- });
- }
- }
- }
- }
-
- if (layer.maskCanvas) {
- const encodedMask = encodeMaskBinary(layer.maskCanvas);
- if (encodedMask) {
- masksMeta[layer.id] = {
- width: encodedMask.width,
- height: encodedMask.height,
- format: 'alpha-8bit',
- };
- encodedMasks.push({
- path: `masks/${safeKey}.bin`,
- record: encodedMask.record,
- });
- }
- }
-
- const { maskCanvas: _mc, ...rest } = layer;
- serializableLayers.push(rest);
- }
-
- // Generate downscaled preview.png
- onProgress?.({
- phase: 'preview',
- current: 0,
- total: 1,
- percent: 8,
- message: 'Generating preview thumbnail...',
- });
- const preview = await generatePreviewPng(data, resolvedGrid);
-
- const manifest: SoraV2Manifest = {
- format: 'sora-v2',
- app: 'Ink Studio',
- version: '2.0',
- tileSize: TILE_SIZE,
- name: data.name,
- dimensions: {
- width: data.dimensions.width,
- height: data.dimensions.height,
- dpi: data.dimensions.dpi ?? 300,
- },
- colorMode: data.colorMode,
- layers: serializableLayers,
- layerFormats,
- layerTileKeys,
- masksMeta,
- perspectiveRuler: data.perspectiveRuler ?? null,
- animationTimeline: data.animationTimeline ?? null,
- timelapse: data.timelapse ?? null,
- preview: preview ? { path: 'preview.png', width: preview.width, height: preview.height } : null,
- savedAt: Date.now(),
- };
-
- const encoder = new TextEncoder();
- const manifestBytes = encoder.encode(JSON.stringify(manifest));
-
- const chunks: Uint8Array[] = [];
- let zipError: Error | null = null;
- const zip = new Zip((err, chunk, _final) => {
- if (err) {
- zipError = err;
- return;
- }
- if (chunk && chunk.byteLength > 0) {
- chunks.push(chunk);
- }
- });
-
- try {
- // 1. manifest.json
- const manifestEntry = new ZipDeflate('manifest.json', { level: 6 });
- zip.add(manifestEntry);
- manifestEntry.push(manifestBytes, true);
- if (zipError) throw zipError;
-
- // 2. preview.png (store uncompressed — PNG is already DEFLATE-compressed)
- if (preview) {
- const previewEntry = new ZipPassThrough('preview.png');
- zip.add(previewEntry);
- previewEntry.push(preview.bytes, true);
- if (zipError) throw zipError;
- }
-
- // 3. Stream native SparseTileGrid tiles in non-blocking chunks
- const totalTiles = pendingTiles.length;
- for (let i = 0; i < totalTiles; i++) {
- const item = pendingTiles[i];
- const { tile, sourceGrid, path } = item;
-
- let rawBytes: Uint8Array | null = tile.data;
- if (!rawBytes && tile.isPagedToDisk) {
- const mm = sourceGrid.getMemoryManager();
- if (mm) {
- // Read directly from scratch driver without inflating RAM cache
- rawBytes = await mm.getDriver().readTile(mm.getSessionId(), tile.layerId, tile.tileX, tile.tileY);
- }
- }
- if (!rawBytes) {
- rawBytes = new Uint8Array(getTileByteSize(tile.format));
- }
-
- const record = encodeNativeTileRecord(tile, rawBytes);
- const entry = new ZipDeflate(path, { level: tileCompressionLevel });
- zip.add(entry);
- entry.push(record, true);
- if (zipError) throw zipError;
-
- const done = i + 1;
- if (done % CHUNK_YIELD_INTERVAL === 0 || done === totalTiles) {
- const pct = 10 + Math.round((done / Math.max(1, totalTiles)) * 75);
- onProgress?.({
- phase: 'tiles',
- current: done,
- total: totalTiles,
- percent: Math.min(85, pct),
- message: `Saving tiles (${done}/${totalTiles})...`,
- });
- if (done < totalTiles) {
- await yieldToMainThread();
- }
- }
- }
-
- // 4. Layer masks
- const totalMasks = encodedMasks.length;
- for (let i = 0; i < totalMasks; i++) {
- const m = encodedMasks[i];
- const entry = new ZipDeflate(m.path, { level: tileCompressionLevel });
- zip.add(entry);
- entry.push(m.record, true);
- if (zipError) throw zipError;
-
- const done = i + 1;
- onProgress?.({
- phase: 'masks',
- current: done,
- total: totalMasks,
- percent: 85 + Math.round((done / Math.max(1, totalMasks)) * 10),
- message: `Saving layer masks (${done}/${totalMasks})...`,
- });
- if (done % CHUNK_YIELD_INTERVAL === 0 && done < totalMasks) {
- await yieldToMainThread();
- }
- }
-
- onProgress?.({
- phase: 'finalizing',
- current: 1,
- total: 1,
- percent: 96,
- message: 'Finalizing .sora archive...',
- });
-
- zip.end();
- if (zipError) throw zipError;
-
- const bytes = concatUint8Arrays(chunks);
- const previewBytes = preview ? preview.bytes : null;
- const previewDataUrl = toPngDataUrl(previewBytes);
-
- onProgress?.({
- phase: 'done',
- current: 1,
- total: 1,
- percent: 100,
- message: 'Saved successfully',
- });
-
- return { bytes, previewBytes, previewDataUrl, manifest };
- } finally {
- if (fallbackTempGrid) {
- fallbackTempGrid.clearAll();
- }
- }
-}
-
-/**
- * Fast preview-only extraction from a `.sora` v2 archive for Recent Documents.
- * Inflates ONLY `preview.png` without decompressing any tile payloads.
- */
-export function extractSoraPreview(input: ArrayBuffer | Uint8Array): Uint8Array | null {
- const raw = input instanceof Uint8Array ? input : new Uint8Array(input);
- if (!isSoraV2Bytes(raw)) return null;
- try {
- const zipBytes = unwrapZipPayload(raw);
- const extracted = unzipSync(zipBytes, {
- filter: (file) => file.name === 'preview.png',
- });
- const png = extracted['preview.png'];
- return png && png.byteLength > 0 ? png : null;
- } catch {
- return null;
- }
-}
-
-/**
- * Parses a `.sora` / `.ink` project with automatic format detection:
- * - Binary `.sora` v2 (ZIP container magic bytes) -> restores native SparseTileGrid tiles, masks, preview, and full metadata
- * - Legacy v1.2 JSON -> falls back to `parseSoraProjectJson` seamlessly
- */
-export async function parseSoraProject(
- input: ArrayBuffer | Uint8Array | string,
- options?: { onProgress?: (progress: SaveProgress) => void }
-): Promise<ParsedSoraProject> {
- const onProgress = options?.onProgress;
-
- if (typeof input === 'string') {
- const v1 = parseSoraProjectJson(input);
- return {
- format: 'v1',
- ...v1,
- };
- }
-
- const rawBytes = input instanceof Uint8Array ? input : new Uint8Array(input);
-
- // Automatic format detection: v2 binary magic bytes vs legacy JSON v1.2
- if (!isSoraV2Bytes(rawBytes)) {
- const text = new TextDecoder('utf-8').decode(rawBytes);
- const v1 = parseSoraProjectJson(text);
- return {
- format: 'v1',
- ...v1,
- };
- }
-
- onProgress?.({
- phase: 'preparing',
- current: 0,
- total: 1,
- percent: 5,
- message: 'Unpacking .sora v2 container...',
- });
-
- const zipBytes = unwrapZipPayload(rawBytes);
- const files = unzipSync(zipBytes);
-
- // Validate all entry paths against path traversal attacks
- const fileNames = Object.keys(files);
- for (const name of fileNames) {
- if (!isSafeZipPath(name)) {
- throw new Error(`Unsafe archive path in .sora v2 file: "${name}"`);
- }
- }
-
- const manifestRaw = files['manifest.json'];
- if (!manifestRaw || manifestRaw.byteLength === 0) {
- throw new Error('Invalid .sora v2 project: missing manifest.json');
- }
- if (manifestRaw.byteLength > MAX_MANIFEST_BYTES) {
- throw new Error('Invalid .sora v2 project: manifest.json exceeds size limit');
- }
-
- const manifestText = new TextDecoder('utf-8').decode(manifestRaw);
- const parsedManifest = JSON.parse(manifestText);
- if (
- !parsedManifest ||
- typeof parsedManifest !== 'object' ||
- !Array.isArray(parsedManifest.layers)
- ) {
- throw new Error('Invalid .sora v2 manifest: missing layers array');
- }
-
- const width = Math.floor(Number(parsedManifest.dimensions?.width) || 0);
- const height = Math.floor(Number(parsedManifest.dimensions?.height) || 0);
- if (width <= 0 || height <= 0 || width > MAX_DOCUMENT_DIM || height > MAX_DOCUMENT_DIM) {
- throw new Error(`Invalid .sora v2 dimensions: ${width}x${height}`);
- }
- const dpi = Number(parsedManifest.dimensions?.dpi) || 300;
- const colorMode: CanvasColorMode = parsedManifest.colorMode || 'color';
- const layers: LayerItem[] = parsedManifest.layers.map((l: any) => sanitizeJsonLayer(l));
-
- // Reverse map safeKey -> layerId from manifest
- const keyToLayerId = new Map<string, string>();
- if (parsedManifest.layerTileKeys && typeof parsedManifest.layerTileKeys === 'object') {
- for (const [layerId, safeKey] of Object.entries(parsedManifest.layerTileKeys)) {
- if (typeof safeKey === 'string' && safeKey.length > 0) {
- keyToLayerId.set(safeKey, layerId);
- }
- }
- }
- for (const layer of layers) {
- if (!keyToLayerId.has(layer.id)) {
- keyToLayerId.set(layer.id, layer.id);
- }
- }
-
- const layerFormats = new Map<string, TileFormat>();
- if (parsedManifest.layerFormats && typeof parsedManifest.layerFormats === 'object') {
- for (const [layerId, fmt] of Object.entries(parsedManifest.layerFormats)) {
- if (fmt === 'monochrome-1bit' || fmt === 'grayscale-8bit' || fmt === 'color-32bit') {
- layerFormats.set(layerId, fmt);
- }
- }
- }
-
- const tileRegex = /^tiles\/([^/]+)\/(-?\d+)_(-?\d+)\.bin$/;
- const maskRegex = /^masks\/([^/]+)\.bin$/;
-
- const tileEntries: Array<{ path: string; layerId: string; tx: number; ty: number }> = [];
- const maskEntries: Array<{ path: string; layerId: string }> = [];
-
- for (const path of fileNames) {
- const tileMatch = tileRegex.exec(path);
- if (tileMatch) {
- const safeKey = tileMatch[1];
- const layerId = keyToLayerId.get(safeKey);
- if (!layerId) continue;
- const tx = parseInt(tileMatch[2], 10);
- const ty = parseInt(tileMatch[3], 10);
- if (!Number.isSafeInteger(tx) || !Number.isSafeInteger(ty)) {
- throw new Error(`Invalid tile coordinates in .sora v2 archive: ${path}`);
- }
- tileEntries.push({ path, layerId, tx, ty });
- continue;
- }
-
- const maskMatch = maskRegex.exec(path);
- if (maskMatch) {
- const safeKey = maskMatch[1];
- const layerId = keyToLayerId.get(safeKey);
- if (layerId) {
- maskEntries.push({ path, layerId });
- }
- }
- }
-
- if (tileEntries.length > MAX_TILE_ENTRIES) {
- throw new Error(`Invalid .sora v2 project: tile count ${tileEntries.length} exceeds limit`);
- }
-
- const restoredTiles: TileBuffer[] = [];
- for (let i = 0; i < tileEntries.length; i++) {
- const entry = tileEntries[i];
- const payload = files[entry.path];
- const tile = decodeNativeTileRecord(entry.layerId, entry.tx, entry.ty, payload);
- restoredTiles.push(tile);
- if (!layerFormats.has(entry.layerId)) {
- layerFormats.set(entry.layerId, tile.format);
- }
-
- const done = i + 1;
- if (done % (CHUNK_YIELD_INTERVAL * 2) === 0 && done < tileEntries.length) {
- onProgress?.({
- phase: 'tiles',
- current: done,
- total: tileEntries.length,
- percent: 15 + Math.round((done / tileEntries.length) * 70),
- message: `Loading tiles (${done}/${tileEntries.length})...`,
- });
- await yieldToMainThread();
- }
- }
-
- const tileGrid = new SparseTileGrid();
- tileGrid.restoreFromSnapshot(restoredTiles, layerFormats);
- for (const layer of layers) {
- if (hasTileBackedLayer(layer)) {
- const fmt = layerFormats.get(layer.id) ?? inferLayerTileFormat(layer);
- tileGrid.setLayerFormat(layer.id, fmt);
- tileGrid.markLayerIngested(layer.id);
- }
- }
-
- const masksBinary = new Map<string, { width: number; height: number; data: Uint8Array }>();
- const layerById = new Map<string, LayerItem>();
- for (const l of layers) layerById.set(l.id, l);
-
- for (const mEntry of maskEntries) {
- const decoded = decodeMaskBinary(files[mEntry.path]);
- masksBinary.set(mEntry.layerId, decoded);
- const layer = layerById.get(mEntry.layerId);
- if (layer) {
- const maskCanvas = createMaskCanvasFromAlpha(decoded.width, decoded.height, decoded.data);
- if (maskCanvas) {
- layer.maskCanvas = maskCanvas;
- layer.maskVersion = (layer.maskVersion || 0) + 1;
- }
- }
- }
-
- const previewPath =
- typeof parsedManifest.preview?.path === 'string' && isSafeZipPath(parsedManifest.preview.path)
- ? parsedManifest.preview.path
- : 'preview.png';
- const previewRaw = files[previewPath];
- const previewBytes = previewRaw && previewRaw.byteLength > 0 ? new Uint8Array(previewRaw) : null;
- const previewDataUrl = toPngDataUrl(previewBytes);
-
- onProgress?.({
- phase: 'done',
- current: 1,
- total: 1,
- percent: 100,
- message: 'Project loaded',
- });
-
- return {
- format: 'v2',
- app: typeof parsedManifest.app === 'string' ? parsedManifest.app : 'Ink Studio',
- version: typeof parsedManifest.version === 'string' ? parsedManifest.version : '2.0',
- name: typeof parsedManifest.name === 'string' ? parsedManifest.name : 'Untitled',
- dimensions: { width, height, dpi },
- colorMode,
- layers,
- tileGrid,
- canvases: {},
- masks: {},
- masksBinary,
- perspectiveRuler: parsedManifest.perspectiveRuler ?? null,
- animationTimeline: parsedManifest.animationTimeline ?? null,
- timelapse: parsedManifest.timelapse ?? null,
- previewBytes,
- previewDataUrl,
- };
-}
-
-/**
- * Serializes the document according to the requested file extension.
- */
-export async function serializeDocument(
- data: SaveDocumentData,
- extension: string
-): Promise<{ data: Blob | ArrayBuffer; mimeType: string; previewDataUrl?: string }> {
- const ext = extension.toLowerCase();
- const tileGrid =
- data.tileGrid ??
- (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : documentStore.getActiveTileGrid());
-
- // 1. PSD/PSB format with full folder hierarchy, blend modes, clipping, alphaLock, and masks
- if (ext === '.psd' || ext === '.psb') {
- await hydratePagedTilesForLayers(tileGrid, data.layers, false);
- const tempCanvases: HTMLCanvasElement[] = [];
- try {
- const tree = buildLayerTree(data.layers);
- const children = buildPsdLayerTree(
- tree,
- data.dimensions,
- data.layerCanvasesMap,
- tileGrid,
- tempCanvases
- );
-
- const dpi = data.dimensions.dpi || 300;
- const { writePsd } = await import('ag-psd');
- const psdBuffer = writePsd(
- {
- width: data.dimensions.width,
- height: data.dimensions.height,
- children,
- imageResources: {
- resolutionInfo: {
- horizontalResolution: dpi,
- horizontalResolutionUnit: 'PPI',
- widthUnit: 'Inches',
- verticalResolution: dpi,
- verticalResolutionUnit: 'PPI',
- heightUnit: 'Inches',
- },
- },
- },
- {
- psb: ext === '.psb',
- noBackground: true,
- }
- );
-
- return {
- data: psdBuffer,
- mimeType: 'image/vnd.adobe.photoshop',
- };
- } finally {
- for (const temp of tempCanvases) {
- releaseTemporaryCanvas(temp);
- }
- }
- }
-
- // 2. Native Ink Studio Project (.sora, .ink) — Binary v2 container
- if (ext === '.ink' || ext === '.sora') {
- const result = await serializeSoraV2(data, tileGrid);
- return {
- data: new Blob([result.bytes as BlobPart], { type: 'application/octet-stream' }),
- mimeType: 'application/octet-stream',
- previewDataUrl: result.previewDataUrl,
- };
- }
-
- // 3. JPEG format (tiled GPU compositor with white background)
- if (ext === '.jpg' || ext === '.jpeg') {
- const exported = await exportImage(
- { ...data, tileGrid },
- { format: 'jpg', quality: 0.92, fillWhiteBackground: true }
- );
- return { data: exported.blob, mimeType: exported.mimeType };
- }
-
- // 4. WebP format (tiled GPU compositor with transparency)
- if (ext === '.webp') {
- const exported = await exportImage(
- { ...data, tileGrid },
- { format: 'webp', quality: 0.92, fillWhiteBackground: false }
- );
- return { data: exported.blob, mimeType: exported.mimeType };
- }
-
- // 5. Default: PNG format (tiled GPU compositor with transparency)
- const exported = await exportImage(
- { ...data, tileGrid },
- { format: 'png', fillWhiteBackground: false }
- );
- return { data: exported.blob, mimeType: exported.mimeType };
-}
-
-/**
- * Triggers fallback download using standard anchor element.
- */
-export function downloadFile(
- content: Blob | ArrayBuffer,
- fileName: string,
- mimeType: string
-) {
- const blob = content instanceof Blob ? content : new Blob([content], { type: mimeType });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = fileName;
- document.body.appendChild(a);
- a.click();
- setTimeout(() => {
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- }, 200);
-}
-
-function getSerializedByteSize(content: Blob | ArrayBuffer): number {
- return content instanceof Blob ? content.size : content.byteLength;
-}
-
-/**
- * Prompts user to select save location and extension via File System Access API or fallback.
- */
-export async function promptSaveAs(
- data: SaveDocumentData,
- defaultExtension: string = '.sora',
- fallbackToDownload: boolean = true
-): Promise<SavedFileInfo> {
- const safeName = data.name.trim().replace(/[^a-zA-Z0-9_\- ]/g, '_') || 'Untitled';
- const suggestedName = `${safeName}${defaultExtension}`;
-
- const types = [
- {
- description: 'Ink Studio Layered Project (*.sora, *.ink)',
- accept: { 'application/octet-stream': ['.sora', '.ink'] },
- },
- {
- description: 'Photoshop Document with Layers (*.psd)',
- accept: { 'image/vnd.adobe.photoshop': ['.psd'] },
- },
- {
- description: 'PNG Image (*.png)',
- accept: { 'image/png': ['.png'] },
- },
- {
- description: 'JPEG Image (*.jpg, *.jpeg)',
- accept: { 'image/jpeg': ['.jpg', '.jpeg'] },
- },
- {
- description: 'WebP Image (*.webp)',
- accept: { 'image/webp': ['.webp'] },
- },
- ];
-
- if (typeof window !== 'undefined' && 'showSaveFilePicker' in window) {
- try {
- const handle = await (window as any).showSaveFilePicker({
- suggestedName,
- types,
- });
-
- const fileName = handle.name;
- const ext = fileName.includes('.')
- ? fileName.slice(fileName.lastIndexOf('.')).toLowerCase()
- : defaultExtension;
-
- const serialized = await serializeDocument(data, ext);
- const writable = await handle.createWritable();
- await writable.write(serialized.data);
- await writable.close();
-
- if (data.tabId) {
- recoveryService.markCleanSaved(data.tabId).catch(console.warn);
- }
-
- return {
- handle,
- name: fileName,
- extension: ext,
- size: getSerializedByteSize(serialized.data),
- previewDataUrl: serialized.previewDataUrl,
- };
- } catch (err: any) {
- if (err.name === 'AbortError') {
- throw new Error('Save canceled');
- }
- console.warn('showSaveFilePicker failed or unsupported, using download fallback:', err);
- }
- }
-
- if (fallbackToDownload) {
- const ext = defaultExtension;
- const serialized = await serializeDocument(data, ext);
- downloadFile(serialized.data, suggestedName, serialized.mimeType);
-
- if (data.tabId) {
- recoveryService.markCleanSaved(data.tabId).catch(console.warn);
- }
-
- return {
- name: suggestedName,
- extension: ext,
- size: getSerializedByteSize(serialized.data),
- previewDataUrl: serialized.previewDataUrl,
- };
- }
-
- throw new Error('Save dialog was not available');
-}
-
-/**
- * Writes directly to an already selected FileSystemFileHandle without prompting.
- */
-export async function saveToExistingHandle(
- data: SaveDocumentData,
- fileInfo: SavedFileInfo
-): Promise<{ size: number; previewDataUrl?: string }> {
- if (!fileInfo.handle || typeof fileInfo.handle.createWritable !== 'function') {
- throw new Error('No valid file handle to save to');
- }
-
- const serialized = await serializeDocument(data, fileInfo.extension);
- const writable = await fileInfo.handle.createWritable();
- await writable.write(serialized.data);
- await writable.close();
-
- if (data.tabId) {
- recoveryService.markCleanSaved(data.tabId).catch(console.warn);
- }
-
- return {
- size: getSerializedByteSize(serialized.data),
- previewDataUrl: serialized.previewDataUrl,
- };
-}
-
-/**
- * Prompts user to choose a download/save path specifically for an exported image (PNG / JPG / WebP).
- */
-export async function promptExportPngImage(
- data: SaveDocumentData,
- defaultName?: string
-): Promise<string> {
- const safeName = (defaultName || data.name || 'artwork').trim().replace(/[^a-zA-Z0-9_\- ]/g, '_');
- const suggestedName = `${safeName}.png`;
-
- const types = [
- {
- description: 'PNG Image (*.png)',
- accept: { 'image/png': ['.png'] },
- },
- {
- description: 'JPEG Image (*.jpg, *.jpeg)',
- accept: { 'image/jpeg': ['.jpg', '.jpeg'] },
- },
- {
- description: 'WebP Image (*.webp)',
- accept: { 'image/webp': ['.webp'] },
- },
- ];
-
- if (typeof window !== 'undefined' && 'showSaveFilePicker' in window) {
- try {
- const handle = await (window as any).showSaveFilePicker({
- suggestedName,
- types,
- });
-
- const fileName: string = handle.name;
- const ext = fileName.includes('.')
- ? fileName.slice(fileName.lastIndexOf('.')).toLowerCase()
- : '.png';
- const serialized = await serializeDocument(data, ext);
- const writable = await handle.createWritable();
- await writable.write(serialized.data);
- await writable.close();
-
- return fileName;
- } catch (err: any) {
- if (err.name === 'AbortError') {
- throw new Error('Export canceled');
- }
- console.warn('showSaveFilePicker failed for export, falling back to download:', err);
- }
- }
-
- const serialized = await serializeDocument(data, '.png');
- downloadFile(serialized.data, suggestedName, 'image/png');
- return suggestedName;
-}
+export type {
+ SavedFileInfo,
+ SaveProgress,
+ SaveDocumentData,
+ InkProjectManifest,
+ ParsedInkProject,
+ ExportImageOptions,
+ ExportImageResult,
+ CompositeCanvasOptions,
+ GpuTilePlanEntry,
+} from './saveManager/types';
+
+export {
+ PRIMARY_PROJECT_EXTENSION,
+ INK_DEFAULT_TILE_EXPORT_SIZE,
+ isInkProjectBytes,
+ canvasToBlob,
+} from './saveManager/types';
+
+export {
+ computeMaxLayerStyleMargin,
+ buildGpuExportTilePlan,
+} from './saveManager/exportGridPrep';
+
+export { toAgPsdBlendMode } from './saveManager/psdExport';
+
+export { compositeCanvasCpuFallback } from './saveManager/cpuComposite';
+
+export {
+ compositeCanvasAsync,
+ createDocumentRegionRenderer,
+ compositeCanvas,
+} from './saveManager/gpuComposite';
+
+export { serializeInkProject } from './saveManager/inkSerialize';
+
+export {
+ extractInkPreview,
+ parseInkProject,
+} from './saveManager/inkParse';
+
+export {
+ exportImage,
+ serializeDocument,
+ downloadFile,
+ promptSaveAs,
+ saveToExistingHandle,
+ promptExportPngImage,
+} from './saveManager/fileActions';
diff --git a/src/utils/saveManager/cpuComposite.ts b/src/utils/saveManager/cpuComposite.ts
new file mode 100644
index 0000000..4234996
--- /dev/null
+++ b/src/utils/saveManager/cpuComposite.ts
@@ -0,0 +1,220 @@
+import { CanvasDimensions, LayerItem, isFolderLikeLayer } from '../../types/editor';
+import { getCanvasCompositeOperation } from '../canvasUtils';
+import {
+ buildLayerTree,
+ groupTreeNodesForCompositing,
+ LayerTreeNode,
+} from '../compositor';
+import { applyAdjustment } from '../tonalEngine';
+import { applyMultiFrameClip, renderFrameBorder } from '../frameEngine';
+import { SparseTileGrid, releaseTemporaryCanvas } from '../tileEngine';
+import { acquireLayerExportCanvas } from './exportGridPrep';
+
+/**
+ * CPU 2D fallback compositor — used strictly when WebGL2 is unavailable.
+ */
+export function compositeCanvasCpuFallback(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement> | undefined,
+ getEffectiveOpacity: (layer: LayerItem) => number,
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
+ fillWhiteBackground: boolean = false,
+ tileGrid?: SparseTileGrid
+): HTMLCanvasElement {
+ const exportCanvas = document.createElement('canvas');
+ exportCanvas.width = dimensions.width;
+ exportCanvas.height = dimensions.height;
+ const ctx = exportCanvas.getContext('2d');
+ if (!ctx) return exportCanvas;
+
+ if (fillWhiteBackground) {
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, dimensions.width, dimensions.height);
+ }
+
+ const getMaskedLayerCanvas = (
+ layer: LayerItem,
+ srcCanvas: HTMLCanvasElement
+ ): { canvas: HTMLCanvasElement; isTemporary: boolean } => {
+ if (!layer.maskCanvas || layer.maskEnabled === false) {
+ return { canvas: srcCanvas, isTemporary: false };
+ }
+ const masked = document.createElement('canvas');
+ masked.width = dimensions.width;
+ masked.height = dimensions.height;
+ const mCtx = masked.getContext('2d');
+ const maskCtx = layer.maskCanvas.getContext('2d', { willReadFrequently: true });
+ if (!mCtx || !maskCtx) {
+ releaseTemporaryCanvas(masked);
+ return { canvas: srcCanvas, isTemporary: false };
+ }
+ mCtx.drawImage(srcCanvas, 0, 0);
+ const imgData = mCtx.getImageData(0, 0, dimensions.width, dimensions.height);
+ const maskData = maskCtx.getImageData(0, 0, dimensions.width, dimensions.height).data;
+ const d = imgData.data;
+ for (let i = 0; i < d.length; i += 4) {
+ if (d[i + 3] === 0) continue;
+ const maskLum = ((0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255) * (maskData[i + 3] / 255);
+ d[i + 3] = Math.round(d[i + 3] * maskLum);
+ }
+ mCtx.putImageData(imgData, 0, 0);
+ return { canvas: masked, isTemporary: true };
+ };
+
+ const renderTreeNodes = (
+ targetCtx: CanvasRenderingContext2D,
+ nodes: LayerTreeNode[],
+ opacityMul: number
+ ) => {
+ const renderOrder = nodes.slice().reverse();
+ const groups = groupTreeNodesForCompositing(renderOrder);
+
+ for (const group of groups) {
+ const baseNode = group.baseNode;
+ const baseLayer = baseNode.layer;
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001) continue;
+
+ if (baseLayer.type === 'frame-folder') {
+ const folderAlpha = opacityMul * baseLayer.opacity;
+ const frames = (baseLayer.comicFrames || []).filter((f) => f.polygon.length >= 3);
+ const shouldClip = frames.length > 0 && frames.some((f) => f.clipChildren !== false);
+ const folderCanvas = document.createElement('canvas');
+ folderCanvas.width = dimensions.width;
+ folderCanvas.height = dimensions.height;
+ const fCtx = folderCanvas.getContext('2d');
+ if (fCtx) {
+ fCtx.save();
+ if (shouldClip) {
+ applyMultiFrameClip(fCtx, frames);
+ }
+ for (const frame of frames) {
+ if (frame.fillBackground !== false) {
+ fCtx.fillStyle = frame.fillColor || '#ffffff';
+ fCtx.beginPath();
+ fCtx.moveTo(frame.polygon[0].x, frame.polygon[0].y);
+ for (let i = 1; i < frame.polygon.length; i++) {
+ fCtx.lineTo(frame.polygon[i].x, frame.polygon[i].y);
+ }
+ fCtx.closePath();
+ fCtx.fill();
+ }
+ }
+ if (baseNode.children.length > 0) {
+ renderTreeNodes(fCtx, baseNode.children, 1.0);
+ }
+ fCtx.restore();
+ for (const frame of frames) {
+ renderFrameBorder(fCtx, frame, false);
+ }
+ targetCtx.save();
+ targetCtx.globalAlpha = Math.max(0, Math.min(1, folderAlpha));
+ const blend = baseLayer.blendMode === 'pass-through' ? 'normal' : baseLayer.blendMode;
+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(blend);
+ targetCtx.drawImage(folderCanvas, 0, 0);
+ targetCtx.restore();
+ }
+ releaseTemporaryCanvas(folderCanvas);
+ continue;
+ }
+
+ if (baseLayer.type === 'folder') {
+ const folderAlpha = opacityMul * baseLayer.opacity;
+ if (baseLayer.blendMode === 'pass-through') {
+ if (baseNode.children.length > 0) {
+ renderTreeNodes(targetCtx, baseNode.children, folderAlpha);
+ }
+ } else {
+ const folderCanvas = document.createElement('canvas');
+ folderCanvas.width = dimensions.width;
+ folderCanvas.height = dimensions.height;
+ const fCtx = folderCanvas.getContext('2d');
+ if (fCtx) {
+ if (baseNode.children.length > 0) {
+ renderTreeNodes(fCtx, baseNode.children, 1.0);
+ }
+ targetCtx.save();
+ targetCtx.globalAlpha = Math.max(0, Math.min(1, folderAlpha));
+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ targetCtx.drawImage(folderCanvas, 0, 0);
+ targetCtx.restore();
+ }
+ releaseTemporaryCanvas(folderCanvas);
+ }
+ continue;
+ }
+
+ if (!isLayerEffectivelyVisible(baseLayer)) continue;
+
+ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
+ const imgData = targetCtx.getImageData(0, 0, dimensions.width, dimensions.height);
+ applyAdjustment(
+ imgData,
+ baseLayer.adjustmentData,
+ baseLayer.maskEnabled !== false ? baseLayer.maskCanvas : undefined,
+ baseLayer.opacity * opacityMul
+ );
+ targetCtx.putImageData(imgData, 0, 0);
+ continue;
+ }
+
+ const baseAcq = acquireLayerExportCanvas(baseLayer, dimensions, layerCanvasesMap, tileGrid);
+ if (!baseAcq.canvas) continue;
+ const maskedBase = getMaskedLayerCanvas(baseLayer, baseAcq.canvas);
+
+ const activeClipped = group.clippedNodes
+ .map((n) => n.layer)
+ .filter((cl) => !isFolderLikeLayer(cl) && cl.type !== 'adjustment' && cl.visible && cl.opacity > 0.001);
+
+ if (activeClipped.length === 0) {
+ targetCtx.save();
+ targetCtx.globalAlpha = Math.max(0, Math.min(1, baseLayer.opacity * opacityMul));
+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ targetCtx.drawImage(maskedBase.canvas, 0, 0);
+ targetCtx.restore();
+ } else {
+ const groupCanvas = document.createElement('canvas');
+ groupCanvas.width = dimensions.width;
+ groupCanvas.height = dimensions.height;
+ const gCtx = groupCanvas.getContext('2d');
+ if (gCtx) {
+ gCtx.save();
+ gCtx.globalAlpha = Math.max(0, Math.min(1, baseLayer.opacity * opacityMul));
+ gCtx.drawImage(maskedBase.canvas, 0, 0);
+ gCtx.restore();
+
+ for (const clipped of activeClipped) {
+ const clipAcq = acquireLayerExportCanvas(clipped, dimensions, layerCanvasesMap, tileGrid);
+ if (!clipAcq.canvas) continue;
+ const maskedClip = getMaskedLayerCanvas(clipped, clipAcq.canvas);
+
+ gCtx.save();
+ gCtx.globalAlpha = Math.max(0, Math.min(1, clipped.opacity * opacityMul));
+ gCtx.globalCompositeOperation = 'source-atop';
+ gCtx.drawImage(maskedClip.canvas, 0, 0);
+ gCtx.restore();
+
+ if (maskedClip.isTemporary) releaseTemporaryCanvas(maskedClip.canvas);
+ if (clipAcq.isTemporary) releaseTemporaryCanvas(clipAcq.canvas);
+ }
+
+ targetCtx.save();
+ targetCtx.globalAlpha = 1.0;
+ targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ targetCtx.drawImage(groupCanvas, 0, 0);
+ targetCtx.restore();
+ }
+ releaseTemporaryCanvas(groupCanvas);
+ }
+
+ if (maskedBase.isTemporary) releaseTemporaryCanvas(maskedBase.canvas);
+ if (baseAcq.isTemporary) releaseTemporaryCanvas(baseAcq.canvas);
+ }
+ };
+
+ const tree = buildLayerTree(layers);
+ renderTreeNodes(ctx, tree, 1.0);
+ void getEffectiveOpacity;
+
+ return exportCanvas;
+}
diff --git a/src/utils/saveManager/exportGridPrep.ts b/src/utils/saveManager/exportGridPrep.ts
new file mode 100644
index 0000000..2c73c0c
--- /dev/null
+++ b/src/utils/saveManager/exportGridPrep.ts
@@ -0,0 +1,235 @@
+import { CanvasDimensions, LayerItem, hasTileBackedLayer } from '../../types/editor';
+import { renderVectorLayer } from '../vectorEngine';
+import { renderBalloonLayerData, renderTextLayerData } from '../vectorLayerRenderer';
+import { SparseTileGrid, TileFormat, releaseTemporaryCanvas } from '../tileEngine';
+import {
+ GpuTilePlanEntry,
+ INK_DEFAULT_TILE_EXPORT_SIZE,
+ MAX_STYLE_MARGIN_PX,
+} from './types';
+
+/**
+ * Resolves a layer's canvas from either the map or temporarily from SparseTileGrid.
+ * Returns `{ canvas, isTemporary }` so caller immediately releases temporary canvases.
+ */
+export function acquireLayerExportCanvas(
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ layerCanvasesMap?: Map<string, HTMLCanvasElement>,
+ tileGrid?: SparseTileGrid
+): { canvas: HTMLCanvasElement | null; isTemporary: boolean } {
+ if (layer.type === 'text' && layer.textData && typeof document !== 'undefined') {
+ const temp = document.createElement('canvas');
+ temp.width = dimensions.width;
+ temp.height = dimensions.height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderTextLayerData(ctx, layer.textData);
+ return { canvas: temp, isTemporary: true };
+ }
+ if (layer.type === 'balloon' && layer.balloonData && typeof document !== 'undefined') {
+ const temp = document.createElement('canvas');
+ temp.width = dimensions.width;
+ temp.height = dimensions.height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
+ return { canvas: temp, isTemporary: true };
+ }
+ const existing = layerCanvasesMap?.get(layer.id);
+ if (existing) {
+ return { canvas: existing, isTemporary: false };
+ }
+ if (tileGrid && tileGrid.hasLayerTiles(layer.id)) {
+ const temp = tileGrid.exportLayerToCanvas(layer.id, dimensions.width, dimensions.height);
+ return { canvas: temp, isTemporary: true };
+ }
+ return { canvas: null, isTemporary: false };
+}
+
+/**
+ * Computes the maximum pixel halo margin required around export tiles so GPU
+ * Layer Styles (Stroke, Drop Shadow, Outer Glow) render seamlessly across tile seams.
+ */
+export function computeMaxLayerStyleMargin(layers: LayerItem[]): number {
+ let maxMargin = 0;
+ for (const layer of layers) {
+ if (!layer.visible || layer.opacity <= 0.001 || !layer.styles) continue;
+ const { stroke, dropShadow, outerGlow } = layer.styles;
+ if (stroke?.enabled && stroke.size > 0 && stroke.opacity > 0) {
+ maxMargin = Math.max(maxMargin, Math.ceil(stroke.size) + 2);
+ }
+ if (dropShadow?.enabled && dropShadow.opacity > 0) {
+ const extent = Math.ceil((dropShadow.distance || 0) + (dropShadow.blur || 0) * 1.5) + 2;
+ maxMargin = Math.max(maxMargin, extent);
+ }
+ if (outerGlow?.enabled && outerGlow.opacity > 0 && outerGlow.blur > 0) {
+ const extent = Math.ceil(outerGlow.blur * 1.5) + 2;
+ maxMargin = Math.max(maxMargin, extent);
+ }
+ }
+ return Math.min(MAX_STYLE_MARGIN_PX, Math.max(0, maxMargin));
+}
+
+export function inferLayerTileFormat(layer: LayerItem): TileFormat {
+ if (layer.expressionColor === 'monochrome') return 'monochrome-1bit';
+ if (layer.expressionColor === 'gray') return 'grayscale-8bit';
+ return 'color-32bit';
+}
+
+/**
+ * Prepares a SparseTileGrid containing all visible tile-backed layers for GPU compositing.
+ * Zero-copy fast path when `tileGrid` already holds all visible raster/vector/text/balloon layers.
+ */
+export function prepareExportTileGrid(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap?: Map<string, HTMLCanvasElement>,
+ tileGrid?: SparseTileGrid
+): { grid: SparseTileGrid; isTemporary: boolean } {
+ const missingLayers: LayerItem[] = [];
+
+ for (const layer of layers) {
+ if (!layer.visible || layer.opacity <= 0.001) continue;
+ if (!hasTileBackedLayer(layer)) continue;
+ const hasTiles = Boolean(tileGrid && tileGrid.hasLayerTiles(layer.id));
+ if (hasTiles) continue;
+
+ const hasVectorSource =
+ (layer.type === 'text' && Boolean(layer.textData)) ||
+ (layer.type === 'balloon' && Boolean(layer.balloonData)) ||
+ (layer.type === 'vector' && Boolean(layer.vectorStrokes && layer.vectorStrokes.length > 0));
+ if (hasVectorSource || layerCanvasesMap?.has(layer.id)) {
+ missingLayers.push(layer);
+ }
+ }
+
+ if (tileGrid && missingLayers.length === 0) {
+ return { grid: tileGrid, isTemporary: false };
+ }
+
+ const tempGrid = new SparseTileGrid();
+ if (tileGrid) {
+ // Share existing TileBuffer references without duplicating pixel buffers
+ for (const [layerId, fmt] of tileGrid.getAllLayerFormats().entries()) {
+ tempGrid.setLayerFormat(layerId, fmt);
+ }
+ for (const tile of tileGrid.getAllTiles()) {
+ if ((tile.lod ?? 0) === 0) {
+ tempGrid.setTile(tile.layerId, tile.tileX, tile.tileY, tile);
+ }
+ }
+ }
+
+ if (typeof document !== 'undefined') {
+ for (const layer of missingLayers) {
+ const fmt = inferLayerTileFormat(layer);
+ if (layer.type === 'text' && layer.textData) {
+ const temp = document.createElement('canvas');
+ temp.width = dimensions.width;
+ temp.height = dimensions.height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderTextLayerData(ctx, layer.textData);
+ tempGrid.ingestCanvas(layer.id, temp, fmt);
+ releaseTemporaryCanvas(temp);
+ } else if (layer.type === 'balloon' && layer.balloonData) {
+ const temp = document.createElement('canvas');
+ temp.width = dimensions.width;
+ temp.height = dimensions.height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
+ tempGrid.ingestCanvas(layer.id, temp, fmt);
+ releaseTemporaryCanvas(temp);
+ } else {
+ const existingCanvas = layerCanvasesMap?.get(layer.id);
+ if (existingCanvas) {
+ tempGrid.ingestCanvas(layer.id, existingCanvas, fmt);
+ } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
+ const temp = document.createElement('canvas');
+ temp.width = dimensions.width;
+ temp.height = dimensions.height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
+ tempGrid.ingestCanvas(layer.id, temp, fmt);
+ releaseTemporaryCanvas(temp);
+ }
+ }
+ }
+ }
+
+ return { grid: tempGrid, isTemporary: true };
+}
+
+/**
+ * Ensures any tiles paged out to SSD scratch disk for visible layers are hydrated in RAM
+ * before GPU or CPU export begins.
+ */
+export async function hydratePagedTilesForLayers(
+ tileGrid: SparseTileGrid | undefined,
+ layers: LayerItem[],
+ visibleOnly: boolean
+): Promise<void> {
+ if (!tileGrid) return;
+ const mm = tileGrid.getMemoryManager();
+ if (!mm) return;
+
+ for (const layer of layers) {
+ if (visibleOnly && (!layer.visible || layer.opacity <= 0.001)) continue;
+ if (!hasTileBackedLayer(layer)) continue;
+ const tiles = tileGrid.getLayerTiles(layer.id, 0);
+ for (const tile of tiles) {
+ if (tile.data === null && tile.isPagedToDisk) {
+ await mm.requestTileData(tile);
+ }
+ }
+ }
+}
+
+/**
+ * Pure geometry planner for tiled GPU FBO export with seam-free Layer Style halo padding.
+ */
+export function buildGpuExportTilePlan(
+ docWidth: number,
+ docHeight: number,
+ maxTileSize: number = INK_DEFAULT_TILE_EXPORT_SIZE,
+ styleMargin: number = 0
+): { fboWidth: number; fboHeight: number; tiles: GpuTilePlanEntry[] } {
+ const safeMaxTile = Math.max(256, Math.floor(maxTileSize));
+ const clampedMargin = Math.max(0, Math.min(styleMargin, Math.floor((safeMaxTile - 256) / 2)));
+ const innerStep = Math.max(256, safeMaxTile - clampedMargin * 2);
+
+ const tiles: GpuTilePlanEntry[] = [];
+ let maxFboW = 1;
+ let maxFboH = 1;
+
+ for (let tileY = 0; tileY < docHeight; tileY += innerStep) {
+ const height = Math.min(innerStep, docHeight - tileY);
+ const padTop = Math.min(clampedMargin, tileY);
+ const padBottom = Math.min(clampedMargin, docHeight - (tileY + height));
+ const fboHeight = height + padTop + padBottom;
+ if (fboHeight > maxFboH) maxFboH = fboHeight;
+
+ for (let tileX = 0; tileX < docWidth; tileX += innerStep) {
+ const width = Math.min(innerStep, docWidth - tileX);
+ const padLeft = Math.min(clampedMargin, tileX);
+ const padRight = Math.min(clampedMargin, docWidth - (tileX + width));
+ const fboWidth = width + padLeft + padRight;
+ if (fboWidth > maxFboW) maxFboW = fboWidth;
+
+ tiles.push({
+ tileX,
+ tileY,
+ width,
+ height,
+ padLeft,
+ padTop,
+ padRight,
+ padBottom,
+ originX: tileX - padLeft,
+ originY: tileY - padTop,
+ fboWidth,
+ fboHeight,
+ });
+ }
+ }
+
+ return { fboWidth: maxFboW, fboHeight: maxFboH, tiles };
+}
diff --git a/src/utils/saveManager/fileActions.ts b/src/utils/saveManager/fileActions.ts
new file mode 100644
index 0000000..946a9dc
--- /dev/null
+++ b/src/utils/saveManager/fileActions.ts
@@ -0,0 +1,378 @@
+import { buildLayerTree } from '../compositor';
+import { recoveryService } from '../../services/recoveryService';
+import { releaseTemporaryCanvas } from '../tileEngine';
+import { documentStore } from '../documentStore';
+import {
+ ExportImageOptions,
+ ExportImageResult,
+ INK_DEFAULT_TILE_EXPORT_SIZE,
+ PRIMARY_PROJECT_EXTENSION,
+ SaveDocumentData,
+ SavedFileInfo,
+ canvasToBlob,
+} from './types';
+import { hydratePagedTilesForLayers } from './exportGridPrep';
+import { buildPsdLayerTree } from './psdExport';
+import { compositeCanvasAsync } from './gpuComposite';
+import { serializeInkProject } from './inkSerialize';
+
+/**
+ * Pixel-accurate tiled GPU image exporter (PNG / JPEG / WebP) with automatic
+ * CPU fallback when WebGL2 is unavailable.
+ */
+export async function exportImage(
+ data: SaveDocumentData,
+ options: ExportImageOptions = {}
+): Promise<ExportImageResult> {
+ const format = options.format ?? 'png';
+ const isJpeg = format === 'jpg' || format === 'jpeg';
+ const isWebp = format === 'webp';
+ const mimeType = isJpeg ? 'image/jpeg' : isWebp ? 'image/webp' : 'image/png';
+ const quality = isJpeg || isWebp ? (options.quality ?? 0.92) : undefined;
+ const fillWhite = options.fillWhiteBackground ?? isJpeg;
+ const tileGrid =
+ data.tileGrid ??
+ (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : documentStore.getActiveTileGrid());
+
+ const onProgress = options.onProgress ?? data.onProgress;
+
+ const { canvas, usedGpu } = await compositeCanvasAsync(
+ data.dimensions,
+ data.layers,
+ data.layerCanvasesMap,
+ data.getEffectiveOpacity,
+ data.isLayerEffectivelyVisible,
+ fillWhite,
+ tileGrid,
+ {
+ tileSize: options.tileSize ?? INK_DEFAULT_TILE_EXPORT_SIZE,
+ colorMode: data.colorMode,
+ onProgress,
+ }
+ );
+
+ try {
+ onProgress?.({
+ phase: 'encoding',
+ current: 1,
+ total: 1,
+ percent: 92,
+ message: `Encoding ${format.toUpperCase()}...`,
+ });
+ const blob = await canvasToBlob(canvas, mimeType, quality);
+ onProgress?.({
+ phase: 'done',
+ current: 1,
+ total: 1,
+ percent: 100,
+ message: 'Export complete',
+ });
+ return {
+ blob,
+ mimeType,
+ width: data.dimensions.width,
+ height: data.dimensions.height,
+ usedGpu,
+ };
+ } finally {
+ releaseTemporaryCanvas(canvas);
+ }
+}
+
+/**
+ * Serializes the document according to the requested file extension.
+ */
+export async function serializeDocument(
+ data: SaveDocumentData,
+ extension: string
+): Promise<{ data: Blob | ArrayBuffer; mimeType: string; previewDataUrl?: string }> {
+ const ext = extension.toLowerCase();
+ const tileGrid =
+ data.tileGrid ??
+ (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : documentStore.getActiveTileGrid());
+
+ // 1. PSD/PSB format with full folder hierarchy, blend modes, clipping, alphaLock, and masks
+ if (ext === '.psd' || ext === '.psb') {
+ await hydratePagedTilesForLayers(tileGrid, data.layers, false);
+ const tempCanvases: HTMLCanvasElement[] = [];
+ try {
+ const tree = buildLayerTree(data.layers);
+ const children = buildPsdLayerTree(
+ tree,
+ data.dimensions,
+ data.layerCanvasesMap,
+ tileGrid,
+ tempCanvases
+ );
+
+ const dpi = data.dimensions.dpi || 300;
+ const { writePsd } = await import('ag-psd');
+ const psdBuffer = writePsd(
+ {
+ width: data.dimensions.width,
+ height: data.dimensions.height,
+ children,
+ imageResources: {
+ resolutionInfo: {
+ horizontalResolution: dpi,
+ horizontalResolutionUnit: 'PPI',
+ widthUnit: 'Inches',
+ verticalResolution: dpi,
+ verticalResolutionUnit: 'PPI',
+ heightUnit: 'Inches',
+ },
+ },
+ },
+ {
+ psb: ext === '.psb',
+ noBackground: true,
+ }
+ );
+
+ return {
+ data: psdBuffer,
+ mimeType: 'image/vnd.adobe.photoshop',
+ };
+ } finally {
+ for (const temp of tempCanvases) {
+ releaseTemporaryCanvas(temp);
+ }
+ }
+ }
+
+ // 2. Native Ink Studio Project (.ink) — Binary v2 container (.sora is read-only)
+ if (ext === '.sora') {
+ throw new Error('Legacy .sora format is read-only. Save as .ink instead.');
+ }
+ if (ext === PRIMARY_PROJECT_EXTENSION) {
+ const result = await serializeInkProject(data, tileGrid);
+ return {
+ data: new Blob([result.bytes as BlobPart], { type: 'application/octet-stream' }),
+ mimeType: 'application/octet-stream',
+ previewDataUrl: result.previewDataUrl,
+ };
+ }
+
+ // 3. JPEG format (tiled GPU compositor with white background)
+ if (ext === '.jpg' || ext === '.jpeg') {
+ const exported = await exportImage(
+ { ...data, tileGrid },
+ { format: 'jpg', quality: 0.92, fillWhiteBackground: true }
+ );
+ return { data: exported.blob, mimeType: exported.mimeType };
+ }
+
+ // 4. WebP format (tiled GPU compositor with transparency)
+ if (ext === '.webp') {
+ const exported = await exportImage(
+ { ...data, tileGrid },
+ { format: 'webp', quality: 0.92, fillWhiteBackground: false }
+ );
+ return { data: exported.blob, mimeType: exported.mimeType };
+ }
+
+ // 5. Default: PNG format (tiled GPU compositor with transparency)
+ const exported = await exportImage(
+ { ...data, tileGrid },
+ { format: 'png', fillWhiteBackground: false }
+ );
+ return { data: exported.blob, mimeType: exported.mimeType };
+}
+
+/**
+ * Triggers fallback download using standard anchor element.
+ */
+export function downloadFile(
+ content: Blob | ArrayBuffer,
+ fileName: string,
+ mimeType: string
+) {
+ const blob = content instanceof Blob ? content : new Blob([content], { type: mimeType });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = fileName;
+ document.body.appendChild(a);
+ a.click();
+ setTimeout(() => {
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ }, 200);
+}
+
+function getSerializedByteSize(content: Blob | ArrayBuffer): number {
+ return content instanceof Blob ? content.size : content.byteLength;
+}
+
+/**
+ * Prompts user to select save location and extension via File System Access API or fallback.
+ */
+export async function promptSaveAs(
+ data: SaveDocumentData,
+ defaultExtension: string = PRIMARY_PROJECT_EXTENSION,
+ fallbackToDownload: boolean = true
+): Promise<SavedFileInfo> {
+ const resolvedDefaultExt =
+ defaultExtension.toLowerCase() === '.sora' ? PRIMARY_PROJECT_EXTENSION : defaultExtension;
+ const safeName = data.name.trim().replace(/[^a-zA-Z0-9_\- ]/g, '_') || 'Untitled';
+ const suggestedName = `${safeName}${resolvedDefaultExt}`;
+
+ const types = [
+ {
+ description: 'Ink Studio Project (*.ink)',
+ accept: { 'application/octet-stream': ['.ink'] },
+ },
+ {
+ description: 'Photoshop Document with Layers (*.psd)',
+ accept: { 'image/vnd.adobe.photoshop': ['.psd'] },
+ },
+ {
+ description: 'PNG Image (*.png)',
+ accept: { 'image/png': ['.png'] },
+ },
+ {
+ description: 'JPEG Image (*.jpg, *.jpeg)',
+ accept: { 'image/jpeg': ['.jpg', '.jpeg'] },
+ },
+ {
+ description: 'WebP Image (*.webp)',
+ accept: { 'image/webp': ['.webp'] },
+ },
+ ];
+
+ if (typeof window !== 'undefined' && 'showSaveFilePicker' in window) {
+ try {
+ const handle = await (window as any).showSaveFilePicker({
+ suggestedName,
+ types,
+ });
+
+ const fileName = handle.name;
+ const ext = fileName.includes('.')
+ ? fileName.slice(fileName.lastIndexOf('.')).toLowerCase()
+ : resolvedDefaultExt;
+
+ const serialized = await serializeDocument(data, ext);
+ const writable = await handle.createWritable();
+ await writable.write(serialized.data);
+ await writable.close();
+
+ if (data.tabId) {
+ recoveryService.markCleanSaved(data.tabId).catch(console.warn);
+ }
+
+ return {
+ handle,
+ name: fileName,
+ extension: ext,
+ size: getSerializedByteSize(serialized.data),
+ previewDataUrl: serialized.previewDataUrl,
+ };
+ } catch (err: any) {
+ if (err.name === 'AbortError') {
+ throw new Error('Save canceled');
+ }
+ console.warn('showSaveFilePicker failed or unsupported, using download fallback:', err);
+ }
+ }
+
+ if (fallbackToDownload) {
+ const ext = resolvedDefaultExt;
+ const serialized = await serializeDocument(data, ext);
+ downloadFile(serialized.data, suggestedName, serialized.mimeType);
+
+ if (data.tabId) {
+ recoveryService.markCleanSaved(data.tabId).catch(console.warn);
+ }
+
+ return {
+ name: suggestedName,
+ extension: ext,
+ size: getSerializedByteSize(serialized.data),
+ previewDataUrl: serialized.previewDataUrl,
+ };
+ }
+
+ throw new Error('Save dialog was not available');
+}
+
+/**
+ * Writes directly to an already selected FileSystemFileHandle without prompting.
+ */
+export async function saveToExistingHandle(
+ data: SaveDocumentData,
+ fileInfo: SavedFileInfo
+): Promise<{ size: number; previewDataUrl?: string }> {
+ if (!fileInfo.handle || typeof fileInfo.handle.createWritable !== 'function') {
+ throw new Error('No valid file handle to save to');
+ }
+
+ const serialized = await serializeDocument(data, fileInfo.extension);
+ const writable = await fileInfo.handle.createWritable();
+ await writable.write(serialized.data);
+ await writable.close();
+
+ if (data.tabId) {
+ recoveryService.markCleanSaved(data.tabId).catch(console.warn);
+ }
+
+ return {
+ size: getSerializedByteSize(serialized.data),
+ previewDataUrl: serialized.previewDataUrl,
+ };
+}
+
+/**
+ * Prompts user to choose a download/save path specifically for an exported image (PNG / JPG / WebP).
+ */
+export async function promptExportPngImage(
+ data: SaveDocumentData,
+ defaultName?: string
+): Promise<string> {
+ const safeName = (defaultName || data.name || 'artwork').trim().replace(/[^a-zA-Z0-9_\- ]/g, '_');
+ const suggestedName = `${safeName}.png`;
+
+ const types = [
+ {
+ description: 'PNG Image (*.png)',
+ accept: { 'image/png': ['.png'] },
+ },
+ {
+ description: 'JPEG Image (*.jpg, *.jpeg)',
+ accept: { 'image/jpeg': ['.jpg', '.jpeg'] },
+ },
+ {
+ description: 'WebP Image (*.webp)',
+ accept: { 'image/webp': ['.webp'] },
+ },
+ ];
+
+ if (typeof window !== 'undefined' && 'showSaveFilePicker' in window) {
+ try {
+ const handle = await (window as any).showSaveFilePicker({
+ suggestedName,
+ types,
+ });
+
+ const fileName: string = handle.name;
+ const ext = fileName.includes('.')
+ ? fileName.slice(fileName.lastIndexOf('.')).toLowerCase()
+ : '.png';
+ const serialized = await serializeDocument(data, ext);
+ const writable = await handle.createWritable();
+ await writable.write(serialized.data);
+ await writable.close();
+
+ return fileName;
+ } catch (err: any) {
+ if (err.name === 'AbortError') {
+ throw new Error('Export canceled');
+ }
+ console.warn('showSaveFilePicker failed for export, falling back to download:', err);
+ }
+ }
+
+ const serialized = await serializeDocument(data, '.png');
+ downloadFile(serialized.data, suggestedName, 'image/png');
+ return suggestedName;
+}
diff --git a/src/utils/saveManager/gpuComposite.ts b/src/utils/saveManager/gpuComposite.ts
new file mode 100644
index 0000000..259a0fc
--- /dev/null
+++ b/src/utils/saveManager/gpuComposite.ts
@@ -0,0 +1,430 @@
+import type { CanvasColorMode, CanvasDimensions, LayerItem } from '../../types/editor';
+import { ViewportCompositor, ViewportTransform } from '../compositor';
+import { SparseTileGrid, releaseTemporaryCanvas } from '../tileEngine';
+import {
+ CompositeCanvasOptions,
+ INK_DEFAULT_TILE_EXPORT_SIZE,
+ yieldToMainThread,
+} from './types';
+import {
+ buildGpuExportTilePlan,
+ computeMaxLayerStyleMargin,
+ hydratePagedTilesForLayers,
+ prepareExportTileGrid,
+} from './exportGridPrep';
+import { compositeCanvasCpuFallback } from './cpuComposite';
+
+function tryCompositeCanvasGpuSync(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement> | undefined,
+ fillWhiteBackground: boolean,
+ tileGrid?: SparseTileGrid,
+ options?: CompositeCanvasOptions
+): HTMLCanvasElement | null {
+ if (typeof document === 'undefined' || dimensions.width <= 0 || dimensions.height <= 0) {
+ return null;
+ }
+
+ const probeCanvas = document.createElement('canvas');
+ const requestedTileSize = options?.tileSize ?? INK_DEFAULT_TILE_EXPORT_SIZE;
+ probeCanvas.width = Math.min(requestedTileSize, dimensions.width);
+ probeCanvas.height = Math.min(requestedTileSize, dimensions.height);
+
+ const compositor = new ViewportCompositor(probeCanvas, { preserveDrawingBuffer: true });
+ if (!compositor.isReady()) {
+ compositor.dispose();
+ releaseTemporaryCanvas(probeCanvas);
+ return null;
+ }
+
+ const prepared = prepareExportTileGrid(dimensions, layers, layerCanvasesMap, tileGrid);
+ const exportCanvas = document.createElement('canvas');
+ exportCanvas.width = dimensions.width;
+ exportCanvas.height = dimensions.height;
+ const dstCtx = exportCanvas.getContext('2d');
+
+ try {
+ if (!dstCtx) {
+ return exportCanvas;
+ }
+
+ const maxGpuTile = Math.min(requestedTileSize, compositor.getMaxTextureSize());
+ const styleMargin = computeMaxLayerStyleMargin(layers);
+ const plan = buildGpuExportTilePlan(dimensions.width, dimensions.height, maxGpuTile, styleMargin);
+
+ if (probeCanvas.width !== plan.fboWidth) probeCanvas.width = plan.fboWidth;
+ if (probeCanvas.height !== plan.fboHeight) probeCanvas.height = plan.fboHeight;
+
+ const total = plan.tiles.length;
+ for (let i = 0; i < total; i++) {
+ const entry = plan.tiles[i];
+ const transform: ViewportTransform = {
+ pan: {
+ x: dimensions.width * 0.5 - entry.originX,
+ y: dimensions.height * 0.5 - entry.originY,
+ },
+ zoom: 1.0,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ };
+
+ compositor.render(layers, transform, dimensions, prepared.grid, {
+ dimensions,
+ colorMode: options?.colorMode,
+ showCheckerboard: false,
+ transparentBackground: !fillWhiteBackground,
+ bypassStackCache: true,
+ devicePixelRatio: 1,
+ });
+
+ dstCtx.drawImage(
+ probeCanvas,
+ entry.padLeft,
+ entry.padTop,
+ entry.width,
+ entry.height,
+ entry.tileX,
+ entry.tileY,
+ entry.width,
+ entry.height
+ );
+
+ if (options?.onProgress) {
+ const done = i + 1;
+ options.onProgress({
+ phase: 'compositing',
+ current: done,
+ total,
+ percent: Math.round((done / total) * 100),
+ message: `Compositing GPU tile ${done}/${total}...`,
+ });
+ }
+ }
+
+ return exportCanvas;
+ } catch (err) {
+ console.warn('GPU tiled export failed, falling back to CPU compositor:', err);
+ releaseTemporaryCanvas(exportCanvas);
+ return null;
+ } finally {
+ compositor.dispose();
+ releaseTemporaryCanvas(probeCanvas);
+ if (prepared.isTemporary) {
+ prepared.grid.clearAll();
+ }
+ }
+}
+
+/**
+ * Asynchronous tiled GPU compositor with paged-tile hydration, progress reporting,
+ * and event-loop yields between tiles. Falls back to CPU only when WebGL2 is unavailable.
+ */
+export async function compositeCanvasAsync(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement> | undefined,
+ getEffectiveOpacity: (layer: LayerItem) => number,
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
+ fillWhiteBackground: boolean = false,
+ tileGrid?: SparseTileGrid,
+ options?: CompositeCanvasOptions
+): Promise<{ canvas: HTMLCanvasElement; usedGpu: boolean }> {
+ await hydratePagedTilesForLayers(tileGrid, layers, true);
+
+ if (typeof document !== 'undefined' && dimensions.width > 0 && dimensions.height > 0) {
+ const requestedTileSize = options?.tileSize ?? INK_DEFAULT_TILE_EXPORT_SIZE;
+ const probeCanvas = document.createElement('canvas');
+ probeCanvas.width = Math.min(requestedTileSize, dimensions.width);
+ probeCanvas.height = Math.min(requestedTileSize, dimensions.height);
+
+ const compositor = new ViewportCompositor(probeCanvas, { preserveDrawingBuffer: true });
+ if (compositor.isReady()) {
+ const prepared = prepareExportTileGrid(dimensions, layers, layerCanvasesMap, tileGrid);
+ const exportCanvas = document.createElement('canvas');
+ exportCanvas.width = dimensions.width;
+ exportCanvas.height = dimensions.height;
+ const dstCtx = exportCanvas.getContext('2d');
+
+ try {
+ if (dstCtx) {
+ const maxGpuTile = Math.min(requestedTileSize, compositor.getMaxTextureSize());
+ const styleMargin = computeMaxLayerStyleMargin(layers);
+ const plan = buildGpuExportTilePlan(dimensions.width, dimensions.height, maxGpuTile, styleMargin);
+
+ if (probeCanvas.width !== plan.fboWidth) probeCanvas.width = plan.fboWidth;
+ if (probeCanvas.height !== plan.fboHeight) probeCanvas.height = plan.fboHeight;
+
+ const total = plan.tiles.length;
+ for (let i = 0; i < total; i++) {
+ const entry = plan.tiles[i];
+ const transform: ViewportTransform = {
+ pan: {
+ x: dimensions.width * 0.5 - entry.originX,
+ y: dimensions.height * 0.5 - entry.originY,
+ },
+ zoom: 1.0,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ };
+
+ compositor.render(layers, transform, dimensions, prepared.grid, {
+ dimensions,
+ colorMode: options?.colorMode,
+ showCheckerboard: false,
+ transparentBackground: !fillWhiteBackground,
+ bypassStackCache: true,
+ devicePixelRatio: 1,
+ });
+
+ dstCtx.drawImage(
+ probeCanvas,
+ entry.padLeft,
+ entry.padTop,
+ entry.width,
+ entry.height,
+ entry.tileX,
+ entry.tileY,
+ entry.width,
+ entry.height
+ );
+
+ if (options?.onProgress) {
+ const done = i + 1;
+ options.onProgress({
+ phase: 'compositing',
+ current: done,
+ total,
+ percent: Math.round((done / total) * 85),
+ message: `Compositing GPU tile ${done}/${total}...`,
+ });
+ }
+
+ if (i + 1 < total) {
+ await yieldToMainThread();
+ }
+ }
+ }
+ return { canvas: exportCanvas, usedGpu: true };
+ } catch (err) {
+ console.warn('Async GPU tiled export failed, falling back to CPU compositor:', err);
+ releaseTemporaryCanvas(exportCanvas);
+ } finally {
+ compositor.dispose();
+ releaseTemporaryCanvas(probeCanvas);
+ if (prepared.isTemporary) {
+ prepared.grid.clearAll();
+ }
+ }
+ } else {
+ compositor.dispose();
+ releaseTemporaryCanvas(probeCanvas);
+ }
+ }
+
+ const cpuCanvas = compositeCanvasCpuFallback(
+ dimensions,
+ layers,
+ layerCanvasesMap,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ fillWhiteBackground,
+ tileGrid
+ );
+ return { canvas: cpuCanvas, usedGpu: false };
+}
+
+/**
+ * Creates a reusable GPU region renderer (with CPU fallback) for rendering arbitrary
+ * document strips (e.g., tall 800x50,000px Webtoon chapter slices without allocating
+ * a monolithic full-height canvas). Caller MUST call `dispose()` when done.
+ */
+export function createDocumentRegionRenderer(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement> | undefined,
+ getEffectiveOpacity: (layer: LayerItem) => number,
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
+ tileGrid?: SparseTileGrid,
+ options?: { colorMode?: CanvasColorMode; maxTileSize?: number }
+): {
+ usedGpu: boolean;
+ renderRegion: (
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ targetCanvas: HTMLCanvasElement,
+ fillWhiteBackground: boolean
+ ) => void;
+ dispose: () => void;
+} {
+ const maxTileSize = options?.maxTileSize ?? INK_DEFAULT_TILE_EXPORT_SIZE;
+ const styleMargin = computeMaxLayerStyleMargin(layers);
+ const prepared = prepareExportTileGrid(dimensions, layers, layerCanvasesMap, tileGrid);
+
+ let gpuCanvas: HTMLCanvasElement | null = null;
+ let compositor: ViewportCompositor | null = null;
+ let usedGpu = false;
+ let cpuFullCache: HTMLCanvasElement | null = null;
+ let cpuFullCacheWhite = false;
+
+ if (typeof document !== 'undefined') {
+ gpuCanvas = document.createElement('canvas');
+ gpuCanvas.width = Math.min(maxTileSize, Math.max(1, dimensions.width));
+ gpuCanvas.height = Math.min(maxTileSize, Math.max(1, dimensions.height));
+ const candidate = new ViewportCompositor(gpuCanvas, { preserveDrawingBuffer: true });
+ if (candidate.isReady()) {
+ compositor = candidate;
+ usedGpu = true;
+ } else {
+ candidate.dispose();
+ releaseTemporaryCanvas(gpuCanvas);
+ gpuCanvas = null;
+ }
+ }
+
+ const renderRegion = (
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ targetCanvas: HTMLCanvasElement,
+ fillWhiteBackground: boolean
+ ): void => {
+ const dstCtx = targetCanvas.getContext('2d');
+ if (!dstCtx || width <= 0 || height <= 0) return;
+
+ if (fillWhiteBackground) {
+ dstCtx.fillStyle = '#ffffff';
+ dstCtx.fillRect(0, 0, width, height);
+ } else {
+ dstCtx.clearRect(0, 0, width, height);
+ }
+
+ if (compositor && gpuCanvas) {
+ const maxGpuTile = Math.min(maxTileSize, compositor.getMaxTextureSize());
+ const clampedMargin = Math.max(0, Math.min(styleMargin, Math.floor((maxGpuTile - 256) / 2)));
+ const innerStep = Math.max(256, maxGpuTile - clampedMargin * 2);
+
+ for (let sy = 0; sy < height; sy += innerStep) {
+ const subH = Math.min(innerStep, height - sy);
+ const docY = y + sy;
+ const padTop = Math.min(clampedMargin, docY);
+ const padBottom = Math.min(clampedMargin, Math.max(0, dimensions.height - (docY + subH)));
+
+ for (let sx = 0; sx < width; sx += innerStep) {
+ const subW = Math.min(innerStep, width - sx);
+ const docX = x + sx;
+ const padLeft = Math.min(clampedMargin, docX);
+ const padRight = Math.min(clampedMargin, Math.max(0, dimensions.width - (docX + subW)));
+
+ const fboW = subW + padLeft + padRight;
+ const fboH = subH + padTop + padBottom;
+ if (gpuCanvas.width < fboW) gpuCanvas.width = fboW;
+ if (gpuCanvas.height < fboH) gpuCanvas.height = fboH;
+
+ const transform: ViewportTransform = {
+ pan: {
+ x: dimensions.width * 0.5 - (docX - padLeft),
+ y: dimensions.height * 0.5 - (docY - padTop),
+ },
+ zoom: 1.0,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ };
+
+ compositor.render(layers, transform, dimensions, prepared.grid, {
+ dimensions,
+ colorMode: options?.colorMode,
+ showCheckerboard: false,
+ transparentBackground: !fillWhiteBackground,
+ bypassStackCache: true,
+ devicePixelRatio: 1,
+ });
+
+ dstCtx.drawImage(gpuCanvas, padLeft, padTop, subW, subH, sx, sy, subW, subH);
+ }
+ }
+ return;
+ }
+
+ // CPU fallback when WebGL2 is unavailable
+ if (!cpuFullCache || cpuFullCacheWhite !== fillWhiteBackground) {
+ if (cpuFullCache) releaseTemporaryCanvas(cpuFullCache);
+ cpuFullCache = compositeCanvasCpuFallback(
+ dimensions,
+ layers,
+ layerCanvasesMap,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ fillWhiteBackground,
+ tileGrid
+ );
+ cpuFullCacheWhite = fillWhiteBackground;
+ }
+ dstCtx.drawImage(cpuFullCache, x, y, width, height, 0, 0, width, height);
+ };
+
+ const dispose = (): void => {
+ if (compositor) {
+ compositor.dispose();
+ compositor = null;
+ }
+ if (gpuCanvas) {
+ releaseTemporaryCanvas(gpuCanvas);
+ gpuCanvas = null;
+ }
+ if (cpuFullCache) {
+ releaseTemporaryCanvas(cpuFullCache);
+ cpuFullCache = null;
+ }
+ if (prepared.isTemporary) {
+ prepared.grid.clearAll();
+ }
+ };
+
+ return { usedGpu, renderRegion, dispose };
+}
+
+/**
+ * Composites all visible layers using tiled offscreen WebGL2 rendering via `ViewportCompositor`
+ * (preserving 100% of GPU blend modes, Layer Styles, Screentones, Layer Color Tint,
+ * Expression Color, Frame Folders, and Adjustment Layers).
+ * Falls back to 2D CPU compositing strictly when WebGL2 is unavailable.
+ */
+export function compositeCanvas(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement> | undefined,
+ getEffectiveOpacity: (layer: LayerItem) => number,
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
+ fillWhiteBackground: boolean = false,
+ tileGrid?: SparseTileGrid,
+ options?: CompositeCanvasOptions
+): HTMLCanvasElement {
+ const gpuResult = tryCompositeCanvasGpuSync(
+ dimensions,
+ layers,
+ layerCanvasesMap,
+ fillWhiteBackground,
+ tileGrid,
+ options
+ );
+ if (gpuResult) {
+ return gpuResult;
+ }
+
+ return compositeCanvasCpuFallback(
+ dimensions,
+ layers,
+ layerCanvasesMap,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ fillWhiteBackground,
+ tileGrid
+ );
+}
diff --git a/src/utils/saveManager/inkCodec.ts b/src/utils/saveManager/inkCodec.ts
new file mode 100644
index 0000000..00933ff
--- /dev/null
+++ b/src/utils/saveManager/inkCodec.ts
@@ -0,0 +1,189 @@
+import { ViewportCompositor } from '../compositor';
+import {
+ SparseTileGrid,
+ TileBuffer,
+ getTileByteSize,
+ releaseTemporaryCanvas,
+} from '../tileEngine';
+import {
+ INK_BYTE_TO_TILE_FORMAT,
+ INK_TILE_FORMAT_TO_BYTE,
+ MASK_BINARY_HEADER_BYTES,
+ MAX_DOCUMENT_DIM,
+ PREVIEW_MAX_DIM,
+ SaveDocumentData,
+ TILE_BINARY_HEADER_BYTES,
+ canvasToBlob,
+} from './types';
+
+export function encodeNativeTileRecord(tile: TileBuffer, rawBytes: Uint8Array): Uint8Array {
+ const fmtByte = INK_TILE_FORMAT_TO_BYTE[tile.format] ?? 2;
+ const out = new Uint8Array(TILE_BINARY_HEADER_BYTES + rawBytes.byteLength);
+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
+ view.setUint8(0, fmtByte);
+ view.setUint32(1, tile.version >>> 0, true);
+ view.setUint32(5, rawBytes.byteLength >>> 0, true);
+ out.set(rawBytes, TILE_BINARY_HEADER_BYTES);
+ return out;
+}
+
+export function decodeNativeTileRecord(
+ layerId: string,
+ tileX: number,
+ tileY: number,
+ payload: Uint8Array
+): TileBuffer {
+ if (payload.byteLength < TILE_BINARY_HEADER_BYTES) {
+ throw new Error(`Corrupted .ink tile (${layerId} ${tileX}_${tileY}): header truncated`);
+ }
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
+ const fmtByte = view.getUint8(0);
+ const format = INK_BYTE_TO_TILE_FORMAT[fmtByte];
+ if (!format) {
+ throw new Error(`Corrupted .ink tile (${layerId} ${tileX}_${tileY}): unknown format byte ${fmtByte}`);
+ }
+ const version = view.getUint32(1, true);
+ const dataLen = view.getUint32(5, true);
+ const expectedLen = getTileByteSize(format);
+ if (dataLen !== expectedLen || payload.byteLength !== TILE_BINARY_HEADER_BYTES + expectedLen) {
+ throw new Error(
+ `Corrupted .ink tile (${layerId} ${tileX}_${tileY}): length mismatch (expected ${expectedLen}, got ${dataLen}/${payload.byteLength - TILE_BINARY_HEADER_BYTES})`
+ );
+ }
+ const data = new Uint8Array(expectedLen);
+ data.set(payload.subarray(TILE_BINARY_HEADER_BYTES, TILE_BINARY_HEADER_BYTES + expectedLen));
+ return {
+ layerId,
+ tileX,
+ tileY,
+ format,
+ data,
+ dirty: true,
+ version: version || 1,
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
+ };
+}
+
+export function encodeMaskBinary(maskCanvas: HTMLCanvasElement): { width: number; height: number; record: Uint8Array } | null {
+ const w = maskCanvas.width;
+ const h = maskCanvas.height;
+ if (w <= 0 || h <= 0 || w > MAX_DOCUMENT_DIM || h > MAX_DOCUMENT_DIM) return null;
+ const ctx = maskCanvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx || typeof ctx.getImageData !== 'function') return null;
+
+ const src = ctx.getImageData(0, 0, w, h).data;
+ const pixelCount = w * h;
+ const record = new Uint8Array(MASK_BINARY_HEADER_BYTES + pixelCount);
+ const view = new DataView(record.buffer, record.byteOffset, record.byteLength);
+ view.setUint32(0, w >>> 0, true);
+ view.setUint32(4, h >>> 0, true);
+
+ for (let p = 0, i = 0; p < pixelCount; p++, i += 4) {
+ record[MASK_BINARY_HEADER_BYTES + p] = Math.round(
+ ((0.299 * src[i] + 0.587 * src[i + 1] + 0.114 * src[i + 2]) * src[i + 3]) / 255
+ );
+ }
+ return { width: w, height: h, record };
+}
+
+export function decodeMaskBinary(payload: Uint8Array): { width: number; height: number; data: Uint8Array } {
+ if (payload.byteLength < MASK_BINARY_HEADER_BYTES) {
+ throw new Error('Corrupted .ink mask: header truncated');
+ }
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
+ const width = view.getUint32(0, true);
+ const height = view.getUint32(4, true);
+ if (width === 0 || height === 0 || width > MAX_DOCUMENT_DIM || height > MAX_DOCUMENT_DIM) {
+ throw new Error(`Invalid .ink mask dimensions: ${width}x${height}`);
+ }
+ const expectedPixels = width * height;
+ if (payload.byteLength !== MASK_BINARY_HEADER_BYTES + expectedPixels) {
+ throw new Error(
+ `Corrupted .ink mask: expected ${expectedPixels} bytes, got ${payload.byteLength - MASK_BINARY_HEADER_BYTES}`
+ );
+ }
+ const data = new Uint8Array(expectedPixels);
+ data.set(payload.subarray(MASK_BINARY_HEADER_BYTES));
+ return { width, height, data };
+}
+
+export function createMaskCanvasFromAlpha(width: number, height: number, alpha: Uint8Array): HTMLCanvasElement | undefined {
+ if (typeof document === 'undefined') return undefined;
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext('2d');
+ if (!ctx || typeof ctx.putImageData !== 'function') return undefined;
+
+ const rgba = new Uint8ClampedArray(width * height * 4);
+ for (let p = 0, i = 0; p < alpha.length; p++, i += 4) {
+ const v = alpha[p];
+ rgba[i] = v;
+ rgba[i + 1] = v;
+ rgba[i + 2] = v;
+ rgba[i + 3] = 255;
+ }
+ if (typeof ImageData !== 'undefined') {
+ ctx.putImageData(new ImageData(rgba, width, height), 0, 0);
+ } else if (typeof ctx.createImageData === 'function') {
+ const imgData = ctx.createImageData(width, height);
+ imgData.data.set(rgba);
+ ctx.putImageData(imgData, 0, 0);
+ }
+ return canvas;
+}
+
+export async function generatePreviewPng(
+ data: SaveDocumentData,
+ tileGrid: SparseTileGrid | undefined
+): Promise<{ bytes: Uint8Array; width: number; height: number } | null> {
+ if (typeof document === 'undefined' || data.dimensions.width <= 0 || data.dimensions.height <= 0) {
+ return null;
+ }
+ const scale = Math.min(1, PREVIEW_MAX_DIM / Math.max(data.dimensions.width, data.dimensions.height));
+ const outW = Math.max(1, Math.round(data.dimensions.width * scale));
+ const outH = Math.max(1, Math.round(data.dimensions.height * scale));
+ const previewCanvas = document.createElement('canvas');
+ previewCanvas.width = outW;
+ previewCanvas.height = outH;
+
+ if (typeof previewCanvas.toBlob !== 'function') {
+ releaseTemporaryCanvas(previewCanvas);
+ return null;
+ }
+
+ try {
+ if (tileGrid) {
+ ViewportCompositor.renderLowResPreview(previewCanvas, data.layers, data.dimensions, tileGrid, {
+ showCheckerboard: false,
+ });
+ } else {
+ const ctx = previewCanvas.getContext('2d');
+ if (!ctx) return null;
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, outW, outH);
+ for (let i = data.layers.length - 1; i >= 0; i--) {
+ const layer = data.layers[i];
+ if (!layer.visible || layer.opacity <= 0.001) continue;
+ const src = data.layerCanvasesMap?.get(layer.id);
+ if (!src) continue;
+ ctx.save();
+ ctx.globalAlpha = Math.max(0, Math.min(1, layer.opacity));
+ ctx.drawImage(src, 0, 0, outW, outH);
+ ctx.restore();
+ }
+ }
+
+ const blob = await canvasToBlob(previewCanvas, 'image/png');
+ const buf = await blob.arrayBuffer();
+ const bytes = new Uint8Array(buf);
+ if (bytes.byteLength === 0) return null;
+ return { bytes, width: outW, height: outH };
+ } catch {
+ return null;
+ } finally {
+ releaseTemporaryCanvas(previewCanvas);
+ }
+}
diff --git a/src/utils/saveManager/inkParse.ts b/src/utils/saveManager/inkParse.ts
new file mode 100644
index 0000000..252deed
--- /dev/null
+++ b/src/utils/saveManager/inkParse.ts
@@ -0,0 +1,256 @@
+import { unzipSync } from 'fflate';
+import { CanvasColorMode, LayerItem, hasTileBackedLayer } from '../../types/editor';
+import { SparseTileGrid, TileBuffer, TileFormat } from '../tileEngine';
+import {
+ CHUNK_YIELD_INTERVAL,
+ MAX_DOCUMENT_DIM,
+ MAX_MANIFEST_BYTES,
+ MAX_TILE_ENTRIES,
+ ParsedInkProject,
+ SaveProgress,
+ isInkProjectBytes,
+ isSafeZipPath,
+ sanitizeJsonLayer,
+ toPngDataUrl,
+ yieldToMainThread,
+} from './types';
+import { inferLayerTileFormat } from './exportGridPrep';
+import {
+ createMaskCanvasFromAlpha,
+ decodeMaskBinary,
+ decodeNativeTileRecord,
+} from './inkCodec';
+
+/**
+ * Extracts `preview.png` from raw ZIP container bytes without inflating tile entries.
+ */
+export function extractZipPreview(zipBytes: Uint8Array): Uint8Array | null {
+ if (!isInkProjectBytes(zipBytes)) return null;
+ try {
+ const extracted = unzipSync(zipBytes, {
+ filter: (file) => file.name === 'preview.png',
+ });
+ const png = extracted['preview.png'];
+ return png && png.byteLength > 0 ? png : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Fast preview-only extraction from a `.ink` archive for Recent Documents.
+ */
+export function extractInkPreview(input: ArrayBuffer | Uint8Array): Uint8Array | null {
+ const raw = input instanceof Uint8Array ? input : new Uint8Array(input);
+ return extractZipPreview(raw);
+}
+
+/**
+ * Unpacks and validates a binary v2 ZIP container (used by `.ink` and the read-only `.sora` migrator).
+ */
+export async function parseInkZipBytes(
+ zipBytes: Uint8Array,
+ options?: { onProgress?: (progress: SaveProgress) => void; containerLabel?: string }
+): Promise<ParsedInkProject> {
+ const onProgress = options?.onProgress;
+ const label = options?.containerLabel ?? '.ink';
+
+ onProgress?.({
+ phase: 'preparing',
+ current: 0,
+ total: 1,
+ percent: 5,
+ message: `Unpacking ${label} container...`,
+ });
+
+ const files = unzipSync(zipBytes);
+
+ const fileNames = Object.keys(files);
+ for (const name of fileNames) {
+ if (!isSafeZipPath(name)) {
+ throw new Error(`Unsafe archive path in ${label} file: "${name}"`);
+ }
+ }
+
+ const manifestRaw = files['manifest.json'];
+ if (!manifestRaw || manifestRaw.byteLength === 0) {
+ throw new Error(`Invalid ${label} project: missing manifest.json`);
+ }
+ if (manifestRaw.byteLength > MAX_MANIFEST_BYTES) {
+ throw new Error(`Invalid ${label} project: manifest.json exceeds size limit`);
+ }
+
+ const manifestText = new TextDecoder('utf-8').decode(manifestRaw);
+ const parsedManifest = JSON.parse(manifestText);
+ if (
+ !parsedManifest ||
+ typeof parsedManifest !== 'object' ||
+ !Array.isArray(parsedManifest.layers)
+ ) {
+ throw new Error(`Invalid ${label} manifest: missing layers array`);
+ }
+
+ const width = Math.floor(Number(parsedManifest.dimensions?.width) || 0);
+ const height = Math.floor(Number(parsedManifest.dimensions?.height) || 0);
+ if (width <= 0 || height <= 0 || width > MAX_DOCUMENT_DIM || height > MAX_DOCUMENT_DIM) {
+ throw new Error(`Invalid ${label} dimensions: ${width}x${height}`);
+ }
+ const dpi = Number(parsedManifest.dimensions?.dpi) || 300;
+ const colorMode: CanvasColorMode = parsedManifest.colorMode || 'color';
+ const layers: LayerItem[] = parsedManifest.layers.map((l: any) => sanitizeJsonLayer(l));
+
+ const keyToLayerId = new Map<string, string>();
+ if (parsedManifest.layerTileKeys && typeof parsedManifest.layerTileKeys === 'object') {
+ for (const [layerId, safeKey] of Object.entries(parsedManifest.layerTileKeys)) {
+ if (typeof safeKey === 'string' && safeKey.length > 0) {
+ keyToLayerId.set(safeKey, layerId);
+ }
+ }
+ }
+ for (const layer of layers) {
+ if (!keyToLayerId.has(layer.id)) {
+ keyToLayerId.set(layer.id, layer.id);
+ }
+ }
+
+ const layerFormats = new Map<string, TileFormat>();
+ if (parsedManifest.layerFormats && typeof parsedManifest.layerFormats === 'object') {
+ for (const [layerId, fmt] of Object.entries(parsedManifest.layerFormats)) {
+ if (fmt === 'monochrome-1bit' || fmt === 'grayscale-8bit' || fmt === 'color-32bit') {
+ layerFormats.set(layerId, fmt);
+ }
+ }
+ }
+
+ const tileRegex = /^tiles\/([^/]+)\/(-?\d+)_(-?\d+)\.bin$/;
+ const maskRegex = /^masks\/([^/]+)\.bin$/;
+
+ const tileEntries: Array<{ path: string; layerId: string; tx: number; ty: number }> = [];
+ const maskEntries: Array<{ path: string; layerId: string }> = [];
+
+ for (const path of fileNames) {
+ const tileMatch = tileRegex.exec(path);
+ if (tileMatch) {
+ const safeKey = tileMatch[1];
+ const layerId = keyToLayerId.get(safeKey);
+ if (!layerId) continue;
+ const tx = parseInt(tileMatch[2], 10);
+ const ty = parseInt(tileMatch[3], 10);
+ if (!Number.isSafeInteger(tx) || !Number.isSafeInteger(ty)) {
+ throw new Error(`Invalid tile coordinates in ${label} archive: ${path}`);
+ }
+ tileEntries.push({ path, layerId, tx, ty });
+ continue;
+ }
+
+ const maskMatch = maskRegex.exec(path);
+ if (maskMatch) {
+ const safeKey = maskMatch[1];
+ const layerId = keyToLayerId.get(safeKey);
+ if (layerId) {
+ maskEntries.push({ path, layerId });
+ }
+ }
+ }
+
+ if (tileEntries.length > MAX_TILE_ENTRIES) {
+ throw new Error(`Invalid ${label} project: tile count ${tileEntries.length} exceeds limit`);
+ }
+
+ const restoredTiles: TileBuffer[] = [];
+ for (let i = 0; i < tileEntries.length; i++) {
+ const entry = tileEntries[i];
+ const payload = files[entry.path];
+ const tile = decodeNativeTileRecord(entry.layerId, entry.tx, entry.ty, payload);
+ restoredTiles.push(tile);
+ if (!layerFormats.has(entry.layerId)) {
+ layerFormats.set(entry.layerId, tile.format);
+ }
+
+ const done = i + 1;
+ if (done % (CHUNK_YIELD_INTERVAL * 2) === 0 && done < tileEntries.length) {
+ onProgress?.({
+ phase: 'tiles',
+ current: done,
+ total: tileEntries.length,
+ percent: 15 + Math.round((done / tileEntries.length) * 70),
+ message: `Loading tiles (${done}/${tileEntries.length})...`,
+ });
+ await yieldToMainThread();
+ }
+ }
+
+ const tileGrid = new SparseTileGrid();
+ tileGrid.restoreFromSnapshot(restoredTiles, layerFormats);
+ for (const layer of layers) {
+ if (hasTileBackedLayer(layer)) {
+ const fmt = layerFormats.get(layer.id) ?? inferLayerTileFormat(layer);
+ tileGrid.setLayerFormat(layer.id, fmt);
+ tileGrid.markLayerIngested(layer.id);
+ }
+ }
+
+ const masksBinary = new Map<string, { width: number; height: number; data: Uint8Array }>();
+ const layerById = new Map<string, LayerItem>();
+ for (const l of layers) layerById.set(l.id, l);
+
+ for (const mEntry of maskEntries) {
+ const decoded = decodeMaskBinary(files[mEntry.path]);
+ masksBinary.set(mEntry.layerId, decoded);
+ const layer = layerById.get(mEntry.layerId);
+ if (layer) {
+ const maskCanvas = createMaskCanvasFromAlpha(decoded.width, decoded.height, decoded.data);
+ if (maskCanvas) {
+ layer.maskCanvas = maskCanvas;
+ layer.maskVersion = (layer.maskVersion || 0) + 1;
+ }
+ }
+ }
+
+ const previewPath =
+ typeof parsedManifest.preview?.path === 'string' && isSafeZipPath(parsedManifest.preview.path)
+ ? parsedManifest.preview.path
+ : 'preview.png';
+ const previewRaw = files[previewPath];
+ const previewBytes = previewRaw && previewRaw.byteLength > 0 ? new Uint8Array(previewRaw) : null;
+ const previewDataUrl = toPngDataUrl(previewBytes);
+
+ onProgress?.({
+ phase: 'done',
+ current: 1,
+ total: 1,
+ percent: 100,
+ message: 'Project loaded',
+ });
+
+ return {
+ format: 'ink-v2',
+ app: typeof parsedManifest.app === 'string' ? parsedManifest.app : 'Ink Studio',
+ version: typeof parsedManifest.version === 'string' ? parsedManifest.version : '2.0',
+ name: typeof parsedManifest.name === 'string' ? parsedManifest.name : 'Untitled',
+ dimensions: { width, height, dpi },
+ colorMode,
+ layers,
+ tileGrid,
+ masksBinary,
+ perspectiveRuler: parsedManifest.perspectiveRuler ?? null,
+ animationTimeline: parsedManifest.animationTimeline ?? null,
+ timelapse: parsedManifest.timelapse ?? null,
+ previewBytes,
+ previewDataUrl,
+ };
+}
+
+/**
+ * Parses a native binary `.ink` project archive.
+ */
+export async function parseInkProject(
+ input: ArrayBuffer | Uint8Array,
+ options?: { onProgress?: (progress: SaveProgress) => void }
+): Promise<ParsedInkProject> {
+ const rawBytes = input instanceof Uint8Array ? input : new Uint8Array(input);
+ if (!isInkProjectBytes(rawBytes)) {
+ throw new Error('Invalid .ink project: expected binary ZIP container');
+ }
+ return parseInkZipBytes(rawBytes, { ...options, containerLabel: '.ink' });
+}
diff --git a/src/utils/saveManager/inkSerialize.ts b/src/utils/saveManager/inkSerialize.ts
new file mode 100644
index 0000000..6fb1cb9
--- /dev/null
+++ b/src/utils/saveManager/inkSerialize.ts
@@ -0,0 +1,279 @@
+import { Zip, ZipDeflate, ZipPassThrough } from 'fflate';
+import { LayerItem, hasTileBackedLayer } from '../../types/editor';
+import {
+ SparseTileGrid,
+ TILE_SIZE,
+ TileBuffer,
+ TileFormat,
+ getTileByteSize,
+} from '../tileEngine';
+import { documentStore } from '../documentStore';
+import {
+ CHUNK_YIELD_INTERVAL,
+ InkProjectManifest,
+ SaveDocumentData,
+ concatUint8Arrays,
+ toPngDataUrl,
+ toSafeZipKey,
+ yieldToMainThread,
+} from './types';
+import { inferLayerTileFormat } from './exportGridPrep';
+import {
+ encodeMaskBinary,
+ encodeNativeTileRecord,
+ generatePreviewPng,
+} from './inkCodec';
+
+/**
+ * Serializes a document into the native binary `.ink` ZIP container:
+ * - `manifest.json` (metadata: document, layers, folders, masks, vectors, text, balloons, perspective, animation, timelapse)
+ * - `preview.png` (downscaled preview for Recent Documents)
+ * - `tiles/<layerKey>/<tx>_<ty>.bin` (native 1-bit/8-bit/32-bit SparseTileGrid buffers)
+ * - `masks/<layerKey>.bin` (8-bit mask luminance buffers)
+ */
+export async function serializeInkProject(
+ data: SaveDocumentData,
+ tileGrid?: SparseTileGrid
+): Promise<{
+ bytes: Uint8Array;
+ previewBytes: Uint8Array | null;
+ previewDataUrl?: string;
+ manifest: InkProjectManifest;
+}> {
+ const onProgress = data.onProgress;
+ const tileCompressionLevel = data.compressionLevel ?? 3;
+ const resolvedGrid =
+ tileGrid ??
+ data.tileGrid ??
+ (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : undefined);
+
+ onProgress?.({
+ phase: 'preparing',
+ current: 0,
+ total: 1,
+ percent: 2,
+ message: 'Preparing project metadata...',
+ });
+
+ const usedKeys = new Set<string>();
+ const layerTileKeys: Record<string, string> = {};
+ const layerFormats: Record<string, TileFormat> = {};
+ const masksMeta: Record<string, { width: number; height: number; format: 'alpha-8bit' }> = {};
+ const encodedMasks: Array<{ path: string; record: Uint8Array }> = [];
+
+ let fallbackTempGrid: SparseTileGrid | null = null;
+
+ type PendingTileSource = {
+ path: string;
+ tile: TileBuffer;
+ sourceGrid: SparseTileGrid;
+ };
+ const pendingTiles: PendingTileSource[] = [];
+ const serializableLayers: Array<Omit<LayerItem, 'maskCanvas'>> = [];
+
+ for (const layer of data.layers) {
+ const safeKey = toSafeZipKey(layer.id, usedKeys);
+ layerTileKeys[layer.id] = safeKey;
+
+ if (hasTileBackedLayer(layer)) {
+ const gridHasTiles = Boolean(resolvedGrid && resolvedGrid.hasLayerTiles(layer.id));
+ if (resolvedGrid && gridHasTiles) {
+ const tiles = resolvedGrid.getLayerTiles(layer.id, 0);
+ const fmt = tiles[0]?.format ?? resolvedGrid.getLayerFormat(layer.id);
+ layerFormats[layer.id] = fmt;
+ for (const tile of tiles) {
+ pendingTiles.push({
+ path: `tiles/${safeKey}/${tile.tileX}_${tile.tileY}.bin`,
+ tile,
+ sourceGrid: resolvedGrid,
+ });
+ }
+ } else {
+ const fmt = resolvedGrid?.getLayerFormat(layer.id) ?? inferLayerTileFormat(layer);
+ layerFormats[layer.id] = fmt;
+
+ const canvas = data.layerCanvasesMap?.get(layer.id);
+ if (canvas && canvas.width > 0 && canvas.height > 0) {
+ if (!fallbackTempGrid) {
+ fallbackTempGrid = new SparseTileGrid();
+ }
+ fallbackTempGrid.ingestCanvas(layer.id, canvas, fmt);
+ const tiles = fallbackTempGrid.getLayerTiles(layer.id, 0);
+ for (const tile of tiles) {
+ pendingTiles.push({
+ path: `tiles/${safeKey}/${tile.tileX}_${tile.tileY}.bin`,
+ tile,
+ sourceGrid: fallbackTempGrid,
+ });
+ }
+ }
+ }
+ }
+
+ if (layer.maskCanvas) {
+ const encodedMask = encodeMaskBinary(layer.maskCanvas);
+ if (encodedMask) {
+ masksMeta[layer.id] = {
+ width: encodedMask.width,
+ height: encodedMask.height,
+ format: 'alpha-8bit',
+ };
+ encodedMasks.push({
+ path: `masks/${safeKey}.bin`,
+ record: encodedMask.record,
+ });
+ }
+ }
+
+ const { maskCanvas: _mc, ...rest } = layer;
+ serializableLayers.push(rest);
+ }
+
+ onProgress?.({
+ phase: 'preview',
+ current: 0,
+ total: 1,
+ percent: 8,
+ message: 'Generating preview thumbnail...',
+ });
+ const preview = await generatePreviewPng(data, resolvedGrid);
+
+ const manifest: InkProjectManifest = {
+ format: 'ink-v2',
+ app: 'Ink Studio',
+ version: '2.0',
+ tileSize: TILE_SIZE,
+ name: data.name,
+ dimensions: {
+ width: data.dimensions.width,
+ height: data.dimensions.height,
+ dpi: data.dimensions.dpi ?? 300,
+ },
+ colorMode: data.colorMode,
+ layers: serializableLayers,
+ layerFormats,
+ layerTileKeys,
+ masksMeta,
+ perspectiveRuler: data.perspectiveRuler ?? null,
+ animationTimeline: data.animationTimeline ?? null,
+ timelapse: data.timelapse ?? null,
+ preview: preview ? { path: 'preview.png', width: preview.width, height: preview.height } : null,
+ savedAt: Date.now(),
+ };
+
+ const encoder = new TextEncoder();
+ const manifestBytes = encoder.encode(JSON.stringify(manifest));
+
+ const chunks: Uint8Array[] = [];
+ let zipError: Error | null = null;
+ const zip = new Zip((err, chunk, _final) => {
+ if (err) {
+ zipError = err;
+ return;
+ }
+ if (chunk && chunk.byteLength > 0) {
+ chunks.push(chunk);
+ }
+ });
+
+ try {
+ const manifestEntry = new ZipDeflate('manifest.json', { level: 6 });
+ zip.add(manifestEntry);
+ manifestEntry.push(manifestBytes, true);
+ if (zipError) throw zipError;
+
+ if (preview) {
+ const previewEntry = new ZipPassThrough('preview.png');
+ zip.add(previewEntry);
+ previewEntry.push(preview.bytes, true);
+ if (zipError) throw zipError;
+ }
+
+ const totalTiles = pendingTiles.length;
+ for (let i = 0; i < totalTiles; i++) {
+ const { tile, sourceGrid, path } = pendingTiles[i];
+
+ let rawBytes: Uint8Array | null = tile.data;
+ if (!rawBytes && tile.isPagedToDisk) {
+ const mm = sourceGrid.getMemoryManager();
+ if (mm) {
+ rawBytes = await mm.getDriver().readTile(mm.getSessionId(), tile.layerId, tile.tileX, tile.tileY);
+ }
+ }
+ if (!rawBytes) {
+ rawBytes = new Uint8Array(getTileByteSize(tile.format));
+ }
+
+ const record = encodeNativeTileRecord(tile, rawBytes);
+ const entry = new ZipDeflate(path, { level: tileCompressionLevel });
+ zip.add(entry);
+ entry.push(record, true);
+ if (zipError) throw zipError;
+
+ const done = i + 1;
+ if (done % CHUNK_YIELD_INTERVAL === 0 || done === totalTiles) {
+ const pct = 10 + Math.round((done / Math.max(1, totalTiles)) * 75);
+ onProgress?.({
+ phase: 'tiles',
+ current: done,
+ total: totalTiles,
+ percent: Math.min(85, pct),
+ message: `Saving tiles (${done}/${totalTiles})...`,
+ });
+ if (done < totalTiles) {
+ await yieldToMainThread();
+ }
+ }
+ }
+
+ const totalMasks = encodedMasks.length;
+ for (let i = 0; i < totalMasks; i++) {
+ const m = encodedMasks[i];
+ const entry = new ZipDeflate(m.path, { level: tileCompressionLevel });
+ zip.add(entry);
+ entry.push(m.record, true);
+ if (zipError) throw zipError;
+
+ const done = i + 1;
+ onProgress?.({
+ phase: 'masks',
+ current: done,
+ total: totalMasks,
+ percent: 85 + Math.round((done / Math.max(1, totalMasks)) * 10),
+ message: `Saving layer masks (${done}/${totalMasks})...`,
+ });
+ if (done % CHUNK_YIELD_INTERVAL === 0 && done < totalMasks) {
+ await yieldToMainThread();
+ }
+ }
+
+ onProgress?.({
+ phase: 'finalizing',
+ current: 1,
+ total: 1,
+ percent: 96,
+ message: 'Finalizing .ink archive...',
+ });
+
+ zip.end();
+ if (zipError) throw zipError;
+
+ const bytes = concatUint8Arrays(chunks);
+ const previewBytes = preview ? preview.bytes : null;
+ const previewDataUrl = toPngDataUrl(previewBytes);
+
+ onProgress?.({
+ phase: 'done',
+ current: 1,
+ total: 1,
+ percent: 100,
+ message: 'Saved successfully',
+ });
+
+ return { bytes, previewBytes, previewDataUrl, manifest };
+ } finally {
+ if (fallbackTempGrid) {
+ fallbackTempGrid.clearAll();
+ }
+ }
+}
diff --git a/src/utils/saveManager/psdExport.ts b/src/utils/saveManager/psdExport.ts
new file mode 100644
index 0000000..41fbbba
--- /dev/null
+++ b/src/utils/saveManager/psdExport.ts
@@ -0,0 +1,236 @@
+import type {
+ BlendMode as AgPsdBlendMode,
+ Layer as AgPsdLayer,
+ LayerMaskData as AgPsdMaskData,
+} from 'ag-psd';
+import {
+ BlendMode,
+ CanvasDimensions,
+ LayerItem,
+ isFolderLikeLayer,
+ hasTileBackedLayer,
+} from '../../types/editor';
+import type { LayerTreeNode } from '../compositor';
+import { SparseTileGrid, TILE_SIZE } from '../tileEngine';
+import { acquireLayerExportCanvas } from './exportGridPrep';
+
+/**
+ * Maps Ink Studio BlendMode to ag-psd BlendMode format.
+ */
+export function toAgPsdBlendMode(mode: BlendMode): AgPsdBlendMode {
+ switch (mode) {
+ case 'color-dodge':
+ case 'color-dodge-glow':
+ return 'color dodge';
+ case 'color-burn':
+ return 'color burn';
+ case 'linear-burn':
+ return 'linear burn';
+ case 'darker-color':
+ return 'darker color';
+ case 'add-glow':
+ return 'linear dodge';
+ case 'lighter-color':
+ return 'lighter color';
+ case 'hard-light':
+ return 'hard light';
+ case 'soft-light':
+ return 'soft light';
+ case 'vivid-light':
+ return 'vivid light';
+ case 'linear-light':
+ return 'linear light';
+ case 'pin-light':
+ return 'pin light';
+ case 'hard-mix':
+ return 'hard mix';
+ case 'pass-through':
+ return 'pass through';
+ case 'normal':
+ case 'multiply':
+ case 'screen':
+ case 'overlay':
+ case 'darken':
+ case 'lighten':
+ case 'difference':
+ case 'exclusion':
+ case 'subtract':
+ case 'divide':
+ case 'hue':
+ case 'saturation':
+ case 'color':
+ case 'luminosity':
+ return mode;
+ default:
+ return 'normal';
+ }
+}
+
+function extractLayerMaskForPsd(layer: LayerItem): AgPsdMaskData | undefined {
+ const maskCanvas = layer.maskCanvas;
+ if (!maskCanvas || maskCanvas.width <= 0 || maskCanvas.height <= 0) {
+ return undefined;
+ }
+
+ const mw = maskCanvas.width;
+ const mh = maskCanvas.height;
+ const maskMeta: AgPsdMaskData = {
+ top: 0,
+ left: 0,
+ bottom: mh,
+ right: mw,
+ defaultColor: 255,
+ disabled: layer.maskEnabled === false,
+ positionRelativeToLayer: layer.maskLinked === false,
+ };
+
+ const ctx = maskCanvas.getContext('2d', { willReadFrequently: true });
+ if (ctx && typeof ctx.getImageData === 'function') {
+ const src = ctx.getImageData(0, 0, mw, mh).data;
+ const out = new Uint8ClampedArray(mw * mh * 4);
+ for (let i = 0; i < src.length; i += 4) {
+ const lum = Math.round(((0.299 * src[i] + 0.587 * src[i + 1] + 0.114 * src[i + 2]) * src[i + 3]) / 255);
+ out[i] = lum;
+ out[i + 1] = lum;
+ out[i + 2] = lum;
+ out[i + 3] = 255;
+ }
+ maskMeta.imageData = { data: out, width: mw, height: mh };
+ } else {
+ maskMeta.canvas = maskCanvas;
+ }
+
+ return maskMeta;
+}
+
+function attachRasterPixelsForPsd(
+ target: AgPsdLayer,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ layerCanvasesMap: Map<string, HTMLCanvasElement> | undefined,
+ tileGrid: SparseTileGrid | undefined,
+ tempCanvases: HTMLCanvasElement[]
+): void {
+ const isVectorText =
+ (layer.type === 'text' && Boolean(layer.textData)) ||
+ (layer.type === 'balloon' && Boolean(layer.balloonData));
+
+ if (!isVectorText && !layerCanvasesMap?.has(layer.id) && tileGrid && tileGrid.hasLayerTiles(layer.id)) {
+ const tiles = tileGrid.getLayerTiles(layer.id, 0);
+ if (tiles.length === 0) return;
+
+ let minX = dimensions.width;
+ let minY = dimensions.height;
+ let maxX = 0;
+ let maxY = 0;
+ for (const tile of tiles) {
+ const tx0 = tile.tileX * TILE_SIZE;
+ const ty0 = tile.tileY * TILE_SIZE;
+ if (tx0 < minX) minX = tx0;
+ if (ty0 < minY) minY = ty0;
+ if (tx0 + TILE_SIZE > maxX) maxX = tx0 + TILE_SIZE;
+ if (ty0 + TILE_SIZE > maxY) maxY = ty0 + TILE_SIZE;
+ }
+ const left = Math.max(0, minX);
+ const top = Math.max(0, minY);
+ const right = Math.min(dimensions.width, maxX);
+ const bottom = Math.min(dimensions.height, maxY);
+ if (left < right && top < bottom) {
+ const imgData = tileGrid.readImageData(layer.id, left, top, right - left, bottom - top);
+ target.left = left;
+ target.top = top;
+ target.right = right;
+ target.bottom = bottom;
+ target.imageData = imgData;
+ }
+ return;
+ }
+
+ const acq = acquireLayerExportCanvas(layer, dimensions, layerCanvasesMap, tileGrid);
+ if (!acq.canvas) return;
+ if (acq.isTemporary) tempCanvases.push(acq.canvas);
+
+ const w = acq.canvas.width;
+ const h = acq.canvas.height;
+ if (w <= 0 || h <= 0) return;
+
+ const ctx = acq.canvas.getContext('2d', { willReadFrequently: true });
+ if (ctx && typeof ctx.getImageData === 'function') {
+ const imgData = ctx.getImageData(0, 0, w, h);
+ target.left = 0;
+ target.top = 0;
+ target.right = w;
+ target.bottom = h;
+ target.imageData = { data: imgData.data, width: w, height: h };
+ } else {
+ target.canvas = acq.canvas;
+ }
+}
+
+export function buildPsdLayerTree(
+ nodes: LayerTreeNode[],
+ dimensions: CanvasDimensions,
+ layerCanvasesMap: Map<string, HTMLCanvasElement> | undefined,
+ tileGrid: SparseTileGrid | undefined,
+ tempCanvases: HTMLCanvasElement[]
+): AgPsdLayer[] {
+ const result: AgPsdLayer[] = [];
+
+ for (let i = nodes.length - 1; i >= 0; i--) {
+ const node = nodes[i];
+ const layer = node.layer;
+ const isFolder = isFolderLikeLayer(layer);
+ if (!isFolder && !hasTileBackedLayer(layer)) continue;
+
+ const psdLayer: AgPsdLayer = {
+ name: layer.name,
+ hidden: !layer.visible,
+ opacity: Math.max(0, Math.min(1, layer.opacity ?? 1)),
+ blendMode: toAgPsdBlendMode(layer.blendMode),
+ };
+
+ if (layer.clipped) {
+ psdLayer.clipping = true;
+ }
+
+ if (layer.alphaLocked || layer.locked) {
+ psdLayer.protected = {
+ transparency: Boolean(layer.alphaLocked),
+ composite: Boolean(layer.locked),
+ position: Boolean(layer.locked),
+ };
+ if (layer.alphaLocked) {
+ psdLayer.transparencyProtected = true;
+ }
+ }
+
+ const mask = extractLayerMaskForPsd(layer);
+ if (mask) {
+ psdLayer.mask = mask;
+ }
+
+ if (isFolder) {
+ psdLayer.opened = !layer.collapsed;
+ psdLayer.children = buildPsdLayerTree(
+ node.children,
+ dimensions,
+ layerCanvasesMap,
+ tileGrid,
+ tempCanvases
+ );
+ } else {
+ attachRasterPixelsForPsd(
+ psdLayer,
+ layer,
+ dimensions,
+ layerCanvasesMap,
+ tileGrid,
+ tempCanvases
+ );
+ }
+
+ result.push(psdLayer);
+ }
+
+ return result;
+}
diff --git a/src/utils/saveManager/types.ts b/src/utils/saveManager/types.ts
new file mode 100644
index 0000000..6d46419
--- /dev/null
+++ b/src/utils/saveManager/types.ts
@@ -0,0 +1,264 @@
+import type {
+ CanvasDimensions,
+ LayerItem,
+ CanvasColorMode,
+ AnimationTimeline,
+ InkTimelapseMetadata,
+} from '../../types/editor';
+import type { PerspectiveRuler } from '../../types/perspective';
+import type { SparseTileGrid, TileFormat } from '../tileEngine';
+
+export const PRIMARY_PROJECT_EXTENSION = '.ink';
+
+export interface SavedFileInfo {
+ handle?: any; // FileSystemFileHandle
+ name: string;
+ extension: string;
+ size?: number;
+ previewDataUrl?: string;
+}
+
+export interface SaveProgress {
+ phase: 'preparing' | 'preview' | 'tiles' | 'masks' | 'compositing' | 'encoding' | 'finalizing' | 'done';
+ current: number;
+ total: number;
+ percent: number;
+ message: string;
+}
+
+export interface SaveDocumentData {
+ name: string;
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: LayerItem[];
+ layerCanvasesMap?: Map<string, HTMLCanvasElement>;
+ tileGrid?: SparseTileGrid;
+ getEffectiveOpacity: (layer: LayerItem) => number;
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
+ tabId?: string;
+ perspectiveRuler?: PerspectiveRuler | null;
+ animationTimeline?: AnimationTimeline | null;
+ timelapse?: InkTimelapseMetadata | null;
+ onProgress?: (progress: SaveProgress) => void;
+ compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
+}
+
+export interface InkProjectManifest {
+ format: 'ink-v2';
+ app: string;
+ version: '2.0';
+ tileSize: number;
+ name: string;
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: Array<Omit<LayerItem, 'maskCanvas'>>;
+ layerFormats: Record<string, TileFormat>;
+ layerTileKeys: Record<string, string>;
+ masksMeta: Record<string, { width: number; height: number; format: 'alpha-8bit' }>;
+ perspectiveRuler?: PerspectiveRuler | null;
+ animationTimeline?: AnimationTimeline | null;
+ timelapse?: InkTimelapseMetadata | null;
+ preview: { path: string; width: number; height: number } | null;
+ savedAt: number;
+}
+
+export interface ParsedInkProject {
+ format: 'ink-v2';
+ app: string;
+ version: string;
+ name: string;
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: LayerItem[];
+ tileGrid: SparseTileGrid;
+ masksBinary: Map<string, { width: number; height: number; data: Uint8Array }>;
+ perspectiveRuler?: PerspectiveRuler | null;
+ animationTimeline?: AnimationTimeline | null;
+ timelapse?: InkTimelapseMetadata | null;
+ previewBytes?: Uint8Array | null;
+ previewDataUrl?: string;
+}
+
+export interface ExportImageOptions {
+ format?: 'png' | 'jpg' | 'jpeg' | 'webp';
+ quality?: number;
+ fillWhiteBackground?: boolean;
+ tileSize?: number;
+ onProgress?: (progress: SaveProgress) => void;
+}
+
+export interface ExportImageResult {
+ blob: Blob;
+ mimeType: string;
+ width: number;
+ height: number;
+ usedGpu: boolean;
+}
+
+export interface CompositeCanvasOptions {
+ tileSize?: number;
+ colorMode?: CanvasColorMode;
+ onProgress?: (progress: SaveProgress) => void;
+}
+
+export interface GpuTilePlanEntry {
+ tileX: number;
+ tileY: number;
+ width: number;
+ height: number;
+ padLeft: number;
+ padTop: number;
+ padRight: number;
+ padBottom: number;
+ originX: number;
+ originY: number;
+ fboWidth: number;
+ fboHeight: number;
+}
+
+export const INK_DEFAULT_TILE_EXPORT_SIZE = 2048;
+
+export const INK_TILE_FORMAT_TO_BYTE: Record<TileFormat, number> = {
+ 'monochrome-1bit': 0,
+ 'grayscale-8bit': 1,
+ 'color-32bit': 2,
+};
+
+export const INK_BYTE_TO_TILE_FORMAT: Record<number, TileFormat> = {
+ 0: 'monochrome-1bit',
+ 1: 'grayscale-8bit',
+ 2: 'color-32bit',
+};
+
+export const TILE_BINARY_HEADER_BYTES = 9; // [format:u8][version:u32 LE][dataLen:u32 LE]
+export const MASK_BINARY_HEADER_BYTES = 8; // [width:u32 LE][height:u32 LE]
+export const MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
+export const MAX_DOCUMENT_DIM = 65536;
+export const MAX_TILE_ENTRIES = 120000;
+export const CHUNK_YIELD_INTERVAL = 8;
+export const MAX_STYLE_MARGIN_PX = 256;
+export const PREVIEW_MAX_DIM = 512;
+
+export function yieldToMainThread(): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+export function bytesToBase64(bytes: Uint8Array): string {
+ if (typeof btoa === 'function') {
+ const chunkSize = 0x8000;
+ let binary = '';
+ for (let i = 0; i < bytes.length; i += chunkSize) {
+ const slice = bytes.subarray(i, Math.min(i + chunkSize, bytes.length));
+ binary += String.fromCharCode(...slice);
+ }
+ return btoa(binary);
+ }
+ let out = '';
+ for (let i = 0; i < bytes.length; i += 3) {
+ const a = bytes[i];
+ const b = i + 1 < bytes.length ? bytes[i + 1] : 0;
+ const c = i + 2 < bytes.length ? bytes[i + 2] : 0;
+ const triple = (a << 16) | (b << 8) | c;
+ out += BASE64_ALPHABET[(triple >> 18) & 63];
+ out += BASE64_ALPHABET[(triple >> 12) & 63];
+ out += i + 1 < bytes.length ? BASE64_ALPHABET[(triple >> 6) & 63] : '=';
+ out += i + 2 < bytes.length ? BASE64_ALPHABET[triple & 63] : '=';
+ }
+ return out;
+}
+
+export function toPngDataUrl(bytes: Uint8Array | null | undefined): string | undefined {
+ if (!bytes || bytes.byteLength === 0) return undefined;
+ const b64 = bytesToBase64(bytes);
+ return b64 ? `data:image/png;base64,${b64}` : undefined;
+}
+
+export function toSafeZipKey(rawId: string, usedKeys: Set<string>): string {
+ let base = rawId.replace(/[^a-zA-Z0-9._-]/g, '_');
+ if (!base || base === '.' || base === '..') {
+ base = 'layer';
+ }
+ // Prevent hidden or traversal-looking segments
+ base = base.replace(/\.{2,}/g, '_');
+ let candidate = base;
+ let suffix = 1;
+ while (usedKeys.has(candidate)) {
+ candidate = `${base}_${suffix++}`;
+ }
+ usedKeys.add(candidate);
+ return candidate;
+}
+
+export function isSafeZipPath(path: string): boolean {
+ if (!path || path.includes('\0') || path.includes('\\') || path.startsWith('/')) {
+ return false;
+ }
+ const segments = path.split('/');
+ for (const seg of segments) {
+ if (!seg || seg === '.' || seg === '..') {
+ return false;
+ }
+ }
+ return true;
+}
+
+export function sanitizeJsonLayer(raw: any): LayerItem {
+ const clean: any = Object.create(null);
+ for (const key of Object.keys(raw)) {
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
+ clean[key] = raw[key];
+ }
+ const normalized: LayerItem = { ...clean };
+ if (normalized.maskCanvas && typeof normalized.maskCanvas.getContext !== 'function') {
+ normalized.maskCanvas = undefined;
+ }
+ return normalized;
+}
+
+/**
+ * Checks whether binary input begins with standard ZIP container magic bytes
+ * (`PK\x03\x04` local file header or `PK\x05\x06` empty archive).
+ */
+export function isInkProjectBytes(input: Uint8Array | ArrayBuffer): boolean {
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
+ if (bytes.byteLength < 4) return false;
+ return (
+ bytes[0] === 0x50 &&
+ bytes[1] === 0x4b &&
+ ((bytes[2] === 0x03 && bytes[3] === 0x04) || (bytes[2] === 0x05 && bytes[3] === 0x06))
+ );
+}
+
+export function concatUint8Arrays(chunks: Uint8Array[]): Uint8Array {
+ let total = 0;
+ for (const c of chunks) total += c.byteLength;
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const c of chunks) {
+ out.set(c, offset);
+ offset += c.byteLength;
+ }
+ return out;
+}
+
+/**
+ * Converts a canvas element into a Blob with the specified mime-type.
+ */
+export function canvasToBlob(
+ canvas: HTMLCanvasElement,
+ mimeType: string = 'image/png',
+ quality?: number
+): Promise<Blob> {
+ return new Promise((resolve, reject) => {
+ canvas.toBlob(
+ (blob) => {
+ if (blob) resolve(blob);
+ else reject(new Error('Canvas toBlob failed'));
+ },
+ mimeType,
+ quality
+ );
+ });
+}
diff --git a/src/utils/selectionUtils.ts b/src/utils/selectionUtils.ts
index 73f1caa..120400b 100644
--- a/src/utils/selectionUtils.ts
+++ b/src/utils/selectionUtils.ts
@@ -1,4 +1,13 @@
-import { CanvasSelection, DirtyRect, WandSettings } from '../types/editor';
+import { CanvasDimensions, CanvasSelection, DirtyRect, LayerItem, TileDelta, WandSettings } from '../types/editor';
+import {
+ SparseTileGrid,
+ TILE_SIZE,
+ TileFormat,
+ TileSnapshotEntry,
+ pixelToTileCoord,
+ releaseTemporaryCanvas,
+} from './tileEngine';
+import { buildCompositedReferenceTile, parseColorToRgba } from './floodFill';
/**
* Checks whether a 2D point lies within an arbitrary polygon using ray-casting.
@@ -928,3 +937,553 @@ export function commitFloatingSelection(
height: Math.max(floating.canvas.height + Math.abs(floating.y - floating.origY), floating.canvas.height),
};
}
+
+/**
+ * Tile-native Magic Wand selection directly from SparseTileGrid (zero full-canvas materialization).
+ */
+export function floodSelectWandOnTileGrid(params: {
+ grid: SparseTileGrid;
+ layers: LayerItem[];
+ activeLayerId: string;
+ dimensions: CanvasDimensions;
+ startX: number;
+ startY: number;
+ settings: WandSettings;
+}): {
+ mask: Uint8Array;
+ bounds: { x: number; y: number; width: number; height: number };
+} {
+ const { grid, layers, activeLayerId, dimensions, startX, startY, settings } = params;
+ const width = dimensions.width;
+ const height = dimensions.height;
+ const mask = new Uint8Array(width * height);
+ if (startX < 0 || startX >= width || startY < 0 || startY >= height) {
+ return { mask, bounds: { x: 0, y: 0, width: 0, height: 0 } };
+ }
+
+ let refLayers: LayerItem[] | null = null;
+ let singleLayerId = activeLayerId;
+ if (settings.referMode === 'all') {
+ refLayers = layers.filter((l) => l.visible && l.type !== 'folder' && l.type !== 'frame-folder');
+ } else if (settings.referMode === 'reference') {
+ const refLayer = layers.find((l) => l.isReference && l.visible);
+ singleLayerId = refLayer ? refLayer.id : activeLayerId;
+ }
+
+ const refTileCache = new Map<number, Uint8ClampedArray | null>();
+ const getRefTile = (tx: number, ty: number): Uint8ClampedArray | null => {
+ const key = (ty + 32768) * 65536 + (tx + 32768);
+ let cached = refTileCache.get(key);
+ if (cached !== undefined) return cached;
+ if (refLayers) {
+ cached = buildCompositedReferenceTile(grid, refLayers, tx, ty);
+ } else {
+ const tile = grid.getTile(singleLayerId, tx, ty, 0);
+ cached = tile && tile.data ? new Uint8ClampedArray(grid.getTileAsRGBA(tile)) : null;
+ }
+ refTileCache.set(key, cached);
+ return cached;
+ };
+
+ const sampleRgba = (x: number, y: number, out: [number, number, number, number]) => {
+ const tile = getRefTile(x >> 8, y >> 8);
+ if (!tile) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ return;
+ }
+ const off = (((y & 255) << 8) | (x & 255)) << 2;
+ out[0] = tile[off];
+ out[1] = tile[off + 1];
+ out[2] = tile[off + 2];
+ out[3] = tile[off + 3];
+ };
+
+ const seed: [number, number, number, number] = [0, 0, 0, 0];
+ sampleRgba(startX, startY, seed);
+ const [sR, sG, sB, sA] = seed;
+ const tolerance = settings.tolerance;
+ const tmp: [number, number, number, number] = [0, 0, 0, 0];
+
+ const colorDiff = (x: number, y: number): number => {
+ sampleRgba(x, y, tmp);
+ if (tmp[3] === 0 && sA === 0) return 0;
+ const dr = tmp[0] - sR;
+ const dg = tmp[1] - sG;
+ const db = tmp[2] - sB;
+ const da = tmp[3] - sA;
+ return Math.sqrt(dr * dr + dg * dg + db * db + da * da) / 2;
+ };
+
+ const matches = (x: number, y: number): boolean => colorDiff(x, y) <= tolerance;
+
+ let minX = width;
+ let maxX = -1;
+ let minY = height;
+ let maxY = -1;
+
+ const markPixel = (x: number, y: number) => {
+ mask[y * width + x] = 255;
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ };
+
+ if (!settings.contiguous) {
+ const maxTx = pixelToTileCoord(width - 1, 0);
+ const maxTy = pixelToTileCoord(height - 1, 0);
+ for (let ty = 0; ty <= maxTy; ty++) {
+ const y0 = ty * TILE_SIZE;
+ const y1 = Math.min(height, y0 + TILE_SIZE);
+ for (let tx = 0; tx <= maxTx; tx++) {
+ const x0 = tx * TILE_SIZE;
+ const x1 = Math.min(width, x0 + TILE_SIZE);
+ const tile = getRefTile(tx, ty);
+ if (!tile) {
+ if (sA === 0 || Math.sqrt(sR * sR + sG * sG + sB * sB + sA * sA) / 2 <= tolerance) {
+ for (let y = y0; y < y1; y++) {
+ mask.fill(255, y * width + x0, y * width + x1);
+ }
+ if (x0 < minX) minX = x0;
+ if (x1 - 1 > maxX) maxX = x1 - 1;
+ if (y0 < minY) minY = y0;
+ if (y1 - 1 > maxY) maxY = y1 - 1;
+ }
+ continue;
+ }
+ for (let y = y0; y < y1; y++) {
+ for (let x = x0; x < x1; x++) {
+ if (matches(x, y)) markPixel(x, y);
+ }
+ }
+ }
+ }
+ } else {
+ const stack: number[] = [startX, startY];
+ while (stack.length > 0) {
+ const cy = stack.pop()!;
+ const cx = stack.pop()!;
+ if (mask[cy * width + cx] !== 0 || !matches(cx, cy)) continue;
+
+ let left = cx;
+ while (left > 0 && mask[cy * width + (left - 1)] === 0 && matches(left - 1, cy)) left--;
+ let right = cx;
+ while (right < width - 1 && mask[cy * width + (right + 1)] === 0 && matches(right + 1, cy)) right++;
+
+ for (let x = left; x <= right; x++) markPixel(x, cy);
+
+ const checkScanline = (ny: number) => {
+ if (ny < 0 || ny >= height) return;
+ let inRun = false;
+ for (let x = left; x <= right; x++) {
+ if (mask[ny * width + x] === 0 && matches(x, ny)) {
+ if (!inRun) {
+ stack.push(x, ny);
+ inRun = true;
+ }
+ } else {
+ inRun = false;
+ }
+ }
+ };
+ checkScanline(cy - 1);
+ checkScanline(cy + 1);
+ }
+ }
+
+ if (settings.antiAlias && maxX >= minX && maxY >= minY) {
+ const featherBuffer = featherSelection(mask, width, height, 1);
+ for (let y = Math.max(0, minY - 1); y <= Math.min(height - 1, maxY + 1); y++) {
+ const row = y * width;
+ for (let x = Math.max(0, minX - 1); x <= Math.min(width - 1, maxX + 1); x++) {
+ if (mask[row + x] === 0 && featherBuffer[row + x] > 0) {
+ if (colorDiff(x, y) <= tolerance + 4) {
+ mask[row + x] = featherBuffer[row + x];
+ }
+ }
+ }
+ }
+ }
+
+ const bounds =
+ maxX >= minX && maxY >= minY
+ ? { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 }
+ : { x: 0, y: 0, width: 0, height: 0 };
+
+ return { mask, bounds };
+}
+
+/**
+ * Tile-native clear selection: erases (or fills white on bg) strictly within selection bounds.
+ */
+export function clearSelectionInTileGrid(params: {
+ grid: SparseTileGrid;
+ layerId: string;
+ dimensions: CanvasDimensions;
+ selection: CanvasSelection;
+ isBackground: boolean;
+ targetFormat: TileFormat;
+ snapshotOut?: Map<string, TileSnapshotEntry>;
+}): { dirtyRect: DirtyRect | null; tileDeltas: TileDelta[] } {
+ const { grid, layerId, dimensions, selection, isBackground, targetFormat } = params;
+ const raw = selection.bounds;
+ if (!raw || raw.width <= 0 || raw.height <= 0) return { dirtyRect: null, tileDeltas: [] };
+
+ const bx = Math.max(0, Math.floor(raw.x));
+ const by = Math.max(0, Math.floor(raw.y));
+ const bx1 = Math.min(dimensions.width, Math.ceil(raw.x + raw.width));
+ const by1 = Math.min(dimensions.height, Math.ceil(raw.y + raw.height));
+ const bw = bx1 - bx;
+ const bh = by1 - by;
+ if (bw <= 0 || bh <= 0) return { dirtyRect: null, tileDeltas: [] };
+
+ const dirtyRect: DirtyRect = { x: bx, y: by, width: bw, height: bh };
+ const beforeSnapshot = params.snapshotOut ?? new Map<string, TileSnapshotEntry>();
+
+ // Fast rect path with zero mask/polygon overhead
+ const hasMask = Boolean(selection.mask && selection.maskWidth && selection.maskHeight);
+ const hasLasso =
+ selection.type === 'lasso' && Boolean(selection.polygon && selection.polygon.length >= 3);
+ if (!hasMask && !hasLasso) {
+ grid.clearRectInLayer(layerId, dirtyRect, isBackground, beforeSnapshot, true);
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId, dirtyRect);
+ grid.notifyChange(true);
+ return { dirtyRect, tileDeltas };
+ }
+
+ // Mask or lasso path: chunked 512x512 compositing directly onto tiles
+ const CHUNK = 512;
+ const maskCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;
+ const mCtx = maskCanvas ? maskCanvas.getContext('2d', { willReadFrequently: true }) : null;
+
+ try {
+ for (let cy = by; cy < by1; cy += CHUNK) {
+ const ch = Math.min(CHUNK, by1 - cy);
+ for (let cx = bx; cx < bx1; cx += CHUNK) {
+ const cw = Math.min(CHUNK, bx1 - cx);
+ let chunkAlpha: Uint8ClampedArray;
+
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ chunkAlpha = new Uint8ClampedArray(cw * ch * 4);
+ const mw = selection.maskWidth;
+ const mh = selection.maskHeight;
+ const rgb = isBackground ? 255 : 0;
+ for (let ly = 0; ly < ch; ly++) {
+ const gy = cy + ly;
+ if (gy < 0 || gy >= mh) continue;
+ const mRow = gy * mw;
+ const dRow = ly * cw * 4;
+ for (let lx = 0; lx < cw; lx++) {
+ const gx = cx + lx;
+ const a = gx >= 0 && gx < mw ? selection.mask[mRow + gx] : 0;
+ if (a > 0) {
+ const off = dRow + lx * 4;
+ chunkAlpha[off] = rgb;
+ chunkAlpha[off + 1] = rgb;
+ chunkAlpha[off + 2] = rgb;
+ chunkAlpha[off + 3] = a;
+ }
+ }
+ }
+ } else if (maskCanvas && mCtx && selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
+ if (maskCanvas.width !== cw) maskCanvas.width = cw;
+ if (maskCanvas.height !== ch) maskCanvas.height = ch;
+ mCtx.clearRect(0, 0, cw, ch);
+ mCtx.save();
+ mCtx.translate(-cx, -cy);
+ mCtx.fillStyle = isBackground ? '#ffffff' : '#000000';
+ mCtx.beginPath();
+ mCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);
+ for (let i = 1; i < selection.polygon.length; i++) {
+ mCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);
+ }
+ mCtx.closePath();
+ mCtx.fill();
+ mCtx.restore();
+ chunkAlpha = mCtx.getImageData(0, 0, cw, ch).data;
+ } else {
+ continue;
+ }
+
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: { data: chunkAlpha, width: cw, height: ch },
+ destX: cx,
+ destY: cy,
+ format: targetFormat,
+ compositeOp: isBackground ? 'source-over' : 'destination-out',
+ opacity: 1.0,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+ }
+ } finally {
+ if (maskCanvas) releaseTemporaryCanvas(maskCanvas);
+ }
+
+ if (!isBackground) {
+ grid.pruneEmptyTiles(layerId);
+ }
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId, dirtyRect);
+ grid.notifyChange(true);
+ return { dirtyRect, tileDeltas };
+}
+
+/**
+ * Tile-native fill selection with solid color (zero full-canvas allocation).
+ */
+export function fillSelectionInTileGrid(params: {
+ grid: SparseTileGrid;
+ layerId: string;
+ dimensions: CanvasDimensions;
+ selection: CanvasSelection;
+ colorCss: string;
+ targetFormat: TileFormat;
+ alphaLocked?: boolean;
+}): { dirtyRect: DirtyRect | null; tileDeltas: TileDelta[] } {
+ const { grid, layerId, dimensions, selection, colorCss, targetFormat, alphaLocked = false } = params;
+ const raw = selection.bounds;
+ if (!raw || raw.width <= 0 || raw.height <= 0) return { dirtyRect: null, tileDeltas: [] };
+
+ const bx = Math.max(0, Math.floor(raw.x));
+ const by = Math.max(0, Math.floor(raw.y));
+ const bx1 = Math.min(dimensions.width, Math.ceil(raw.x + raw.width));
+ const by1 = Math.min(dimensions.height, Math.ceil(raw.y + raw.height));
+ const bw = bx1 - bx;
+ const bh = by1 - by;
+ if (bw <= 0 || bh <= 0) return { dirtyRect: null, tileDeltas: [] };
+
+ const dirtyRect: DirtyRect = { x: bx, y: by, width: bw, height: bh };
+ const [r, g, b, a] = parseColorToRgba(colorCss);
+ const beforeSnapshot = new Map<string, TileSnapshotEntry>();
+ const CHUNK = 512;
+ const polyCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;
+ const pCtx = polyCanvas ? polyCanvas.getContext('2d', { willReadFrequently: true }) : null;
+
+ try {
+ for (let cy = by; cy < by1; cy += CHUNK) {
+ const ch = Math.min(CHUNK, by1 - cy);
+ for (let cx = bx; cx < bx1; cx += CHUNK) {
+ const cw = Math.min(CHUNK, bx1 - cx);
+ let chunkData: Uint8ClampedArray;
+
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ chunkData = new Uint8ClampedArray(cw * ch * 4);
+ const mw = selection.maskWidth;
+ const mh = selection.maskHeight;
+ for (let ly = 0; ly < ch; ly++) {
+ const gy = cy + ly;
+ if (gy < 0 || gy >= mh) continue;
+ const mRow = gy * mw;
+ const dRow = ly * cw * 4;
+ for (let lx = 0; lx < cw; lx++) {
+ const gx = cx + lx;
+ const ma = gx >= 0 && gx < mw ? selection.mask[mRow + gx] : 0;
+ if (ma > 0) {
+ const off = dRow + lx * 4;
+ chunkData[off] = r;
+ chunkData[off + 1] = g;
+ chunkData[off + 2] = b;
+ chunkData[off + 3] = Math.round((a * ma) / 255);
+ }
+ }
+ }
+ } else if (polyCanvas && pCtx && selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
+ if (polyCanvas.width !== cw) polyCanvas.width = cw;
+ if (polyCanvas.height !== ch) polyCanvas.height = ch;
+ pCtx.clearRect(0, 0, cw, ch);
+ pCtx.save();
+ pCtx.translate(-cx, -cy);
+ pCtx.fillStyle = colorCss;
+ pCtx.beginPath();
+ pCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);
+ for (let i = 1; i < selection.polygon.length; i++) {
+ pCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);
+ }
+ pCtx.closePath();
+ pCtx.fill();
+ pCtx.restore();
+ chunkData = pCtx.getImageData(0, 0, cw, ch).data;
+ } else {
+ // Solid rect fill
+ chunkData = new Uint8ClampedArray(cw * ch * 4);
+ for (let off = 0; off < chunkData.length; off += 4) {
+ chunkData[off] = r;
+ chunkData[off + 1] = g;
+ chunkData[off + 2] = b;
+ chunkData[off + 3] = a;
+ }
+ }
+
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: { data: chunkData, width: cw, height: ch },
+ destX: cx,
+ destY: cy,
+ format: targetFormat,
+ compositeOp: alphaLocked ? 'source-atop' : 'source-over',
+ opacity: 1.0,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+ }
+ } finally {
+ if (polyCanvas) releaseTemporaryCanvas(polyCanvas);
+ }
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId, dirtyRect);
+ grid.notifyChange(true);
+ return { dirtyRect, tileDeltas };
+}
+
+/**
+ * Tile-native selection lift: extracts ONLY `selection.bounds` from SparseTileGrid into a
+ * tight floatingCanvas, snapshots only the affected tiles, and clears the selected pixels in tiles.
+ */
+export function liftSelectionFromTileGrid(params: {
+ grid: SparseTileGrid;
+ layerId: string;
+ dimensions: CanvasDimensions;
+ selection: CanvasSelection;
+ isBackground: boolean;
+ targetFormat: TileFormat;
+}): {
+ floatingCanvas: HTMLCanvasElement;
+ beforeTileSnapshot: Map<string, TileSnapshotEntry>;
+ bounds: DirtyRect;
+} | null {
+ const { grid, layerId, dimensions, selection, isBackground, targetFormat } = params;
+ const raw = selection.bounds;
+ if (!raw || raw.width <= 0 || raw.height <= 0 || typeof document === 'undefined') return null;
+
+ const bx = Math.max(0, Math.floor(raw.x));
+ const by = Math.max(0, Math.floor(raw.y));
+ const bx1 = Math.min(dimensions.width, Math.ceil(raw.x + raw.width));
+ const by1 = Math.min(dimensions.height, Math.ceil(raw.y + raw.height));
+ const bw = bx1 - bx;
+ const bh = by1 - by;
+ if (bw <= 0 || bh <= 0) return null;
+
+ const b: DirtyRect = { x: bx, y: by, width: bw, height: bh };
+
+ const floatingCanvas = grid.createRegionCanvas(layerId, b);
+ if (!floatingCanvas) return null;
+ const floatCtx = floatingCanvas.getContext('2d', { willReadFrequently: true });
+ if (!floatCtx) {
+ releaseTemporaryCanvas(floatingCanvas);
+ return null;
+ }
+
+ // Apply selection mask / lasso clip to extracted floatingCanvas
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ const img = floatCtx.getImageData(0, 0, bw, bh);
+ const d = img.data;
+ const mw = selection.maskWidth;
+ const mh = selection.maskHeight;
+ for (let y = 0; y < bh; y++) {
+ const sy = by + y;
+ const mRow = sy * mw;
+ const dRow = y * bw * 4;
+ for (let x = 0; x < bw; x++) {
+ const sx = bx + x;
+ const ma = sy >= 0 && sy < mh && sx >= 0 && sx < mw ? selection.mask[mRow + sx] : 0;
+ const off = dRow + x * 4;
+ if (ma === 0) {
+ d[off + 3] = 0;
+ } else if (ma < 255) {
+ d[off + 3] = Math.round((d[off + 3] * ma) / 255);
+ }
+ }
+ }
+ floatCtx.putImageData(img, 0, 0);
+ } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
+ floatCtx.save();
+ floatCtx.globalCompositeOperation = 'destination-in';
+ floatCtx.beginPath();
+ const poly = selection.polygon;
+ floatCtx.moveTo(poly[0].x - bx, poly[0].y - by);
+ for (let i = 1; i < poly.length; i++) {
+ floatCtx.lineTo(poly[i].x - bx, poly[i].y - by);
+ }
+ floatCtx.closePath();
+ floatCtx.fill();
+ floatCtx.restore();
+ }
+
+ const beforeTileSnapshot = grid.snapshotTilesInRect(layerId, b);
+ clearSelectionInTileGrid({
+ grid,
+ layerId,
+ dimensions,
+ selection,
+ isBackground,
+ targetFormat,
+ snapshotOut: beforeTileSnapshot,
+ });
+
+ return { floatingCanvas, beforeTileSnapshot, bounds: b };
+}
+
+/**
+ * Tile-native commit of a floating selection canvas back onto SparseTileGrid.
+ */
+export function commitFloatingSelectionToTileGrid(params: {
+ grid: SparseTileGrid;
+ layerId: string;
+ dimensions: CanvasDimensions;
+ floating: NonNullable<CanvasSelection['floating']>;
+ targetFormat: TileFormat;
+}): { dirtyRect: DirtyRect; tileDeltas: TileDelta[] } {
+ const { grid, layerId, dimensions, floating, targetFormat } = params;
+ const fCtx = floating.canvas.getContext('2d', { willReadFrequently: true });
+ const beforeSnapshot = new Map<string, TileSnapshotEntry>(floating.beforeTileSnapshot ?? []);
+
+ const dx = Math.round(floating.x);
+ const dy = Math.round(floating.y);
+ const fw = floating.canvas.width;
+ const fh = floating.canvas.height;
+
+ const clipX0 = Math.max(0, dx);
+ const clipY0 = Math.max(0, dy);
+ const clipX1 = Math.min(dimensions.width, dx + fw);
+ const clipY1 = Math.min(dimensions.height, dy + fh);
+
+ if (fCtx && clipX1 > clipX0 && clipY1 > clipY0) {
+ const srcX = clipX0 - dx;
+ const srcY = clipY0 - dy;
+ const copyW = clipX1 - clipX0;
+ const copyH = clipY1 - clipY0;
+ const imgData = fCtx.getImageData(srcX, srcY, copyW, copyH);
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: imgData,
+ destX: clipX0,
+ destY: clipY0,
+ format: targetFormat,
+ compositeOp: 'source-over',
+ opacity: 1.0,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+
+ const minX = Math.max(0, Math.min(dx, Math.round(floating.origX)));
+ const minY = Math.max(0, Math.min(dy, Math.round(floating.origY)));
+ const maxX = Math.min(dimensions.width, Math.max(dx + fw, Math.round(floating.origX) + fw));
+ const maxY = Math.min(dimensions.height, Math.max(dy + fh, Math.round(floating.origY) + fh));
+ const dirtyRect: DirtyRect = {
+ x: minX,
+ y: minY,
+ width: Math.max(1, maxX - minX),
+ height: Math.max(1, maxY - minY),
+ };
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId, dirtyRect);
+ grid.notifyChange(true);
+ return { dirtyRect, tileDeltas };
+}
diff --git a/src/utils/shapeEngine.ts b/src/utils/shapeEngine.ts
index 9388917..cf1d21c 100644
--- a/src/utils/shapeEngine.ts
+++ b/src/utils/shapeEngine.ts
@@ -1,5 +1,6 @@
-import { CanvasColorMode, CanvasSelection, DirtyRect } from '../types/editor';
+import { CanvasColorMode, CanvasDimensions, CanvasSelection, DirtyRect, TileDelta } from '../types/editor';
import { createSelectionMask } from './tonalEngine';
+import { SparseTileGrid, TileFormat, TileSnapshotEntry, releaseTemporaryCanvas } from './tileEngine';
export type ShapeKind =
| 'line'
@@ -528,3 +529,106 @@ export function rasterizeShapeToCanvas(
return { x: rx, y: ry, width: rw, height: rh };
}
+
+/**
+ * Tile-native shape rasterizer: renders strictly into a tight dirty-rect canvas and
+ * composites directly into SparseTileGrid tiles with zero full-document canvas allocation.
+ */
+export function rasterizeShapeToTileGrid(
+ grid: SparseTileGrid,
+ layerId: string,
+ dimensions: CanvasDimensions,
+ preview: ShapeDragPreview,
+ strokeColor: string,
+ fillColor: string,
+ selection: CanvasSelection | null,
+ colorMode: CanvasColorMode,
+ isMonoLayer: boolean,
+ alphaLocked: boolean = false
+): { dirtyRect: DirtyRect | null; tileDeltas: TileDelta[] } {
+ const geom = computeShapeGeometry(
+ preview.start,
+ preview.end,
+ preview.settings,
+ preview.shiftKey,
+ preview.altKey
+ );
+ if (geom.length < 1 && geom.width < 1 && geom.height < 1) {
+ return { dirtyRect: null, tileDeltas: [] };
+ }
+
+ const cw = dimensions.width;
+ const ch = dimensions.height;
+ const pad = Math.ceil(
+ Math.max(preview.settings.strokeWidth * 4, preview.settings.shape === 'arrow' ? 40 : 12)
+ );
+ const rx = Math.max(0, Math.floor(geom.x - pad));
+ const ry = Math.max(0, Math.floor(geom.y - pad));
+ const maxX = Math.min(cw, Math.ceil(geom.x + geom.width + pad));
+ const maxY = Math.min(ch, Math.ceil(geom.y + geom.height + pad));
+ const rw = maxX - rx;
+ const rh = maxY - ry;
+ if (rw <= 0 || rh <= 0) return { dirtyRect: null, tileDeltas: [] };
+
+ const off = document.createElement('canvas');
+ off.width = rw;
+ off.height = rh;
+ const offCtx = off.getContext('2d', { willReadFrequently: true });
+ if (!offCtx) {
+ releaseTemporaryCanvas(off);
+ return { dirtyRect: null, tileDeltas: [] };
+ }
+
+ try {
+ offCtx.save();
+ offCtx.translate(-rx, -ry);
+ drawShapeToContext(offCtx, preview, strokeColor, fillColor);
+ offCtx.restore();
+
+ const binaryEdges = !preview.settings.antiAlias || colorMode === 'monochrome' || isMonoLayer;
+ const selMask = selection ? createSelectionMask(selection, cw, ch) : null;
+ const img = offCtx.getImageData(0, 0, rw, rh);
+
+ if (binaryEdges || selMask) {
+ const d = img.data;
+ for (let y = 0; y < rh; y++) {
+ const gy = ry + y;
+ for (let x = 0; x < rw; x++) {
+ const idx = (y * rw + x) * 4;
+ if (selMask) {
+ const gx = rx + x;
+ const m = selMask[gy * cw + gx];
+ if (m === 0) {
+ d[idx + 3] = 0;
+ continue;
+ } else if (m < 255) {
+ d[idx + 3] = Math.round((d[idx + 3] * m) / 255);
+ }
+ }
+ if (binaryEdges) {
+ d[idx + 3] = d[idx + 3] >= 128 ? 255 : 0;
+ }
+ }
+ }
+ }
+
+ const targetFormat: TileFormat = isMonoLayer || colorMode === 'monochrome' ? 'monochrome-1bit' : 'color-32bit';
+ const beforeSnapshot = new Map<string, TileSnapshotEntry>();
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: img,
+ destX: rx,
+ destY: ry,
+ format: targetFormat,
+ compositeOp: alphaLocked ? 'source-atop' : 'source-over',
+ opacity: 1.0,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ const dirtyRect: DirtyRect = { x: rx, y: ry, width: rw, height: rh };
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId, dirtyRect);
+ return { dirtyRect, tileDeltas };
+ } finally {
+ releaseTemporaryCanvas(off);
+ }
+}
diff --git a/src/utils/stampEngine.ts b/src/utils/stampEngine.ts
deleted file mode 100644
index 495ae0d..0000000
--- a/src/utils/stampEngine.ts
+++ /dev/null
@@ -1,2637 +0,0 @@
-import {
- Point,
- BrushSettings,
- ToolType,
- CspSpraySettings,
- CspTaperSettings,
- CspSubTip,
- BrushDynamics,
- CspAngleDynamicsMode,
- CspTipFlipMode,
- CspPaperTextureMode,
- CspBlendTipsMode,
- CspSensorConfig,
-} from '../types/editor';
-import {
- PaintReservoir,
- LayerPixelSampler,
- sampleCanvasColor,
- parseColorToRgb,
- rgbToHex,
-} from './colorMixingEngine';
-import { getPaperGrain, paperGrainTable, GRAIN_SIZE } from './pencilEngine';
-import { GpuDab, WebGlBrushEngine } from './webglBrushEngine';
-import {
- evaluateFastSpline,
- dabHashFloat,
- evaluateCspSensor,
- computeEllipticalStepDistance,
- computeGapAdjustedAlpha,
- computeSubpixelDabDimensions,
- resolveTipFlipSigns,
- applyCspPaperTextureAlpha,
-} from '../engine/CspBrushEngine';
-
-export interface TexturedBrushOptions {
- size: number;
- minSizeFactor?: number;
- opacity?: number;
- flow?: number;
- brushDensity?: number;
- adjustDensityByGap?: boolean;
- blendTipsMode?: CspBlendTipsMode;
- spacing?: number; // 0.01 to 1.0 (relative to brush width)
- thickness?: number; // 0.05 to 1.0 (elliptical aspect ratio)
- thicknessVertical?: boolean;
- flipH?: CspTipFlipMode;
- flipV?: CspTipFlipMode;
- angle?: number; // rotation in degrees
- angleDynamics?: CspAngleDynamicsMode;
- rotationRandomScale?: number;
- hardness?: number;
- antiAlias?: number;
- isColorTip?: boolean;
- pressureCurve?: [number, number][];
- velocityCurve?: [number, number][];
- usePressure?: boolean;
- useTilt?: boolean;
- tiltScale?: number;
- useVelocity?: boolean;
- sizeSensor?: CspSensorConfig;
- opacitySensor?: CspSensorConfig;
- densitySensor?: CspSensorConfig;
- subTips?: CspSubTip[];
- subTipOrder?: 'random' | 'sequential' | 'direction' | 'reverse';
- subTipImages?: HTMLImageElement[];
- spray?: CspSpraySettings;
- taper?: CspTaperSettings;
- colorMixing?: boolean;
- perceptualMixing?: boolean;
- amountOfPaint?: number;
- densityOfPaint?: number;
- colorStretch?: number;
- mixingMode?: 'blend' | 'running_color' | 'smear';
- wetEdge?: number;
- wetEdgeRadius?: number;
- wetEdgeAlphaPower?: number;
- wetEdgeValuePower?: number;
- grain?: number;
- textureDensity?: number;
- paperTextureMode?: CspPaperTextureMode;
- paperTextureBrightness?: number;
- paperTextureContrast?: number;
- paperTextureInverted?: boolean;
- paperTextureImage?: HTMLImageElement;
- paperTextureScale?: number;
- paperTextureRotate?: number;
- dualBrush?: boolean;
- dualTipImage?: HTMLImageElement;
- dualBrushCompositeMode?: string;
- useGpu?: boolean;
- underlyingCanvas?: HTMLCanvasElement;
- sampler?: LayerPixelSampler;
- reservoir?: PaintReservoir;
- isEraser?: boolean;
- isBgEraser?: boolean;
- alphaLocked?: boolean;
- isTransparentInk?: boolean;
- strokeIndex?: number;
- totalLength?: number;
- currentStrokeDist?: number;
- dynamics?: BrushDynamics;
- secondaryColor?: string;
-}
-
-// -------------------------------------------------------------
-// Color Dynamics & HSV Jitter Utilities
-// -------------------------------------------------------------
-
-export function rgbToHsv(r: number, g: number, b: number): [number, number, number] {
- const max = Math.max(r, g, b);
- const min = Math.min(r, g, b);
- const d = max - min;
- let h = 0;
- const s = max === 0 ? 0 : d / max;
- const v = max;
-
- if (max !== min) {
- if (max === r) {
- h = (g - b) / d + (g < b ? 6 : 0);
- } else if (max === g) {
- h = (b - r) / d + 2;
- } else {
- h = (r - g) / d + 4;
- }
- h *= 60;
- }
- return [h, s, v];
-}
-
-export function hsvToRgb(h: number, s: number, v: number): [number, number, number] {
- const c = v * s;
- const hp = (((h % 360) + 360) % 360) / 60;
- const x = c * (1 - Math.abs((hp % 2) - 1));
- let r1 = 0;
- let g1 = 0;
- let b1 = 0;
-
- if (hp >= 0 && hp < 1) {
- r1 = c; g1 = x; b1 = 0;
- } else if (hp >= 1 && hp < 2) {
- r1 = x; g1 = c; b1 = 0;
- } else if (hp >= 2 && hp < 3) {
- r1 = 0; g1 = c; b1 = x;
- } else if (hp >= 3 && hp < 4) {
- r1 = 0; g1 = x; b1 = c;
- } else if (hp >= 4 && hp < 5) {
- r1 = x; g1 = 0; b1 = c;
- } else if (hp >= 5 && hp < 6) {
- r1 = c; g1 = 0; b1 = x;
- }
-
- const m = v - c;
- return [
- Math.max(0, Math.min(1, r1 + m)),
- Math.max(0, Math.min(1, g1 + m)),
- Math.max(0, Math.min(1, b1 + m)),
- ];
-}
-
-export function applyColorDynamics(
- primaryRgb: { r: number; g: number; b: number },
- secondaryRgb: { r: number; g: number; b: number },
- dynamics?: BrushDynamics,
- rng: () => number = Math.random
-): { r: number; g: number; b: number; hex: string } {
- if (!dynamics || !dynamics.colorJitterEnabled) {
- const ir = Math.round(primaryRgb.r * 255);
- const ig = Math.round(primaryRgb.g * 255);
- const ib = Math.round(primaryRgb.b * 255);
- return {
- r: primaryRgb.r,
- g: primaryRgb.g,
- b: primaryRgb.b,
- hex: rgbToHex(ir, ig, ib),
- };
- }
-
- let r = primaryRgb.r;
- let g = primaryRgb.g;
- let b = primaryRgb.b;
-
- if (dynamics.foregroundBackgroundJitter > 0) {
- const mix = rng() * dynamics.foregroundBackgroundJitter;
- r = r + (secondaryRgb.r - r) * mix;
- g = g + (secondaryRgb.g - g) * mix;
- b = b + (secondaryRgb.b - b) * mix;
- }
-
- if (dynamics.hueJitter > 0 || dynamics.saturationJitter > 0 || dynamics.brightnessJitter > 0) {
- let [h, s, v] = rgbToHsv(r, g, b);
-
- if (dynamics.hueJitter > 0) {
- h = (h + (rng() - 0.5) * dynamics.hueJitter * 360 + 360) % 360;
- }
- if (dynamics.saturationJitter > 0) {
- s = Math.max(0, Math.min(1, s * (1.0 + (rng() * 2 - 1) * dynamics.saturationJitter)));
- }
- if (dynamics.brightnessJitter > 0) {
- v = Math.max(0, Math.min(1, v * (1.0 + (rng() * 2 - 1) * dynamics.brightnessJitter)));
- }
-
- [r, g, b] = hsvToRgb(h, s, v);
- }
-
- r = Math.max(0, Math.min(1, r));
- g = Math.max(0, Math.min(1, g));
- b = Math.max(0, Math.min(1, b));
-
- const ir = Math.round(r * 255);
- const ig = Math.round(g * 255);
- const ib = Math.round(b * 255);
-
- return {
- r,
- g,
- b,
- hex: rgbToHex(ir, ig, ib),
- };
-}
-
-// -------------------------------------------------------------
-// Hardware-Accelerated World-Locked Paper Grain Masking (CPU/Color-Mixing Parity)
-// -------------------------------------------------------------
-
-let _invertedGrainCanvas: HTMLCanvasElement | null = null;
-let _grainScratchCanvas: HTMLCanvasElement | null = null;
-let _grainScratchCtx: CanvasRenderingContext2D | null = null;
-let _grainPattern: CanvasPattern | null = null;
-let _customGrainCanvasCache = new WeakMap<HTMLImageElement, { canvas: HTMLCanvasElement; pattern: CanvasPattern | null }>();
-
-function getInvertedGrainPattern(
- scratchCtx: CanvasRenderingContext2D,
- paperTextureImage?: HTMLImageElement
-): CanvasPattern | null {
- if (typeof scratchCtx.createPattern !== 'function') return null;
-
- if (
- paperTextureImage &&
- paperTextureImage.complete !== false &&
- (paperTextureImage.naturalWidth || paperTextureImage.width) > 0
- ) {
- const cached = _customGrainCanvasCache.get(paperTextureImage);
- if (cached) return cached.pattern;
- const w = paperTextureImage.naturalWidth || paperTextureImage.width;
- const h = paperTextureImage.naturalHeight || paperTextureImage.height;
- const c = document.createElement('canvas');
- c.width = w;
- c.height = h;
- const gCtx = c.getContext('2d', { willReadFrequently: true });
- if (gCtx && typeof gCtx.getImageData === 'function') {
- gCtx.drawImage(paperTextureImage, 0, 0, w, h);
- const img = gCtx.getImageData(0, 0, w, h);
- const d = img.data;
- for (let i = 0; i < d.length; i += 4) {
- const lum = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
- const inv = 255 - Math.round(lum);
- d[i] = 255;
- d[i + 1] = 255;
- d[i + 2] = 255;
- d[i + 3] = inv;
- }
- gCtx.putImageData(img, 0, 0);
- const pat = scratchCtx.createPattern(c, 'repeat');
- _customGrainCanvasCache.set(paperTextureImage, { canvas: c, pattern: pat });
- return pat;
- }
- }
-
- if (!_invertedGrainCanvas) {
- const c = document.createElement('canvas');
- c.width = GRAIN_SIZE;
- c.height = GRAIN_SIZE;
- const gCtx = c.getContext('2d');
- if (!gCtx) return null;
- const img = gCtx.createImageData(GRAIN_SIZE, GRAIN_SIZE);
- const d = img.data;
- for (let i = 0; i < paperGrainTable.length; i++) {
- const p = i * 4;
- d[p] = 255;
- d[p + 1] = 255;
- d[p + 2] = 255;
- // Alpha = (1 - paperHeight) so destination-out removes pigment in paper valleys
- d[p + 3] = 255 - paperGrainTable[i];
- }
- gCtx.putImageData(img, 0, 0);
- _invertedGrainCanvas = c;
- _grainPattern = scratchCtx.createPattern(c, 'repeat');
- }
-
- return _grainPattern;
-}
-
-/**
- * Applies world-anchored per-pixel paper/canvas grain onto a CPU dab stamp using hardware 2D compositing.
- * Returns a pooled canvas containing the grain-masked dab, or null if unsupported (falls back to scalar grain).
- */
-function applyCpuPerPixelPaperGrain(
- master: CanvasImageSource,
- worldX: number,
- worldY: number,
- renderW: number,
- renderH: number,
- grainAmount: number,
- pressure: number,
- paperScale: number = 1.0,
- paperTextureImage?: HTMLImageElement
-): HTMLCanvasElement | null {
- if (typeof document === 'undefined' || grainAmount <= 0.005) return null;
- if (!_grainScratchCanvas) {
- _grainScratchCanvas = document.createElement('canvas');
- _grainScratchCanvas.width = 128;
- _grainScratchCanvas.height = 128;
- _grainScratchCtx = _grainScratchCanvas.getContext('2d');
- }
- const sCtx = _grainScratchCtx;
- if (!sCtx || typeof sCtx.createPattern !== 'function') return null;
-
- const pat = getInvertedGrainPattern(sCtx, paperTextureImage);
- if (!pat) return null;
-
- const bufSize = 128;
- const p = Math.max(0, Math.min(1, pressure));
- const heavyExcess = Math.max(0, (p - 0.52) / 0.48);
- const penetration = Math.min(0.92, p * 0.28 + heavyExcess * heavyExcess * 0.64);
- const effDensity = Math.max(0, Math.min(0.98, grainAmount * (1.0 - penetration * 0.85)));
- if (effDensity <= 0.005) return null;
-
- sCtx.save();
- sCtx.globalCompositeOperation = 'source-over';
- sCtx.globalAlpha = 1.0;
- sCtx.clearRect(0, 0, bufSize, bufSize);
- sCtx.drawImage(master, 0, 0, bufSize, bufSize);
-
- // Align world-space paper pattern onto the dab's local [0..bufSize] frame
- const scale = Math.max(0.1, paperScale);
- const sx = (bufSize / Math.max(1, renderW)) * scale;
- const sy = (bufSize / Math.max(1, renderH)) * scale;
- const offX = -((worldX - renderW * 0.5) / scale);
- const offY = -((worldY - renderH * 0.5) / scale);
-
- sCtx.globalCompositeOperation = 'destination-out';
- sCtx.globalAlpha = effDensity;
- sCtx.fillStyle = pat;
- sCtx.scale(sx, sy);
- sCtx.translate(offX, offY);
- sCtx.fillRect(-offX, -offY, bufSize / sx, bufSize / sy);
- sCtx.restore();
-
- return _grainScratchCanvas;
-}
-
-// -------------------------------------------------------------
-// High-Efficiency Tinted Tip Master Buffer & Bounded LRU Pools
-// -------------------------------------------------------------
-
-const MAX_CACHE_ENTRIES = 160;
-const MAX_RADIAL_MASKS = 96;
-const tintedMasterCache = new Map<string, HTMLCanvasElement>();
-const radialMaskCache = new Map<string, HTMLCanvasElement>();
-const canvasPool: HTMLCanvasElement[] = [];
-const sourceIdMap = new WeakMap<object, number>();
-let nextSourceId = 1;
-
-function getUniqueSourceKey(source: CanvasImageSource, fallbackPrefix: string): string {
- if (typeof source === 'object' && source !== null) {
- let id = sourceIdMap.get(source);
- if (!id) {
- id = nextSourceId++;
- sourceIdMap.set(source, id);
- }
- return `${fallbackPrefix}_${id}`;
- }
- return fallbackPrefix;
-}
-
-function getPooledCanvas(w: number, h: number): HTMLCanvasElement {
- const targetW = Math.max(1, w);
- const targetH = Math.max(1, h);
- for (let i = 0; i < canvasPool.length; i++) {
- const c = canvasPool[i];
- if (c.width === targetW && c.height === targetH) {
- canvasPool.splice(i, 1);
- return c;
- }
- }
- const canvas = document.createElement('canvas');
- canvas.width = targetW;
- canvas.height = targetH;
- return canvas;
-}
-
-function evictOrAllocateMasterCanvas(w: number, h: number): HTMLCanvasElement {
- const targetW = Math.max(1, w);
- const targetH = Math.max(1, h);
- if (tintedMasterCache.size >= MAX_CACHE_ENTRIES) {
- const oldestKey = tintedMasterCache.keys().next().value;
- if (oldestKey) {
- const canvas = tintedMasterCache.get(oldestKey)!;
- tintedMasterCache.delete(oldestKey);
- if (canvas.width !== targetW || canvas.height !== targetH) {
- canvas.width = targetW;
- canvas.height = targetH;
- }
- return canvas;
- }
- }
- return getPooledCanvas(targetW, targetH);
-}
-
-/**
- * Generic tinted master offscreen canvas generator.
- * Uses fine 21-bit color quantization (step of 2/255) to eliminate 15-bit Mach banding while retaining high cache hits.
- */
-export function getTintedMasterCanvas(
- source: CanvasImageSource,
- sourceKey: string,
- color: string,
- w: number,
- h: number,
- isColorTip: boolean = false
-): HTMLCanvasElement {
- if (isColorTip) {
- const key = `color_${sourceKey}_${w}x${h}`;
- const cached = tintedMasterCache.get(key);
- if (cached) return cached;
-
- const canvas = evictOrAllocateMasterCanvas(w, h);
- const ctx = canvas.getContext('2d');
- if (ctx) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.globalCompositeOperation = 'source-over';
- ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
- }
- tintedMasterCache.set(key, canvas);
- return canvas;
- }
-
- const rgb = parseColorToRgb(color);
- const qR = rgb.r & ~1;
- const qG = rgb.g & ~1;
- const qB = rgb.b & ~1;
- const quantizedHex = rgbToHex(qR, qG, qB);
-
- const key = `${sourceKey}_${quantizedHex}_${w}x${h}`;
- const cached = tintedMasterCache.get(key);
- if (cached) return cached;
-
- const canvas = evictOrAllocateMasterCanvas(w, h);
- const ctx = canvas.getContext('2d');
- if (!ctx) return canvas;
-
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.globalCompositeOperation = 'source-over';
- ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
-
- ctx.globalCompositeOperation = 'source-in';
- ctx.fillStyle = quantizedHex;
- ctx.fillRect(0, 0, canvas.width, canvas.height);
-
- tintedMasterCache.set(key, canvas);
- return canvas;
-}
-
-export function getTintedTipMaster(
- tipImage: HTMLImageElement,
- color: string,
- isColorTip: boolean = false
-): HTMLCanvasElement {
- const w = tipImage.naturalWidth || tipImage.width || 64;
- const h = tipImage.naturalHeight || tipImage.height || 64;
- const uniqueKey = getUniqueSourceKey(tipImage, 'tip');
- return getTintedMasterCanvas(tipImage, uniqueKey, color, w, h, isColorTip);
-}
-
-/**
- * Pre-computes or retrieves an analytical Hermite radial dab master with CSP 4-level Anti-Aliasing.
- */
-export function getRadialDabMaster(
- hardness: number,
- color: string,
- isEraser: boolean = false,
- targetSize?: number,
- antiAlias: number = 2
-): HTMLCanvasElement {
- const clampedH = Math.max(0, Math.min(1.0, hardness));
- const qH = Math.round(clampedH * 20) / 20;
- const aaLevel = Math.max(0, Math.min(3, Math.round(antiAlias)));
-
- let size = 128;
- let qDiameter = 124;
- if (targetSize !== undefined && targetSize > 0) {
- if (targetSize <= 8) {
- size = 24;
- qDiameter = Math.max(1, Math.round(targetSize));
- } else if (targetSize <= 24) {
- size = 48;
- qDiameter = Math.max(4, Math.round(targetSize / 2) * 2);
- } else if (targetSize <= 64) {
- size = 64;
- qDiameter = Math.max(16, Math.round(targetSize / 4) * 4);
- } else {
- size = 128;
- qDiameter = 124;
- }
- }
-
- const aaKeySuffix = aaLevel === 2 ? '' : `_aa${aaLevel}`;
- const maskKey = targetSize === undefined ? `${qH}_128${aaKeySuffix}` : `${qH}_${size}_${qDiameter}${aaKeySuffix}`;
- let maskCanvas = radialMaskCache.get(maskKey);
- if (!maskCanvas) {
- if (radialMaskCache.size >= MAX_RADIAL_MASKS) {
- const oldest = radialMaskCache.keys().next().value;
- if (oldest !== undefined) radialMaskCache.delete(oldest);
- }
-
- maskCanvas = document.createElement('canvas');
- maskCanvas.width = size;
- maskCanvas.height = size;
- const ctx = maskCanvas.getContext('2d');
- if (ctx) {
- const imgData = ctx.createImageData(size, size);
- const data = imgData.data;
- const cx = size / 2;
- const cy = size / 2;
- const radius = size / 2 - 1;
-
- const aaScale = aaLevel === 0 ? 0 : aaLevel === 1 ? 0.6 : aaLevel === 3 ? 1.65 : 1.0;
- const baseAaTexels = qH >= 0.98
- ? 1.15
- : targetSize === undefined
- ? 1.0
- : Math.max(0.85, Math.min(2.4, (radius / Math.max(1.5, qDiameter * 0.5)) * 0.85));
- const aaTexels = baseAaTexels * aaScale;
- const rCore = Math.min(radius - Math.max(0, aaTexels), radius * qH);
-
- for (let y = 0; y < size; y++) {
- const dy = y - cy + 0.5;
- const rowOffset = y * size * 4;
- for (let x = 0; x < size; x++) {
- const dx = x - cx + 0.5;
- const dist = Math.hypot(dx, dy);
- let alpha = 0;
-
- if (aaLevel === 0) {
- alpha = dist <= radius ? 1.0 : 0.0;
- } else if (qH >= 0.98) {
- const u = Math.max(0, Math.min(1.0, (radius - dist) / Math.max(0.25, aaTexels) + 0.5));
- alpha = u * u * (3.0 - 2.0 * u);
- } else if (dist <= rCore) {
- alpha = 1.0;
- } else if (dist < radius) {
- const t = (dist - rCore) / Math.max(1e-4, radius - rCore);
- if (qH <= 0.05) {
- alpha = 0.5 * (1.0 + Math.cos(t * Math.PI));
- } else {
- alpha = 1.0 - (3.0 * t * t - 2.0 * t * t * t);
- }
- }
-
- if (alpha > 0.002) {
- const idx = rowOffset + x * 4;
- data[idx] = 255;
- data[idx + 1] = 255;
- data[idx + 2] = 255;
- data[idx + 3] = Math.round(alpha * 255);
- }
- }
- }
- ctx.putImageData(imgData, 0, 0);
- }
- radialMaskCache.set(maskKey, maskCanvas);
- }
-
- const effectiveColor = isEraser ? '#000000' : color;
- return getTintedMasterCanvas(maskCanvas, `radial_${maskKey}`, effectiveColor, size, size);
-}
-
-/**
- * Draws a single textured or analytical brush stamp (dab) onto the destination context.
- * Supports sub-pixel 2D area conservation, horizontal/vertical flips, and binary AA.
- */
-export function drawSingleStamp(
- ctx: CanvasRenderingContext2D,
- stampSource: CanvasImageSource,
- x: number,
- y: number,
- width: number,
- height: number,
- angleRad: number,
- alpha: number,
- isEraser: boolean = false,
- isBgEraser: boolean = false,
- alphaLocked: boolean = false,
- isTransparentInk: boolean = false,
- flipX: number = 1,
- flipY: number = 1,
- antiAlias: number = 2,
- _blendTipsMode?: CspBlendTipsMode
-) {
- if (width < 0.08 || height < 0.08 || alpha <= 0.002) return;
-
- const minRenderDim = antiAlias === 0 ? 1.0 : 0.75;
- const sub = computeSubpixelDabDimensions(width, height, alpha, minRenderDim);
- const renderW = sub.renderW;
- const renderH = sub.renderH;
- const effAlpha = antiAlias === 0 ? (sub.effAlpha >= 0.45 ? 1.0 : 0) : sub.effAlpha;
- if (effAlpha <= 0.002) return;
-
- const targetOp: GlobalCompositeOperation = isBgEraser
- ? 'source-over'
- : (isTransparentInk || isEraser)
- ? 'destination-out'
- : alphaLocked
- ? 'source-atop'
- : 'source-over';
-
- const prevSmooth = ctx.imageSmoothingEnabled;
- if (antiAlias === 0 && prevSmooth !== false) {
- ctx.imageSmoothingEnabled = false;
- }
-
- // Ultra-fast path for unrotated, unflipped stamps
- if (Math.abs(angleRad) < 0.001 && flipX >= 0 && flipY >= 0) {
- const prevAlpha = ctx.globalAlpha;
- const prevOp = ctx.globalCompositeOperation;
- ctx.globalCompositeOperation = targetOp;
- ctx.globalAlpha = effAlpha;
- const drawX = antiAlias === 0 ? Math.round(x - renderW / 2) : x - renderW / 2;
- const drawY = antiAlias === 0 ? Math.round(y - renderH / 2) : y - renderH / 2;
- ctx.drawImage(stampSource, drawX, drawY, renderW, renderH);
- ctx.globalAlpha = prevAlpha;
- ctx.globalCompositeOperation = prevOp;
- if (antiAlias === 0 && prevSmooth !== false) {
- ctx.imageSmoothingEnabled = prevSmooth;
- }
- return;
- }
-
- ctx.save();
- ctx.globalCompositeOperation = targetOp;
- ctx.globalAlpha = effAlpha;
- ctx.translate(x, y);
- if (Math.abs(angleRad) >= 0.001) {
- ctx.rotate(angleRad);
- }
- if ((flipX < 0 || flipY < 0) && typeof ctx.scale === 'function') {
- ctx.scale(flipX < 0 ? -1 : 1, flipY < 0 ? -1 : 1);
- }
- ctx.drawImage(stampSource, -renderW / 2, -renderH / 2, renderW, renderH);
- ctx.restore();
- if (antiAlias === 0 && prevSmooth !== false) {
- ctx.imageSmoothingEnabled = prevSmooth;
- }
-}
-
-/**
- * Deterministic multi-tip stamp selector.
- * Uses dabHashFloat for 'random' order so live stroke preview and commit bake select identical tips!
- */
-function selectTipImage(
- tipImages: HTMLImageElement[] | undefined,
- fallbackTip: HTMLImageElement,
- order: 'random' | 'sequential' | 'direction' | 'reverse' = 'sequential',
- dabIndex: number = 0,
- tangentAngle: number = 0,
- x: number = 0,
- y: number = 0
-): HTMLImageElement {
- if (!tipImages || tipImages.length <= 1) {
- return tipImages && tipImages.length === 1 ? tipImages[0] : fallbackTip;
- }
-
- const count = tipImages.length;
- if (order === 'random') {
- const idx = Math.floor(dabHashFloat(x, y, dabIndex, 97) * count) % count;
- return tipImages[idx];
- } else if (order === 'reverse') {
- const idx = (count - 1 - (dabIndex % count)) % count;
- return tipImages[idx];
- } else if (order === 'direction') {
- const normAngle = ((tangentAngle % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
- const idx = Math.floor((normAngle / (2 * Math.PI)) * count) % count;
- return tipImages[idx];
- } else {
- return tipImages[dabIndex % count];
- }
-}
-
-/**
- * Determines whether a textured brush configuration can execute on WebGlBrushEngine
- * (instanced GPU FBO stamps). Falls back cleanly to Canvas 2D for binary pixel AA=0,
- * stateful CPU colorMixingEngine, multi-subTip textures, or unavailable WebGL context.
- */
-export function canUseWebGlForTexturedBrush(options: TexturedBrushOptions): boolean {
- if (options.useGpu === false) return false;
- if (options.colorMixing) return false;
- if ((options.antiAlias ?? 2) === 0) return false;
- if (options.subTipImages && options.subTipImages.length > 1) return false;
- return WebGlBrushEngine.getInstance().isAvailable();
-}
-
-/**
- * Determines whether a radial/soft brush configuration can execute on WebGlBrushEngine.
- */
-export function canUseWebGlForRadialBrush(options?: RadialMixingOptions): boolean {
- if (options?.useGpu === false) return false;
- if (options?.colorMixing) return false;
- if ((options?.antiAlias ?? 2) === 0) return false;
- return WebGlBrushEngine.getInstance().isAvailable();
-}
-
-/**
- * Flushes a collected GpuDab[] batch for a textured brush to targetCtx via WebGlBrushEngine.
- */
-export function flushTexturedGpuDabs(
- ctx: CanvasRenderingContext2D,
- dabs: GpuDab[],
- tipImage: HTMLImageElement,
- color: string,
- options: TexturedBrushOptions
-): boolean {
- if (dabs.length === 0) return true;
- const gpu = WebGlBrushEngine.getInstance();
- if (!gpu.isAvailable()) return false;
-
- const isEraser = Boolean(options.isEraser);
- const isBgEraser = Boolean(options.isBgEraser);
- const tool: ToolType = isEraser || isBgEraser ? 'eraser' : 'brush';
- const settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean } = {
- size: options.size,
- minSizeFactor: options.minSizeFactor ?? 0,
- color,
- opacity: options.opacity ?? 1.0,
- flow: options.flow ?? 0.85,
- spacing: options.spacing ?? 0.08,
- usePressure: options.usePressure !== false,
- smoothing: false,
- stabilization: 0,
- hardness: options.hardness ?? 1.0,
- antiAlias: options.antiAlias ?? 2,
- wetEdge: options.wetEdge ?? 0,
- grain: options.grain ?? options.textureDensity ?? 0,
- textureDensity: options.textureDensity,
- paperTextureMode: options.paperTextureMode,
- paperTextureBrightness: options.paperTextureBrightness,
- paperTextureContrast: options.paperTextureContrast,
- paperTextureInverted: options.paperTextureInverted,
- paperTextureImage: options.paperTextureImage,
- paperTextureScale: options.paperTextureScale,
- paperTextureRotate: options.paperTextureRotate,
- customTipImage: tipImage,
- isColorTip: options.isColorTip,
- subTips: options.subTips,
- dualBrush: options.dualBrush,
- dualTipImage: options.dualTipImage,
- dualBrushCompositeMode: options.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode'],
- colorMixing: false,
- isTransparentInk: Boolean(options.isTransparentInk),
- alphaLocked: Boolean(options.alphaLocked),
- isBgEraser,
- };
-
- const docW = options.underlyingCanvas?.width || ctx.canvas?.width || 1024;
- const docH = options.underlyingCanvas?.height || ctx.canvas?.height || 1024;
- return gpu.renderDabsToContext(ctx, dabs, settings, tool, docW, docH, options.underlyingCanvas);
-}
-
-/**
- * Flushes a collected GpuDab[] batch for a radial/soft brush to targetCtx via WebGlBrushEngine.
- */
-export function flushRadialGpuDabs(
- ctx: CanvasRenderingContext2D,
- dabs: GpuDab[],
- color: string,
- hardness: number,
- isEraser: boolean,
- isBgEraser: boolean,
- mixingOptions?: RadialMixingOptions
-): boolean {
- if (dabs.length === 0) return true;
- const gpu = WebGlBrushEngine.getInstance();
- if (!gpu.isAvailable()) return false;
-
- const tool: ToolType = isEraser || isBgEraser ? 'eraser' : 'brush';
- const settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean } = {
- size: 10,
- minSizeFactor: 0,
- color,
- opacity: 1.0,
- flow: 1.0,
- spacing: 0.08,
- usePressure: true,
- smoothing: false,
- stabilization: 0,
- hardness,
- antiAlias: mixingOptions?.antiAlias ?? 2,
- wetEdge: 0,
- grain: mixingOptions?.grain ?? 0,
- paperTextureMode: mixingOptions?.paperTextureMode,
- paperTextureBrightness: mixingOptions?.paperTextureBrightness,
- paperTextureContrast: mixingOptions?.paperTextureContrast,
- paperTextureInverted: mixingOptions?.paperTextureInverted,
- paperTextureImage: mixingOptions?.paperTextureImage,
- paperTextureScale: mixingOptions?.paperTextureScale,
- paperTextureRotate: mixingOptions?.paperTextureRotate,
- dualBrush: mixingOptions?.dualBrush,
- dualTipImage: mixingOptions?.dualTipImage,
- dualBrushCompositeMode: mixingOptions?.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode'],
- colorMixing: false,
- isTransparentInk: Boolean(mixingOptions?.isTransparentInk),
- alphaLocked: Boolean(mixingOptions?.alphaLocked),
- isBgEraser,
- };
-
- const docW = mixingOptions?.underlyingCanvas?.width || ctx.canvas?.width || 1024;
- const docH = mixingOptions?.underlyingCanvas?.height || ctx.canvas?.height || 1024;
- return gpu.renderDabsToContext(ctx, dabs, settings, tool, docW, docH, mixingOptions?.underlyingCanvas);
-}
-
-/**
- * Draws a single textured dot at pointer down.
- */
-export function drawTexturedDot(
- ctx: CanvasRenderingContext2D,
- point: Point,
- color: string,
- tipImage: HTMLImageElement,
- options: TexturedBrushOptions,
- batchGpuDabs?: GpuDab[]
-) {
- const isEraser = options.isEraser ?? false;
- const isBgEraser = options.isBgEraser ?? false;
- let effectiveColor = isBgEraser ? '#ffffff' : color;
- const baseDensity = options.brushDensity ?? options.flow ?? 0.85;
- let effectiveFlow = computeGapAdjustedAlpha(baseDensity, options.spacing ?? 0.08, options.adjustDensityByGap);
-
- const effPressure = evaluateFastSpline(point.pressure, options.pressureCurve);
- const minFactor = options.minSizeFactor ?? 0.2;
- const effWidth = point.width > 0
- ? Math.max(0.4, point.width)
- : Math.max(0.5, options.size * (minFactor + (1.0 - minFactor) * effPressure));
-
- const isColorMixing = Boolean(options.colorMixing) && !isEraser;
-
- if (isColorMixing) {
- if (!options.reservoir) {
- options.reservoir = new PaintReservoir(color);
- }
-
- let sampled = { r: 255, g: 255, b: 255, a: 0 };
- if (options.sampler) {
- sampled = options.sampler.sampleColor(point.x, point.y, Math.max(2, effWidth / 2));
- } else {
- const sampleCanvas = options.underlyingCanvas || ctx.canvas;
- const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;
- if (sampleCtx) {
- sampled = sampleCanvasColor(sampleCtx, point.x, point.y, Math.max(2, effWidth / 2));
- }
- }
-
- const mixed = options.reservoir.mixWithCanvas(
- sampled,
- options.amountOfPaint ?? 0.65,
- options.densityOfPaint ?? 0.9,
- options.colorStretch ?? 0.75,
- options.mixingMode ?? 'blend',
- effPressure,
- effectiveFlow,
- 0,
- options.perceptualMixing !== false
- );
-
- effectiveColor = mixed.colorHex;
- effectiveFlow = mixed.alpha;
-
- if (options.sampler) {
- options.sampler.depositDab(
- point.x,
- point.y,
- effWidth * 0.5,
- mixed.r,
- mixed.g,
- mixed.b,
- mixed.alpha
- );
- }
- }
-
- const gpuDabs: GpuDab[] | null = batchGpuDabs || null;
- const activeTip = selectTipImage(options.subTipImages, tipImage, options.subTipOrder, 0, 0, point.x, point.y);
- const isColorTip = Boolean(options.isColorTip || (options.subTips && options.subTips[0]?.isColor));
- const master = gpuDabs ? null : getTintedTipMaster(activeTip, effectiveColor, isColorTip);
-
- const aspect = (activeTip.naturalHeight || activeTip.height || 1) / (activeTip.naturalWidth || activeTip.width || 1);
- const thickness = options.thickness ?? 1.0;
- const isVert = Boolean(options.thicknessVertical);
- const useTilt = Boolean(options.useTilt || options.angleDynamics === 'tilt');
-
- const tiltX = useTilt ? (point.tiltX ?? 0) : 0;
- const tiltY = useTilt ? (point.tiltY ?? 0) : 0;
- const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
- const tiltSpread = tiltMagnitude * (options.tiltScale ?? 1.0);
- const grainPressure = useTilt && tiltMagnitude > 0.01
- ? effPressure * (1.0 - tiltMagnitude * 0.55)
- : effPressure;
-
- let angleRad = ((options.angle ?? 0) * Math.PI) / 180;
- if (useTilt && tiltMagnitude > 0.05) {
- angleRad = Math.atan2(tiltY, tiltX) + angleRad;
- }
- if (point.twist && (options.angleDynamics === 'twist' || useTilt)) {
- angleRad += (point.twist * Math.PI) / 180;
- }
-
- const sensorOpacity = evaluateCspSensor(
- options.opacitySensor,
- effPressure,
- tiltMagnitude,
- 0,
- dabHashFloat(point.x, point.y, 0, 41)
- );
- const sensorDensity = evaluateCspSensor(
- options.densitySensor,
- effPressure,
- tiltMagnitude,
- 0,
- dabHashFloat(point.x, point.y, 0, 42)
- );
- effectiveFlow *= sensorOpacity * sensorDensity;
- if (useTilt && tiltMagnitude > 0.03) {
- // Contact pressure spreads over larger tilted area -> softer graphite/chalk deposition
- effectiveFlow *= 1.0 - tiltMagnitude * 0.28;
- }
-
- // CPU Paper Texture modulation when not rendering on GPU (GPU shader samples paper grain per pixel)
- const grainAmount = options.grain ?? options.textureDensity ?? 0;
- const hasPerPixelCpuGrain = !gpuDabs && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
- if (!gpuDabs && grainAmount > 0.005 && !hasPerPixelCpuGrain) {
- const scale = Math.max(0.1, options.paperTextureScale ?? 1.0);
- const gNorm = getPaperGrain(point.x / scale, point.y / scale) / 255.0;
- effectiveFlow = applyCspPaperTextureAlpha(
- effectiveFlow,
- gNorm,
- grainAmount,
- grainPressure,
- options.paperTextureMode ?? 'subtract',
- options.paperTextureBrightness ?? 0,
- options.paperTextureContrast ?? 0,
- Boolean(options.paperTextureInverted)
- );
- }
- if (effectiveFlow <= 0.002) return;
-
- const dynamics = options.dynamics;
- const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
- const sizeJitter = Math.max(0, Math.min(1, dynamics?.sizeJitter ?? 0));
- const angleJitter = Math.max(0, Math.min(1, dynamics?.angleJitter ?? 0));
- const roundnessJitter = Math.max(0, Math.min(1, dynamics?.roundnessJitter ?? 0));
- const scatter = Math.max(0, Math.min(5, dynamics?.scatter ?? 0));
- const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
- const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
- const primRgb = (colorJitterEnabled || gpuDabs) ? parseColorToRgb(effectiveColor) : null;
- const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
- const aaMode = options.antiAlias ?? 2;
-
- for (let k = 0; k < dabCount; k++) {
- let curDabW = effWidth;
- if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - dabHashFloat(point.x, point.y, k, 1) * sizeJitter);
- }
- curDabW = Math.max(0.1, curDabW);
-
- let curDabThickness = thickness;
- if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(point.x, point.y, k, 2) * roundnessJitter);
- }
-
- let curDabAngle = angleRad;
- if (angleJitter > 0) {
- curDabAngle += (dabHashFloat(point.x, point.y, k, 3) - 0.5) * Math.PI * 2 * angleJitter;
- }
-
- let curDabX = point.x;
- let curDabY = point.y;
- if (scatter > 0) {
- const th = dabHashFloat(point.x, point.y, k, 4) * Math.PI * 2;
- const sDist = dabHashFloat(point.x, point.y, k, 5) * effWidth * scatter;
- curDabX += Math.cos(th) * sDist;
- curDabY += Math.sin(th) * sDist;
- }
-
- let curDabAlpha = effectiveFlow;
- if (flowJitter > 0) {
- curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(point.x, point.y, k, 6) * flowJitter);
- }
-
- let curMaster = master;
- let dabR = primRgb ? primRgb.r / 255 : 0;
- let dabG = primRgb ? primRgb.g / 255 : 0;
- let dabB = primRgb ? primRgb.b / 255 : 0;
- if (colorJitterEnabled && primRgb && secRgb && dynamics) {
- let salt = 20;
- const cd = applyColorDynamics(
- { r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
- { r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
- dynamics,
- () => dabHashFloat(point.x, point.y, k, salt++)
- );
- dabR = cd.r;
- dabG = cd.g;
- dabB = cd.b;
- if (!gpuDabs) {
- curMaster = getTintedTipMaster(activeTip, cd.hex, isColorTip);
- }
- }
-
- let dotRenderW = isVert ? curDabW * curDabThickness : curDabW;
- let dotRenderH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
- if (useTilt && tiltMagnitude > 0.01) {
- dotRenderW *= 1.0 + tiltSpread * 1.85;
- dotRenderH *= Math.max(0.55, 1.0 - tiltMagnitude * 0.25);
- }
- const flips = resolveTipFlipSigns(options.flipH, options.flipV, k, curDabX, curDabY);
-
- if (curMaster && hasPerPixelCpuGrain) {
- const grained = applyCpuPerPixelPaperGrain(
- curMaster,
- curDabX,
- curDabY,
- dotRenderW,
- dotRenderH,
- grainAmount,
- grainPressure,
- options.paperTextureScale ?? 1.0,
- options.paperTextureImage
- );
- if (grained) curMaster = grained;
- }
-
- if (options.spray?.enabled) {
- const pCount = options.spray.density;
- const pSize = Math.max(1, options.spray.size);
- const radius = curDabW / 2;
- for (let i = 0; i < pCount; i++) {
- const u1 = dabHashFloat(curDabX, curDabY, k * 64 + i, 31);
- const u2 = dabHashFloat(curDabX, curDabY, k * 64 + i, 32);
- const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));
- const th = Math.PI * 2 * dabHashFloat(curDabX, curDabY, k * 64 + i, 33);
- const spX = curDabX + r * Math.cos(th);
- const spY = curDabY + r * Math.sin(th);
- const spW = isVert ? pSize * curDabThickness : pSize;
- const spH = isVert ? pSize * aspect : pSize * aspect * curDabThickness;
- if (gpuDabs) {
- gpuDabs.push({
- x: spX,
- y: spY,
- width: spW,
- height: spH,
- angle: curDabAngle,
- r: dabR,
- g: dabG,
- b: dabB,
- alpha: curDabAlpha,
- pressure: grainPressure,
- strokeDist: 0,
- flipX: flips.signX,
- flipY: flips.signY,
- });
- } else if (curMaster) {
- drawSingleStamp(
- ctx,
- curMaster,
- spX,
- spY,
- spW,
- spH,
- curDabAngle,
- curDabAlpha,
- isEraser,
- isBgEraser,
- options.alphaLocked,
- options.isTransparentInk,
- flips.signX,
- flips.signY,
- aaMode,
- options.blendTipsMode
- );
- }
- }
- } else if (gpuDabs) {
- gpuDabs.push({
- x: curDabX,
- y: curDabY,
- width: dotRenderW,
- height: dotRenderH,
- angle: curDabAngle,
- r: dabR,
- g: dabG,
- b: dabB,
- alpha: curDabAlpha,
- pressure: grainPressure,
- strokeDist: 0,
- flipX: flips.signX,
- flipY: flips.signY,
- });
- } else if (curMaster) {
- drawSingleStamp(
- ctx,
- curMaster,
- curDabX,
- curDabY,
- dotRenderW,
- dotRenderH,
- curDabAngle,
- curDabAlpha,
- isEraser,
- isBgEraser,
- options.alphaLocked,
- options.isTransparentInk,
- flips.signX,
- flips.signY,
- aaMode,
- options.blendTipsMode
- );
- }
- }
-}
-
-// -------------------------------------------------------------
-// Cubic Bézier Evaluation & Zero-Allocation Arc-Length Scratch
-// -------------------------------------------------------------
-
-export interface EvaluatedBezierSample {
- x: number;
- y: number;
- width: number;
- pressure: number;
- dx: number;
- dy: number;
- speed: number;
- tiltX: number;
- tiltY: number;
- twist: number;
-}
-
-const _sharedSample: EvaluatedBezierSample = {
- x: 0,
- y: 0,
- width: 0,
- pressure: 0,
- dx: 0,
- dy: 0,
- speed: 0,
- tiltX: 0,
- tiltY: 0,
- twist: 0,
-};
-
-function evalCubicBezierInto(
- p0: Point,
- c1: Point,
- c2: Point,
- p3: Point,
- t: number,
- out: EvaluatedBezierSample
-): EvaluatedBezierSample {
- const invT = 1.0 - t;
- const invT2 = invT * invT;
- const invT3 = invT2 * invT;
- const t2 = t * t;
- const t3 = t2 * t;
-
- const b = 3.0 * invT2 * t;
- const c = 3.0 * invT * t2;
-
- out.x = invT3 * p0.x + b * c1.x + c * c2.x + t3 * p3.x;
- out.y = invT3 * p0.y + b * c1.y + c * c2.y + t3 * p3.y;
- out.width = invT3 * p0.width + b * c1.width + c * c2.width + t3 * p3.width;
- out.pressure = invT3 * p0.pressure + b * c1.pressure + c * c2.pressure + t3 * p3.pressure;
- out.tiltX = invT * (p0.tiltX ?? 0) + t * (p3.tiltX ?? 0);
- out.tiltY = invT * (p0.tiltY ?? 0) + t * (p3.tiltY ?? 0);
- out.twist = invT * (p0.twist ?? 0) + t * (p3.twist ?? 0);
-
- const dx = 3.0 * invT2 * (c1.x - p0.x) + 6.0 * invT * t * (c2.x - c1.x) + 3.0 * t2 * (p3.x - c2.x);
- const dy = 3.0 * invT2 * (c1.y - p0.y) + 6.0 * invT * t * (c2.y - c1.y) + 3.0 * t2 * (p3.y - c2.y);
- out.dx = dx;
- out.dy = dy;
- out.speed = Math.hypot(dx, dy);
- return out;
-}
-
-export function evalCubicBezier(
- p0: Point,
- c1: Point,
- c2: Point,
- p3: Point,
- t: number
-): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number; tiltX?: number; tiltY?: number; twist?: number } {
- const out: EvaluatedBezierSample = {
- x: 0, y: 0, width: 0, pressure: 0, dx: 0, dy: 0, speed: 0, tiltX: 0, tiltY: 0, twist: 0,
- };
- return evalCubicBezierInto(p0, c1, c2, p3, t, out);
-}
-
-export interface ArcLengthTable {
- totalLength: number;
- distances: number[];
-}
-
-// Fast reusable internal Float64Array arc-length scratch to avoid per-segment heap allocations
-const _fastArcDistances = new Float64Array(65);
-
-function buildFastArcLengthScratch(p0: Point, c1: Point, c2: Point, p3: Point): { totalLength: number; steps: number } {
- const polyLen =
- Math.hypot(c1.x - p0.x, c1.y - p0.y) +
- Math.hypot(c2.x - c1.x, c2.y - c1.y) +
- Math.hypot(p3.x - c2.x, p3.y - c2.y);
- const steps = Math.max(24, Math.min(64, Math.ceil(polyLen * 0.5)));
- _fastArcDistances[0] = 0;
- let total = 0;
- let prevX = p0.x;
- let prevY = p0.y;
-
- for (let i = 1; i <= steps; i++) {
- const t = i / steps;
- const invT = 1.0 - t;
- const invT2 = invT * invT;
- const invT3 = invT2 * invT;
- const t2 = t * t;
- const t3 = t2 * t;
-
- const x = invT3 * p0.x + 3.0 * invT2 * t * c1.x + 3.0 * invT * t2 * c2.x + t3 * p3.x;
- const y = invT3 * p0.y + 3.0 * invT2 * t * c1.y + 3.0 * invT * t2 * c2.y + t3 * p3.y;
-
- total += Math.hypot(x - prevX, y - prevY);
- _fastArcDistances[i] = total;
- prevX = x;
- prevY = y;
- }
-
- return { totalLength: total, steps };
-}
-
-function sampleFastArcLengthInto(
- p0: Point,
- c1: Point,
- c2: Point,
- p3: Point,
- targetDist: number,
- totalLength: number,
- steps: number,
- out: EvaluatedBezierSample
-): EvaluatedBezierSample {
- if (totalLength <= 0.0001 || targetDist <= 0) {
- return evalCubicBezierInto(p0, c1, c2, p3, 0, out);
- }
- if (targetDist >= totalLength) {
- return evalCubicBezierInto(p0, c1, c2, p3, 1.0, out);
- }
-
- let low = 0;
- let high = steps - 1;
- while (low < high) {
- const mid = (low + high + 1) >>> 1;
- if (_fastArcDistances[mid] <= targetDist) {
- low = mid;
- } else {
- high = mid - 1;
- }
- }
- const d0 = _fastArcDistances[low];
- const d1 = _fastArcDistances[low + 1];
- const frac = d1 > d0 ? (targetDist - d0) / (d1 - d0) : 0;
- const t = (low + frac) / steps;
- return evalCubicBezierInto(p0, c1, c2, p3, Math.max(0, Math.min(1.0, t)), out);
-}
-
-export function buildCubicArcLengthTable(p0: Point, c1: Point, c2: Point, p3: Point): ArcLengthTable {
- const { totalLength, steps } = buildFastArcLengthScratch(p0, c1, c2, p3);
- const distances: number[] = new Array(steps + 1);
- for (let i = 0; i <= steps; i++) {
- distances[i] = _fastArcDistances[i];
- }
- return { totalLength, distances };
-}
-
-export function getCubicPointAtArcLength(
- p0: Point,
- c1: Point,
- c2: Point,
- p3: Point,
- targetDist: number,
- table: ArcLengthTable
-): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number; tiltX?: number; tiltY?: number; twist?: number } {
- const { totalLength, distances } = table;
- if (totalLength <= 0.0001 || targetDist <= 0) {
- return evalCubicBezier(p0, c1, c2, p3, 0);
- }
- if (targetDist >= totalLength) {
- return evalCubicBezier(p0, c1, c2, p3, 1.0);
- }
-
- const steps = distances.length - 1;
- let low = 0;
- let high = steps - 1;
- while (low < high) {
- const mid = (low + high + 1) >>> 1;
- if (distances[mid] <= targetDist) {
- low = mid;
- } else {
- high = mid - 1;
- }
- }
- const idx = low;
- const d0 = distances[idx];
- const d1 = distances[idx + 1];
- const frac = d1 > d0 ? (targetDist - d0) / (d1 - d0) : 0;
- const t = (idx + frac) / steps;
-
- return evalCubicBezier(p0, c1, c2, p3, Math.max(0, Math.min(1.0, t)));
-}
-
-/**
- * Draws textured CSP brush stamps along a cubic Bézier curve using zero-allocation arc-length parameterization.
- */
-export function drawTexturedCubicBezierSegment(
- ctx: CanvasRenderingContext2D,
- p0: Point,
- c1: Point,
- c2: Point,
- p3: Point,
- color: string,
- tipImage: HTMLImageElement,
- options: TexturedBrushOptions,
- remainderDist: number = 0,
- dabCounter: { count: number } = { count: 0 },
- batchGpuDabs?: GpuDab[]
-): number {
- const { totalLength: totalCurveLength, steps: arcSteps } = buildFastArcLengthScratch(p0, c1, c2, p3);
- if (totalCurveLength < 0.08) {
- return Math.max(0, remainderDist - totalCurveLength);
- }
-
- const isEraser = options.isEraser ?? false;
- const isBgEraser = options.isBgEraser ?? false;
- const baseColor = isBgEraser ? '#ffffff' : color;
-
- const isColorMixing = Boolean(options.colorMixing) && !isEraser;
- const sampler = options.sampler;
-
- if (isColorMixing && !options.reservoir) {
- options.reservoir = new PaintReservoir(color);
- }
-
- const reservoir = options.reservoir;
- const aspect = (tipImage.naturalHeight || tipImage.height || 1) / (tipImage.naturalWidth || tipImage.width || 1);
- const baseAngleRad = ((options.angle ?? 0) * Math.PI) / 180;
- const rawDensity = options.brushDensity ?? options.flow ?? 0.85;
- const spacingRatio = Math.max(0.015, Math.min(1.0, options.spacing ?? 0.07));
- const baseFlow = computeGapAdjustedAlpha(rawDensity, spacingRatio, options.adjustDensityByGap);
- const thickness = options.thickness ?? 1.0;
- const isVert = Boolean(options.thicknessVertical);
- const rotationRandomScale = options.rotationRandomScale ?? 0;
- const useTilt = Boolean(options.useTilt || options.angleDynamics === 'tilt');
- const aaMode = options.antiAlias ?? 2;
- const grainAmount = options.grain ?? options.textureDensity ?? 0;
-
- const gpuDabs: GpuDab[] | null = batchGpuDabs || null;
-
- let smoothCos = Math.cos(baseAngleRad);
- let smoothSin = Math.sin(baseAngleRad);
-
- let currentDist = remainderDist > 0 ? remainderDist : 0;
-
- while (currentDist <= totalCurveLength) {
- const pt = sampleFastArcLengthInto(p0, c1, c2, p3, currentDist, totalCurveLength, arcSteps, _sharedSample);
- const effPressure = Math.max(0, Math.min(1, pt.pressure));
- const curvedPressure = options.pressureCurve ? evaluateFastSpline(effPressure, options.pressureCurve) : effPressure;
- const minFactor = Math.max(0, Math.min(1.0, options.minSizeFactor ?? 0));
-
- let curWidth = pt.width > 0
- ? pt.width
- : (options.usePressure !== false
- ? options.size * (minFactor + (1.0 - minFactor) * curvedPressure)
- : options.size);
-
- const strokeDist = (options.currentStrokeDist ?? 0) + currentDist;
-
- // CSP Starting & Ending taper modulation (supports sharpness curves + Size/Density/Opacity targets)
- let taperAlphaScale = 1.0;
- if (options.taper) {
- const inSharp = 0.35 + (1.0 - (options.taper.startingSharpness ?? 0.5)) * 1.1;
- const outSharp = 0.35 + (1.0 - (options.taper.endingSharpness ?? 0.5)) * 1.1;
- const inLen = options.taper.inLength || (options.taper.inRatio ? options.taper.inRatio * 2.5 : 0);
- if (options.taper.useIn && inLen > 0 && strokeDist < inLen) {
- const inFactor = Math.pow(Math.max(0.01, Math.min(1.0, strokeDist / inLen)), inSharp);
- if (options.taper.affectSize !== false) curWidth *= inFactor;
- if (options.taper.affectDensity || options.taper.affectOpacity) taperAlphaScale *= inFactor;
- }
- if (options.totalLength && options.totalLength > 0) {
- const distFromEnd = options.totalLength - strokeDist;
- const outLen = options.taper.outLength || (options.taper.outRatio ? options.taper.outRatio * 3.0 : 0);
- if (options.taper.useOut && outLen > 0 && distFromEnd < outLen) {
- const outFactor = Math.pow(Math.max(0.01, Math.min(1.0, distFromEnd / outLen)), outSharp);
- if (options.taper.affectSize !== false) curWidth *= outFactor;
- if (options.taper.affectDensity || options.taper.affectOpacity) taperAlphaScale *= outFactor;
- }
- }
- }
-
- const dabSeq = dabCounter.count++;
-
- const tiltX = useTilt ? pt.tiltX : 0;
- const tiltY = useTilt ? pt.tiltY : 0;
- const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
- const tiltSpread = tiltMagnitude * (options.tiltScale ?? 1.0);
- const grainPressure = useTilt && tiltMagnitude > 0.01
- ? effPressure * (1.0 - tiltMagnitude * 0.55)
- : effPressure;
-
- // Multi-sensor CSP size modulation
- if (options.sizeSensor) {
- curWidth *= evaluateCspSensor(
- options.sizeSensor,
- effPressure,
- tiltMagnitude,
- pt.speed * 0.05,
- dabHashFloat(pt.x, pt.y, dabSeq, 50)
- );
- }
- curWidth = Math.max(0.1, curWidth);
-
- let stampAngle = baseAngleRad;
- if ((options.angleDynamics === 'direction' || options.angleDynamics === 'direction-random') && pt.speed > 0.05) {
- const targetAngle = Math.atan2(pt.dy, pt.dx) + baseAngleRad;
- const tCos = Math.cos(targetAngle);
- const tSin = Math.sin(targetAngle);
- smoothCos = smoothCos * 0.6 + tCos * 0.4;
- smoothSin = smoothSin * 0.6 + tSin * 0.4;
- stampAngle = Math.atan2(smoothSin, smoothCos);
- }
- if (options.angleDynamics === 'random' || options.angleDynamics === 'direction-random') {
- const rScale = options.angleDynamics === 'random' ? 1.0 : (rotationRandomScale || 0.35);
- stampAngle += (dabHashFloat(pt.x, pt.y, dabSeq, 12) - 0.5) * Math.PI * 2 * rScale;
- } else if (rotationRandomScale > 0) {
- stampAngle += (dabHashFloat(pt.x, pt.y, dabSeq, 12) - 0.5) * Math.PI * 2 * rotationRandomScale;
- }
-
- if (useTilt && tiltMagnitude > 0.05) {
- stampAngle = Math.atan2(tiltY, tiltX) + baseAngleRad;
- }
- if (pt.twist && (options.angleDynamics === 'twist' || useTilt)) {
- stampAngle += (pt.twist * Math.PI) / 180;
- }
-
- let dabColor = baseColor;
- let dabAlpha = baseFlow * taperAlphaScale;
-
- if (options.opacitySensor) {
- dabAlpha *= evaluateCspSensor(
- options.opacitySensor,
- effPressure,
- tiltMagnitude,
- pt.speed * 0.05,
- dabHashFloat(pt.x, pt.y, dabSeq, 51)
- );
- }
- if (options.densitySensor) {
- dabAlpha *= evaluateCspSensor(
- options.densitySensor,
- effPressure,
- tiltMagnitude,
- pt.speed * 0.05,
- dabHashFloat(pt.x, pt.y, dabSeq, 52)
- );
- }
- if (useTilt && tiltMagnitude > 0.03) {
- // Spread graphite/chalk deposition over wider tilted contact patch
- dabAlpha *= 1.0 - tiltMagnitude * 0.28;
- }
-
- if (isColorMixing && reservoir) {
- let sampled = { r: 255, g: 255, b: 255, a: 0 };
- if (sampler) {
- sampled = sampler.sampleColor(pt.x, pt.y, curWidth * 0.45);
- } else {
- const sampleCanvas = options.underlyingCanvas || ctx.canvas;
- const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;
- if (sampleCtx) {
- sampled = sampleCanvasColor(sampleCtx, pt.x, pt.y, curWidth * 0.45);
- }
- }
-
- const mixed = reservoir.mixWithCanvas(
- sampled,
- options.amountOfPaint ?? 0.65,
- options.densityOfPaint ?? 0.9,
- options.colorStretch ?? 0.75,
- options.mixingMode ?? 'blend',
- effPressure,
- dabAlpha,
- Math.max(0.2, curWidth * spacingRatio),
- options.perceptualMixing !== false
- );
-
- dabColor = mixed.colorHex;
- dabAlpha = mixed.alpha;
-
- if (sampler && mixed.alpha > 0.002) {
- sampler.depositDab(
- pt.x,
- pt.y,
- curWidth * 0.45,
- mixed.r,
- mixed.g,
- mixed.b,
- mixed.alpha
- );
- }
- }
-
- // CPU paper grain parity (when rendering live on Canvas2D without GPU batch)
- const hasPerPixelCpuGrain = !gpuDabs && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
- if (!gpuDabs && grainAmount > 0.005 && !hasPerPixelCpuGrain) {
- const scale = Math.max(0.1, options.paperTextureScale ?? 1.0);
- const gNorm = getPaperGrain(pt.x / scale, pt.y / scale) / 255.0;
- dabAlpha = applyCspPaperTextureAlpha(
- dabAlpha,
- gNorm,
- grainAmount,
- grainPressure,
- options.paperTextureMode ?? 'subtract',
- options.paperTextureBrightness ?? 0,
- options.paperTextureContrast ?? 0,
- Boolean(options.paperTextureInverted)
- );
- }
-
- const activeTip = selectTipImage(
- options.subTipImages,
- tipImage,
- options.subTipOrder,
- dabSeq,
- stampAngle,
- pt.x,
- pt.y
- );
- const isColorTip = Boolean(options.isColorTip || (options.subTips && options.subTips[0]?.isColor));
- const master = gpuDabs ? null : getTintedTipMaster(activeTip, dabColor, isColorTip);
-
- let tx = 1;
- let ty = 0;
- let nx = 0;
- let ny = 1;
- if (pt.speed > 0.001) {
- tx = pt.dx / pt.speed;
- ty = pt.dy / pt.speed;
- nx = -ty;
- ny = tx;
- }
-
- const dynamics = options.dynamics;
- const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
- const sizeJitter = Math.max(0, Math.min(1, dynamics?.sizeJitter ?? 0));
- const angleJitter = Math.max(0, Math.min(1, dynamics?.angleJitter ?? 0));
- const roundnessJitter = Math.max(0, Math.min(1, dynamics?.roundnessJitter ?? 0));
- const scatter = Math.max(0, Math.min(5, dynamics?.scatter ?? 0));
- const scatterBothAxes = Boolean(dynamics?.scatterBothAxes);
- const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
- const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
- const primRgb = (colorJitterEnabled || gpuDabs) ? parseColorToRgb(dabColor) : null;
- const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
-
- let stepRefW = isVert ? curWidth * thickness : curWidth;
- let stepRefH = isVert ? curWidth * aspect : curWidth * aspect * thickness;
-
- for (let k = 0; k < dabCount; k++) {
- const seedIdx = dabSeq * 16 + k;
- let curDabW = curWidth;
- if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 1) * sizeJitter);
- }
- curDabW = Math.max(0.1, curDabW);
-
- let curDabThickness = thickness;
- if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 2) * roundnessJitter);
- }
-
- let curDabAngle = stampAngle;
- if (angleJitter > 0) {
- curDabAngle += (dabHashFloat(pt.x, pt.y, seedIdx, 3) - 0.5) * Math.PI * 2 * angleJitter;
- }
-
- let curDabX = pt.x;
- let curDabY = pt.y;
- if (scatter > 0) {
- const perpDist = (dabHashFloat(pt.x, pt.y, seedIdx, 4) * 2 - 1) * curWidth * scatter;
- let sOffX = nx * perpDist;
- let sOffY = ny * perpDist;
- if (scatterBothAxes) {
- const tangDist = (dabHashFloat(pt.x, pt.y, seedIdx, 5) * 2 - 1) * curWidth * scatter;
- sOffX += tx * tangDist;
- sOffY += ty * tangDist;
- }
- curDabX += sOffX;
- curDabY += sOffY;
- }
-
- let curDabAlpha = dabAlpha;
- if (flowJitter > 0) {
- curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 6) * flowJitter);
- }
-
- let curMaster = master;
- let dabR = primRgb ? primRgb.r / 255 : 0;
- let dabG = primRgb ? primRgb.g / 255 : 0;
- let dabB = primRgb ? primRgb.b / 255 : 0;
-
- if (colorJitterEnabled && primRgb && secRgb && dynamics) {
- let salt = 20;
- const cd = applyColorDynamics(
- { r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
- { r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
- dynamics,
- () => dabHashFloat(pt.x, pt.y, seedIdx, salt++)
- );
- dabR = cd.r;
- dabG = cd.g;
- dabB = cd.b;
- if (!gpuDabs) {
- curMaster = getTintedTipMaster(activeTip, cd.hex, isColorTip);
- }
- }
-
- let finalW = isVert ? curDabW * curDabThickness : curDabW;
- let finalH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
- if (useTilt && tiltMagnitude > 0.01) {
- finalW *= 1.0 + tiltSpread * 1.85;
- finalH *= Math.max(0.55, 1.0 - tiltMagnitude * 0.25);
- }
- stepRefW = finalW;
- stepRefH = finalH;
-
- if (curDabAlpha <= 0.002) continue;
-
- const flips = resolveTipFlipSigns(options.flipH, options.flipV, seedIdx, curDabX, curDabY);
-
- if (curMaster && hasPerPixelCpuGrain) {
- const grained = applyCpuPerPixelPaperGrain(
- curMaster,
- curDabX,
- curDabY,
- finalW,
- finalH,
- grainAmount,
- grainPressure,
- options.paperTextureScale ?? 1.0,
- options.paperTextureImage
- );
- if (grained) curMaster = grained;
- }
-
- if (options.spray?.enabled) {
- const pCount = options.spray.density;
- const pSize = Math.max(1, options.spray.size);
- const radius = curDabW / 2;
- for (let sp = 0; sp < pCount; sp++) {
- const u1 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 31);
- const u2 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 32);
- const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));
- const th = Math.PI * 2 * dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 33);
- const spX = curDabX + r * Math.cos(th);
- const spY = curDabY + r * Math.sin(th);
- const spW = isVert ? pSize * curDabThickness : pSize;
- const spH = isVert ? pSize * aspect : pSize * aspect * curDabThickness;
- if (gpuDabs) {
- gpuDabs.push({
- x: spX,
- y: spY,
- width: spW,
- height: spH,
- angle: curDabAngle,
- r: dabR,
- g: dabG,
- b: dabB,
- alpha: curDabAlpha,
- pressure: grainPressure,
- strokeDist,
- flipX: flips.signX,
- flipY: flips.signY,
- });
- } else if (curMaster) {
- drawSingleStamp(
- ctx,
- curMaster,
- spX,
- spY,
- spW,
- spH,
- curDabAngle,
- curDabAlpha,
- isEraser,
- isBgEraser,
- options.alphaLocked,
- options.isTransparentInk,
- flips.signX,
- flips.signY,
- aaMode,
- options.blendTipsMode
- );
- }
- }
- } else if (gpuDabs) {
- gpuDabs.push({
- x: curDabX,
- y: curDabY,
- width: finalW,
- height: finalH,
- angle: curDabAngle,
- r: dabR,
- g: dabG,
- b: dabB,
- alpha: curDabAlpha,
- pressure: grainPressure,
- strokeDist,
- flipX: flips.signX,
- flipY: flips.signY,
- });
- } else if (curMaster) {
- drawSingleStamp(
- ctx,
- curMaster,
- curDabX,
- curDabY,
- finalW,
- finalH,
- curDabAngle,
- curDabAlpha,
- isEraser,
- isBgEraser,
- options.alphaLocked,
- options.isTransparentInk,
- flips.signX,
- flips.signY,
- aaMode,
- options.blendTipsMode
- );
- }
- }
-
- const requiredStep = computeEllipticalStepDistance(
- stepRefW,
- stepRefH,
- stampAngle,
- pt.dx,
- pt.dy,
- spacingRatio,
- 0.15
- );
- currentDist += requiredStep;
- }
-
- return Math.max(0, currentDist - totalCurveLength);
-}
-
-export function drawTexturedBezierSegment(
- ctx: CanvasRenderingContext2D,
- start: Point,
- control: Point,
- end: Point,
- color: string,
- tipImage: HTMLImageElement,
- options: TexturedBrushOptions,
- remainderDist: number = 0,
- dabCounter: { count: number } = { count: 0 }
-): number {
- const c1: Point = {
- x: start.x + (2.0 / 3.0) * (control.x - start.x),
- y: start.y + (2.0 / 3.0) * (control.y - start.y),
- pressure: start.pressure + (2.0 / 3.0) * (control.pressure - start.pressure),
- width: start.width + (2.0 / 3.0) * (control.width - start.width),
- };
- const c2: Point = {
- x: end.x + (2.0 / 3.0) * (control.x - end.x),
- y: end.y + (2.0 / 3.0) * (control.y - end.y),
- pressure: end.pressure + (2.0 / 3.0) * (control.pressure - end.pressure),
- width: end.width + (2.0 / 3.0) * (control.width - end.width),
- };
- return drawTexturedCubicBezierSegment(
- ctx,
- start,
- c1,
- c2,
- end,
- color,
- tipImage,
- options,
- remainderDist,
- dabCounter
- );
-}
-
-export function renderCompleteTexturedStroke(
- ctx: CanvasRenderingContext2D,
- points: Point[],
- color: string,
- tipImage: HTMLImageElement,
- options: TexturedBrushOptions
-) {
- if (!points || points.length === 0) return;
-
- if (options.colorMixing && !options.reservoir) {
- options.reservoir = new PaintReservoir(color);
- }
- if (!options.underlyingCanvas) {
- options.underlyingCanvas = ctx.canvas;
- }
- if (options.colorMixing && !options.sampler && options.underlyingCanvas) {
- options.sampler = new LayerPixelSampler(options.underlyingCanvas);
- }
-
- let totalLen = 0;
- for (let i = 1; i < points.length; i++) {
- totalLen += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
- }
- options.totalLength = totalLen;
- options.currentStrokeDist = 0;
-
- const emitStroke = (batchGpuDabs: GpuDab[] | undefined) => {
- options.currentStrokeDist = 0;
- drawTexturedDot(ctx, points[0], color, tipImage, options, batchGpuDabs);
- if (points.length === 1) return;
-
- const dabCounter = { count: 0 };
- let accDist = Math.max(0.15, points[0].width * (options.spacing ?? 0.07));
-
- if (points.length === 2) {
- const p0 = points[0];
- const p1 = points[1];
- const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
- drawTexturedCubicBezierSegment(ctx, p0, c1, c2, p1, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
- } else {
- const p0 = points[0];
- const p1 = points[1];
- const p2 = points[2];
- const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
- accDist = drawTexturedCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
- options.currentStrokeDist = (options.currentStrokeDist ?? 0) + Math.hypot(p1.x - p0.x, p1.y - p0.y);
-
- for (let i = 2; i < points.length - 1; i++) {
- const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
- accDist = drawTexturedCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, tipImage, options, accDist, dabCounter, batchGpuDabs);
- options.currentStrokeDist = (options.currentStrokeDist ?? 0) + Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
- }
-
- const n = points.length;
- const pPrev2 = points[n - 3];
- const pPrev = points[n - 2];
- const pLast = points[n - 1];
- const last = centripetalCatmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- drawTexturedCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
- }
- };
-
- if (canUseWebGlForTexturedBrush(options)) {
- const batchGpuDabs: GpuDab[] = [];
- emitStroke(batchGpuDabs);
- if (flushTexturedGpuDabs(ctx, batchGpuDabs, tipImage, color, options)) {
- return;
- }
- }
-
- // Clean Canvas 2D fallback (binary AA=0, colorMixingEngine, multi-subTip, or unavailable WebGL)
- emitStroke(undefined);
-}
-
-/**
- * Centripetal Catmull-Rom spline (alpha = 0.5) to cubic Bézier control points.
- */
-export function centripetalCatmullRomToBezier(
- p0: Point,
- p1: Point,
- p2: Point,
- p3: Point
-): { c1: Point; c2: Point } {
- const effP0 = p1.isCorner ? p1 : p0;
- const effP3 = p2.isCorner ? p2 : p3;
-
- const d01 = Math.hypot(p1.x - effP0.x, p1.y - effP0.y);
- const d12 = Math.hypot(p2.x - p1.x, p2.y - p1.y);
- const d23 = Math.hypot(effP3.x - p2.x, effP3.y - p2.y);
-
- const dt0 = Math.max(1e-4, Math.sqrt(d01));
- const dt1 = Math.max(1e-4, Math.sqrt(d12));
- const dt2 = Math.max(1e-4, Math.sqrt(d23));
-
- const t1x = (p2.x - p1.x) / dt1 - (p1.x - effP0.x) / dt0 + (p2.x - effP0.x) / (dt0 + dt1);
- const t1y = (p2.y - p1.y) / dt1 - (p1.y - effP0.y) / dt0 + (p2.y - effP0.y) / (dt0 + dt1);
- const t2x = (effP3.x - p2.x) / dt2 - (p2.x - p1.x) / dt1 + (effP3.x - p1.x) / (dt1 + dt2);
- const t2y = (effP3.y - p2.y) / dt2 - (p2.y - p1.y) / dt1 + (effP3.y - p1.y) / (dt1 + dt2);
-
- let dx1 = (t1x * dt1) / 3;
- let dy1 = (t1y * dt1) / 3;
- let dx2 = (t2x * dt1) / 3;
- let dy2 = (t2y * dt1) / 3;
-
- if (d12 > 0.001) {
- const maxHandle = d12 * 0.48;
- const len1 = Math.hypot(dx1, dy1);
- if (len1 > maxHandle) {
- const s = maxHandle / len1;
- dx1 *= s;
- dy1 *= s;
- }
- const len2 = Math.hypot(dx2, dy2);
- if (len2 > maxHandle) {
- const s = maxHandle / len2;
- dx2 *= s;
- dy2 *= s;
- }
- }
-
- const minP = Math.min(p1.pressure, p2.pressure);
- const maxP = Math.max(p1.pressure, p2.pressure);
- const minW = Math.min(p1.width, p2.width);
- const maxW = Math.max(p1.width, p2.width);
-
- const c1: Point = {
- x: p1.x + dx1,
- y: p1.y + dy1,
- pressure: Math.max(minP, Math.min(maxP, p1.pressure + (p2.pressure - effP0.pressure) / 6)),
- width: Math.max(minW, Math.min(maxW, p1.width + (p2.width - effP0.width) / 6)),
- };
-
- const c2: Point = {
- x: p2.x - dx2,
- y: p2.y - dy2,
- pressure: Math.max(minP, Math.min(maxP, p2.pressure - (effP3.pressure - p1.pressure) / 6)),
- width: Math.max(minW, Math.min(maxW, p2.width - (effP3.width - p1.width) / 6)),
- };
-
- return { c1, c2 };
-}
-
-export interface RadialMixingOptions {
- colorMixing?: boolean;
- perceptualMixing?: boolean;
- amountOfPaint?: number;
- densityOfPaint?: number;
- colorStretch?: number;
- mixingMode?: 'blend' | 'running_color' | 'smear';
- underlyingCanvas?: HTMLCanvasElement;
- sampler?: LayerPixelSampler;
- reservoir?: PaintReservoir;
- alphaLocked?: boolean;
- isTransparentInk?: boolean;
- dynamics?: BrushDynamics;
- secondaryColor?: string;
- useGpu?: boolean;
- dualBrush?: boolean;
- dualTipImage?: HTMLImageElement;
- dualBrushCompositeMode?: string;
- // Extended CSP Options for analytical round/elliptical brushes
- useTilt?: boolean;
- tiltScale?: number;
- thicknessVertical?: boolean;
- flipH?: CspTipFlipMode;
- flipV?: CspTipFlipMode;
- antiAlias?: number;
- angleDynamics?: CspAngleDynamicsMode;
- rotationRandomScale?: number;
- adjustDensityByGap?: boolean;
- blendTipsMode?: CspBlendTipsMode;
- grain?: number;
- paperTextureMode?: CspPaperTextureMode;
- paperTextureBrightness?: number;
- paperTextureContrast?: number;
- paperTextureInverted?: boolean;
- paperTextureImage?: HTMLImageElement;
- paperTextureScale?: number;
- paperTextureRotate?: number;
- sizeSensor?: CspSensorConfig;
- opacitySensor?: CspSensorConfig;
- densitySensor?: CspSensorConfig;
- taper?: CspTaperSettings;
- totalLength?: number;
- currentStrokeDist?: number;
-}
-
-/**
- * Draws a single radial/elliptical dot.
- */
-export function drawRadialDot(
- ctx: CanvasRenderingContext2D,
- point: Point,
- color: string,
- hardness: number = 1.0,
- flow: number = 1.0,
- isEraser: boolean = false,
- isBgEraser: boolean = false,
- mixingOptions?: RadialMixingOptions,
- thickness: number = 1.0,
- angleRad: number = 0,
- batchGpuDabs?: GpuDab[]
-) {
- const isColorMixing = Boolean(mixingOptions?.colorMixing) && !isEraser && !isBgEraser;
- let dabColor = isBgEraser ? '#ffffff' : color;
- let dabFlow = computeGapAdjustedAlpha(flow, 0.08, mixingOptions?.adjustDensityByGap);
- let w = Math.max(0.4, point.width);
- const aaMode = mixingOptions?.antiAlias ?? 2;
- const isVert = Boolean(mixingOptions?.thicknessVertical);
- // Default useTilt to true ONLY when mixingOptions is undefined (legacy unit test compatibility) or explicitly true
- const useTilt = mixingOptions === undefined ? true : Boolean(mixingOptions.useTilt);
- const tiltX = useTilt ? (point.tiltX ?? 0) : 0;
- const tiltY = useTilt ? (point.tiltY ?? 0) : 0;
- const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
- const tiltSpread = tiltMagnitude * (mixingOptions?.tiltScale ?? 1.0);
-
- if (mixingOptions?.sizeSensor) {
- w = Math.max(
- 0.15,
- w *
- evaluateCspSensor(
- mixingOptions.sizeSensor,
- point.pressure ?? 1.0,
- tiltMagnitude,
- 0,
- dabHashFloat(point.x, point.y, 0, 50)
- )
- );
- }
- if (mixingOptions?.opacitySensor) {
- dabFlow *= evaluateCspSensor(
- mixingOptions.opacitySensor,
- point.pressure ?? 1.0,
- tiltMagnitude,
- 0,
- dabHashFloat(point.x, point.y, 0, 51)
- );
- }
- if (mixingOptions?.densitySensor) {
- dabFlow *= evaluateCspSensor(
- mixingOptions.densitySensor,
- point.pressure ?? 1.0,
- tiltMagnitude,
- 0,
- dabHashFloat(point.x, point.y, 0, 52)
- );
- }
-
- if (isColorMixing) {
- if (!mixingOptions!.reservoir) {
- mixingOptions!.reservoir = new PaintReservoir(dabColor);
- }
- const reservoir = mixingOptions!.reservoir;
- let sampled = { r: 255, g: 255, b: 255, a: 0 };
- if (mixingOptions!.sampler) {
- sampled = mixingOptions!.sampler.sampleColor(point.x, point.y, Math.max(1, w / 2));
- } else {
- const sampleCanvas = mixingOptions!.underlyingCanvas || ctx.canvas;
- const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;
- if (sampleCtx) {
- sampled = sampleCanvasColor(sampleCtx, point.x, point.y, Math.max(1, w / 2));
- }
- }
-
- const mixed = reservoir.mixWithCanvas(
- sampled,
- mixingOptions!.amountOfPaint ?? 0.65,
- mixingOptions!.densityOfPaint ?? 0.9,
- mixingOptions!.colorStretch ?? 0.75,
- mixingOptions!.mixingMode ?? 'blend',
- point.pressure ?? 1.0,
- dabFlow,
- 0,
- mixingOptions!.perceptualMixing !== false
- );
-
- dabColor = mixed.colorHex;
- dabFlow = mixed.alpha;
-
- if (mixingOptions!.sampler && mixed.alpha > 0.002) {
- mixingOptions!.sampler.depositDab(
- point.x,
- point.y,
- w * 0.5,
- mixed.r,
- mixed.g,
- mixed.b,
- mixed.alpha
- );
- }
- }
- if (dabFlow <= 0.002) return;
-
- let dotW = w;
- let dotAngle = angleRad;
- if (useTilt && tiltMagnitude > 0.01) {
- const tiltAzimuth = Math.atan2(tiltY, tiltX);
- dotW = w * (1.0 + tiltSpread * 1.8);
- if (tiltMagnitude > 0.05) {
- dotAngle = tiltAzimuth;
- }
- }
- if (point.twist && (useTilt || mixingOptions?.angleDynamics === 'twist')) {
- dotAngle += (point.twist * Math.PI) / 180;
- }
-
- const gpuDabs: GpuDab[] | null = batchGpuDabs || null;
- const grainAmount = mixingOptions?.grain ?? 0;
- if (!gpuDabs && grainAmount > 0.005) {
- const scale = Math.max(0.1, mixingOptions?.paperTextureScale ?? 1.0);
- const gNorm = getPaperGrain(point.x / scale, point.y / scale) / 255.0;
- dabFlow = applyCspPaperTextureAlpha(
- dabFlow,
- gNorm,
- grainAmount,
- point.pressure ?? 0.5,
- mixingOptions?.paperTextureMode ?? 'subtract',
- mixingOptions?.paperTextureBrightness ?? 0,
- mixingOptions?.paperTextureContrast ?? 0,
- Boolean(mixingOptions?.paperTextureInverted)
- );
- }
-
- const master = gpuDabs ? null : getRadialDabMaster(hardness, dabColor, isEraser && !isBgEraser, dotW, aaMode);
-
- const dynamics = mixingOptions?.dynamics;
- const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
- const sizeJitter = Math.max(0, Math.min(1, dynamics?.sizeJitter ?? 0));
- const angleJitter = Math.max(0, Math.min(1, dynamics?.angleJitter ?? 0));
- const roundnessJitter = Math.max(0, Math.min(1, dynamics?.roundnessJitter ?? 0));
- const scatter = Math.max(0, Math.min(5, dynamics?.scatter ?? 0));
- const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
- const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
- const primRgb = (colorJitterEnabled || gpuDabs) ? parseColorToRgb(dabColor) : null;
- const secRgb = colorJitterEnabled ? parseColorToRgb(mixingOptions?.secondaryColor || '#ffffff') : null;
-
- for (let k = 0; k < dabCount; k++) {
- let curDabW = dotW;
- if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - dabHashFloat(point.x, point.y, k, 1) * sizeJitter);
- }
- curDabW = Math.max(0.1, curDabW);
-
- let curDabThickness = thickness;
- if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(point.x, point.y, k, 2) * roundnessJitter);
- }
-
- let curDabRot = dotAngle;
- if (angleJitter > 0) {
- curDabRot += (dabHashFloat(point.x, point.y, k, 3) - 0.5) * Math.PI * 2 * angleJitter;
- }
-
- let curDabX = point.x;
- let curDabY = point.y;
- if (scatter > 0) {
- const th = dabHashFloat(point.x, point.y, k, 4) * Math.PI * 2;
- const sDist = dabHashFloat(point.x, point.y, k, 5) * w * scatter;
- curDabX += Math.cos(th) * sDist;
- curDabY += Math.sin(th) * sDist;
- }
-
- let curDabFlow = dabFlow;
- if (flowJitter > 0) {
- curDabFlow *= Math.max(0.005, 1.0 - dabHashFloat(point.x, point.y, k, 6) * flowJitter);
- }
-
- let curMaster = master;
- let rNorm = primRgb ? primRgb.r / 255 : 0;
- let gNorm = primRgb ? primRgb.g / 255 : 0;
- let bNorm = primRgb ? primRgb.b / 255 : 0;
- if (colorJitterEnabled && primRgb && secRgb && dynamics) {
- let salt = 20;
- const cd = applyColorDynamics(
- { r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
- { r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
- dynamics,
- () => dabHashFloat(point.x, point.y, k, salt++)
- );
- rNorm = cd.r;
- gNorm = cd.g;
- bNorm = cd.b;
- if (!gpuDabs) {
- curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser, curDabW, aaMode);
- }
- }
-
- let finalW = isVert ? curDabW * curDabThickness : curDabW;
- let finalH = isVert ? curDabW : curDabW * curDabThickness;
- if (useTilt && tiltMagnitude > 0.01) {
- finalW = w * (1.0 + tiltSpread * 1.8);
- finalH = (w * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
- }
-
- if (gpuDabs) {
- gpuDabs.push({
- x: curDabX,
- y: curDabY,
- width: finalW,
- height: finalH,
- angle: curDabRot,
- r: rNorm,
- g: gNorm,
- b: bNorm,
- alpha: curDabFlow,
- pressure: point.pressure ?? 1.0,
- strokeDist: 0,
- flipX: 1,
- flipY: 1,
- });
- } else if (curMaster) {
- drawSingleStamp(
- ctx,
- curMaster,
- curDabX,
- curDabY,
- finalW,
- finalH,
- curDabRot,
- curDabFlow,
- isEraser,
- isBgEraser,
- mixingOptions?.alphaLocked,
- mixingOptions?.isTransparentInk,
- 1,
- 1,
- aaMode,
- mixingOptions?.blendTipsMode
- );
- }
- }
-}
-
-/**
- * Draws smooth analytical radial/elliptical dabs along a cubic Bézier curve using zero-allocation arc-length parameterization.
- */
-export function drawRadialCubicBezierSegment(
- ctx: CanvasRenderingContext2D,
- p0: Point,
- c1: Point,
- c2: Point,
- p3: Point,
- color: string,
- hardness: number = 1.0,
- flow: number = 1.0,
- spacing: number = 0.08,
- isEraser: boolean = false,
- isBgEraser: boolean = false,
- remainderDist: number = 0,
- thickness: number = 1.0,
- angleRad: number = 0,
- mixingOptions?: RadialMixingOptions,
- batchGpuDabs?: GpuDab[]
-): number {
- const { totalLength: totalCurveLength, steps: arcSteps } = buildFastArcLengthScratch(p0, c1, c2, p3);
- if (totalCurveLength < 0.08) {
- return Math.max(0, remainderDist - totalCurveLength);
- }
-
- const isColorMixing = Boolean(mixingOptions?.colorMixing) && !isEraser && !isBgEraser;
- const dynamics = mixingOptions?.dynamics;
- const gpuDabs: GpuDab[] | null = batchGpuDabs || null;
- const aaMode = mixingOptions?.antiAlias ?? 2;
- const isVert = Boolean(mixingOptions?.thicknessVertical);
- const useTilt = mixingOptions === undefined ? true : Boolean(mixingOptions.useTilt);
- const grainAmount = mixingOptions?.grain ?? 0;
-
- if (isColorMixing && mixingOptions && !mixingOptions.reservoir) {
- mixingOptions.reservoir = new PaintReservoir(color);
- }
- const reservoir = mixingOptions?.reservoir;
- const sampler = mixingOptions?.sampler;
- const avgSegWidth = Math.max(0.5, (p0.width + p3.width) * 0.5);
- const staticMaster = (isColorMixing || gpuDabs) ? null : getRadialDabMaster(hardness, color, isEraser && !isBgEraser, avgSegWidth, aaMode);
- const spacingRatio = Math.max(0.015, Math.min(1.0, spacing));
- const gapAdjustedFlow = computeGapAdjustedAlpha(flow, spacingRatio, mixingOptions?.adjustDensityByGap);
- let currentDist = remainderDist > 0 ? remainderDist : 0;
-
- const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
- const sizeJitter = Math.max(0, Math.min(1, dynamics?.sizeJitter ?? 0));
- const angleJitter = Math.max(0, Math.min(1, dynamics?.angleJitter ?? 0));
- const roundnessJitter = Math.max(0, Math.min(1, dynamics?.roundnessJitter ?? 0));
- const scatter = Math.max(0, Math.min(5, dynamics?.scatter ?? 0));
- const scatterBothAxes = Boolean(dynamics?.scatterBothAxes);
- const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
- const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
- const baseRgb = (colorJitterEnabled || gpuDabs) ? parseColorToRgb(isBgEraser ? '#ffffff' : color) : null;
- const secRgb = colorJitterEnabled ? parseColorToRgb(mixingOptions?.secondaryColor || '#ffffff') : null;
-
- let smoothCos = Math.cos(angleRad);
- let smoothSin = Math.sin(angleRad);
- let dabStepIdx = 0;
-
- while (currentDist <= totalCurveLength) {
- const pt = sampleFastArcLengthInto(p0, c1, c2, p3, currentDist, totalCurveLength, arcSteps, _sharedSample);
- let curWidth = Math.max(0.2, pt.width);
- dabStepIdx++;
-
- const tiltX = useTilt ? pt.tiltX : 0;
- const tiltY = useTilt ? pt.tiltY : 0;
- const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
- const tiltSpread = tiltMagnitude * (mixingOptions?.tiltScale ?? 1.0);
-
- if (mixingOptions?.sizeSensor) {
- curWidth *= evaluateCspSensor(
- mixingOptions.sizeSensor,
- pt.pressure,
- tiltMagnitude,
- pt.speed * 0.05,
- dabHashFloat(pt.x, pt.y, dabStepIdx, 50)
- );
- curWidth = Math.max(0.15, curWidth);
- }
-
- let dabRot = angleRad;
- const angleMode = mixingOptions?.angleDynamics;
- if ((angleMode === 'direction' || angleMode === 'direction-random') && pt.speed > 0.05) {
- const targetA = Math.atan2(pt.dy, pt.dx) + angleRad;
- smoothCos = smoothCos * 0.6 + Math.cos(targetA) * 0.4;
- smoothSin = smoothSin * 0.6 + Math.sin(targetA) * 0.4;
- dabRot = Math.atan2(smoothSin, smoothCos);
- }
- if (angleMode === 'random' || angleMode === 'direction-random') {
- const rScale = angleMode === 'random' ? 1.0 : (mixingOptions?.rotationRandomScale || 0.35);
- dabRot += (dabHashFloat(pt.x, pt.y, dabStepIdx, 12) - 0.5) * Math.PI * 2 * rScale;
- }
-
- if (useTilt && tiltMagnitude > 0.05) {
- dabRot = Math.atan2(tiltY, tiltX);
- }
- if (pt.twist && (useTilt || angleMode === 'twist')) {
- dabRot += (pt.twist * Math.PI) / 180;
- }
-
- let dabMaster = staticMaster;
- let dabFlow = gapAdjustedFlow;
- let dabRgb = baseRgb;
-
- if (mixingOptions?.opacitySensor) {
- dabFlow *= evaluateCspSensor(
- mixingOptions.opacitySensor,
- pt.pressure,
- tiltMagnitude,
- pt.speed * 0.05,
- dabHashFloat(pt.x, pt.y, dabStepIdx, 51)
- );
- }
- if (mixingOptions?.densitySensor) {
- dabFlow *= evaluateCspSensor(
- mixingOptions.densitySensor,
- pt.pressure,
- tiltMagnitude,
- pt.speed * 0.05,
- dabHashFloat(pt.x, pt.y, dabStepIdx, 52)
- );
- }
-
- // Preliminary step estimate for color mixing distance integration
- const prelimStep = Math.max(0.15, curWidth * spacingRatio);
-
- if (isColorMixing && reservoir) {
- let sampled = { r: 255, g: 255, b: 255, a: 0 };
- if (sampler) {
- sampled = sampler.sampleColor(pt.x, pt.y, curWidth * 0.45);
- } else {
- const sampleCanvas = mixingOptions?.underlyingCanvas || ctx.canvas;
- const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;
- if (sampleCtx) {
- sampled = sampleCanvasColor(sampleCtx, pt.x, pt.y, curWidth * 0.45);
- }
- }
-
- const mixed = reservoir.mixWithCanvas(
- sampled,
- mixingOptions?.amountOfPaint ?? 0.65,
- mixingOptions?.densityOfPaint ?? 0.9,
- mixingOptions?.colorStretch ?? 0.75,
- mixingOptions?.mixingMode ?? 'blend',
- pt.pressure ?? 1.0,
- dabFlow,
- prelimStep,
- mixingOptions?.perceptualMixing !== false
- );
-
- if (!gpuDabs) {
- dabMaster = getRadialDabMaster(hardness, mixed.colorHex, false, curWidth, aaMode);
- } else {
- dabRgb = { r: mixed.r, g: mixed.g, b: mixed.b };
- }
- dabFlow = mixed.alpha;
-
- if (sampler && mixed.alpha > 0.002) {
- sampler.depositDab(
- pt.x,
- pt.y,
- curWidth * 0.45,
- mixed.r,
- mixed.g,
- mixed.b,
- mixed.alpha
- );
- }
- }
-
- if (!gpuDabs && grainAmount > 0.005) {
- const scale = Math.max(0.1, mixingOptions?.paperTextureScale ?? 1.0);
- const gNorm = getPaperGrain(pt.x / scale, pt.y / scale) / 255.0;
- dabFlow = applyCspPaperTextureAlpha(
- dabFlow,
- gNorm,
- grainAmount,
- pt.pressure ?? 0.5,
- mixingOptions?.paperTextureMode ?? 'subtract',
- mixingOptions?.paperTextureBrightness ?? 0,
- mixingOptions?.paperTextureContrast ?? 0,
- Boolean(mixingOptions?.paperTextureInverted)
- );
- }
-
- let tx = 1;
- let ty = 0;
- let nx = 0;
- let ny = 1;
- if (pt.speed > 0.001) {
- tx = pt.dx / pt.speed;
- ty = pt.dy / pt.speed;
- nx = -ty;
- ny = tx;
- }
-
- let stepRefW = isVert ? curWidth * thickness : curWidth;
- let stepRefH = isVert ? curWidth : curWidth * thickness;
-
- for (let k = 0; k < dabCount; k++) {
- const seedIdx = dabStepIdx * 16 + k;
- let curDabW = curWidth;
- if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 1) * sizeJitter);
- }
- curDabW = Math.max(0.1, curDabW);
-
- let curDabThickness = thickness;
- if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 2) * roundnessJitter);
- }
-
- let curDabRot = dabRot;
- if (angleJitter > 0) {
- curDabRot += (dabHashFloat(pt.x, pt.y, seedIdx, 3) - 0.5) * Math.PI * 2 * angleJitter;
- }
-
- let curDabX = pt.x;
- let curDabY = pt.y;
- if (scatter > 0) {
- const perpDist = (dabHashFloat(pt.x, pt.y, seedIdx, 4) * 2 - 1) * curWidth * scatter;
- let sOffX = nx * perpDist;
- let sOffY = ny * perpDist;
- if (scatterBothAxes) {
- const tangDist = (dabHashFloat(pt.x, pt.y, seedIdx, 5) * 2 - 1) * curWidth * scatter;
- sOffX += tx * tangDist;
- sOffY += ty * tangDist;
- }
- curDabX += sOffX;
- curDabY += sOffY;
- }
-
- let curDabFlow = dabFlow;
- if (flowJitter > 0) {
- curDabFlow *= Math.max(0.005, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 6) * flowJitter);
- }
-
- let curMaster = dabMaster;
- let rNorm = dabRgb ? dabRgb.r / 255 : 0;
- let gNorm = dabRgb ? dabRgb.g / 255 : 0;
- let bNorm = dabRgb ? dabRgb.b / 255 : 0;
-
- if (colorJitterEnabled && dabRgb && secRgb && dynamics) {
- let salt = 20;
- const cd = applyColorDynamics(
- { r: dabRgb.r / 255, g: dabRgb.g / 255, b: dabRgb.b / 255 },
- { r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
- dynamics,
- () => dabHashFloat(pt.x, pt.y, seedIdx, salt++)
- );
- rNorm = cd.r;
- gNorm = cd.g;
- bNorm = cd.b;
- if (!gpuDabs) {
- curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser, curDabW, aaMode);
- }
- }
-
- let finalW = isVert ? curDabW * curDabThickness : curDabW;
- let finalH = isVert ? curDabW : curDabW * curDabThickness;
- if (useTilt && tiltMagnitude > 0.01) {
- finalW = curDabW * (1.0 + tiltSpread * 1.8);
- finalH = (curDabW * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
- }
- stepRefW = finalW;
- stepRefH = finalH;
-
- if (curDabFlow <= 0.002) continue;
-
- const flips = resolveTipFlipSigns(mixingOptions?.flipH, mixingOptions?.flipV, seedIdx, curDabX, curDabY);
-
- if (gpuDabs) {
- gpuDabs.push({
- x: curDabX,
- y: curDabY,
- width: finalW,
- height: finalH,
- angle: curDabRot,
- r: rNorm,
- g: gNorm,
- b: bNorm,
- alpha: curDabFlow,
- pressure: pt.pressure ?? 1.0,
- strokeDist: currentDist,
- flipX: flips.signX,
- flipY: flips.signY,
- });
- } else if (curMaster) {
- drawSingleStamp(
- ctx,
- curMaster,
- curDabX,
- curDabY,
- finalW,
- finalH,
- curDabRot,
- curDabFlow,
- isEraser,
- isBgEraser,
- mixingOptions?.alphaLocked,
- mixingOptions?.isTransparentInk,
- flips.signX,
- flips.signY,
- aaMode,
- mixingOptions?.blendTipsMode
- );
- }
- }
-
- // Sub-pixel hairline-safe & ellipse-aware directional step (zero 0.4px beading floor!)
- const requiredStep = computeEllipticalStepDistance(
- stepRefW,
- stepRefH,
- dabRot,
- pt.dx,
- pt.dy,
- spacingRatio,
- 0.12
- );
- currentDist += requiredStep;
- }
-
- return Math.max(0, currentDist - totalCurveLength);
-}
-
-/**
- * Renders an entire completed radial/elliptical dab stroke onto the target context.
- */
-export function renderCompleteRadialStroke(
- ctx: CanvasRenderingContext2D,
- points: Point[],
- color: string,
- hardness: number = 1.0,
- flow: number = 1.0,
- spacing: number = 0.08,
- isEraser: boolean = false,
- isBgEraser: boolean = false,
- thickness: number = 1.0,
- angleRad: number = 0,
- mixingOptions?: RadialMixingOptions
-) {
- if (!points || points.length === 0) return;
-
- if (mixingOptions?.colorMixing && !isEraser && !isBgEraser) {
- if (!mixingOptions.reservoir) {
- mixingOptions.reservoir = new PaintReservoir(color);
- }
- if (!mixingOptions.sampler && mixingOptions.underlyingCanvas) {
- mixingOptions.sampler = new LayerPixelSampler(mixingOptions.underlyingCanvas);
- }
- }
-
- const emitStroke = (batchGpuDabs: GpuDab[] | undefined) => {
- drawRadialDot(ctx, points[0], color, hardness, flow, isEraser, isBgEraser, mixingOptions, thickness, angleRad, batchGpuDabs);
- if (points.length === 1) return;
-
- const firstWidth = Math.max(0.2, points[0].width);
- let accDist = Math.max(0.12, firstWidth * spacing);
-
- if (points.length === 2) {
- const p0 = points[0];
- const p1 = points[1];
- const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
- drawRadialCubicBezierSegment(ctx, p0, c1, c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
- } else {
- const p0 = points[0];
- const p1 = points[1];
- const p2 = points[2];
- const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
- accDist = drawRadialCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
-
- for (let i = 2; i < points.length - 1; i++) {
- const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
- accDist = drawRadialCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
- }
-
- const n = points.length;
- const pPrev2 = points[n - 3];
- const pPrev = points[n - 2];
- const pLast = points[n - 1];
- const last = centripetalCatmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- drawRadialCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
- }
- };
-
- if (canUseWebGlForRadialBrush(mixingOptions)) {
- const batchGpuDabs: GpuDab[] = [];
- emitStroke(batchGpuDabs);
- if (flushRadialGpuDabs(ctx, batchGpuDabs, color, hardness, isEraser, isBgEraser, mixingOptions)) {
- return;
- }
- }
-
- // Clean Canvas 2D fallback
- emitStroke(undefined);
-}
diff --git a/src/utils/sutParser.ts b/src/utils/sutParser.ts
index 9a6cffa..1561471 100644
--- a/src/utils/sutParser.ts
+++ b/src/utils/sutParser.ts
@@ -1,4 +1,3 @@
-import initSqlJs from 'sql.js';
import { unzlibSync, inflateSync } from 'fflate';
import {
CspAngleDynamicsMode,
@@ -11,25 +10,12 @@ import {
CspTaperSettings,
CspTipFlipMode,
} from '../types/editor';
-import { evaluateFastSpline } from '../engine/CspBrushEngine';
+import { evaluateFastSpline } from '../engine/BrushEngine';
+import { isNativeRustAvailable, parseSutSqliteNative } from './nativeBackend';
const MAX_DECOMPRESSED_BLOB_BYTES = 64 * 1024 * 1024;
const MAX_COMPRESSED_BLOB_BYTES = 16 * 1024 * 1024;
-let sqlJsPromise: Promise<any> | null = null;
-
-async function getSql() {
- if (!sqlJsPromise) {
- sqlJsPromise = initSqlJs({
- locateFile: () => '/sql-wasm.wasm',
- }).catch((err) => {
- sqlJsPromise = null;
- throw err;
- });
- }
- return await sqlJsPromise;
-}
-
/**
* Searches for a byte sequence in a Uint8Array.
*/
@@ -628,132 +614,78 @@ export async function parseSutFile(
fileName: string = 'Brush.sut'
): Promise<CspBrush> {
const rawBytes = fileBuffer instanceof Uint8Array ? fileBuffer : new Uint8Array(fileBuffer);
- const sqliteData = extractSqliteFromBuffer(rawBytes);
-
- if (!sqliteData) {
- throw new Error('Invalid Clip Studio Paint file: No SQLite database header found in .sut');
+ if (!isNativeRustAvailable()) {
+ throw new Error('Parsing .sut files requires the native desktop Rust SQLite backend.');
}
- const SQL = await getSql();
- let db: any = null;
-
- try {
- db = new SQL.Database(sqliteData);
-
- const tablesQuery = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
- const tables: string[] = [];
- if (tablesQuery.length > 0 && tablesQuery[0].values) {
- for (const row of tablesQuery[0].values) {
- if (row[0]) tables.push(String(row[0]));
- }
- }
-
- let brushName = fileName.replace(/\.sut$/i, '').trim();
- let variantId: number | null = null;
-
- if (tables.includes('Node')) {
- try {
- const nodeRes = db.exec('SELECT NodeName, NodeVariantId FROM Node LIMIT 1');
- if (nodeRes.length > 0 && nodeRes[0].values && nodeRes[0].values.length > 0) {
- const row = nodeRes[0].values[0];
- if (row[0] && typeof row[0] === 'string' && row[0].trim().length > 0) {
- brushName = row[0].trim();
- }
- if (row[1] !== null && row[1] !== undefined && Number.isFinite(Number(row[1]))) {
- variantId = Math.trunc(Number(row[1]));
- }
- }
- } catch {
- // Fallback to filename
- }
- }
-
- let brushSize = 16;
- let minSizeFactor = 0.2;
- let opacity = 1.0;
- let flow = 0.85;
- let adjustDensityByGap = false;
- let blendTipsMode: CspBlendTipsMode = 'darken';
- let spacing = 0.08;
- let hardness = 1.0;
- let thickness = 1.0;
- let thicknessVertical = false;
- let flipH: CspTipFlipMode = 'none';
- let flipV: CspTipFlipMode = 'none';
- let angle = 0;
- let angleDynamics: CspAngleDynamicsMode = 'none';
- let rotationRandomScale = 0;
- let antiAlias = 2;
- let stabilization = 0;
- let postCorrection = 0;
- let sharpCorners = true;
- let usePressure = true;
- let useVelocity = false;
- let useTilt = false;
- let pressureCurve: [number, number][] | undefined = undefined;
- let velocityCurve: [number, number][] | undefined = undefined;
- let sizeSensor: CspSensorConfig | undefined = undefined;
- let opacitySensor: CspSensorConfig | undefined = undefined;
- let densitySensor: CspSensorConfig | undefined = undefined;
- let colorMixing = false;
- let amountOfPaint = 0.7;
- let densityOfPaint = 0.8;
- let colorStretch = 0.6;
- let mixingMode: 'blend' | 'running_color' | 'smear' = 'blend';
- let wetEdge = 0;
- let wetEdgeRadius = 3.0;
- let wetEdgeAlphaPower = 20;
- let wetEdgeValuePower = 0;
- let textureDensity = 0;
- let paperTextureScale = 1.0;
- let paperTextureRotate = 0;
- let paperTextureMode: CspPaperTextureMode = 'subtract';
- let paperTextureBrightness = 0;
- let paperTextureContrast = 0;
- let paperTextureInverted = false;
- let spray: CspSpraySettings | undefined = undefined;
- let taper: CspTaperSettings | undefined = undefined;
- let isRibbon = false;
- let dualBrush = false;
- let dualBrushCompositeMode = 'multiply';
- let rawPatternArrayBlob: Uint8Array | null = null;
- let rawTextureImageBlob: Uint8Array | null = null;
- let rawDualPatternBlob: Uint8Array | null = null;
-
- if (tables.includes('Variant')) {
- try {
- const pragmaCols = db.exec('PRAGMA table_info(Variant)');
- const colNames: string[] = [];
- if (pragmaCols.length > 0 && pragmaCols[0].values) {
- for (const row of pragmaCols[0].values) {
- colNames.push(String(row[1]));
- }
- }
-
- const colMap = new Map<string, string>();
- for (const c of colNames) {
- colMap.set(c.toLowerCase(), c);
- }
-
- const varRes =
- variantId !== null
- ? db.exec('SELECT * FROM Variant WHERE _PW_ID = ? LIMIT 1', [variantId])
- : db.exec('SELECT * FROM Variant LIMIT 1');
-
- if (varRes.length > 0 && varRes[0].values && varRes[0].values.length > 0) {
- const row = varRes[0].values[0];
- const getVal = (aliases: string[]): any => {
- for (const a of aliases) {
- const exact = colMap.get(a.toLowerCase());
- if (exact) {
- const idx = varRes[0].columns.indexOf(exact);
- if (idx !== -1 && row[idx] !== null && row[idx] !== undefined) {
- return row[idx];
- }
- }
+ const extracted = await parseSutSqliteNative(rawBytes);
+
+ let brushName = extracted.nodeName || fileName.replace(/\.sut$/i, '').trim();
+
+ let brushSize = 16;
+ let minSizeFactor = 0.2;
+ let opacity = 1.0;
+ let flow = 0.85;
+ let adjustDensityByGap = false;
+ let blendTipsMode: CspBlendTipsMode = 'darken';
+ let spacing = 0.08;
+ let hardness = 1.0;
+ let thickness = 1.0;
+ let thicknessVertical = false;
+ let flipH: CspTipFlipMode = 'none';
+ let flipV: CspTipFlipMode = 'none';
+ let angle = 0;
+ let angleDynamics: CspAngleDynamicsMode = 'none';
+ let rotationRandomScale = 0;
+ let antiAlias = 2;
+ let stabilization = 0;
+ let postCorrection = 0;
+ let sharpCorners = true;
+ let usePressure = true;
+ let useVelocity = false;
+ let useTilt = false;
+ let pressureCurve: [number, number][] | undefined = undefined;
+ let velocityCurve: [number, number][] | undefined = undefined;
+ let sizeSensor: CspSensorConfig | undefined = undefined;
+ let opacitySensor: CspSensorConfig | undefined = undefined;
+ let densitySensor: CspSensorConfig | undefined = undefined;
+ let colorMixing = false;
+ let amountOfPaint = 0.7;
+ let densityOfPaint = 0.8;
+ let colorStretch = 0.6;
+ let mixingMode: 'blend' | 'running_color' | 'smear' = 'blend';
+ let wetEdge = 0;
+ let wetEdgeRadius = 3.0;
+ let wetEdgeAlphaPower = 20;
+ let wetEdgeValuePower = 0;
+ let textureDensity = 0;
+ let paperTextureScale = 1.0;
+ let paperTextureRotate = 0;
+ let paperTextureMode: CspPaperTextureMode = 'subtract';
+ let paperTextureBrightness = 0;
+ let paperTextureContrast = 0;
+ let paperTextureInverted = false;
+ let spray: CspSpraySettings | undefined = undefined;
+ let taper: CspTaperSettings | undefined = undefined;
+ let isRibbon = false;
+ let dualBrush = false;
+ let dualBrushCompositeMode = 'multiply';
+ let rawPatternArrayBlob: Uint8Array | null = null;
+ let rawTextureImageBlob: Uint8Array | null = null;
+ let rawDualPatternBlob: Uint8Array | null = null;
+
+ if (extracted.variantValues.size > 0) {
+ try {
+ {
+ const getVal = (aliases: string[]): any => {
+ for (const a of aliases) {
+ const v = extracted.variantValues.get(a.toLowerCase());
+ if (v !== undefined && v !== null) {
+ return v;
}
- return null;
- };
+ }
+ return null;
+ };
// Size
const rawSize = getVal(['BrushSize', 'Size', 'PenSize', 'BrushSizeVal', 'LineWidth']);
@@ -1055,48 +987,39 @@ export async function parseSutFile(
}
}
- // 4. MaterialFile extraction
+ // 4. MaterialFile extraction (from native Rust rusqlite rows)
const materialMap = new Map<string, { mainPng: Uint8Array; width: number; height: number }>();
const allMaterialsList: { mainPng: Uint8Array; catalogPath: string; width: number; height: number }[] = [];
- if (tables.includes('MaterialFile')) {
- try {
- const matRes = db.exec('SELECT _PW_ID, OriginalPath, FileData, CatalogPath FROM MaterialFile');
- if (matRes.length > 0 && matRes[0].values) {
- for (const row of matRes[0].values) {
- const fileData = row[2];
- const catPath = row[3] ? String(row[3]) : '';
- const pwId = String(row[0]);
-
- if (fileData instanceof Uint8Array && fileData.length > 0) {
- const mainPng = extractMaterialPng(fileData);
- if (mainPng) {
- let width = 64;
- let height = 64;
- if (mainPng.length >= 24) {
- const view = new DataView(mainPng.buffer, mainPng.byteOffset, mainPng.byteLength);
- width = view.getUint32(16, false);
- height = view.getUint32(20, false);
- }
-
- const entry = { mainPng, width, height };
- if (catPath) materialMap.set(catPath, entry);
- materialMap.set(pwId, entry);
-
- const uuidMatch = catPath.match(
- /[a-f0-9]{10}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{10}/i
- );
- if (uuidMatch) {
- materialMap.set(uuidMatch[0], entry);
- }
-
- allMaterialsList.push({ mainPng, catalogPath: catPath, width, height });
- }
- }
+ for (const mat of extracted.materials) {
+ const fileData = mat.fileData;
+ const catPath = mat.catalogPath || '';
+ const pwId = mat.pwId;
+
+ if (fileData.length > 0) {
+ const mainPng = extractMaterialPng(fileData);
+ if (mainPng) {
+ let width = 64;
+ let height = 64;
+ if (mainPng.length >= 24) {
+ const view = new DataView(mainPng.buffer, mainPng.byteOffset, mainPng.byteLength);
+ width = view.getUint32(16, false);
+ height = view.getUint32(20, false);
}
+
+ const entry = { mainPng, width, height };
+ if (catPath) materialMap.set(catPath, entry);
+ materialMap.set(pwId, entry);
+
+ const uuidMatch = catPath.match(
+ /[a-f0-9]{10}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{10}/i
+ );
+ if (uuidMatch) {
+ materialMap.set(uuidMatch[0], entry);
+ }
+
+ allMaterialsList.push({ mainPng, catalogPath: catPath, width, height });
}
- } catch {
- // MaterialFile fallback
}
}
@@ -1261,13 +1184,4 @@ export async function parseSutFile(
};
return cspBrush;
- } finally {
- if (db) {
- try {
- db.close();
- } catch {
- // Ignore close error
- }
- }
- }
}
diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.ts
index b417f22..717184d 100644
--- a/src/utils/tileEngine.ts
+++ b/src/utils/tileEngine.ts
@@ -9,1274 +9,63 @@
* and an on-demand multi-resolution Mipmap Tile Pyramid (LOD 0 to LOD 3).
*/
-import { TileDelta } from '../types/editor';
-import { yieldToMain } from './asyncCompression';
-
-export const TILE_SIZE = 256;
-export const TILE_PIXELS = TILE_SIZE * TILE_SIZE; // 65,536 pixels
-export const BYTES_1BIT = TILE_PIXELS >> 3; // 8,192 bytes (8 KB)
-export const BYTES_8BIT = TILE_PIXELS; // 65,536 bytes (64 KB)
-export const BYTES_32BIT = TILE_PIXELS << 2; // 262,144 bytes (256 KB)
-
-export type TileFormat = 'monochrome-1bit' | 'grayscale-8bit' | 'color-32bit';
-
-export interface TileBuffer {
- layerId: string;
- tileX: number;
- tileY: number;
- format: TileFormat;
- data: Uint8Array | null; // null when paged out to disk
- dirty: boolean;
- version: number;
- isPagedToDisk: boolean;
- lastAccessTimestamp: number;
- lod: number; // 0 = 1:1 (256x256 doc area), 1 = 1/2 (512x512), 2 = 1/4 (1024x1024), 3 = 1/8 (2048x2048)
- solidColorU32?: number; // When defined on a color-32bit tile, all 65,536 pixels share this exact U32 RGBA value
-}
-
-export function getTileByteSize(format: TileFormat): number {
- if (format === 'monochrome-1bit') return BYTES_1BIT;
- if (format === 'grayscale-8bit') return BYTES_8BIT;
- return BYTES_32BIT;
-}
-
-// System endianness detection for 32-bit operations
-export const isLittleEndian = (() => {
- if (typeof ArrayBuffer === 'undefined') return true;
- const buf = new ArrayBuffer(4);
- new Uint32Array(buf)[0] = 0x11223344;
- return new Uint8Array(buf)[0] === 0x44;
-})();
-
-// Default binary colors in system byte order
-// Black ink: RGBA(0, 0, 0, 255)
-export const INK_BLACK_U32 = isLittleEndian ? 0xff000000 : 0x000000ff;
-// Transparent: RGBA(0, 0, 0, 0)
-export const TRANSPARENT_U32 = 0x00000000;
-// Paper white: RGBA(255, 255, 255, 255)
-export const PAPER_WHITE_U32 = 0xffffffff;
-
-/**
- * 256-entry lookup table mapping a 1-bit byte (8 pixels)
- * into eight 32-bit pixel values for ultra-fast zero-loop unpacking.
- */
-const LUT_1BIT_TO_RGBA_BLACK = new Uint32Array(256 * 8);
-const LUT_1BIT_TO_RGBA_WHITE = new Uint32Array(256 * 8);
-
-for (let b = 0; b < 256; b++) {
- const offset = b * 8;
- for (let bit = 0; bit < 8; bit++) {
- // MSB first: bit 7 is the leftmost pixel
- const isSet = (b & (1 << (7 - bit))) !== 0;
- LUT_1BIT_TO_RGBA_BLACK[offset + bit] = isSet ? INK_BLACK_U32 : TRANSPARENT_U32;
- LUT_1BIT_TO_RGBA_WHITE[offset + bit] = isSet ? PAPER_WHITE_U32 : TRANSPARENT_U32;
- }
-}
-
-/**
- * Get tile coordinate from document pixel coordinate.
- */
-export function pixelToTileCoord(pixel: number, lod: number = 0): number {
- const tileSizeDoc = TILE_SIZE << lod;
- return Math.floor(pixel / tileSizeDoc);
-}
-
-/**
- * Spatial hash map key for tiles.
- * LOD 0 produces backwards-compatible key: `${layerId}:${tileX}:${tileY}`.
- * LOD > 0 produces: `${layerId}:${lod}:${tileX}:${tileY}`.
- */
-export function getTileKey(layerId: string, tileX: number, tileY: number, lod: number = 0): string {
- return lod === 0 ? `${layerId}:${tileX}:${tileY}` : `${layerId}:${lod}:${tileX}:${tileY}`;
-}
-
-/**
- * Parse spatial hash map key into components.
- */
-export function parseTileKey(key: string): { layerId: string; tileX: number; tileY: number; lod: number } {
- const parts = key.split(':');
- if (parts.length === 4) {
- return {
- layerId: parts[0],
- lod: parseInt(parts[1], 10),
- tileX: parseInt(parts[2], 10),
- tileY: parseInt(parts[3], 10),
- };
- }
- return {
- layerId: parts[0],
- tileX: parseInt(parts[1], 10),
- tileY: parseInt(parts[2], 10),
- lod: 0,
- };
-}
-
-let nextGlobalTileVersion = 1;
-
-export function allocateTileVersion(): number {
- return ++nextGlobalTileVersion;
-}
-
-export function reserveTileVersion(version: number): void {
- if (Number.isFinite(version) && version > nextGlobalTileVersion) {
- nextGlobalTileVersion = Math.floor(version);
- }
-}
-
-/**
- * Allocate a new TileBuffer with zero-initialized memory.
- */
-export function createTileBuffer(
- layerId: string,
- tileX: number,
- tileY: number,
- format: TileFormat,
- lod: number = 0
-): TileBuffer {
- const size = getTileByteSize(format);
-
- return {
- layerId,
- tileX,
- tileY,
- format,
- data: new Uint8Array(size),
- dirty: true,
- version: allocateTileVersion(),
- isPagedToDisk: false,
- lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
- lod,
- };
-}
-
-/**
- * Set a single 1-bit pixel (MSB first packing).
- */
-export function setPixel1Bit(data: Uint8Array, x: number, y: number, value: boolean | number): void {
- const pixelIndex = y * TILE_SIZE + x;
- const byteIndex = pixelIndex >> 3;
- const bitOffset = 7 - (pixelIndex & 7);
- if (value) {
- data[byteIndex] |= 1 << bitOffset;
- } else {
- data[byteIndex] &= ~(1 << bitOffset);
- }
-}
-
-/**
- * Get a single 1-bit pixel (MSB first packing). Returns 0 or 1.
- */
-export function getPixel1Bit(data: Uint8Array, x: number, y: number): number {
- const pixelIndex = y * TILE_SIZE + x;
- const byteIndex = pixelIndex >> 3;
- const bitOffset = 7 - (pixelIndex & 7);
- return (data[byteIndex] >> bitOffset) & 1;
-}
-
-/**
- * Unpacks an 8,192-byte 1-bit tile into a 262,144-byte RGBA buffer
- * using the precomputed 32-bit LUT.
- */
-export function unpack1BitToRGBA(
- src1Bit: Uint8Array,
- dstRGBA: Uint8ClampedArray | Uint8Array,
- inkColorU32: number = INK_BLACK_U32,
- paperColorU32: number = TRANSPARENT_U32
-): void {
- const dst32 = new Uint32Array(dstRGBA.buffer, dstRGBA.byteOffset, TILE_PIXELS);
-
- if (inkColorU32 === INK_BLACK_U32 && paperColorU32 === TRANSPARENT_U32) {
- // Fast path: direct copy from black ink LUT
- let dstOffset = 0;
- for (let i = 0; i < BYTES_1BIT; i++) {
- const lutOffset = src1Bit[i] * 8;
- dst32[dstOffset] = LUT_1BIT_TO_RGBA_BLACK[lutOffset];
- dst32[dstOffset + 1] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 1];
- dst32[dstOffset + 2] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 2];
- dst32[dstOffset + 3] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 3];
- dst32[dstOffset + 4] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 4];
- dst32[dstOffset + 5] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 5];
- dst32[dstOffset + 6] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 6];
- dst32[dstOffset + 7] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 7];
- dstOffset += 8;
- }
- } else {
- // General path with custom colors
- let dstOffset = 0;
- for (let i = 0; i < BYTES_1BIT; i++) {
- const b = src1Bit[i];
- dst32[dstOffset] = (b & 0x80) ? inkColorU32 : paperColorU32;
- dst32[dstOffset + 1] = (b & 0x40) ? inkColorU32 : paperColorU32;
- dst32[dstOffset + 2] = (b & 0x20) ? inkColorU32 : paperColorU32;
- dst32[dstOffset + 3] = (b & 0x10) ? inkColorU32 : paperColorU32;
- dst32[dstOffset + 4] = (b & 0x08) ? inkColorU32 : paperColorU32;
- dst32[dstOffset + 5] = (b & 0x04) ? inkColorU32 : paperColorU32;
- dst32[dstOffset + 6] = (b & 0x02) ? inkColorU32 : paperColorU32;
- dst32[dstOffset + 7] = (b & 0x01) ? inkColorU32 : paperColorU32;
- dstOffset += 8;
- }
- }
-}
-
-/**
- * Packs a 256x256 RGBA buffer (262,144 bytes) into an 8,192-byte 1-bit tile.
- * Applies perceptual ITU-R BT.601 luminance thresholding and alpha checking.
- */
-export function packRGBATo1Bit(
- srcRGBA: Uint8ClampedArray | Uint8Array,
- dst1Bit: Uint8Array,
- threshold: number = 128
-): void {
- const thresh1000 = threshold * 1000;
- const src32 =
- srcRGBA.byteOffset % 4 === 0
- ? new Uint32Array(srcRGBA.buffer, srcRGBA.byteOffset, TILE_PIXELS)
- : null;
- let srcOffset = 0;
-
- for (let i = 0; i < BYTES_1BIT; i++) {
- if (src32 !== null) {
- const p = i << 3;
- if (
- (src32[p] |
- src32[p + 1] |
- src32[p + 2] |
- src32[p + 3] |
- src32[p + 4] |
- src32[p + 5] |
- src32[p + 6] |
- src32[p + 7]) === 0
- ) {
- dst1Bit[i] = 0;
- srcOffset += 32;
- continue;
- }
- }
- let byteVal = 0;
- for (let bit = 7; bit >= 0; bit--) {
- const a = srcRGBA[srcOffset + 3];
- if (a >= 24) {
- // Luminance: 0.299*R + 0.587*G + 0.114*B (integer scaled x1000)
- const lum1000 =
- srcRGBA[srcOffset] * 299 +
- srcRGBA[srcOffset + 1] * 587 +
- srcRGBA[srcOffset + 2] * 114;
- // Dark pixels become ink (1), light pixels transparent (0)
- if (lum1000 < thresh1000) {
- byteVal |= 1 << bit;
- }
- }
- srcOffset += 4;
- }
- dst1Bit[i] = byteVal;
- }
-}
-
-/**
- * Unpacks an 8-bit grayscale tile into RGBA.
- */
-export function unpack8BitToRGBA(
- src8Bit: Uint8Array,
- dstRGBA: Uint8ClampedArray | Uint8Array
-): void {
- const dst32 = new Uint32Array(dstRGBA.buffer, dstRGBA.byteOffset, TILE_PIXELS);
- for (let i = 0; i < TILE_PIXELS; i++) {
- const val = src8Bit[i];
- if (val === 0) {
- dst32[i] = TRANSPARENT_U32;
- } else {
- const a = 255;
- dst32[i] = isLittleEndian
- ? (a << 24) | (val << 16) | (val << 8) | val
- : (val << 24) | (val << 16) | (val << 8) | a;
- }
- }
-}
-
-/**
- * Packs RGBA to 8-bit grayscale using perceptual ITU-R BT.601 luminance.
- */
-export function packRGBATo8Bit(
- srcRGBA: Uint8ClampedArray | Uint8Array,
- dst8Bit: Uint8Array
-): void {
- let srcOffset = 0;
- for (let i = 0; i < TILE_PIXELS; i++) {
- const a = srcRGBA[srcOffset + 3];
- if (a < 10) {
- dst8Bit[i] = 0;
- } else {
- const r = srcRGBA[srcOffset];
- const g = srcRGBA[srcOffset + 1];
- const b = srcRGBA[srcOffset + 2];
- dst8Bit[i] = Math.round((r * 299 + g * 587 + b * 114) / 1000);
- }
- srcOffset += 4;
- }
-}
-
-/**
- * High-speed Run-Length Encoding (RLE) for compressing tile data.
- */
-export function compressRLE(data: Uint8Array): Uint8Array {
- const len = data.length;
- if (len === 0) return new Uint8Array(0);
-
- const output = new Uint8Array(len * 2);
- let outIdx = 0;
- let i = 0;
-
- while (i < len) {
- const val = data[i];
- let run = 1;
- while (i + run < len && data[i + run] === val && run < 255) {
- run++;
- }
- output[outIdx++] = run;
- output[outIdx++] = val;
- i += run;
- }
-
- return output.subarray(0, outIdx);
-}
-
-/**
- * Decompresses RLE-encoded byte buffer back to target length.
- */
-export function decompressRLE(compressed: Uint8Array, expectedLength: number): Uint8Array {
- const output = new Uint8Array(expectedLength);
- let inIdx = 0;
- let outIdx = 0;
- const inLen = compressed.length;
-
- while (inIdx + 1 < inLen && outIdx < expectedLength) {
- const count = compressed[inIdx++];
- const val = compressed[inIdx++];
- for (let c = 0; c < count && outIdx < expectedLength; c++) {
- output[outIdx++] = val;
- }
- }
-
- return output;
-}
-
-export function serializeTileBuffer(tile: TileBuffer): Uint8Array {
- const tileBytes = tile.data || new Uint8Array(getTileByteSize(tile.format));
- const rle = compressRLE(tileBytes);
- const headerSize = 13;
- const packet = new Uint8Array(headerSize + rle.length);
- const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
-
- view.setInt32(0, tile.tileX, true);
- view.setInt32(4, tile.tileY, true);
- const formatCode = tile.format === 'monochrome-1bit' ? 1 : tile.format === 'grayscale-8bit' ? 2 : 4;
- view.setUint8(8, formatCode);
- view.setUint32(9, tile.version, true);
-
- packet.set(rle, headerSize);
- return packet;
-}
-
-export function deserializeTileBuffer(layerId: string, packet: Uint8Array): TileBuffer {
- if (!packet || packet.byteLength < 13) {
- return createTileBuffer(layerId, 0, 0, 'color-32bit', 0);
- }
- const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
- const tileX = view.getInt32(0, true);
- const tileY = view.getInt32(4, true);
- const formatCode = view.getUint8(8);
- const version = view.getUint32(9, true);
-
- const format: TileFormat = formatCode === 1 ? 'monochrome-1bit' : formatCode === 2 ? 'grayscale-8bit' : 'color-32bit';
- const expectedLen = getTileByteSize(format);
-
- const rlePayload = packet.subarray(13);
- const data = decompressRLE(rlePayload, expectedLen);
-
- return {
- layerId,
- tileX,
- tileY,
- format,
- data,
- dirty: true,
- version,
- isPagedToDisk: false,
- lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
- lod: 0,
- };
-}
-
-// ============================================================================
-// Multi-Resolution Mipmap Downsampling (2x2 Child Tiles -> 1 Parent LOD Tile)
-// ============================================================================
-
-const _downsampleRgbaScratch = new Uint8ClampedArray(BYTES_32BIT);
-const _downsampleRgbaView = new Uint8Array(_downsampleRgbaScratch.buffer);
-const _downsample8BitScratch = new Uint8Array(BYTES_8BIT);
-const _downsample1BitScratch = new Uint8Array(BYTES_1BIT);
-
-// Precomputed 256-entry LUT mapping an 8-bit 1-bit-row byte to a 4-bit downsampled nibble (2x1 horizontal OR)
-const _lut1BitByteToNibble = (() => {
- const lut = new Uint8Array(256);
- for (let b = 0; b < 256; b++) {
- let nib = 0;
- if (b & 0xc0) nib |= 0x08;
- if (b & 0x30) nib |= 0x04;
- if (b & 0x0c) nib |= 0x02;
- if (b & 0x03) nib |= 0x01;
- lut[b] = nib;
- }
- return lut;
-})();
-
-// Fast 2-bit popcount and coverage RGBA LUT for box-filtering monochrome-1bit -> color-32bit LOD tiles
-const _pop2 = new Uint8Array([0, 1, 1, 2]);
-const _monoCovU32 = new Uint32Array(
- isLittleEndian
- ? [0x00000000, 0x40000000, 0x80000000, 0xbf000000, 0xff000000]
- : [0x00000000, 0x00000040, 0x00000080, 0x000000bf, 0x000000ff]
-);
-
-/**
- * Downsample 4 child tiles (2x2 cluster) at LOD k-1 into a single destination tile at LOD k.
- * Reuses pre-allocated scratch buffers for zero 256KB heap allocations during zoom-out LOD builds.
- */
-export function downsample2x2ToParentTile(
- childTiles: [TileBuffer | null, TileBuffer | null, TileBuffer | null, TileBuffer | null],
- dstTile: TileBuffer
-): boolean {
- const c0 = childTiles[0];
- const c1 = childTiles[1];
- const c2 = childTiles[2];
- const c3 = childTiles[3];
- if (
- (!c0 || c0.data === null) &&
- (!c1 || c1.data === null) &&
- (!c2 || c2.data === null) &&
- (!c3 || c3.data === null)
- ) {
- dstTile.solidColorU32 = undefined;
- return false;
- }
-
- if (!dstTile.data) {
- dstTile.data = new Uint8Array(getTileByteSize(dstTile.format));
- }
-
- const format = dstTile.format;
- const dst = dstTile.data;
- dstTile.solidColorU32 = undefined;
-
- // Fast path #1: All 4 child tiles are identical solid color-32bit tiles (e.g. solid white paper)
- if (
- format === 'color-32bit' &&
- c0 && c1 && c2 && c3 &&
- c0.solidColorU32 !== undefined &&
- c0.solidColorU32 === c1.solidColorU32 &&
- c0.solidColorU32 === c2.solidColorU32 &&
- c0.solidColorU32 === c3.solidColorU32
- ) {
- const dst32 = new Uint32Array(dst.buffer, dst.byteOffset, TILE_PIXELS);
- dst32.fill(c0.solidColorU32);
- dstTile.solidColorU32 = c0.solidColorU32;
- dstTile.dirty = false;
- dstTile.version++;
- return true;
- }
-
- dst.fill(0);
- const dst32 = format === 'color-32bit'
- ? new Uint32Array(dst.buffer, dst.byteOffset, TILE_PIXELS)
- : null;
-
- for (let q = 0; q < 4; q++) {
- const child = childTiles[q];
- if (!child || !child.data) continue;
-
- let childData = child.data;
- const xBase = (q & 1) ? 128 : 0;
- const yBase = (q >= 2) ? 128 : 0;
-
- if (format === 'color-32bit') {
- // Fast path #2: Uniform solid quadrant
- if (child.solidColorU32 !== undefined && dst32) {
- const fillU32 = child.solidColorU32;
- for (let ly = 0; ly < 128; ly++) {
- const rowStart = (yBase + ly) * TILE_SIZE + xBase;
- dst32.fill(fillU32, rowStart, rowStart + 128);
- }
- continue;
- }
-
- if (child.format === 'monochrome-1bit' && dst32) {
- // Fast zero-unpack 2x2 bit-counting box filter: 1-bit ink -> anti-aliased black coverage RGBA
- for (let ly = 0; ly < 128; ly++) {
- const sy0 = ly << 1;
- const srcRow0 = sy0 << 5;
- const srcRow1 = (sy0 + 1) << 5;
- const dstRowBase = (yBase + ly) * TILE_SIZE + xBase;
- for (let bx = 0; bx < 32; bx++) {
- const b0 = childData[srcRow0 + bx];
- const b1 = childData[srcRow1 + bx];
- if ((b0 | b1) === 0) continue;
- const outOff = dstRowBase + (bx << 2);
- dst32[outOff] = _monoCovU32[_pop2[(b0 >> 6) & 3] + _pop2[(b1 >> 6) & 3]];
- dst32[outOff + 1] = _monoCovU32[_pop2[(b0 >> 4) & 3] + _pop2[(b1 >> 4) & 3]];
- dst32[outOff + 2] = _monoCovU32[_pop2[(b0 >> 2) & 3] + _pop2[(b1 >> 2) & 3]];
- dst32[outOff + 3] = _monoCovU32[_pop2[b0 & 3] + _pop2[b1 & 3]];
- }
- }
- continue;
- } else if (child.format === 'monochrome-1bit') {
- unpack1BitToRGBA(childData, _downsampleRgbaScratch);
- childData = _downsampleRgbaView;
- } else if (child.format === 'grayscale-8bit') {
- unpack8BitToRGBA(childData, _downsampleRgbaScratch);
- childData = _downsampleRgbaView;
- }
- for (let ly = 0; ly < 128; ly++) {
- const sy0 = ly << 1;
- const dy = yBase + ly;
- const dstRowOffset = dy * TILE_SIZE + xBase;
- const srcRowOffset0 = sy0 * TILE_SIZE;
- const srcRowOffset1 = (sy0 + 1) * TILE_SIZE;
-
- for (let lx = 0; lx < 128; lx++) {
- const sx0 = lx << 1;
- const p00 = (srcRowOffset0 + sx0) << 2;
- const p10 = p00 + 4;
- const p01 = (srcRowOffset1 + sx0) << 2;
- const p11 = p01 + 4;
-
- const a0 = childData[p00 + 3];
- const a1 = childData[p10 + 3];
- const a2 = childData[p01 + 3];
- const a3 = childData[p11 + 3];
- const sumA = a0 + a1 + a2 + a3;
-
- if (sumA === 0) {
- continue; // dst is already zero-initialized
- }
- const outIdx = (dstRowOffset + lx) << 2;
- if (sumA === 1020) {
- dst[outIdx] = (childData[p00] + childData[p10] + childData[p01] + childData[p11] + 2) >> 2;
- dst[outIdx + 1] = (childData[p00 + 1] + childData[p10 + 1] + childData[p01 + 1] + childData[p11 + 1] + 2) >> 2;
- dst[outIdx + 2] = (childData[p00 + 2] + childData[p10 + 2] + childData[p01 + 2] + childData[p11 + 2] + 2) >> 2;
- dst[outIdx + 3] = 255;
- } else {
- const halfA = sumA >> 1;
- dst[outIdx + 3] = sumA >> 2;
- dst[outIdx] = ((childData[p00] * a0 + childData[p10] * a1 + childData[p01] * a2 + childData[p11] * a3 + halfA) / sumA) | 0;
- dst[outIdx + 1] = ((childData[p00 + 1] * a0 + childData[p10 + 1] * a1 + childData[p01 + 1] * a2 + childData[p11 + 1] * a3 + halfA) / sumA) | 0;
- dst[outIdx + 2] = ((childData[p00 + 2] * a0 + childData[p10 + 2] * a1 + childData[p01 + 2] * a2 + childData[p11 + 2] * a3 + halfA) / sumA) | 0;
- }
- }
- }
- } else if (format === 'grayscale-8bit') {
- if (child.format === 'color-32bit') {
- packRGBATo8Bit(childData, _downsample8BitScratch);
- childData = _downsample8BitScratch;
- } else if (child.format === 'monochrome-1bit') {
- unpack1BitToRGBA(childData, _downsampleRgbaScratch);
- packRGBATo8Bit(_downsampleRgbaScratch, _downsample8BitScratch);
- childData = _downsample8BitScratch;
- }
- for (let ly = 0; ly < 128; ly++) {
- const sy0 = ly << 1;
- const sy1 = sy0 + 1;
- const dy = yBase + ly;
- const dstRowOffset = dy * TILE_SIZE;
- const srcRowOffset0 = sy0 * TILE_SIZE;
- const srcRowOffset1 = sy1 * TILE_SIZE;
-
- for (let lx = 0; lx < 128; lx++) {
- const sx0 = lx << 1;
- const sx1 = sx0 + 1;
- const dx = xBase + lx;
-
- const v00 = childData[srcRowOffset0 + sx0];
- const v10 = childData[srcRowOffset0 + sx1];
- const v01 = childData[srcRowOffset1 + sx0];
- const v11 = childData[srcRowOffset1 + sx1];
-
- dst[dstRowOffset + dx] = (v00 + v10 + v01 + v11) >> 2;
- }
- }
- } else {
- if (child.format === 'color-32bit') {
- packRGBATo1Bit(childData, _downsample1BitScratch);
- childData = _downsample1BitScratch;
- } else if (child.format === 'grayscale-8bit') {
- unpack8BitToRGBA(childData, _downsampleRgbaScratch);
- packRGBATo1Bit(_downsampleRgbaScratch, _downsample1BitScratch);
- childData = _downsample1BitScratch;
- }
- const dstByteBaseX = xBase >> 3;
- for (let ly = 0; ly < 128; ly++) {
- const sy0 = ly << 1;
- const srcRow0 = sy0 << 5;
- const srcRow1 = (sy0 + 1) << 5;
- const dstRow = ((yBase + ly) << 5) + dstByteBaseX;
-
- for (let bx = 0; bx < 16; bx++) {
- const sBx = bx << 1;
- const comb0 = childData[srcRow0 + sBx] | childData[srcRow1 + sBx];
- const comb1 = childData[srcRow0 + sBx + 1] | childData[srcRow1 + sBx + 1];
- dst[dstRow + bx] = (_lut1BitByteToNibble[comb0] << 4) | _lut1BitByteToNibble[comb1];
- }
- }
- }
- }
-
- dstTile.dirty = false;
- dstTile.version++;
- return true;
-}
-
-// ============================================================================
-// Scratch Disk Driver Interface & Implementations
-// ============================================================================
-
-export interface TileWritePayload {
- layerId: string;
- tileX: number;
- tileY: number;
- data: Uint8Array;
-}
-
-export interface IScratchDiskDriver {
- init(sessionId: string): Promise<void>;
- writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number>;
- readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array>;
- clear(sessionId: string): Promise<void>;
-}
-
-export function isTauriEnvironment(): boolean {
- if (typeof window === 'undefined') return false;
- return Boolean(
- (window as any).__TAURI_INTERNALS__ ||
- (window as any).__TAURI__ ||
- (window as any).isTauri
- );
-}
-
-const _tileBatchEncoder = new TextEncoder();
-const _tileBatchDecoder = new TextDecoder();
-const MIN_TILE_BATCH_RECORD_BYTES = 14; // layerIdLen(u16) + tx(i32) + ty(i32) + dataLen(u32)
-
-/**
- * Packs a batch of tiles into a compact little-endian binary frame for raw Tauri IPC:
- * `[count:u32][layerIdLen:u16, layerId(utf8), tx:i32, ty:i32, dataLen:u32, data]...`
- */
-export function packTileWriteBatch(tiles: TileWritePayload[]): Uint8Array {
- const encodedIds: Uint8Array[] = new Array(tiles.length);
- let totalBytes = 4;
-
- for (let i = 0; i < tiles.length; i++) {
- const idBytes = _tileBatchEncoder.encode(tiles[i].layerId);
- if (idBytes.byteLength > 0xffff) {
- throw new Error(`Layer ID exceeds u16 byte length limit: ${tiles[i].layerId}`);
- }
- encodedIds[i] = idBytes;
- totalBytes += MIN_TILE_BATCH_RECORD_BYTES + idBytes.byteLength + tiles[i].data.byteLength;
- }
-
- const out = new Uint8Array(totalBytes);
- const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
- view.setUint32(0, tiles.length, true);
-
- let offset = 4;
- for (let i = 0; i < tiles.length; i++) {
- const t = tiles[i];
- const idBytes = encodedIds[i];
-
- view.setUint16(offset, idBytes.byteLength, true);
- offset += 2;
-
- out.set(idBytes, offset);
- offset += idBytes.byteLength;
-
- view.setInt32(offset, t.tileX, true);
- offset += 4;
-
- view.setInt32(offset, t.tileY, true);
- offset += 4;
-
- view.setUint32(offset, t.data.byteLength, true);
- offset += 4;
-
- out.set(t.data, offset);
- offset += t.data.byteLength;
- }
-
- return out;
-}
-
-/**
- * Unpacks a compact binary tile batch frame back into TileWritePayload entries.
- */
-export function unpackTileWriteBatch(buffer: Uint8Array | ArrayBuffer): TileWritePayload[] {
- const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
- if (bytes.byteLength < 4) {
- throw new Error('Truncated tile batch header');
- }
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- const count = view.getUint32(0, true);
- if (count > Math.floor((bytes.byteLength - 4) / MIN_TILE_BATCH_RECORD_BYTES)) {
- throw new Error('Truncated tile batch payload');
- }
-
- const tiles: TileWritePayload[] = new Array(count);
- let offset = 4;
-
- for (let i = 0; i < count; i++) {
- if (offset + 2 > bytes.byteLength) {
- throw new Error('Truncated tile record layerIdLen');
- }
- const idLen = view.getUint16(offset, true);
- offset += 2;
-
- if (offset + idLen + 12 > bytes.byteLength) {
- throw new Error('Truncated tile record metadata');
- }
- const layerId = _tileBatchDecoder.decode(bytes.subarray(offset, offset + idLen));
- offset += idLen;
-
- const tileX = view.getInt32(offset, true);
- offset += 4;
- const tileY = view.getInt32(offset, true);
- offset += 4;
- const dataLen = view.getUint32(offset, true);
- offset += 4;
-
- if (offset + dataLen > bytes.byteLength) {
- throw new Error('Truncated tile record data');
- }
- const data = bytes.slice(offset, offset + dataLen);
- offset += dataLen;
-
- tiles[i] = { layerId, tileX, tileY, data };
- }
-
- if (offset !== bytes.byteLength) {
- throw new Error('Unexpected trailing bytes in tile batch payload');
- }
-
- return tiles;
-}
-
-/**
- * Production Tauri v2 Rust Scratch Disk Driver.
- * Direct raw binary IPC with high-throughput LZ4 compression and atomic file index tables.
- */
-export class TauriScratchDiskDriver implements IScratchDiskDriver {
- private invokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;
-
- private getInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {
- if (!this.invokePromise) {
- this.invokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);
- }
- return this.invokePromise;
- }
-
- public async init(sessionId: string): Promise<void> {
- const invoke = await this.getInvoke();
- await invoke('scratch_disk_init', { sessionId });
- }
-
- public async writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number> {
- if (tiles.length === 0) return 0;
- const invoke = await this.getInvoke();
- const packed = packTileWriteBatch(tiles);
- return invoke<number>('scratch_disk_write_tiles', packed, {
- headers: {
- 'x-session-id': encodeURIComponent(sessionId),
- },
- });
- }
-
- public async readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array> {
- const invoke = await this.getInvoke();
- const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('scratch_disk_read_tile', undefined, {
- headers: {
- 'x-session-id': encodeURIComponent(sessionId),
- 'x-layer-id': encodeURIComponent(layerId),
- 'x-tile-x': String(tileX),
- 'x-tile-y': String(tileY),
- },
- });
- if (raw instanceof Uint8Array) return raw;
- if (raw instanceof ArrayBuffer) return new Uint8Array(raw);
- return new Uint8Array(raw);
- }
-
- public async clear(sessionId: string): Promise<void> {
- const invoke = await this.getInvoke();
- await invoke('scratch_disk_clear', { sessionId });
- }
-}
-
-/**
- * High-speed In-Memory / Fallback Scratch Disk Driver.
- * Used during automated Vitest suites and pure browser previews without Tauri.
- */
-export class InMemoryScratchDiskDriver implements IScratchDiskDriver {
- private storage: Map<string, Uint8Array> = new Map();
-
- public async init(sessionId: string): Promise<void> {
- await this.clear(sessionId);
- }
-
- public async writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number> {
- for (const t of tiles) {
- const copy = new Uint8Array(t.data.byteLength);
- copy.set(t.data);
- this.storage.set(`${sessionId}:${t.layerId}:${t.tileX}:${t.tileY}`, copy);
- }
- return tiles.length;
- }
-
- public async readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array> {
- const key = `${sessionId}:${layerId}:${tileX}:${tileY}`;
- const found = this.storage.get(key);
- if (!found) {
- throw new Error(`Tile not found on in-memory scratch disk: ${key}`);
- }
- const copy = new Uint8Array(found.byteLength);
- copy.set(found);
- return copy;
- }
-
- public async clear(sessionId: string): Promise<void> {
- const prefix = `${sessionId}:`;
- for (const key of Array.from(this.storage.keys())) {
- if (key.startsWith(prefix)) {
- this.storage.delete(key);
- }
- }
- }
-}
-
-export function createDefaultScratchDiskDriver(): IScratchDiskDriver {
- return isTauriEnvironment() ? new TauriScratchDiskDriver() : new InMemoryScratchDiskDriver();
-}
-
-// ============================================================================
-// TileMemoryManager (LRU Eviction & Transparent Page-In)
-// ============================================================================
-
-export interface TileMemoryManagerOptions {
- budgetMb?: number;
- driver?: IScratchDiskDriver;
- sessionId?: string;
- onMemoryChanged?: () => void;
-}
-
-export class TileMemoryManager {
- private sessionId: string;
- private budgetBytes: number;
- private activeBytes: number = 0;
- private grid: SparseTileGrid;
- private driver: IScratchDiskDriver;
- private viewportFrustum: { minX: number; minY: number; maxX: number; maxY: number } | null = null;
- private activeLayerId: string | null = null;
- private layerVisibility: Map<string, boolean> = new Map();
- private inFlightPageIns: Map<string, Promise<Uint8Array>> = new Map();
- private evictionPromise: Promise<void> | null = null;
- private needsAnotherEvictionPass: boolean = false;
- private onMemoryChanged?: () => void;
-
- constructor(grid: SparseTileGrid, options?: TileMemoryManagerOptions) {
- this.grid = grid;
- const mb = options?.budgetMb ?? 1024;
- this.budgetBytes = Math.max(1, mb) * 1024 * 1024;
- this.sessionId = options?.sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
- this.driver = options?.driver || createDefaultScratchDiskDriver();
- this.onMemoryChanged = options?.onMemoryChanged;
- void this.driver.init(this.sessionId);
- }
-
- public getSessionId(): string {
- return this.sessionId;
- }
-
- public getDriver(): IScratchDiskDriver {
- return this.driver;
- }
-
- public setDriver(driver: IScratchDiskDriver): void {
- this.driver = driver;
- void this.driver.init(this.sessionId);
- }
-
- public setBudgetMb(mb: number): void {
- this.budgetBytes = Math.max(1, mb) * 1024 * 1024;
- void this.checkBudgetAndEvict();
- }
-
- public getBudgetBytes(): number {
- return this.budgetBytes;
- }
-
- public getActiveMemoryBytes(): number {
- return this.activeBytes;
- }
-
- public updateViewport(
- frustum: { minX: number; minY: number; maxX: number; maxY: number } | null,
- activeLayerId?: string | null,
- layerVisibility?: Map<string, boolean>
- ): void {
- this.viewportFrustum = frustum;
- if (activeLayerId !== undefined) this.activeLayerId = activeLayerId;
- if (layerVisibility !== undefined) this.layerVisibility = layerVisibility;
- }
-
- public notifyTileAllocated(tile: TileBuffer): void {
- if (tile.data !== null) {
- this.activeBytes += tile.data.byteLength;
- tile.lastAccessTimestamp = typeof performance !== 'undefined' ? performance.now() : Date.now();
- if (tile.lod === 0) {
- if (this.onMemoryChanged) {
- this.onMemoryChanged();
- } else {
- void this.checkBudgetAndEvict();
- }
- }
- }
- }
-
- public notifyTileFreed(tile: TileBuffer): void {
- if (tile.data !== null) {
- this.activeBytes = Math.max(0, this.activeBytes - tile.data.byteLength);
- }
- }
-
- public touchTile(tile: TileBuffer): void {
- tile.lastAccessTimestamp = typeof performance !== 'undefined' ? performance.now() : Date.now();
- }
-
- /**
- * Transparent Page-In: Asynchronously loads and decompresses a tile from scratch disk.
- */
- public async requestTileData(tile: TileBuffer): Promise<Uint8Array> {
- if (tile.data !== null) {
- this.touchTile(tile);
- return tile.data;
- }
-
- if (!tile.isPagedToDisk) {
- const size = getTileByteSize(tile.format);
- tile.data = new Uint8Array(size);
- this.notifyTileAllocated(tile);
- return tile.data;
- }
-
- const key = getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod);
- let inFlight = this.inFlightPageIns.get(key);
- if (!inFlight) {
- inFlight = (async () => {
- try {
- const raw = await this.driver.readTile(this.sessionId, tile.layerId, tile.tileX, tile.tileY);
- if (tile.data === null) {
- tile.data = raw;
- this.activeBytes += raw.byteLength;
- }
- tile.isPagedToDisk = true;
- tile.dirty = true;
- tile.version = allocateTileVersion();
- this.touchTile(tile);
- void this.checkBudgetAndEvict();
- this.grid.bumpLayerVersion(tile.layerId);
- this.grid.notifyChange();
- return tile.data;
- } finally {
- this.inFlightPageIns.delete(key);
- }
- })();
- this.inFlightPageIns.set(key, inFlight);
- }
- return inFlight;
- }
-
- /**
- * Evaluates memory consumption against the configured RAM budget.
- * Runs an LRU eviction pass prioritizing hidden layers, outside frustum, and inactive layers.
- */
- public async checkBudgetAndEvict(): Promise<void> {
- if (this.evictionPromise) {
- this.needsAnotherEvictionPass = true;
- return this.evictionPromise;
- }
-
- if (this.activeBytes <= this.budgetBytes) {
- return;
- }
-
- this.evictionPromise = (async () => {
- try {
- while (this.activeBytes > this.budgetBytes) {
- this.needsAnotherEvictionPass = false;
- const evictedCount = await this.performEvictionPass();
- if (evictedCount === 0) {
- break;
- }
- if (!this.needsAnotherEvictionPass && this.activeBytes <= this.budgetBytes) {
- break;
- }
- }
- } finally {
- this.evictionPromise = null;
- this.needsAnotherEvictionPass = false;
- }
- })();
-
- return this.evictionPromise;
- }
-
- private static readonly MAX_EVICT_BATCH_TILES = 32;
-
- private async performEvictionPass(): Promise<number> {
- // 1. First drop any in-memory LOD > 0 tiles (they can always be re-downsampled on demand with 0 IO)
- let droppedLodBytes = 0;
- for (const tile of this.grid.tilesIterable()) {
- if (tile.lod > 0 && tile.data !== null) {
- this.activeBytes -= tile.data.byteLength;
- droppedLodBytes += tile.data.byteLength;
- tile.data = null;
- tile.dirty = true;
- tile.version = allocateTileVersion();
- }
- }
-
- if (this.activeBytes <= this.budgetBytes) {
- return droppedLodBytes > 0 ? 1 : 0;
- }
-
- // 2. Gather candidate LOD 0 tiles with active data
- const candidates: TileBuffer[] = [];
- for (const tile of this.grid.tilesIterable()) {
- if (tile.lod === 0 && tile.data !== null) {
- candidates.push(tile);
- }
- }
-
- if (candidates.length === 0) {
- return droppedLodBytes > 0 ? 1 : 0;
- }
-
- const frustum = this.viewportFrustum;
- const activeLayer = this.activeLayerId;
- const layerVis = this.layerVisibility;
-
- // 3. Score candidate eviction priority
- const scored = candidates.map((tile) => {
- const isHidden = layerVis.get(tile.layerId) === false;
- const isInactiveLayer = activeLayer !== null && tile.layerId !== activeLayer;
-
- let frustumDist = 0;
- if (frustum) {
- const minTx = pixelToTileCoord(frustum.minX, 0);
- const maxTx = pixelToTileCoord(frustum.maxX, 0);
- const minTy = pixelToTileCoord(frustum.minY, 0);
- const maxTy = pixelToTileCoord(frustum.maxY, 0);
-
- const dx = tile.tileX < minTx ? minTx - tile.tileX : tile.tileX > maxTx ? tile.tileX - maxTx : 0;
- const dy = tile.tileY < minTy ? minTy - tile.tileY : tile.tileY > maxTy ? tile.tileY - maxTy : 0;
- frustumDist = dx * dx + dy * dy;
- }
-
- let tier = 2;
- if (isHidden) {
- tier = 0; // Tier 0: Hidden layer tiles (evict first)
- } else if (frustumDist > 0) {
- tier = 1; // Tier 1: Outside viewport frustum (farthest first)
- } else if (isInactiveLayer) {
- tier = 2; // Tier 2: Inside frustum, but inactive layer (LRU)
- } else {
- tier = 3; // Tier 3: Inside frustum and active drawing layer (protected, evicted last if needed)
- }
-
- return {
- tile,
- tier,
- frustumDist,
- lastAccess: tile.lastAccessTimestamp,
- };
- });
-
- scored.sort((a, b) => {
- if (a.tier !== b.tier) return a.tier - b.tier;
- if (a.tier === 1 && a.frustumDist !== b.frustumDist) {
- return b.frustumDist - a.frustumDist; // Farthest distance outside frustum first
- }
- return a.lastAccess - b.lastAccess; // Oldest access timestamp first
- });
-
- // 4. Batch evict until within 90% of budget
- const targetBytes = this.budgetBytes * 0.9;
- const toEvict: TileBuffer[] = [];
- let projectedBytes = this.activeBytes;
-
- for (const item of scored) {
- if (projectedBytes <= targetBytes) break;
- toEvict.push(item.tile);
- projectedBytes -= item.tile.data?.byteLength || 0;
- }
-
- if (toEvict.length > 0) {
- try {
- await this.evictTiles(toEvict);
- return toEvict.length;
- } catch (err) {
- console.warn('[TileMemoryManager] Eviction write failed; aborting pass:', err);
- return 0;
- }
- }
-
- return droppedLodBytes > 0 ? 1 : 0;
- }
-
- public async evictTiles(tiles: TileBuffer[]): Promise<void> {
- if (tiles.length === 0) return;
-
- const batchSize = TileMemoryManager.MAX_EVICT_BATCH_TILES;
- for (let start = 0; start < tiles.length; start += batchSize) {
- const end = Math.min(tiles.length, start + batchSize);
- const payloads: TileWritePayload[] = [];
- const validTiles: TileBuffer[] = [];
-
- for (let i = start; i < end; i++) {
- const tile = tiles[i];
- if (tile.data !== null) {
- payloads.push({
- layerId: tile.layerId,
- tileX: tile.tileX,
- tileY: tile.tileY,
- data: tile.data,
- });
- validTiles.push(tile);
- }
- }
-
- if (payloads.length > 0) {
- await this.driver.writeTiles(this.sessionId, payloads);
- for (const tile of validTiles) {
- if (tile.data) {
- this.activeBytes = Math.max(0, this.activeBytes - tile.data.byteLength);
- tile.data = null;
- tile.isPagedToDisk = true;
- tile.dirty = false;
- }
- }
- }
-
- if (end < tiles.length) {
- await yieldToMain();
- }
- }
- }
-
- /**
- * Drops all cached LOD > 0 tiles and evicts up to `bytesToFree` of LOD 0 tiles to scratch disk.
- * Used by DocumentStore to cooperatively reclaim RAM from inactive document tabs.
- */
- public async evictBytesToDisk(bytesToFree: number): Promise<number> {
- if (bytesToFree <= 0 || this.activeBytes <= 0) return 0;
- let freed = 0;
-
- // 1. Drop regenerable LOD > 0 tiles first (zero disk I/O)
- for (const tile of this.grid.tilesIterable()) {
- if (tile.lod > 0 && tile.data !== null) {
- const sz = tile.data.byteLength;
- this.activeBytes = Math.max(0, this.activeBytes - sz);
- freed += sz;
- tile.data = null;
- tile.dirty = true;
- tile.version = allocateTileVersion();
- }
- }
-
- if (freed >= bytesToFree) return freed;
-
- // 2. Evict LOD 0 tiles oldest-first to scratch disk
- const lod0: TileBuffer[] = [];
- for (const tile of this.grid.tilesIterable()) {
- if (tile.lod === 0 && tile.data !== null) {
- lod0.push(tile);
- }
- }
- lod0.sort((a, b) => a.lastAccessTimestamp - b.lastAccessTimestamp);
-
- const toEvict: TileBuffer[] = [];
- for (const tile of lod0) {
- if (freed >= bytesToFree) break;
- toEvict.push(tile);
- freed += tile.data?.byteLength || 0;
- }
-
- if (toEvict.length > 0) {
- await this.evictTiles(toEvict);
- }
-
- return freed;
- }
-
- /**
- * Offloads all in-memory tiles of this document to scratch disk.
- */
- public async evictAllToDisk(): Promise<number> {
- return this.evictBytesToDisk(this.activeBytes);
- }
-
- public async clear(): Promise<void> {
- this.inFlightPageIns.clear();
- this.activeBytes = 0;
- await this.driver.clear(this.sessionId);
- }
-}
+import type { BlendMode, CanvasDimensions, DirtyRect, TileDelta } from '../types/editor';
+import { TileMemoryManager, type TileMemoryManagerOptions } from './tileEngine/memoryManager';
+import * as mipmapOps from './tileEngine/mipmap';
+import { type CompositeStrokeOptions, compositeStrokeToTiles as compositeStrokeOp } from './tileEngine/strokeComposite';
+import * as tileFillOps from './tileEngine/tileFill';
+import * as tileIOOps from './tileEngine/tileIO';
+import * as tileOps from './tileEngine/tileOps';
+import * as tileRenderOps from './tileEngine/tileRender';
+import * as tileSnapshotOps from './tileEngine/tileSnapshots';
+import {
+ BYTES_32BIT,
+ type ISparseTileGridHost,
+ type TileBuffer,
+ type TileFormat,
+ type TileMemoryStats,
+ type TileSnapshotEntry,
+ createTileBuffer,
+ getTileKey,
+ packTileCoord,
+} from './tileEngine/types';
+
+export {
+ TILE_SIZE,
+ TILE_PIXELS,
+ BYTES_1BIT,
+ BYTES_8BIT,
+ BYTES_32BIT,
+ getTileByteSize,
+ isLittleEndian,
+ INK_BLACK_U32,
+ TRANSPARENT_U32,
+ PAPER_WHITE_U32,
+ pixelToTileCoord,
+ getTileKey,
+ parseTileKey,
+ allocateTileVersion,
+ reserveTileVersion,
+ createTileBuffer,
+ releaseTemporaryCanvas,
+} from './tileEngine/types';
+export type { TileFormat, TileBuffer, TileMemoryStats, TileSnapshotEntry } from './tileEngine/types';
+export type { TileDelta } from '../types/editor';
+export * from './tileEngine/pixelCodec';
+export { downsample2x2ToParentTile } from './tileEngine/mipmap';
+export * from './tileEngine/scratchDriver';
+export * from './tileEngine/memoryManager';
+export type { CompositeStrokeOptions } from './tileEngine/strokeComposite';
+export * from './tileEngine/serialization';
let nextSparseTileGridId = 1;
-/**
- * Releases an HTMLCanvasElement's backing store immediately so Chromium/WebView2 reclaims RAM.
- */
-export function releaseTemporaryCanvas(canvas: HTMLCanvasElement | null | undefined): void {
- if (!canvas) return;
- try {
- canvas.width = 0;
- canvas.height = 0;
- } catch {
- // Ignore read-only or detached mock canvases in tests
- }
-}
-
-// ============================================================================
-// SparseTileGrid
-// ============================================================================
-
/**
* Sparse Virtual Tile Grid
*
* Sole authoritative backing store for all layer pixel data in Ink Studio.
* Completely deprecates multi-gigabyte full-sized DOM layer canvases.
*/
-const TILE_COORD_BIAS = 32768;
-const TILE_COORD_STRIDE = 65536;
-
-function packTileCoord(tx: number, ty: number): number {
- return (ty + TILE_COORD_BIAS) * TILE_COORD_STRIDE + (tx + TILE_COORD_BIAS);
-}
-
-function unpackTileCoordX(packed: number): number {
- return (packed % TILE_COORD_STRIDE) - TILE_COORD_BIAS;
-}
-
-function unpackTileCoordY(packed: number): number {
- return Math.floor(packed / TILE_COORD_STRIDE) - TILE_COORD_BIAS;
-}
-
export class SparseTileGrid {
private readonly gridId: number = nextSparseTileGridId++;
private tiles: Map<string, TileBuffer> = new Map();
@@ -1294,64 +83,51 @@ export class SparseTileGrid {
private globalVersionCounter: number = 1;
private contentVersion: number = 1;
private gridEpoch: number = 0;
+ private readonly host: ISparseTileGridHost;
constructor(memoryManagerOptions?: TileMemoryManagerOptions) {
+ this.host = {
+ tiles: this.tiles,
+ layerLod0Tiles: this.layerLod0Tiles,
+ layerLodOccupancy: this.layerLodOccupancy,
+ layerFormats: this.layerFormats,
+ ingestedLayers: this.ingestedLayers,
+ dirtyLodTiles: this.dirtyLodTiles,
+ layerVersions: this.layerVersions,
+ scratchRGBA: this.scratchRGBA,
+ writeScratchRGBA: this.writeScratchRGBA,
+ getThumbCanvas: () => this.thumbCanvas,
+ setThumbCanvas: (canvas) => { this.thumbCanvas = canvas; },
+ getMemoryManager: () => this.memoryManager,
+ incrementGridEpochAndContentVersion: () => { this.gridEpoch++; this.contentVersion++; },
+ registerLod0Tile: (tile) => tileSnapshotOps.registerLod0Tile(this.host, tile),
+ unregisterLod0Tile: (tile) => tileSnapshotOps.unregisterLod0Tile(this.host, tile),
+ tilesIterable: () => this.tilesIterable(),
+ bumpLayerVersion: (id) => this.bumpLayerVersion(id),
+ notifyChange: (imm) => this.notifyChange(imm),
+ hasLayerTiles: (id) => this.hasLayerTiles(id),
+ hasPopulatedLodTile: (id, tx, ty, lod) => this.hasPopulatedLodTile(id, tx, ty, lod),
+ setLayerFormat: (id, fmt) => this.setLayerFormat(id, fmt),
+ getLayerFormat: (id) => this.getLayerFormat(id),
+ getTile: (id, tx, ty, lod) => this.getTile(id, tx, ty, lod),
+ getOrCreateTile: (id, tx, ty, fmt, lod) => this.getOrCreateTile(id, tx, ty, fmt, lod),
+ setTile: (id, tx, ty, tile) => this.setTile(id, tx, ty, tile),
+ deleteTile: (id, tx, ty, lod) => this.deleteTile(id, tx, ty, lod),
+ getLayerTiles: (id, lod) => this.getLayerTiles(id, lod),
+ getTileAsRGBA: (tile) => this.getTileAsRGBA(tile),
+ isLodTileDirty: (id, tx, ty, lod) => this.isLodTileDirty(id, tx, ty, lod),
+ markLodAncestorsDirty: (id, tx, ty) => this.markLodAncestorsDirty(id, tx, ty),
+ generateLodTile: (id, tx, ty, lod) => this.generateLodTile(id, tx, ty, lod),
+ getOrBuildLod3Tiles: (id) => this.getOrBuildLod3Tiles(id),
+ writeImageData: (id, img, dx, dy, fmt, sup) => this.writeImageData(id, img, dx, dy, fmt, sup),
+ renderLayerToCanvas: (id, c, r) => this.renderLayerToCanvas(id, c, r),
+ fillLayerSolidWhite: (id, w, h, fmt) => this.fillLayerSolidWhite(id, w, h, fmt),
+ clearLayer: (id) => this.clearLayer(id),
+ clearAll: () => this.clearAll(),
+ };
this.memoryManager = new TileMemoryManager(this, memoryManagerOptions);
}
- private registerLod0Tile(tile: TileBuffer): void {
- if ((tile.lod ?? 0) !== 0) return;
- let set = this.layerLod0Tiles.get(tile.layerId);
- if (!set) {
- set = new Set<TileBuffer>();
- this.layerLod0Tiles.set(tile.layerId, set);
- }
- if (set.has(tile)) return;
- set.add(tile);
-
- let occ = this.layerLodOccupancy.get(tile.layerId);
- if (!occ) {
- occ = [new Map<number, number>(), new Map<number, number>(), new Map<number, number>()];
- this.layerLodOccupancy.set(tile.layerId, occ);
- }
- let tx = tile.tileX;
- let ty = tile.tileY;
- for (let i = 0; i < 3; i++) {
- tx = tx >> 1;
- ty = ty >> 1;
- const pk = packTileCoord(tx, ty);
- occ[i].set(pk, (occ[i].get(pk) ?? 0) + 1);
- }
- }
-
- private unregisterLod0Tile(tile: TileBuffer): void {
- if ((tile.lod ?? 0) !== 0) return;
- const set = this.layerLod0Tiles.get(tile.layerId);
- if (!set || !set.delete(tile)) return;
- if (set.size === 0) {
- this.layerLod0Tiles.delete(tile.layerId);
- }
-
- const occ = this.layerLodOccupancy.get(tile.layerId);
- if (!occ) return;
- let tx = tile.tileX;
- let ty = tile.tileY;
- for (let i = 0; i < 3; i++) {
- tx = tx >> 1;
- ty = ty >> 1;
- const pk = packTileCoord(tx, ty);
- const next = (occ[i].get(pk) ?? 0) - 1;
- if (next <= 0) {
- occ[i].delete(pk);
- } else {
- occ[i].set(pk, next);
- }
- }
- if (set.size === 0) {
- this.layerLodOccupancy.delete(tile.layerId);
- }
- }
-
public getGridId(): number {
return this.gridId;
}
@@ -1446,16 +222,12 @@ export class SparseTileGrid {
const fmt = format || this.getLayerFormat(layerId);
tile = createTileBuffer(layerId, tileX, tileY, fmt, lod);
this.tiles.set(key, tile);
- if (lod === 0) {
- this.registerLod0Tile(tile);
- }
- if (this.memoryManager) {
- this.memoryManager.notifyTileAllocated(tile);
- }
+ if (lod === 0) tileSnapshotOps.registerLod0Tile(this.host, tile);
+ this.memoryManager?.notifyTileAllocated(tile);
} else if (tile.data === null && tile.isPagedToDisk && this.memoryManager) {
void this.memoryManager.requestTileData(tile);
- } else if (this.memoryManager) {
- this.memoryManager.touchTile(tile);
+ } else {
+ this.memoryManager?.touchTile(tile);
}
return tile;
}
@@ -1464,1739 +236,165 @@ export class SparseTileGrid {
const key = getTileKey(layerId, tileX, tileY, tile.lod);
const existing = this.tiles.get(key);
if (existing) {
- if ((existing.lod ?? 0) === 0) {
- this.unregisterLod0Tile(existing);
- }
- if (this.memoryManager) {
- this.memoryManager.notifyTileFreed(existing);
- }
+ if ((existing.lod ?? 0) === 0) tileSnapshotOps.unregisterLod0Tile(this.host, existing);
+ this.memoryManager?.notifyTileFreed(existing);
}
this.tiles.set(key, tile);
- if ((tile.lod ?? 0) === 0) {
- this.registerLod0Tile(tile);
- }
- if (this.memoryManager) {
- this.memoryManager.notifyTileAllocated(tile);
- }
+ if ((tile.lod ?? 0) === 0) tileSnapshotOps.registerLod0Tile(this.host, tile);
+ this.memoryManager?.notifyTileAllocated(tile);
if (tile.lod === 0) {
this.setLayerFormat(layerId, tile.format);
this.markLodAncestorsDirty(layerId, tileX, tileY);
this.bumpLayerVersion(layerId);
}
- this.notifyChange();
- }
-
- public deleteTile(layerId: string, tileX: number, tileY: number, lod: number = 0): void {
- const key = getTileKey(layerId, tileX, tileY, lod);
- const tile = this.tiles.get(key);
- if (tile) {
- if ((tile.lod ?? 0) === 0) {
- this.unregisterLod0Tile(tile);
- }
- if (this.memoryManager) {
- this.memoryManager.notifyTileFreed(tile);
- }
- this.tiles.delete(key);
- if (lod === 0) {
- this.markLodAncestorsDirty(layerId, tileX, tileY);
- this.bumpLayerVersion(layerId);
- }
- }
- }
-
- public getLayerTiles(layerId: string, lod: number = 0): TileBuffer[] {
- if (lod === 0) {
- const set = this.layerLod0Tiles.get(layerId);
- return set ? Array.from(set) : [];
- }
- const result: TileBuffer[] = [];
- for (const tile of this.tiles.values()) {
- if (tile.layerId === layerId && (tile.lod ?? 0) === lod) {
- result.push(tile);
- }
- }
- return result;
- }
-
- public getTilesInBounds(
- layerId: string,
- minX: number,
- minY: number,
- maxX: number,
- maxY: number,
- lod: number = 0
- ): TileBuffer[] {
- if (lod === 0 && !this.hasLayerTiles(layerId)) {
- return [];
- }
- const minTileX = pixelToTileCoord(minX, lod);
- const minTileY = pixelToTileCoord(minY, lod);
- const maxTileX = pixelToTileCoord(maxX, lod);
- const maxTileY = pixelToTileCoord(maxY, lod);
-
- const result: TileBuffer[] = [];
- for (let ty = minTileY; ty <= maxTileY; ty++) {
- for (let tx = minTileX; tx <= maxTileX; tx++) {
- if (lod > 0 && !this.hasPopulatedLodTile(layerId, tx, ty, lod)) {
- const direct = this.getTile(layerId, tx, ty, lod);
- if (direct) result.push(direct);
- continue;
- }
- let tile = this.getTile(layerId, tx, ty, lod);
- if (lod > 0 && (!tile || this.isLodTileDirty(layerId, tx, ty, lod))) {
- tile = this.generateLodTile(layerId, tx, ty, lod);
- }
- if (tile) {
- result.push(tile);
- }
- }
- }
- return result;
- }
-
- public getIntersectingCoords(
- minX: number,
- minY: number,
- maxX: number,
- maxY: number,
- lod: number = 0
- ): Array<{ tileX: number; tileY: number }> {
- const minTileX = pixelToTileCoord(minX, lod);
- const minTileY = pixelToTileCoord(minY, lod);
- const maxTileX = pixelToTileCoord(maxX, lod);
- const maxTileY = pixelToTileCoord(maxY, lod);
-
- const coords: Array<{ tileX: number; tileY: number }> = [];
- for (let ty = minTileY; ty <= maxTileY; ty++) {
- for (let tx = minTileX; tx <= maxTileX; tx++) {
- coords.push({ tileX: tx, tileY: ty });
- }
- }
- return coords;
- }
-
- /**
- * Transparently returns a 256x256 RGBA Uint8ClampedArray for WebGL texture upload or 2D blitting.
- * If tile data is paged to disk, kicks off an asynchronous fetch without freezing rendering.
- */
- public getTileAsRGBA(tile: TileBuffer): Uint8ClampedArray {
- if (tile.data === null) {
- if (tile.isPagedToDisk && this.memoryManager) {
- void this.memoryManager.requestTileData(tile);
- }
- this.scratchRGBA.fill(0);
- return this.scratchRGBA;
- }
-
- if (tile.format === 'color-32bit') {
- return new Uint8ClampedArray(tile.data.buffer, tile.data.byteOffset, BYTES_32BIT);
- }
- if (tile.format === 'monochrome-1bit') {
- unpack1BitToRGBA(tile.data, this.scratchRGBA);
- return this.scratchRGBA;
- }
- // 8-bit grayscale
- unpack8BitToRGBA(tile.data, this.scratchRGBA);
- return this.scratchRGBA;
- }
-
- /**
- * Writes an ImageData or RGBA buffer into the sparse tile grid.
- * Only allocates tiles that actually intersect the drawn rectangle.
- */
- public writeImageData(
- layerId: string,
- imgData: { data: Uint8ClampedArray | Uint8Array; width: number; height: number },
- destX: number,
- destY: number,
- format?: TileFormat,
- suppressNotify: boolean = false
- ): { minTileX: number; minTileY: number; maxTileX: number; maxTileY: number } {
- this.ingestedLayers.add(layerId);
- if (format) {
- this.setLayerFormat(layerId, format);
- }
- const targetFormat = format || this.getLayerFormat(layerId);
- const w = imgData.width;
- const h = imgData.height;
- if (w <= 0 || h <= 0) {
- return { minTileX: 0, minTileY: 0, maxTileX: 0, maxTileY: 0 };
- }
-
- const minTileX = pixelToTileCoord(destX, 0);
- const minTileY = pixelToTileCoord(destY, 0);
- const maxTileX = pixelToTileCoord(destX + w - 1, 0);
- const maxTileY = pixelToTileCoord(destY + h - 1, 0);
-
- const tileScratch = this.writeScratchRGBA;
- const srcData = imgData.data;
- const src32 =
- srcData.byteOffset % 4 === 0 && srcData.byteLength >= w * h * 4
- ? new Uint32Array(srcData.buffer, srcData.byteOffset, w * h)
- : null;
-
- for (let ty = minTileY; ty <= maxTileY; ty++) {
- const tileDocY = ty * TILE_SIZE;
- for (let tx = minTileX; tx <= maxTileX; tx++) {
- const tileDocX = tx * TILE_SIZE;
-
- const srcStartX = Math.max(0, tileDocX - destX);
- const srcStartY = Math.max(0, tileDocY - destY);
- const srcEndX = Math.min(w, tileDocX + TILE_SIZE - destX);
- const srcEndY = Math.min(h, tileDocY + TILE_SIZE - destY);
-
- if (srcStartX >= srcEndX || srcStartY >= srcEndY) continue;
-
- let existingTile = this.getTile(layerId, tx, ty, 0);
- if (!existingTile) {
- let hasNonZero = false;
- if (src32 !== null) {
- outer32: for (let sy = srcStartY; sy < srcEndY; sy++) {
- const rowOff = sy * w;
- for (let sx = rowOff + srcStartX, end = rowOff + srcEndX; sx < end; sx++) {
- if (src32[sx] !== 0) {
- hasNonZero = true;
- break outer32;
- }
- }
- }
- } else {
- outer: for (let sy = srcStartY; sy < srcEndY; sy++) {
- let idx = (sy * w + srcStartX) * 4;
- const endIdx = (sy * w + srcEndX) * 4;
- for (; idx < endIdx; idx += 4) {
- if (srcData[idx + 3] !== 0 || srcData[idx] !== 0 || srcData[idx + 1] !== 0 || srcData[idx + 2] !== 0) {
- hasNonZero = true;
- break outer;
- }
- }
- }
- }
- if (!hasNonZero) continue;
- existingTile = this.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
- }
-
- const tile = existingTile;
- if (tile.format !== targetFormat) {
- if (tile.data !== null) {
- this.memoryManager?.notifyTileFreed(tile);
- }
- tile.format = targetFormat;
- tile.data = new Uint8Array(getTileByteSize(targetFormat));
- this.memoryManager?.notifyTileAllocated(tile);
- } else if (tile.data === null) {
- tile.data = new Uint8Array(getTileByteSize(tile.format));
- this.memoryManager?.notifyTileAllocated(tile);
- }
-
- if (tile.format === 'color-32bit') {
- for (let sy = srcStartY; sy < srcEndY; sy++) {
- const tileLocalY = destY + sy - tileDocY;
- const tileLocalX = destX + srcStartX - tileDocX;
- const copyWidth = srcEndX - srcStartX;
-
- const srcByteOffset = (sy * w + srcStartX) * 4;
- const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
-
- tile.data.set(
- srcData.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
- tileByteOffset
- );
- }
- } else if (tile.format === 'monochrome-1bit') {
- const dst = tile.data;
- const localStartX = destX + srcStartX - tileDocX;
- const copyWidth = srcEndX - srcStartX;
- const localEndX = localStartX + copyWidth;
-
- for (let sy = srcStartY; sy < srcEndY; sy++) {
- const tileLocalY = destY + sy - tileDocY;
- const rowByteBase = tileLocalY << 5; // TILE_SIZE / 8 = 32
- let lx = localStartX;
- let srcPixIdx = sy * w + srcStartX;
- let srcOff = srcPixIdx << 2;
-
- // Leading unaligned pixels before an 8-pixel boundary
- if ((lx & 7) !== 0) {
- const byteIdx = rowByteBase + (lx >> 3);
- let byteVal = dst[byteIdx];
- const stop = Math.min(localEndX, (lx + 7) & ~7);
- while (lx < stop) {
- const mask = 1 << (7 - (lx & 7));
- const a = srcData[srcOff + 3];
- if (
- a >= 24 &&
- srcData[srcOff] * 299 + srcData[srcOff + 1] * 587 + srcData[srcOff + 2] * 114 < 128000
- ) {
- byteVal |= mask;
- } else {
- byteVal &= ~mask;
- }
- lx++;
- srcPixIdx++;
- srcOff += 4;
- }
- dst[byteIdx] = byteVal;
- }
-
- // Full 8-pixel aligned bytes
- while (lx + 8 <= localEndX) {
- const byteIdx = rowByteBase + (lx >> 3);
- if (
- src32 !== null &&
- (src32[srcPixIdx] |
- src32[srcPixIdx + 1] |
- src32[srcPixIdx + 2] |
- src32[srcPixIdx + 3] |
- src32[srcPixIdx + 4] |
- src32[srcPixIdx + 5] |
- src32[srcPixIdx + 6] |
- src32[srcPixIdx + 7]) === 0
- ) {
- dst[byteIdx] = 0;
- lx += 8;
- srcPixIdx += 8;
- srcOff += 32;
- continue;
- }
- let byteVal = 0;
- for (let bit = 7; bit >= 0; bit--) {
- const a = srcData[srcOff + 3];
- if (
- a >= 24 &&
- srcData[srcOff] * 299 + srcData[srcOff + 1] * 587 + srcData[srcOff + 2] * 114 < 128000
- ) {
- byteVal |= 1 << bit;
- }
- srcOff += 4;
- }
- dst[byteIdx] = byteVal;
- lx += 8;
- srcPixIdx += 8;
- }
-
- // Trailing unaligned pixels
- if (lx < localEndX) {
- const byteIdx = rowByteBase + (lx >> 3);
- let byteVal = dst[byteIdx];
- while (lx < localEndX) {
- const mask = 1 << (7 - (lx & 7));
- const a = srcData[srcOff + 3];
- if (
- a >= 24 &&
- srcData[srcOff] * 299 + srcData[srcOff + 1] * 587 + srcData[srcOff + 2] * 114 < 128000
- ) {
- byteVal |= mask;
- } else {
- byteVal &= ~mask;
- }
- lx++;
- srcOff += 4;
- }
- dst[byteIdx] = byteVal;
- }
- }
- } else {
- unpack8BitToRGBA(tile.data, tileScratch);
- for (let sy = srcStartY; sy < srcEndY; sy++) {
- const tileLocalY = destY + sy - tileDocY;
- const tileLocalX = destX + srcStartX - tileDocX;
- const copyWidth = srcEndX - srcStartX;
-
- const srcByteOffset = (sy * w + srcStartX) * 4;
- const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
-
- tileScratch.set(
- srcData.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
- tileByteOffset
- );
- }
- packRGBATo8Bit(tileScratch, tile.data);
- }
-
- tile.solidColorU32 = undefined;
- tile.dirty = true;
- tile.version = allocateTileVersion();
- this.markLodAncestorsDirty(layerId, tx, ty);
- }
- }
-
- this.bumpLayerVersion(layerId);
- if (!suppressNotify) {
- this.notifyChange();
- }
- return { minTileX, minTileY, maxTileX, maxTileY };
- }
-
- /**
- * Composites an isolated stroke RGBA buffer directly onto LOD 0 tiles in-place,
- * avoiding full-region canvas allocation, existing-tile unpacking, and separate
- * binarization passes. Records pre-edit tile snapshots into `snapshotOut` only
- * for tiles with non-zero stroke pixels.
- */
- public compositeStrokeToTiles(options: {
- layerId: string;
- strokeData: { data: Uint8ClampedArray | Uint8Array; width: number; height: number };
- destX: number;
- destY: number;
- format: TileFormat;
- compositeOp: 'source-over' | 'destination-out' | 'source-atop';
- opacity: number;
- monochrome?: {
- threshold: number;
- expressBlack: boolean;
- expressWhite: boolean;
- };
- selectionMask?: {
- mask: Uint8Array;
- bounds: { x: number; y: number; width: number; height: number };
- } | null;
- snapshotOut?: Map<string, { format: TileFormat; data: Uint8Array | null }>;
- suppressNotify?: boolean;
- }): boolean {
- const {
- layerId,
- strokeData,
- destX,
- destY,
- format: targetFormat,
- compositeOp,
- monochrome,
- selectionMask,
- snapshotOut,
- suppressNotify = false,
- } = options;
- const opacity = Math.max(0, Math.min(1, options.opacity));
- const w = strokeData.width;
- const h = strokeData.height;
- if (w <= 0 || h <= 0 || opacity <= 0.001) return false;
-
- this.ingestedLayers.add(layerId);
- this.setLayerFormat(layerId, targetFormat);
-
- const minTileX = pixelToTileCoord(destX, 0);
- const minTileY = pixelToTileCoord(destY, 0);
- const maxTileX = pixelToTileCoord(destX + w - 1, 0);
- const maxTileY = pixelToTileCoord(destY + h - 1, 0);
-
- const srcData = strokeData.data;
- const src32 =
- srcData.byteOffset % 4 === 0 && srcData.byteLength >= w * h * 4
- ? new Uint32Array(srcData.buffer, srcData.byteOffset, w * h)
- : null;
-
- const monoThresh = Math.max(1, Math.min(255, monochrome?.threshold ?? 128));
- const monoExpressBlack = monochrome?.expressBlack !== false;
- const hasSelMask = Boolean(selectionMask?.mask);
- const selMask = selectionMask?.mask ?? null;
- const selBx = selectionMask ? Math.floor(selectionMask.bounds.x) : 0;
- const selBy = selectionMask ? Math.floor(selectionMask.bounds.y) : 0;
- const selBw = selectionMask ? Math.ceil(selectionMask.bounds.width) : 0;
- const selBh = selectionMask ? Math.ceil(selectionMask.bounds.height) : 0;
- const fullOpacity = opacity >= 0.999;
-
- let anyModified = false;
-
- for (let ty = minTileY; ty <= maxTileY; ty++) {
- const tileDocY = ty * TILE_SIZE;
- for (let tx = minTileX; tx <= maxTileX; tx++) {
- const tileDocX = tx * TILE_SIZE;
-
- const srcStartX = Math.max(0, tileDocX - destX);
- const srcStartY = Math.max(0, tileDocY - destY);
- const srcEndX = Math.min(w, tileDocX + TILE_SIZE - destX);
- const srcEndY = Math.min(h, tileDocY + TILE_SIZE - destY);
- if (srcStartX >= srcEndX || srcStartY >= srcEndY) continue;
-
- let existingTile = this.getTile(layerId, tx, ty, 0);
-
- // Erasing or alpha-locking against an empty tile is a no-op
- if ((compositeOp === 'destination-out' || compositeOp === 'source-atop') && (!existingTile || !existingTile.data)) {
- if (existingTile && existingTile.data === null && existingTile.isPagedToDisk && this.memoryManager) {
- void this.memoryManager.requestTileData(existingTile);
- }
- continue;
- }
-
- // Fast zero-scan: skip tiles where the stroke overlap is completely transparent
- let hasNonZero = false;
- if (src32 !== null) {
- outerZero32: for (let sy = srcStartY; sy < srcEndY; sy++) {
- const rowOff = sy * w;
- for (let sx = rowOff + srcStartX, end = rowOff + srcEndX; sx < end; sx++) {
- if ((src32[sx] >>> 24) !== 0) {
- hasNonZero = true;
- break outerZero32;
- }
- }
- }
- } else {
- outerZero8: for (let sy = srcStartY; sy < srcEndY; sy++) {
- let off = (sy * w + srcStartX) << 2;
- const endOff = (sy * w + srcEndX) << 2;
- for (; off < endOff; off += 4) {
- if (srcData[off + 3] !== 0) {
- hasNonZero = true;
- break outerZero8;
- }
- }
- }
- }
- if (!hasNonZero) continue;
-
- // Snapshot pre-edit tile state before mutating
- if (snapshotOut) {
- const tileKey = getTileKey(layerId, tx, ty, 0);
- if (!snapshotOut.has(tileKey)) {
- snapshotOut.set(tileKey, {
- format: existingTile ? existingTile.format : targetFormat,
- data: existingTile?.data ? new Uint8Array(existingTile.data) : null,
- });
- }
- }
-
- const tile = existingTile ?? this.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
- if (tile.format !== targetFormat) {
- const prevRGBA = tile.data ? new Uint8Array(this.getTileAsRGBA(tile)) : null;
- if (tile.data !== null) {
- this.memoryManager?.notifyTileFreed(tile);
- }
- tile.format = targetFormat;
- tile.data = new Uint8Array(getTileByteSize(targetFormat));
- if (prevRGBA) {
- if (targetFormat === 'color-32bit') {
- tile.data.set(prevRGBA);
- } else if (targetFormat === 'monochrome-1bit') {
- packRGBATo1Bit(prevRGBA, tile.data, monoThresh);
- } else {
- packRGBATo8Bit(prevRGBA, tile.data);
- }
- }
- this.memoryManager?.notifyTileAllocated(tile);
- } else if (tile.data === null) {
- tile.data = new Uint8Array(getTileByteSize(tile.format));
- this.memoryManager?.notifyTileAllocated(tile);
- }
-
- const localStartX = destX + srcStartX - tileDocX;
- const copyWidth = srcEndX - srcStartX;
-
- if (tile.format === 'monochrome-1bit') {
- const dst = tile.data;
- for (let sy = srcStartY; sy < srcEndY; sy++) {
- const tileLocalY = destY + sy - tileDocY;
- const docY = destY + sy;
- const rowByteBase = tileLocalY << 5;
- let srcOff = (sy * w + srcStartX) << 2;
- const selRowValid = hasSelMask && docY >= selBy && docY < selBy + selBh;
- const selRowOff = selRowValid ? (docY - selBy) * selBw : 0;
-
- for (let dx = 0; dx < copyWidth; dx++, srcOff += 4) {
- const sa = srcData[srcOff + 3];
- if (sa === 0) continue;
-
- let effA = fullOpacity ? sa : Math.round(sa * opacity);
- if (hasSelMask) {
- const docX = destX + srcStartX + dx;
- if (!selRowValid || docX < selBx || docX >= selBx + selBw) continue;
- const ma = selMask![selRowOff + (docX - selBx)];
- if (ma === 0) continue;
- if (ma < 255) {
- effA = Math.round((effA * ma) / 255);
- }
- }
-
- const lx = localStartX + dx;
- const byteIdx = rowByteBase + (lx >> 3);
- const mask = 1 << (7 - (lx & 7));
-
- if (compositeOp === 'destination-out') {
- if (effA >= 128) {
- dst[byteIdx] &= ~mask;
- }
- } else if (compositeOp === 'source-atop') {
- if ((dst[byteIdx] & mask) === 0) continue;
- const r = srcData[srcOff];
- const g = srcData[srcOff + 1];
- const b = srcData[srcOff + 2];
- const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;
- const outLum = (lum * effA) / 255;
- if (outLum < monoThresh && monoExpressBlack) {
- dst[byteIdx] |= mask;
- } else {
- dst[byteIdx] &= ~mask;
- }
- } else {
- const hadInk = (dst[byteIdx] & mask) !== 0;
- const r = srcData[srcOff];
- const g = srcData[srcOff + 1];
- const b = srcData[srcOff + 2];
- const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;
- if (!hadInk) {
- if (effA >= 128 && lum < monoThresh && monoExpressBlack) {
- dst[byteIdx] |= mask;
- }
- } else {
- const outLum = (lum * effA) / 255;
- if (outLum >= monoThresh || !monoExpressBlack) {
- dst[byteIdx] &= ~mask;
- }
- }
- }
- }
- }
- } else if (tile.format === 'color-32bit') {
- const dst = tile.data;
- for (let sy = srcStartY; sy < srcEndY; sy++) {
- const tileLocalY = destY + sy - tileDocY;
- const docY = destY + sy;
- let srcOff = (sy * w + srcStartX) << 2;
- let dstOff = (tileLocalY * TILE_SIZE + localStartX) << 2;
- const selRowValid = hasSelMask && docY >= selBy && docY < selBy + selBh;
- const selRowOff = selRowValid ? (docY - selBy) * selBw : 0;
-
- for (let dx = 0; dx < copyWidth; dx++, srcOff += 4, dstOff += 4) {
- const sa = srcData[srcOff + 3];
- if (sa === 0) continue;
-
- let effA = fullOpacity ? sa : Math.round(sa * opacity);
- if (effA === 0) continue;
-
- let maskFrac = 1.0;
- if (hasSelMask) {
- const docX = destX + srcStartX + dx;
- if (!selRowValid || docX < selBx || docX >= selBx + selBw) continue;
- const ma = selMask![selRowOff + (docX - selBx)];
- if (ma === 0) continue;
- if (ma < 255) maskFrac = ma / 255;
- }
-
- const sr = srcData[srcOff];
- const sg = srcData[srcOff + 1];
- const sb = srcData[srcOff + 2];
- const da = dst[dstOff + 3];
-
- let outR = dst[dstOff];
- let outG = dst[dstOff + 1];
- let outB = dst[dstOff + 2];
- let outA = da;
-
- if (compositeOp === 'destination-out') {
- if (da === 0) continue;
- if (effA === 255) {
- outR = 0;
- outG = 0;
- outB = 0;
- outA = 0;
- } else {
- outA = Math.round(da * (1 - effA / 255));
- if (outA === 0) {
- outR = 0;
- outG = 0;
- outB = 0;
- }
- }
- } else if (compositeOp === 'source-atop') {
- if (da === 0) continue;
- if (effA === 255) {
- outR = sr;
- outG = sg;
- outB = sb;
- } else {
- const sA = effA / 255;
- const inv = 1 - sA;
- outR = Math.round(sr * sA + outR * inv);
- outG = Math.round(sg * sA + outG * inv);
- outB = Math.round(sb * sA + outB * inv);
- }
- } else {
- if (effA === 255 || da === 0) {
- outR = sr;
- outG = sg;
- outB = sb;
- outA = effA;
- } else {
- const sA = effA / 255;
- const dA = da / 255;
- const invSA = 1 - sA;
- const compA = sA + dA * invSA;
- if (compA > 0) {
- const invOut = 1 / compA;
- outR = Math.round((sr * sA + outR * dA * invSA) * invOut);
- outG = Math.round((sg * sA + outG * dA * invSA) * invOut);
- outB = Math.round((sb * sA + outB * dA * invSA) * invOut);
- outA = Math.round(compA * 255);
- }
- }
- }
-
- if (maskFrac < 1.0) {
- const invM = 1 - maskFrac;
- const bA = da / 255;
- const aA = outA / 255;
- const mixA = bA * invM + aA * maskFrac;
- if (mixA <= 0.0001) {
- dst[dstOff] = 0;
- dst[dstOff + 1] = 0;
- dst[dstOff + 2] = 0;
- dst[dstOff + 3] = 0;
- } else {
- const invMixA = 1 / mixA;
- dst[dstOff] = Math.round((dst[dstOff] * bA * invM + outR * aA * maskFrac) * invMixA);
- dst[dstOff + 1] = Math.round((dst[dstOff + 1] * bA * invM + outG * aA * maskFrac) * invMixA);
- dst[dstOff + 2] = Math.round((dst[dstOff + 2] * bA * invM + outB * aA * maskFrac) * invMixA);
- dst[dstOff + 3] = Math.round(mixA * 255);
- }
- } else {
- dst[dstOff] = outR;
- dst[dstOff + 1] = outG;
- dst[dstOff + 2] = outB;
- dst[dstOff + 3] = outA;
- }
- }
- }
- } else {
- // grayscale-8bit fallback
- const tileScratch = this.writeScratchRGBA;
- unpack8BitToRGBA(tile.data, tileScratch);
- for (let sy = srcStartY; sy < srcEndY; sy++) {
- const tileLocalY = destY + sy - tileDocY;
- let srcOff = (sy * w + srcStartX) << 2;
- let dstOff = (tileLocalY * TILE_SIZE + localStartX) << 2;
- for (let dx = 0; dx < copyWidth; dx++, srcOff += 4, dstOff += 4) {
- const sa = srcData[srcOff + 3];
- if (sa === 0) continue;
- const effA = fullOpacity ? sa : Math.round(sa * opacity);
- if (compositeOp === 'destination-out') {
- tileScratch[dstOff + 3] = Math.round(tileScratch[dstOff + 3] * (1 - effA / 255));
- } else if (effA > 0) {
- const sA = effA / 255;
- const inv = 1 - sA;
- tileScratch[dstOff] = Math.round(srcData[srcOff] * sA + tileScratch[dstOff] * inv);
- tileScratch[dstOff + 1] = Math.round(srcData[srcOff + 1] * sA + tileScratch[dstOff + 1] * inv);
- tileScratch[dstOff + 2] = Math.round(srcData[srcOff + 2] * sA + tileScratch[dstOff + 2] * inv);
- tileScratch[dstOff + 3] = Math.min(255, Math.round(tileScratch[dstOff + 3] * inv + effA));
- }
- }
- }
- packRGBATo8Bit(tileScratch, tile.data);
- }
-
- tile.solidColorU32 = undefined;
- tile.dirty = true;
- tile.version = allocateTileVersion();
- this.markLodAncestorsDirty(layerId, tx, ty);
- anyModified = true;
- }
- }
-
- if (anyModified) {
- this.bumpLayerVersion(layerId);
- if (!suppressNotify) {
- this.notifyChange();
- }
- }
- return anyModified;
- }
-
- public readImageData(
- layerId: string,
- x: number,
- y: number,
- width: number,
- height: number
- ): { data: Uint8ClampedArray; width: number; height: number } {
- const outData = new Uint8ClampedArray(width * height * 4);
- if (width <= 0 || height <= 0) return { data: outData, width, height };
-
- const minTileX = pixelToTileCoord(x, 0);
- const minTileY = pixelToTileCoord(y, 0);
- const maxTileX = pixelToTileCoord(x + width - 1, 0);
- const maxTileY = pixelToTileCoord(y + height - 1, 0);
-
- for (let ty = minTileY; ty <= maxTileY; ty++) {
- const tileDocY = ty * TILE_SIZE;
- for (let tx = minTileX; tx <= maxTileX; tx++) {
- const tile = this.getTile(layerId, tx, ty, 0);
- if (!tile) continue;
-
- const tileDocX = tx * TILE_SIZE;
- const tileRGBA = this.getTileAsRGBA(tile);
-
- const interStartX = Math.max(x, tileDocX);
- const interStartY = Math.max(y, tileDocY);
- const interEndX = Math.min(x + width, tileDocX + TILE_SIZE);
- const interEndY = Math.min(y + height, tileDocY + TILE_SIZE);
-
- for (let py = interStartY; py < interEndY; py++) {
- const tileLocalY = py - tileDocY;
- const tileLocalX = interStartX - tileDocX;
- const outLocalY = py - y;
- const outLocalX = interStartX - x;
- const copyWidth = interEndX - interStartX;
-
- const tileOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
- const outOffset = (outLocalY * width + outLocalX) * 4;
-
- outData.set(tileRGBA.subarray(tileOffset, tileOffset + copyWidth * 4), outOffset);
- }
- }
- }
-
- return { data: outData, width, height };
- }
-
- public renderLayerToCanvas(
- layerId: string,
- targetCanvas: HTMLCanvasElement,
- dirtyRect?: { x: number; y: number; width: number; height: number }
- ): void {
- const ctx = targetCanvas.getContext('2d');
- if (!ctx) return;
-
- let minX = 0;
- let minY = 0;
- let maxX = targetCanvas.width;
- let maxY = targetCanvas.height;
-
- if (dirtyRect) {
- minX = Math.max(0, Math.floor(dirtyRect.x));
- minY = Math.max(0, Math.floor(dirtyRect.y));
- maxX = Math.min(targetCanvas.width, Math.ceil(dirtyRect.x + dirtyRect.width));
- maxY = Math.min(targetCanvas.height, Math.ceil(dirtyRect.y + dirtyRect.height));
- }
-
- if (maxX <= minX || maxY <= minY) return;
-
- const minTileX = pixelToTileCoord(minX, 0);
- const minTileY = pixelToTileCoord(minY, 0);
- const maxTileX = pixelToTileCoord(maxX - 1, 0);
- const maxTileY = pixelToTileCoord(maxY - 1, 0);
-
- for (let ty = minTileY; ty <= maxTileY; ty++) {
- const tileDocY = ty * TILE_SIZE;
- const validH = Math.min(TILE_SIZE, targetCanvas.height - tileDocY);
- if (validH <= 0) continue;
- for (let tx = minTileX; tx <= maxTileX; tx++) {
- const tileDocX = tx * TILE_SIZE;
- const validW = Math.min(TILE_SIZE, targetCanvas.width - tileDocX);
- if (validW <= 0) continue;
- const tile = this.getTile(layerId, tx, ty, 0);
- if (!tile) {
- ctx.clearRect(tileDocX, tileDocY, validW, validH);
- continue;
- }
-
- const rgba = this.getTileAsRGBA(tile);
- if (typeof ImageData !== 'undefined') {
- const clamped = new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, BYTES_32BIT);
- const imgData = new ImageData(clamped, TILE_SIZE, TILE_SIZE);
- ctx.putImageData(imgData, tileDocX, tileDocY, 0, 0, validW, validH);
- }
- }
- }
- }
-
- /**
- * Populates a temporary (or caller-supplied pooled) HTMLCanvasElement strictly sized to `rect` from tiles.
- * When `targetCanvas` is omitted, caller must release the returned canvas via `releaseTemporaryCanvas(canvas)`.
- */
- public createRegionCanvas(
- layerId: string,
- rect: { x: number; y: number; width: number; height: number },
- targetCanvas?: HTMLCanvasElement | null
- ): HTMLCanvasElement | null {
- if (typeof document === 'undefined' || rect.width <= 0 || rect.height <= 0) return null;
- const w = Math.max(1, Math.ceil(rect.width));
- const h = Math.max(1, Math.ceil(rect.height));
- const canvas = targetCanvas || document.createElement('canvas');
- const resized = canvas.width !== w || canvas.height !== h;
- if (canvas.width !== w) canvas.width = w;
- if (canvas.height !== h) canvas.height = h;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return canvas;
- if (!resized) {
- if (typeof ctx.resetTransform === 'function') {
- ctx.resetTransform();
- } else {
- ctx.setTransform(1, 0, 0, 1, 0, 0);
- }
- ctx.clearRect(0, 0, w, h);
- }
-
- if (this.hasLayerTiles(layerId) && typeof ImageData !== 'undefined') {
- const originX = Math.floor(rect.x);
- const originY = Math.floor(rect.y);
- const minTileX = pixelToTileCoord(originX, 0);
- const minTileY = pixelToTileCoord(originY, 0);
- const maxTileX = pixelToTileCoord(originX + w - 1, 0);
- const maxTileY = pixelToTileCoord(originY + h - 1, 0);
-
- for (let ty = minTileY; ty <= maxTileY; ty++) {
- const tileDocY = ty * TILE_SIZE;
- const interStartY = Math.max(originY, tileDocY);
- const interEndY = Math.min(originY + h, tileDocY + TILE_SIZE);
- const dirtyH = interEndY - interStartY;
- if (dirtyH <= 0) continue;
- const dirtyY = interStartY - tileDocY;
-
- for (let tx = minTileX; tx <= maxTileX; tx++) {
- const tile = this.getTile(layerId, tx, ty, 0);
- if (!tile) continue;
-
- const tileDocX = tx * TILE_SIZE;
- const interStartX = Math.max(originX, tileDocX);
- const interEndX = Math.min(originX + w, tileDocX + TILE_SIZE);
- const dirtyW = interEndX - interStartX;
- if (dirtyW <= 0) continue;
- const dirtyX = interStartX - tileDocX;
-
- const rgba = this.getTileAsRGBA(tile);
- const clamped = new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, BYTES_32BIT);
- const imgData = new ImageData(clamped, TILE_SIZE, TILE_SIZE);
- ctx.putImageData(
- imgData,
- tileDocX - originX,
- tileDocY - originY,
- dirtyX,
- dirtyY,
- dirtyW,
- dirtyH
- );
- }
- }
- }
- return canvas;
+ this.notifyChange();
}
- /**
- * Materializes a full-layer temporary HTMLCanvasElement from tiles (for export/filters).
- * Caller MUST release it immediately after use via `releaseTemporaryCanvas(canvas)`.
- */
- public exportLayerToCanvas(layerId: string, width: number, height: number): HTMLCanvasElement | null {
- if (typeof document === 'undefined' || width <= 0 || height <= 0) return null;
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- if (this.hasLayerTiles(layerId)) {
- this.renderLayerToCanvas(layerId, canvas);
+ public deleteTile(layerId: string, tileX: number, tileY: number, lod: number = 0): void {
+ const key = getTileKey(layerId, tileX, tileY, lod);
+ const tile = this.tiles.get(key);
+ if (tile) {
+ if ((tile.lod ?? 0) === 0) tileSnapshotOps.unregisterLod0Tile(this.host, tile);
+ this.memoryManager?.notifyTileFreed(tile);
+ this.tiles.delete(key);
+ if (lod === 0) {
+ this.markLodAncestorsDirty(layerId, tileX, tileY);
+ this.bumpLayerVersion(layerId);
+ }
}
- return canvas;
}
- /**
- * Ensures mipmap tiles at `targetLod` (0..3) exist and are up-to-date for all populated regions of `layerId`.
- */
- public getOrBuildLodTiles(layerId: string, targetLod: number): TileBuffer[] {
- const lod = Math.max(0, Math.min(3, Math.floor(targetLod)));
+ public getLayerTiles(layerId: string, lod: number = 0): TileBuffer[] {
if (lod === 0) {
- return this.getLayerTiles(layerId);
- }
-
- const occ = this.layerLodOccupancy.get(layerId);
- const lodOccMap = occ ? occ[lod - 1] : null;
- if (!lodOccMap || lodOccMap.size === 0) {
- return this.getLayerTiles(layerId, lod);
+ const set = this.layerLod0Tiles.get(layerId);
+ return set ? Array.from(set) : [];
}
-
const result: TileBuffer[] = [];
- for (const packed of lodOccMap.keys()) {
- const tx = unpackTileCoordX(packed);
- const ty = unpackTileCoordY(packed);
- let tile = this.getTile(layerId, tx, ty, lod);
- if (!tile || tile.data === null || this.isLodTileDirty(layerId, tx, ty, lod)) {
- tile = this.generateLodTile(layerId, tx, ty, lod);
- }
- if (tile && tile.data !== null) {
+ for (const tile of this.tiles.values()) {
+ if (tile.layerId === layerId && (tile.lod ?? 0) === lod) {
result.push(tile);
}
}
return result;
}
- /**
- * Ensures LOD 3 mipmap tiles exist and are up-to-date for all populated regions of `layerId`.
- */
- public getOrBuildLod3Tiles(layerId: string): TileBuffer[] {
- return this.getOrBuildLodTiles(layerId, 3);
+ public getTilesInBounds(layerId: string, minX: number, minY: number, maxX: number, maxY: number, lod: number = 0): TileBuffer[] {
+ return tileIOOps.getTilesInBounds(this.host, layerId, minX, minY, maxX, maxY, lod);
}
- /**
- * Generates a layer thumbnail directly from LOD 3 mipmap tiles (1/8 resolution: 2048px per tile).
- * Completely bypasses full-size canvas allocation and full-resolution pixel reads.
- */
- public generateThumbnail(
- layerId: string,
- thumbWidth: number,
- thumbHeight: number,
- docDimensions: { width: number; height: number },
- preserveAlpha: boolean = true
- ): string {
- if (typeof document === 'undefined') return '';
- if (!this.thumbCanvas) {
- this.thumbCanvas = document.createElement('canvas');
- }
- const canvas = this.thumbCanvas;
- if (canvas.width !== thumbWidth) canvas.width = thumbWidth;
- if (canvas.height !== thumbHeight) canvas.height = thumbHeight;
- const ctx = canvas.getContext('2d');
- if (!ctx) return '';
-
- const docW = Math.max(1, docDimensions.width);
- const docH = Math.max(1, docDimensions.height);
-
- const tiles = this.getOrBuildLod3Tiles(layerId);
-
- if (tiles.length === 0) {
- if (preserveAlpha) {
- ctx.clearRect(0, 0, thumbWidth, thumbHeight);
- return canvas.toDataURL('image/png');
- }
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, thumbWidth, thumbHeight);
- return canvas.toDataURL('image/jpeg', 0.65);
- }
-
- const renderLod = 3;
- const lodDocSize = TILE_SIZE << renderLod; // 2048 document pixels per LOD 3 tile
- const thumbImg = ctx.createImageData(thumbWidth, thumbHeight);
- const outData = thumbImg.data;
- if (!preserveAlpha) {
- outData.fill(255);
- }
- const scaleX = docW / thumbWidth;
- const scaleY = docH / thumbHeight;
-
- for (const tile of tiles) {
- const tileDocX = tile.tileX * lodDocSize;
- const tileDocY = tile.tileY * lodDocSize;
-
- const x0 = Math.max(0, Math.floor((tileDocX / docW) * thumbWidth));
- const y0 = Math.max(0, Math.floor((tileDocY / docH) * thumbHeight));
- const x1 = Math.min(thumbWidth, Math.ceil(((tileDocX + lodDocSize) / docW) * thumbWidth));
- const y1 = Math.min(thumbHeight, Math.ceil(((tileDocY + lodDocSize) / docH) * thumbHeight));
-
- if (x0 >= x1 || y0 >= y1) continue;
-
- const rgba = this.getTileAsRGBA(tile);
-
- for (let py = y0; py < y1; py++) {
- const docY = (py + 0.5) * scaleY;
- const ly = Math.min(TILE_SIZE - 1, Math.max(0, Math.floor(((docY - tileDocY) / lodDocSize) * TILE_SIZE)));
- const ly2 = Math.min(TILE_SIZE - 1, ly + 1);
- for (let px = x0; px < x1; px++) {
- const docX = (px + 0.5) * scaleX;
- const lx = Math.min(TILE_SIZE - 1, Math.max(0, Math.floor(((docX - tileDocX) / lodDocSize) * TILE_SIZE)));
- const lx2 = Math.min(TILE_SIZE - 1, lx + 1);
-
- let srcIdx = (ly * TILE_SIZE + lx) * 4;
- if (rgba[srcIdx + 3] === 0) {
- const alt1 = (ly * TILE_SIZE + lx2) * 4;
- const alt2 = (ly2 * TILE_SIZE + lx) * 4;
- const alt3 = (ly2 * TILE_SIZE + lx2) * 4;
- if (rgba[alt1 + 3] > 0) srcIdx = alt1;
- else if (rgba[alt2 + 3] > 0) srcIdx = alt2;
- else if (rgba[alt3 + 3] > 0) srcIdx = alt3;
- }
-
- const sa = rgba[srcIdx + 3];
- if (sa > 0) {
- const dstIdx = (py * thumbWidth + px) * 4;
- if (preserveAlpha || sa === 255) {
- outData[dstIdx] = rgba[srcIdx];
- outData[dstIdx + 1] = rgba[srcIdx + 1];
- outData[dstIdx + 2] = rgba[srcIdx + 2];
- outData[dstIdx + 3] = sa;
- } else {
- const a = sa / 255;
- const inv = 1 - a;
- outData[dstIdx] = Math.round(rgba[srcIdx] * a + 255 * inv);
- outData[dstIdx + 1] = Math.round(rgba[srcIdx + 1] * a + 255 * inv);
- outData[dstIdx + 2] = Math.round(rgba[srcIdx + 2] * a + 255 * inv);
- outData[dstIdx + 3] = 255;
- }
- }
- }
- }
- }
-
- ctx.putImageData(thumbImg, 0, 0);
- return preserveAlpha ? canvas.toDataURL('image/png') : canvas.toDataURL('image/jpeg', 0.65);
+ public getIntersectingCoords(minX: number, minY: number, maxX: number, maxY: number, lod: number = 0): Array<{ tileX: number; tileY: number }> {
+ return tileIOOps.getIntersectingCoords(minX, minY, maxX, maxY, lod);
}
- // ==========================================================================
- // On-Demand Mipmap Pyramid Management
- // ==========================================================================
+ public getTileAsRGBA(tile: TileBuffer): Uint8ClampedArray {
+ return tileIOOps.getTileAsRGBA(this.host, tile);
+ }
- public isLodTileDirty(layerId: string, tileX: number, tileY: number, lod: number): boolean {
- if (lod <= 0) return false;
- return this.dirtyLodTiles.has(getTileKey(layerId, tileX, tileY, lod));
+ public writeImageData(
+ layerId: string,
+ imgData: { data: Uint8ClampedArray | Uint8Array; width: number; height: number },
+ destX: number,
+ destY: number,
+ format?: TileFormat,
+ suppressNotify: boolean = false
+ ): { minTileX: number; minTileY: number; maxTileX: number; maxTileY: number } {
+ return tileIOOps.writeImageData(this.host, layerId, imgData, destX, destY, format, suppressNotify);
}
- public markLodAncestorsDirty(layerId: string, tileX: number, tileY: number): void {
- let tx = tileX;
- let ty = tileY;
- for (let lod = 1; lod <= 3; lod++) {
- tx = tx >> 1;
- ty = ty >> 1;
- const key = getTileKey(layerId, tx, ty, lod);
- this.dirtyLodTiles.add(key);
- const existing = this.tiles.get(key);
- if (existing) {
- existing.dirty = true;
- }
- }
+ public compositeStrokeToTiles(options: CompositeStrokeOptions): boolean {
+ return compositeStrokeOp(this.host, options);
}
- /**
- * Generates or downsamples a specific LOD tile from its 4 child tiles at LOD - 1.
- */
- public generateLodTile(layerId: string, lodTx: number, lodTy: number, targetLod: number): TileBuffer | null {
- if (targetLod <= 0) {
- return this.getTile(layerId, lodTx, lodTy, 0);
- }
+ public readImageData(layerId: string, x: number, y: number, width: number, height: number): { data: Uint8ClampedArray; width: number; height: number } {
+ return tileIOOps.readImageData(this.host, layerId, x, y, width, height);
+ }
- const key = getTileKey(layerId, lodTx, lodTy, targetLod);
+ public renderLayerToCanvas(layerId: string, targetCanvas: HTMLCanvasElement, dirtyRect?: { x: number; y: number; width: number; height: number }): void {
+ tileRenderOps.renderLayerToCanvas(this.host, layerId, targetCanvas, dirtyRect);
+ }
- // O(1) empty-region fast-out: if no LOD 0 tile exists anywhere under this LOD node,
- // never recurse or allocate a temporary 256KB TileBuffer.
- if (!this.hasPopulatedLodTile(layerId, lodTx, lodTy, targetLod)) {
- const stale = this.tiles.get(key);
- if (stale) {
- this.memoryManager?.notifyTileFreed(stale);
- this.tiles.delete(key);
- }
- this.dirtyLodTiles.delete(key);
- return null;
- }
+ public createRegionCanvas(layerId: string, rect: { x: number; y: number; width: number; height: number }, targetCanvas?: HTMLCanvasElement | null): HTMLCanvasElement | null {
+ return tileRenderOps.createRegionCanvas(this.host, layerId, rect, targetCanvas);
+ }
- const childLod = targetLod - 1;
- const cX0 = lodTx << 1;
- const cY0 = lodTy << 1;
-
- let c00 = this.getTile(layerId, cX0, cY0, childLod);
- let c10 = this.getTile(layerId, cX0 + 1, cY0, childLod);
- let c01 = this.getTile(layerId, cX0, cY0 + 1, childLod);
- let c11 = this.getTile(layerId, cX0 + 1, cY0 + 1, childLod);
-
- if (childLod > 0) {
- if (this.hasPopulatedLodTile(layerId, cX0, cY0, childLod)) {
- if (!c00 || c00.data === null || this.isLodTileDirty(layerId, cX0, cY0, childLod)) {
- c00 = this.generateLodTile(layerId, cX0, cY0, childLod);
- }
- } else {
- c00 = null;
- }
- if (this.hasPopulatedLodTile(layerId, cX0 + 1, cY0, childLod)) {
- if (!c10 || c10.data === null || this.isLodTileDirty(layerId, cX0 + 1, cY0, childLod)) {
- c10 = this.generateLodTile(layerId, cX0 + 1, cY0, childLod);
- }
- } else {
- c10 = null;
- }
- if (this.hasPopulatedLodTile(layerId, cX0, cY0 + 1, childLod)) {
- if (!c01 || c01.data === null || this.isLodTileDirty(layerId, cX0, cY0 + 1, childLod)) {
- c01 = this.generateLodTile(layerId, cX0, cY0 + 1, childLod);
- }
- } else {
- c01 = null;
- }
- if (this.hasPopulatedLodTile(layerId, cX0 + 1, cY0 + 1, childLod)) {
- if (!c11 || c11.data === null || this.isLodTileDirty(layerId, cX0 + 1, cY0 + 1, childLod)) {
- c11 = this.generateLodTile(layerId, cX0 + 1, cY0 + 1, childLod);
- }
- } else {
- c11 = null;
- }
- }
+ public exportLayerToCanvas(layerId: string, width: number, height: number): HTMLCanvasElement | null {
+ return tileRenderOps.exportLayerToCanvas(this.host, layerId, width, height);
+ }
- const firstChild =
- (c00 && c00.data !== null ? c00 : null) ||
- (c10 && c10.data !== null ? c10 : null) ||
- (c01 && c01.data !== null ? c01 : null) ||
- (c11 && c11.data !== null ? c11 : null);
+ public getOrBuildLodTiles(layerId: string, targetLod: number): TileBuffer[] {
+ return mipmapOps.getOrBuildLodTiles(this.host, layerId, targetLod);
+ }
- let tile = this.tiles.get(key);
- if (!firstChild) {
- if (tile) {
- this.memoryManager?.notifyTileFreed(tile);
- this.tiles.delete(key);
- }
- this.dirtyLodTiles.delete(key);
- return null;
- }
+ public getOrBuildLod3Tiles(layerId: string): TileBuffer[] {
+ return this.getOrBuildLodTiles(layerId, 3);
+ }
- // Ephemeral display LOD > 0 tiles for monochrome-1bit layers use box-filtered color-32bit
- // coverage instead of bitwise-OR dilation so zoomed-out lines match live mipmapped drafts.
- const format: TileFormat =
- firstChild.format === 'monochrome-1bit' ? 'color-32bit' : firstChild.format;
+ public generateThumbnail(layerId: string, thumbWidth: number, thumbHeight: number, docDimensions: { width: number; height: number }, preserveAlpha: boolean = true): string {
+ return tileRenderOps.generateThumbnail(this.host, layerId, thumbWidth, thumbHeight, docDimensions, preserveAlpha);
+ }
- let allocatedNew = false;
- if (!tile) {
- tile = createTileBuffer(layerId, lodTx, lodTy, format, targetLod);
- this.tiles.set(key, tile);
- allocatedNew = true;
- } else if (tile.format !== format) {
- if (tile.data !== null) {
- this.memoryManager?.notifyTileFreed(tile);
- }
- tile.format = format;
- tile.data = new Uint8Array(getTileByteSize(format));
- allocatedNew = true;
- } else if (tile.data === null) {
- allocatedNew = true;
- }
+ public isLodTileDirty(layerId: string, tileX: number, tileY: number, lod: number): boolean {
+ return mipmapOps.isLodTileDirty(this.host, layerId, tileX, tileY, lod);
+ }
- const success = downsample2x2ToParentTile([c00, c10, c01, c11], tile);
- if (!success) {
- if (!allocatedNew) {
- this.memoryManager?.notifyTileFreed(tile);
- }
- this.tiles.delete(key);
- this.dirtyLodTiles.delete(key);
- return null;
- }
+ public markLodAncestorsDirty(layerId: string, tileX: number, tileY: number): void {
+ mipmapOps.markLodAncestorsDirty(this.host, layerId, tileX, tileY);
+ }
- if (allocatedNew) {
- this.memoryManager?.notifyTileAllocated(tile);
- }
- tile.dirty = true;
- tile.version = allocateTileVersion();
- this.dirtyLodTiles.delete(key);
- return tile;
+ public generateLodTile(layerId: string, lodTx: number, lodTy: number, targetLod: number): TileBuffer | null {
+ return mipmapOps.generateLodTile(this.host, layerId, lodTx, lodTy, targetLod);
}
- /**
- * Progressively downsamples up to `maxCount` dirty mipmap tiles.
- */
public updateDirtyMipmaps(maxCount: number = 16): number {
- let count = 0;
- const keys = Array.from(this.dirtyLodTiles);
-
- // Process lower LODs (LOD 1) before higher LODs (LOD 2, 3)
- keys.sort((a, b) => {
- const pa = parseTileKey(a);
- const pb = parseTileKey(b);
- return pa.lod - pb.lod;
- });
-
- for (const key of keys) {
- if (count >= maxCount) break;
- this.dirtyLodTiles.delete(key);
- const { layerId, tileX, tileY, lod } = parseTileKey(key);
- this.generateLodTile(layerId, tileX, tileY, lod);
- count++;
- }
-
- return count;
+ return mipmapOps.updateDirtyMipmaps(this.host, maxCount);
}
- /**
- * Flushes all pending dirty mipmap tiles immediately.
- */
public flushMipmaps(layerId?: string): void {
- const keys = Array.from(this.dirtyLodTiles);
- keys.sort((a, b) => {
- const pa = parseTileKey(a);
- const pb = parseTileKey(b);
- return pa.lod - pb.lod;
- });
-
- for (const key of keys) {
- const { layerId: lId, tileX, tileY, lod } = parseTileKey(key);
- if (!layerId || lId === layerId) {
- this.dirtyLodTiles.delete(key);
- this.generateLodTile(lId, tileX, tileY, lod);
- }
- }
+ mipmapOps.flushMipmaps(this.host, layerId);
}
- public fillLayerSolidColor(
- layerId: string,
- width: number,
- height: number,
- colorCss: string,
- format?: TileFormat
- ): void {
- const lower = (colorCss || '').trim().toLowerCase();
- if (!lower || lower === 'transparent') {
- this.clearLayer(layerId);
- this.ingestedLayers.add(layerId);
- if (format) this.setLayerFormat(layerId, format);
- return;
- }
- if (lower === '#ffffff' || lower === '#fff' || lower === 'white') {
- this.fillLayerSolidWhite(layerId, width, height, format);
- return;
- }
-
- let r = 255, g = 255, b = 255, a = 255;
- if (lower.startsWith('#')) {
- const hex = lower.slice(1);
- if (hex.length === 3) {
- r = parseInt(hex[0] + hex[0], 16) || 0;
- g = parseInt(hex[1] + hex[1], 16) || 0;
- b = parseInt(hex[2] + hex[2], 16) || 0;
- } else if (hex.length >= 6) {
- r = parseInt(hex.slice(0, 2), 16) || 0;
- g = parseInt(hex.slice(2, 4), 16) || 0;
- b = parseInt(hex.slice(4, 6), 16) || 0;
- if (hex.length === 8) {
- a = parseInt(hex.slice(6, 8), 16) || 255;
- }
- }
- } else if (lower === 'black') {
- r = 0; g = 0; b = 0;
- }
-
- this.clearLayer(layerId);
- this.ingestedLayers.add(layerId);
- if (format) this.setLayerFormat(layerId, format);
- if (width <= 0 || height <= 0) return;
-
- const targetFormat = format || this.getLayerFormat(layerId);
- const pixelU32 = isLittleEndian
- ? ((a << 24) | (b << 16) | (g << 8) | r) >>> 0
- : ((r << 24) | (g << 16) | (b << 8) | a) >>> 0;
- const grayVal = Math.round((r * 299 + g * 587 + b * 114) / 1000);
- const isInk1Bit = a >= 24 && grayVal < 128;
-
- if (targetFormat === 'monochrome-1bit' && !isInk1Bit) {
- this.notifyChange();
- return;
- }
-
- const maxTileX = pixelToTileCoord(width - 1, 0);
- const maxTileY = pixelToTileCoord(height - 1, 0);
-
- for (let ty = 0; ty <= maxTileY; ty++) {
- const tileDocY = ty * TILE_SIZE;
- const validH = Math.min(TILE_SIZE, height - tileDocY);
- for (let tx = 0; tx <= maxTileX; tx++) {
- const tileDocX = tx * TILE_SIZE;
- const validW = Math.min(TILE_SIZE, width - tileDocX);
- const tile = this.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
- if (!tile.data) {
- tile.data = new Uint8Array(getTileByteSize(tile.format));
- this.memoryManager?.notifyTileAllocated(tile);
- }
- if (tile.format === 'color-32bit') {
- const dst32 = new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS);
- if (validW === TILE_SIZE && validH === TILE_SIZE) {
- dst32.fill(pixelU32);
- tile.solidColorU32 = pixelU32;
- } else {
- tile.solidColorU32 = undefined;
- dst32.fill(0);
- for (let y = 0; y < validH; y++) {
- const rowStart = y * TILE_SIZE;
- dst32.fill(pixelU32, rowStart, rowStart + validW);
- }
- }
- } else if (tile.format === 'grayscale-8bit') {
- tile.solidColorU32 = undefined;
- if (validW === TILE_SIZE && validH === TILE_SIZE) {
- tile.data.fill(grayVal);
- } else {
- tile.data.fill(0);
- for (let y = 0; y < validH; y++) {
- const rowStart = y * TILE_SIZE;
- tile.data.fill(grayVal, rowStart, rowStart + validW);
- }
- }
- } else {
- tile.solidColorU32 = undefined;
- tile.data.fill(0);
- for (let y = 0; y < validH; y++) {
- for (let x = 0; x < validW; x++) {
- setPixel1Bit(tile.data, x, y, true);
- }
- }
- }
- tile.dirty = true;
- tile.version = allocateTileVersion();
- this.markLodAncestorsDirty(layerId, tx, ty);
- }
- }
- this.bumpLayerVersion(layerId);
- this.notifyChange();
+ public fillLayerSolidColor(layerId: string, width: number, height: number, colorCss: string, format?: TileFormat): void {
+ tileFillOps.fillLayerSolidColor(this.host, layerId, width, height, colorCss, format);
}
public fillLayerSolidWhite(layerId: string, width: number, height: number, format?: TileFormat): void {
- this.clearLayer(layerId);
- this.ingestedLayers.add(layerId);
- if (format) {
- this.setLayerFormat(layerId, format);
- }
- if (width <= 0 || height <= 0) return;
-
- const targetFormat = format || this.getLayerFormat(layerId);
- if (targetFormat === 'monochrome-1bit') {
- // Solid white in monochrome-1bit has 0 black ink bits
- this.notifyChange();
- return;
- }
-
- const maxTileX = pixelToTileCoord(width - 1, 0);
- const maxTileY = pixelToTileCoord(height - 1, 0);
-
- for (let ty = 0; ty <= maxTileY; ty++) {
- const tileDocY = ty * TILE_SIZE;
- const validH = Math.min(TILE_SIZE, height - tileDocY);
- for (let tx = 0; tx <= maxTileX; tx++) {
- const tileDocX = tx * TILE_SIZE;
- const validW = Math.min(TILE_SIZE, width - tileDocX);
- const tile = this.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
- if (!tile.data) {
- tile.data = new Uint8Array(getTileByteSize(tile.format));
- this.memoryManager?.notifyTileAllocated(tile);
- }
- if (validW === TILE_SIZE && validH === TILE_SIZE) {
- if (tile.format === 'color-32bit') {
- new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS).fill(PAPER_WHITE_U32);
- tile.solidColorU32 = PAPER_WHITE_U32;
- } else {
- tile.data.fill(255);
- tile.solidColorU32 = undefined;
- }
- } else if (tile.format === 'color-32bit') {
- tile.solidColorU32 = undefined;
- const dst32 = new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS);
- dst32.fill(0);
- for (let y = 0; y < validH; y++) {
- const rowStart = y * TILE_SIZE;
- dst32.fill(PAPER_WHITE_U32, rowStart, rowStart + validW);
- }
- } else {
- tile.solidColorU32 = undefined;
- tile.data.fill(0);
- for (let y = 0; y < validH; y++) {
- const rowStart = y * TILE_SIZE;
- tile.data.fill(255, rowStart, rowStart + validW);
- }
- }
- tile.dirty = true;
- tile.version = allocateTileVersion();
- this.markLodAncestorsDirty(layerId, tx, ty);
- }
- }
- this.bumpLayerVersion(layerId);
- this.notifyChange();
+ tileFillOps.fillLayerSolidWhite(this.host, layerId, width, height, format);
}
public ingestCanvas(layerId: string, canvas: HTMLCanvasElement, format?: TileFormat): void {
- if (canvas.width <= 0 || canvas.height <= 0) return;
- if (format) {
- this.setLayerFormat(layerId, format);
- }
- if ((canvas as any).__isBlank) {
- this.clearLayer(layerId);
- this.ingestedLayers.add(layerId);
- if (format) {
- this.setLayerFormat(layerId, format);
- }
- return;
- }
- if ((canvas as any).__isSolidWhite) {
- this.fillLayerSolidWhite(layerId, canvas.width, canvas.height, format);
- return;
- }
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return;
-
- this.clearLayer(layerId);
- this.ingestedLayers.add(layerId);
- if (format) {
- this.setLayerFormat(layerId, format);
- }
- const w = canvas.width;
- const h = canvas.height;
- if (w * h <= 1024 * 1024) {
- const imgData = ctx.getImageData(0, 0, w, h);
- this.writeImageData(layerId, imgData, 0, 0, format, true);
- } else {
- const stripH = TILE_SIZE;
- for (let y = 0; y < h; y += stripH) {
- const curH = Math.min(stripH, h - y);
- const stripData = ctx.getImageData(0, y, w, curH);
- this.writeImageData(layerId, stripData, 0, y, format, true);
- }
- }
- this.notifyChange();
+ tileFillOps.ingestCanvas(this.host, layerId, canvas, format);
}
public clearLayer(layerId: string): void {
- this.ingestedLayers.delete(layerId);
- this.layerLod0Tiles.delete(layerId);
- this.layerLodOccupancy.delete(layerId);
- const prefix = `${layerId}:`;
- const toDelete: string[] = [];
- for (const [key, tile] of this.tiles.entries()) {
- if (key.startsWith(prefix)) {
- toDelete.push(key);
- if (this.memoryManager) {
- this.memoryManager.notifyTileFreed(tile);
- }
- }
- }
- for (const key of toDelete) {
- this.tiles.delete(key);
- this.dirtyLodTiles.delete(key);
- }
- this.bumpLayerVersion(layerId);
- this.notifyChange();
+ tileSnapshotOps.clearLayer(this.host, layerId);
}
public cloneLayer(srcLayerId: string, dstLayerId: string): void {
- this.clearLayer(dstLayerId);
- this.ingestedLayers.add(dstLayerId);
- this.setLayerFormat(dstLayerId, this.getLayerFormat(srcLayerId));
- const srcTiles = this.getLayerTiles(srcLayerId, 0);
- for (const srcTile of srcTiles) {
- if (!srcTile.data && srcTile.isPagedToDisk && this.memoryManager) {
- void this.memoryManager.requestTileData(srcTile);
- }
- const clonedData = srcTile.data ? new Uint8Array(srcTile.data.length) : new Uint8Array(getTileByteSize(srcTile.format));
- if (srcTile.data) clonedData.set(srcTile.data);
-
- const clonedTile: TileBuffer = {
- layerId: dstLayerId,
- tileX: srcTile.tileX,
- tileY: srcTile.tileY,
- format: srcTile.format,
- data: clonedData,
- dirty: true,
- version: allocateTileVersion(),
- isPagedToDisk: false,
- lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
- lod: 0,
- solidColorU32: srcTile.solidColorU32,
- };
- this.setTile(dstLayerId, srcTile.tileX, srcTile.tileY, clonedTile);
- }
+ tileSnapshotOps.cloneLayer(this.host, srcLayerId, dstLayerId);
}
- public getMemoryStats(): {
- totalBytes: number;
- activeBytes: number;
- pagedBytes: number;
- tileCount: number;
- activeTileCount: number;
- pagedTileCount: number;
- formatCounts: Record<TileFormat, number>;
- lodCounts: Record<number, number>;
- } {
- let totalBytes = 0;
- let activeBytes = 0;
- let pagedBytes = 0;
- let activeTileCount = 0;
- let pagedTileCount = 0;
-
- const formatCounts: Record<TileFormat, number> = {
- 'monochrome-1bit': 0,
- 'grayscale-8bit': 0,
- 'color-32bit': 0,
- };
- const lodCounts: Record<number, number> = { 0: 0, 1: 0, 2: 0, 3: 0 };
-
- for (const tile of this.tiles.values()) {
- const bSize = getTileByteSize(tile.format);
- totalBytes += bSize;
- lodCounts[tile.lod ?? 0] = (lodCounts[tile.lod ?? 0] || 0) + 1;
-
- if (tile.data !== null) {
- activeBytes += tile.data.byteLength;
- activeTileCount++;
- formatCounts[tile.format]++;
- } else if (tile.isPagedToDisk) {
- pagedBytes += bSize;
- pagedTileCount++;
- }
- }
-
- return {
- totalBytes,
- activeBytes,
- pagedBytes,
- tileCount: this.tiles.size,
- activeTileCount,
- pagedTileCount,
- formatCounts,
- lodCounts,
- };
+ public getMemoryStats(): TileMemoryStats {
+ return tileSnapshotOps.getMemoryStats(this.host);
}
- public snapshotLayerTiles(
- layerId: string
- ): Map<string, { format: TileFormat; data: Uint8Array | null }> {
- const snapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>();
- for (const tile of this.getLayerTiles(layerId, 0)) {
- const key = getTileKey(layerId, tile.tileX, tile.tileY, 0);
- if (tile.data) {
- const copy = new Uint8Array(tile.data.length);
- copy.set(tile.data);
- snapshot.set(key, { format: tile.format, data: copy });
- } else {
- snapshot.set(key, { format: tile.format, data: null });
- }
- }
- return snapshot;
+ public snapshotLayerTiles(layerId: string): Map<string, TileSnapshotEntry> {
+ return tileSnapshotOps.snapshotLayerTiles(this.host, layerId);
}
- public snapshotTilesInRect(
- layerId: string,
- bounds: { x: number; y: number; width: number; height: number }
- ): Map<string, { format: TileFormat; data: Uint8Array | null }> {
- const snapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>();
- if (bounds.width <= 0 || bounds.height <= 0) return snapshot;
-
- const minTileX = pixelToTileCoord(bounds.x, 0);
- const minTileY = pixelToTileCoord(bounds.y, 0);
- const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1, 0);
- const maxTileY = pixelToTileCoord(bounds.y + bounds.height - 1, 0);
-
- const layerFormat = this.getLayerFormat(layerId);
-
- for (let ty = minTileY; ty <= maxTileY; ty++) {
- for (let tx = minTileX; tx <= maxTileX; tx++) {
- const key = getTileKey(layerId, tx, ty, 0);
- const tile = this.getTile(layerId, tx, ty, 0);
- if (tile && tile.data) {
- const copy = new Uint8Array(tile.data.length);
- copy.set(tile.data);
- snapshot.set(key, { format: tile.format, data: copy });
- } else {
- snapshot.set(key, { format: layerFormat, data: null });
- }
- }
- }
-
- return snapshot;
+ public snapshotTilesInRect(layerId: string, bounds: { x: number; y: number; width: number; height: number }): Map<string, TileSnapshotEntry> {
+ return tileSnapshotOps.snapshotTilesInRect(this.host, layerId, bounds);
}
- public computeDeltasFromSnapshot(
- beforeSnapshot: Map<string, { format: TileFormat; data: Uint8Array | null }>,
- layerId: string,
- bounds?: { x: number; y: number; width: number; height: number }
- ): TileDelta[] {
- const deltas: TileDelta[] = [];
- const keysToCheck = new Set<string>(beforeSnapshot.keys());
-
- if (beforeSnapshot.size === 0 && bounds && bounds.width > 0 && bounds.height > 0) {
- const minTileX = pixelToTileCoord(bounds.x, 0);
- const minTileY = pixelToTileCoord(bounds.y, 0);
- const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1, 0);
- const maxTileY = pixelToTileCoord(bounds.y + bounds.height - 1, 0);
- for (let ty = minTileY; ty <= maxTileY; ty++) {
- for (let tx = minTileX; tx <= maxTileX; tx++) {
- keysToCheck.add(getTileKey(layerId, tx, ty, 0));
- }
- }
- }
-
- for (const key of keysToCheck) {
- if (beforeSnapshot.size > 0 && !beforeSnapshot.has(key)) continue;
- const before = beforeSnapshot.get(key);
- const { tileX, tileY } = parseTileKey(key);
- const currentTile = this.getTile(layerId, tileX, tileY, 0);
-
- const beforeData = before ? before.data : null;
- const currentData = currentTile && currentTile.data ? currentTile.data : null;
- const format = currentTile ? currentTile.format : (before ? before.format : this.getLayerFormat(layerId));
-
- if (beforeData === null && currentData === null) continue;
-
- let changed = false;
- if ((beforeData === null) !== (currentData === null)) {
- changed = true;
- } else if (beforeData && currentData) {
- if (beforeData.byteLength !== currentData.byteLength) {
- changed = true;
- } else if (
- beforeData.byteLength % 4 === 0 &&
- beforeData.byteOffset % 4 === 0 &&
- currentData.byteOffset % 4 === 0
- ) {
- const len32 = beforeData.byteLength >>> 2;
- const b32 = new Uint32Array(beforeData.buffer, beforeData.byteOffset, len32);
- const c32 = new Uint32Array(currentData.buffer, currentData.byteOffset, len32);
- for (let i = 0; i < len32; i++) {
- if (b32[i] !== c32[i]) {
- changed = true;
- break;
- }
- }
- } else {
- for (let i = 0; i < beforeData.byteLength; i++) {
- if (beforeData[i] !== currentData[i]) {
- changed = true;
- break;
- }
- }
- }
- }
-
- if (changed) {
- deltas.push({
- key,
- format,
- beforeData,
- afterData: currentData ? new Uint8Array(currentData) : null,
- });
- }
- }
-
- return deltas;
+ public computeDeltasFromSnapshot(beforeSnapshot: Map<string, TileSnapshotEntry>, layerId: string, bounds?: { x: number; y: number; width: number; height: number }): TileDelta[] {
+ return tileSnapshotOps.computeDeltasFromSnapshot(this.host, beforeSnapshot, layerId, bounds);
}
public applyTileDeltas(deltas: TileDelta[], direction: 'undo' | 'redo'): void {
- for (const delta of deltas) {
- const { layerId, tileX, tileY } = parseTileKey(delta.key);
- const targetData = direction === 'undo' ? delta.beforeData : delta.afterData;
-
- if (!targetData) {
- this.deleteTile(layerId, tileX, tileY, 0);
- } else {
- let tile = this.getTile(layerId, tileX, tileY, 0);
- if (!tile) {
- tile = this.getOrCreateTile(layerId, tileX, tileY, delta.format, 0);
- }
- if (!tile.data || tile.data.byteLength !== targetData.byteLength) {
- if (tile.data) {
- this.memoryManager?.notifyTileFreed(tile);
- }
- tile.data = new Uint8Array(targetData.length);
- this.memoryManager?.notifyTileAllocated(tile);
- }
- tile.data.set(targetData);
- tile.solidColorU32 = undefined;
- tile.format = delta.format;
- this.setLayerFormat(layerId, delta.format);
- tile.dirty = true;
- tile.version = allocateTileVersion();
- this.markLodAncestorsDirty(layerId, tileX, tileY);
- this.bumpLayerVersion(layerId);
- }
- }
- this.notifyChange();
+ tileSnapshotOps.applyTileDeltas(this.host, deltas, direction);
}
public clearAll(): void {
- if (this.memoryManager) {
- for (const tile of this.tiles.values()) {
- this.memoryManager.notifyTileFreed(tile);
- }
- }
- this.tiles.clear();
- this.layerLod0Tiles.clear();
- this.layerLodOccupancy.clear();
- this.layerFormats.clear();
- this.ingestedLayers.clear();
- this.dirtyLodTiles.clear();
- this.layerVersions.clear();
- this.gridEpoch++;
- this.contentVersion++;
- this.notifyChange(true);
+ tileSnapshotOps.clearAll(this.host);
}
public tilesIterable(): IterableIterator<TileBuffer> {
@@ -3212,537 +410,130 @@ export class SparseTileGrid {
}
public restoreFromSnapshot(tiles: TileBuffer[], layerFormats?: Map<string, TileFormat>): void {
- this.clearAll();
- if (layerFormats) {
- for (const [layerId, fmt] of layerFormats.entries()) {
- this.layerFormats.set(layerId, fmt);
- }
- }
- for (const tile of tiles) {
- if (tile.version > 0) {
- reserveTileVersion(tile.version);
- } else {
- tile.version = allocateTileVersion();
- }
- tile.dirty = true;
- this.tiles.set(getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0), tile);
- if ((tile.lod ?? 0) === 0) {
- this.registerLod0Tile(tile);
- }
- if (this.memoryManager) {
- this.memoryManager.notifyTileAllocated(tile);
- }
- if ((tile.lod ?? 0) === 0) {
- this.bumpLayerVersion(tile.layerId);
- }
- }
- this.notifyChange(true);
+ tileSnapshotOps.restoreFromSnapshot(this.host, tiles, layerFormats);
}
-}
-
-// ============================================================================
-// Snapshot Serialization
-// ============================================================================
-const FORMAT_TO_BYTE: Record<TileFormat, number> = {
- 'monochrome-1bit': 0,
- 'grayscale-8bit': 1,
- 'color-32bit': 2,
-};
-
-const BYTE_TO_FORMAT: TileFormat[] = [
- 'monochrome-1bit',
- 'grayscale-8bit',
- 'color-32bit',
-];
-
-const _sharedTileEncoder = new TextEncoder();
-
-function encodeLayerIdCached(cache: Map<string, Uint8Array>, layerId: string): Uint8Array {
- let bytes = cache.get(layerId);
- if (!bytes) {
- bytes = _sharedTileEncoder.encode(layerId);
- cache.set(layerId, bytes);
+ public getPixelRGBA(
+ layerId: string,
+ x: number,
+ y: number,
+ out?: [number, number, number, number]
+ ): [number, number, number, number] {
+ return tileOps.getPixelRGBA(this.host, layerId, x, y, out);
}
- return bytes;
-}
-export function serializeSparseTileGrid(grid: SparseTileGrid): Uint8Array {
- const layerKeyCache = new Map<string, Uint8Array>();
- const layerFormats = grid.getAllLayerFormats();
-
- let totalBytes = 4 + 1 + 4;
-
- const encodedFormats: Array<{ keyBytes: Uint8Array; format: TileFormat }> = [];
- for (const [layerId, fmt] of layerFormats.entries()) {
- const keyBytes = encodeLayerIdCached(layerKeyCache, layerId);
- encodedFormats.push({ keyBytes, format: fmt });
- totalBytes += 2 + keyBytes.length + 1;
- }
-
- totalBytes += 4;
-
- const encodedTiles: Array<{ keyBytes: Uint8Array; tile: TileBuffer; data: Uint8Array | null }> = [];
- for (const t of grid.tilesIterable()) {
- if ((t.lod ?? 0) !== 0) continue;
- const keyBytes = encodeLayerIdCached(layerKeyCache, t.layerId);
- const data = t.data;
- encodedTiles.push({ keyBytes, tile: t, data });
- const dataLen = data ? data.byteLength : 0;
- totalBytes += 2 + keyBytes.length + 4 + 4 + 1 + 4 + 4 + dataLen;
- }
-
- const out = new Uint8Array(totalBytes);
- const view = new DataView(out.buffer, out.byteOffset, totalBytes);
-
- let offset = 0;
- out[offset++] = 0x49; // 'I'
- out[offset++] = 0x4e; // 'N'
- out[offset++] = 0x4b; // 'K'
- out[offset++] = 0x47; // 'G'
- out[offset++] = 1; // Version
-
- view.setUint32(offset, encodedFormats.length, true);
- offset += 4;
-
- for (const item of encodedFormats) {
- view.setUint16(offset, item.keyBytes.length, true);
- offset += 2;
- out.set(item.keyBytes, offset);
- offset += item.keyBytes.length;
- out[offset++] = FORMAT_TO_BYTE[item.format] ?? 2;
- }
-
- view.setUint32(offset, encodedTiles.length, true);
- offset += 4;
-
- for (const item of encodedTiles) {
- const t = item.tile;
- view.setUint16(offset, item.keyBytes.length, true);
- offset += 2;
- out.set(item.keyBytes, offset);
- offset += item.keyBytes.length;
-
- view.setInt32(offset, t.tileX, true);
- offset += 4;
- view.setInt32(offset, t.tileY, true);
- offset += 4;
- out[offset++] = FORMAT_TO_BYTE[t.format] ?? 2;
- view.setUint32(offset, t.version, true);
- offset += 4;
-
- const data = item.data;
- const dataLen = data ? data.byteLength : 0;
- view.setUint32(offset, dataLen, true);
- offset += 4;
- if (data) {
- out.set(data, offset);
- offset += dataLen;
- }
+ public snapshotSingleTileInto(
+ layerId: string,
+ tileX: number,
+ tileY: number,
+ snapshotOut: Map<string, TileSnapshotEntry>
+ ): void {
+ tileOps.snapshotSingleTileInto(this.host, layerId, tileX, tileY, snapshotOut);
}
- return out;
-}
-
-/**
- * Time-sliced asynchronous SparseTileGrid serializer for background recovery checkpoints.
- * Yields to the browser event loop every ~4ms and supports cooperative cancellation
- * if the user resumes drawing mid-snapshot. Produces identical INKG v1 output.
- */
-export async function serializeSparseTileGridAsync(
- grid: SparseTileGrid,
- options?: { shouldAbort?: () => boolean; chunkBudgetMs?: number }
-): Promise<Uint8Array | null> {
- if (options?.shouldAbort?.()) return null;
-
- const budgetMs = options?.chunkBudgetMs ?? 4;
- const layerKeyCache = new Map<string, Uint8Array>();
- const layerFormats = grid.getAllLayerFormats();
-
- let totalBytes = 4 + 1 + 4;
-
- const encodedFormats: Array<{ keyBytes: Uint8Array; format: TileFormat }> = [];
- for (const [layerId, fmt] of layerFormats.entries()) {
- const keyBytes = encodeLayerIdCached(layerKeyCache, layerId);
- encodedFormats.push({ keyBytes, format: fmt });
- totalBytes += 2 + keyBytes.length + 1;
- }
-
- totalBytes += 4;
-
- // Capture immutable per-tile references (data ref + metadata) before yielding
- const encodedTiles: Array<{
- keyBytes: Uint8Array;
- tileX: number;
- tileY: number;
- formatByte: number;
- version: number;
- data: Uint8Array | null;
- }> = [];
-
- for (const t of grid.tilesIterable()) {
- if ((t.lod ?? 0) !== 0) continue;
- const keyBytes = encodeLayerIdCached(layerKeyCache, t.layerId);
- const data = t.data;
- encodedTiles.push({
- keyBytes,
- tileX: t.tileX,
- tileY: t.tileY,
- formatByte: FORMAT_TO_BYTE[t.format] ?? 2,
- version: t.version,
- data,
- });
- const dataLen = data ? data.byteLength : 0;
- totalBytes += 2 + keyBytes.length + 4 + 4 + 1 + 4 + 4 + dataLen;
- }
-
- if (options?.shouldAbort?.()) return null;
-
- const out = new Uint8Array(totalBytes);
- const view = new DataView(out.buffer, out.byteOffset, totalBytes);
-
- let offset = 0;
- out[offset++] = 0x49; // 'I'
- out[offset++] = 0x4e; // 'N'
- out[offset++] = 0x4b; // 'K'
- out[offset++] = 0x47; // 'G'
- out[offset++] = 1; // Version
-
- view.setUint32(offset, encodedFormats.length, true);
- offset += 4;
-
- for (const item of encodedFormats) {
- view.setUint16(offset, item.keyBytes.length, true);
- offset += 2;
- out.set(item.keyBytes, offset);
- offset += item.keyBytes.length;
- out[offset++] = FORMAT_TO_BYTE[item.format] ?? 2;
- }
-
- view.setUint32(offset, encodedTiles.length, true);
- offset += 4;
-
- const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
- let sliceStart = now();
-
- for (let i = 0; i < encodedTiles.length; i++) {
- const item = encodedTiles[i];
- view.setUint16(offset, item.keyBytes.length, true);
- offset += 2;
- out.set(item.keyBytes, offset);
- offset += item.keyBytes.length;
-
- view.setInt32(offset, item.tileX, true);
- offset += 4;
- view.setInt32(offset, item.tileY, true);
- offset += 4;
- out[offset++] = item.formatByte;
- view.setUint32(offset, item.version, true);
- offset += 4;
-
- const dataLen = item.data ? item.data.byteLength : 0;
- view.setUint32(offset, dataLen, true);
- offset += 4;
- if (item.data) {
- out.set(item.data, offset);
- offset += dataLen;
- }
-
- if ((i & 15) === 15 && i + 1 < encodedTiles.length && now() - sliceStart >= budgetMs) {
- await yieldToMain();
- if (options?.shouldAbort?.()) return null;
- sliceStart = now();
- }
+ public restoreLayerSnapshot(
+ layerId: string,
+ snapshot: Map<string, TileSnapshotEntry>,
+ suppressNotify: boolean = false
+ ): void {
+ tileOps.restoreLayerSnapshot(this.host, layerId, snapshot, suppressNotify);
}
- return out;
-}
-
-export function deserializeSparseTileGrid(grid: SparseTileGrid, buffer: Uint8Array): void {
- if (buffer.byteLength < 9) {
- throw new Error('Invalid SparseTileGrid buffer: too short');
- }
- if (
- buffer[0] !== 0x49 ||
- buffer[1] !== 0x4e ||
- buffer[2] !== 0x4b ||
- buffer[3] !== 0x47
- ) {
- throw new Error('Invalid SparseTileGrid buffer: bad magic');
- }
- const version = buffer[4];
- if (version !== 1) {
- throw new Error(`Unsupported SparseTileGrid version: ${version}`);
- }
-
- const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
- const decoder = new TextDecoder();
- let offset = 5;
-
- const formatCount = view.getUint32(offset, true);
- offset += 4;
-
- const layerFormats = new Map<string, TileFormat>();
- for (let i = 0; i < formatCount; i++) {
- const kLen = view.getUint16(offset, true);
- offset += 2;
- const kBytes = buffer.subarray(offset, offset + kLen);
- const layerId = decoder.decode(kBytes);
- offset += kLen;
- const fmtByte = buffer[offset++];
- layerFormats.set(layerId, BYTE_TO_FORMAT[fmtByte] || 'color-32bit');
- }
-
- const tileCount = view.getUint32(offset, true);
- offset += 4;
-
- const restoredTiles: TileBuffer[] = [];
- for (let i = 0; i < tileCount; i++) {
- const kLen = view.getUint16(offset, true);
- offset += 2;
- const kBytes = buffer.subarray(offset, offset + kLen);
- const layerId = decoder.decode(kBytes);
- offset += kLen;
-
- const tileX = view.getInt32(offset, true);
- offset += 4;
- const tileY = view.getInt32(offset, true);
- offset += 4;
- const fmtByte = buffer[offset++];
- const format = BYTE_TO_FORMAT[fmtByte] || 'color-32bit';
- const ver = view.getUint32(offset, true);
- offset += 4;
-
- const dLen = view.getUint32(offset, true);
- offset += 4;
- const data = new Uint8Array(dLen);
- data.set(buffer.subarray(offset, offset + dLen));
- offset += dLen;
-
- restoredTiles.push({
- layerId,
- tileX,
- tileY,
- format,
- data,
- dirty: true,
- version: ver,
- isPagedToDisk: false,
- lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
- lod: 0,
- });
- }
-
- grid.restoreFromSnapshot(restoredTiles, layerFormats);
-}
-
-export function serializeTileDeltas(deltas: TileDelta[]): Uint8Array {
- let totalBytes = 2 + 1 + 4;
- const encodedKeys: Uint8Array[] = new Array(deltas.length);
-
- for (let i = 0; i < deltas.length; i++) {
- const d = deltas[i];
- const keyBytes = _sharedTileEncoder.encode(d.key);
- encodedKeys[i] = keyBytes;
-
- totalBytes += 2 + keyBytes.length;
- totalBytes += 1;
- totalBytes += 1;
- if (d.beforeData && d.beforeData.byteLength > 0) {
- totalBytes += 4 + d.beforeData.byteLength;
- }
- totalBytes += 1;
- if (d.afterData && d.afterData.byteLength > 0) {
- totalBytes += 4 + d.afterData.byteLength;
- }
+ public getLayerTileBounds(layerId: string, dims: CanvasDimensions): DirtyRect | null {
+ return tileOps.getLayerTileBounds(this.host, layerId, dims);
}
- const out = new Uint8Array(totalBytes);
- const view = new DataView(out.buffer, out.byteOffset, totalBytes);
-
- let offset = 0;
- out[offset++] = 0x54; // 'T'
- out[offset++] = 0x44; // 'D'
- out[offset++] = 1; // Version
- view.setUint32(offset, deltas.length, true);
- offset += 4;
-
- for (let i = 0; i < deltas.length; i++) {
- const d = deltas[i];
- const keyBytes = encodedKeys[i];
-
- view.setUint16(offset, keyBytes.length, true);
- offset += 2;
- out.set(keyBytes, offset);
- offset += keyBytes.length;
-
- out[offset++] = FORMAT_TO_BYTE[d.format] ?? 2;
-
- if (d.beforeData && d.beforeData.byteLength > 0) {
- out[offset++] = 1;
- view.setUint32(offset, d.beforeData.byteLength, true);
- offset += 4;
- out.set(d.beforeData, offset);
- offset += d.beforeData.byteLength;
- } else {
- out[offset++] = 0;
- }
-
- if (d.afterData && d.afterData.byteLength > 0) {
- out[offset++] = 1;
- view.setUint32(offset, d.afterData.byteLength, true);
- offset += 4;
- out.set(d.afterData, offset);
- offset += d.afterData.byteLength;
- } else {
- out[offset++] = 0;
- }
+ public getLayerContentBounds(
+ layerId: string,
+ dims: CanvasDimensions,
+ isBackground: boolean = false
+ ): DirtyRect | null {
+ return tileOps.getLayerContentBounds(this.host, layerId, dims, isBackground);
}
- return out;
-}
-
-/**
- * Time-sliced asynchronous TileDelta serializer for large multi-tile operations
- * (full-canvas fills, filters, transforms, clears). Yields every ~4ms so UI stays responsive.
- */
-export async function serializeTileDeltasAsync(
- deltas: TileDelta[],
- chunkBudgetMs: number = 4
-): Promise<Uint8Array> {
- if (deltas.length <= 16) {
- return serializeTileDeltas(deltas);
+ public pruneEmptyTiles(layerId: string): number {
+ return tileOps.pruneEmptyTiles(this.host, layerId);
}
- let totalBytes = 2 + 1 + 4;
- const encodedKeys: Uint8Array[] = new Array(deltas.length);
-
- for (let i = 0; i < deltas.length; i++) {
- const d = deltas[i];
- const keyBytes = _sharedTileEncoder.encode(d.key);
- encodedKeys[i] = keyBytes;
-
- totalBytes += 2 + keyBytes.length + 1 + 1 + 1;
- if (d.beforeData && d.beforeData.byteLength > 0) {
- totalBytes += 4 + d.beforeData.byteLength;
- }
- if (d.afterData && d.afterData.byteLength > 0) {
- totalBytes += 4 + d.afterData.byteLength;
- }
+ public clearRectInLayer(
+ layerId: string,
+ rect: DirtyRect,
+ fillWhite: boolean = false,
+ snapshotOut?: Map<string, TileSnapshotEntry>,
+ suppressNotify: boolean = false
+ ): void {
+ tileOps.clearRectInLayer(this.host, layerId, rect, fillWhite, snapshotOut, suppressNotify);
}
- const out = new Uint8Array(totalBytes);
- const view = new DataView(out.buffer, out.byteOffset, totalBytes);
-
- let offset = 0;
- out[offset++] = 0x54; // 'T'
- out[offset++] = 0x44; // 'D'
- out[offset++] = 1; // Version
- view.setUint32(offset, deltas.length, true);
- offset += 4;
-
- const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
- let sliceStart = now();
-
- for (let i = 0; i < deltas.length; i++) {
- const d = deltas[i];
- const keyBytes = encodedKeys[i];
-
- view.setUint16(offset, keyBytes.length, true);
- offset += 2;
- out.set(keyBytes, offset);
- offset += keyBytes.length;
-
- out[offset++] = FORMAT_TO_BYTE[d.format] ?? 2;
-
- if (d.beforeData && d.beforeData.byteLength > 0) {
- out[offset++] = 1;
- view.setUint32(offset, d.beforeData.byteLength, true);
- offset += 4;
- out.set(d.beforeData, offset);
- offset += d.beforeData.byteLength;
- } else {
- out[offset++] = 0;
+ public transformLayerTiles(
+ layerId: string,
+ visitor: (rgba: Uint8ClampedArray, tileX: number, tileY: number) => boolean | void,
+ options?: {
+ targetFormat?: TileFormat;
+ monoThreshold?: number;
+ snapshotOut?: Map<string, TileSnapshotEntry>;
+ suppressNotify?: boolean;
+ }
+ ): boolean {
+ return tileOps.transformLayerTiles(this.host, layerId, visitor, options);
+ }
+
+ public mergeLayersInGrid(
+ srcLayerId: string,
+ dstLayerId: string,
+ options: {
+ opacity: number;
+ blendMode: BlendMode;
+ visible: boolean;
+ maskCanvas?: HTMLCanvasElement;
+ maskEnabled?: boolean;
+ dimensions: CanvasDimensions;
+ dstFormat?: TileFormat;
}
+ ): void {
+ tileOps.mergeLayersInGrid(this.host, srcLayerId, dstLayerId, options);
+ }
- if (d.afterData && d.afterData.byteLength > 0) {
- out[offset++] = 1;
- view.setUint32(offset, d.afterData.byteLength, true);
- offset += 4;
- out.set(d.afterData, offset);
- offset += d.afterData.byteLength;
- } else {
- out[offset++] = 0;
- }
+ public applyMaskCanvasToLayer(
+ layerId: string,
+ maskCanvas: HTMLCanvasElement,
+ dimensions: CanvasDimensions
+ ): void {
+ tileOps.applyMaskCanvasToLayer(this.host, layerId, maskCanvas, dimensions);
+ }
- if ((i & 7) === 7 && i + 1 < deltas.length && now() - sliceStart >= chunkBudgetMs) {
- await yieldToMain();
- sliceStart = now();
+ public resizeLayerInGrid(
+ layerId: string,
+ oldDims: CanvasDimensions,
+ newDims: CanvasDimensions,
+ options: {
+ scaleContent: boolean;
+ offsetX: number;
+ offsetY: number;
+ isBackground: boolean;
+ backgroundColor: string;
+ targetFormat: TileFormat;
}
+ ): void {
+ tileOps.resizeLayerInGrid(this.host, layerId, oldDims, newDims, options);
}
- return out;
-}
-
-export function deserializeTileDeltas(buffer: Uint8Array): TileDelta[] {
- if (buffer.byteLength < 7) {
- throw new Error('Invalid TileDelta buffer: too short');
- }
- if (buffer[0] !== 0x54 || buffer[1] !== 0x44) {
- throw new Error('Invalid TileDelta buffer: bad magic');
- }
- const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
- const version = buffer[2];
- if (version !== 1) {
- throw new Error(`Unsupported TileDelta version: ${version}`);
+ public copyLayerTilesSnapshot(layerId: string): {
+ format: TileFormat;
+ tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }>;
+ } {
+ return tileOps.copyLayerTilesSnapshot(this.host, layerId);
}
- let offset = 3;
- const count = view.getUint32(offset, true);
- offset += 4;
-
- const decoder = new TextDecoder();
- const deltas: TileDelta[] = [];
-
- for (let i = 0; i < count; i++) {
- const keyLen = view.getUint16(offset, true);
- offset += 2;
- const keyBytes = buffer.subarray(offset, offset + keyLen);
- const key = decoder.decode(keyBytes);
- offset += keyLen;
-
- const formatByte = buffer[offset++];
- const format = BYTE_TO_FORMAT[formatByte] || 'color-32bit';
-
- const hasBefore = buffer[offset++];
- let beforeData: Uint8Array | null = null;
- if (hasBefore === 1) {
- const bLen = view.getUint32(offset, true);
- offset += 4;
- beforeData = new Uint8Array(bLen);
- beforeData.set(buffer.subarray(offset, offset + bLen));
- offset += bLen;
- }
-
- const hasAfter = buffer[offset++];
- let afterData: Uint8Array | null = null;
- if (hasAfter === 1) {
- const aLen = view.getUint32(offset, true);
- offset += 4;
- afterData = new Uint8Array(aLen);
- afterData.set(buffer.subarray(offset, offset + aLen));
- offset += aLen;
+ public pasteLayerTilesSnapshot(
+ dstLayerId: string,
+ snapshot: {
+ format: TileFormat;
+ tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }>;
}
-
- deltas.push({
- key,
- format,
- beforeData,
- afterData,
- });
+ ): void {
+ tileOps.pasteLayerTilesSnapshot(this.host, dstLayerId, snapshot);
}
-
- return deltas;
}
// Global sparse tile grid singleton
diff --git a/src/utils/tileEngine/memoryManager.ts b/src/utils/tileEngine/memoryManager.ts
new file mode 100644
index 0000000..7ebc08c
--- /dev/null
+++ b/src/utils/tileEngine/memoryManager.ts
@@ -0,0 +1,390 @@
+/**
+ * TileMemoryManager: LRU tile RAM budgeting, tiered eviction to SSD scratch disk,
+ * and transparent async page-in.
+ */
+
+import { yieldToMain } from '../asyncCompression';
+import {
+ IScratchDiskDriver,
+ TileWritePayload,
+ createDefaultScratchDiskDriver,
+} from './scratchDriver';
+import {
+ ISparseTileGridMemoryHost,
+ TileBuffer,
+ allocateTileVersion,
+ getTileByteSize,
+ getTileKey,
+ pixelToTileCoord,
+} from './types';
+
+export interface TileMemoryManagerOptions {
+ budgetMb?: number;
+ driver?: IScratchDiskDriver;
+ sessionId?: string;
+ onMemoryChanged?: () => void;
+}
+
+export class TileMemoryManager {
+ private sessionId: string;
+ private budgetBytes: number;
+ private activeBytes: number = 0;
+ private grid: ISparseTileGridMemoryHost;
+ private driver: IScratchDiskDriver;
+ private viewportFrustum: { minX: number; minY: number; maxX: number; maxY: number } | null = null;
+ private activeLayerId: string | null = null;
+ private layerVisibility: Map<string, boolean> = new Map();
+ private inFlightPageIns: Map<string, Promise<Uint8Array>> = new Map();
+ private evictionPromise: Promise<void> | null = null;
+ private needsAnotherEvictionPass: boolean = false;
+ private onMemoryChanged?: () => void;
+
+ constructor(grid: ISparseTileGridMemoryHost, options?: TileMemoryManagerOptions) {
+ this.grid = grid;
+ const mb = options?.budgetMb ?? 1024;
+ this.budgetBytes = Math.max(1, mb) * 1024 * 1024;
+ this.sessionId = options?.sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
+ this.driver = options?.driver || createDefaultScratchDiskDriver();
+ this.onMemoryChanged = options?.onMemoryChanged;
+ void this.driver.init(this.sessionId);
+ }
+
+ public getSessionId(): string {
+ return this.sessionId;
+ }
+
+ public getDriver(): IScratchDiskDriver {
+ return this.driver;
+ }
+
+ public setDriver(driver: IScratchDiskDriver): void {
+ this.driver = driver;
+ void this.driver.init(this.sessionId);
+ }
+
+ public setBudgetMb(mb: number): void {
+ this.budgetBytes = Math.max(1, mb) * 1024 * 1024;
+ void this.checkBudgetAndEvict();
+ }
+
+ public getBudgetBytes(): number {
+ return this.budgetBytes;
+ }
+
+ public getActiveMemoryBytes(): number {
+ return this.activeBytes;
+ }
+
+ public updateViewport(
+ frustum: { minX: number; minY: number; maxX: number; maxY: number } | null,
+ activeLayerId?: string | null,
+ layerVisibility?: Map<string, boolean>
+ ): void {
+ this.viewportFrustum = frustum;
+ if (activeLayerId !== undefined) this.activeLayerId = activeLayerId;
+ if (layerVisibility !== undefined) this.layerVisibility = layerVisibility;
+ }
+
+ public notifyTileAllocated(tile: TileBuffer): void {
+ if (tile.data !== null) {
+ this.activeBytes += tile.data.byteLength;
+ tile.lastAccessTimestamp = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ if (tile.lod === 0) {
+ if (this.onMemoryChanged) {
+ this.onMemoryChanged();
+ } else {
+ void this.checkBudgetAndEvict();
+ }
+ }
+ }
+ }
+
+ public notifyTileFreed(tile: TileBuffer): void {
+ if (tile.data !== null) {
+ this.activeBytes = Math.max(0, this.activeBytes - tile.data.byteLength);
+ }
+ }
+
+ public touchTile(tile: TileBuffer): void {
+ tile.lastAccessTimestamp = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ }
+
+ /**
+ * Transparent Page-In: Asynchronously loads and decompresses a tile from scratch disk.
+ */
+ public async requestTileData(tile: TileBuffer): Promise<Uint8Array> {
+ if (tile.data !== null) {
+ this.touchTile(tile);
+ return tile.data;
+ }
+
+ if (!tile.isPagedToDisk) {
+ const size = getTileByteSize(tile.format);
+ tile.data = new Uint8Array(size);
+ this.notifyTileAllocated(tile);
+ return tile.data;
+ }
+
+ const key = getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod);
+ let inFlight = this.inFlightPageIns.get(key);
+ if (!inFlight) {
+ inFlight = (async () => {
+ try {
+ const raw = await this.driver.readTile(this.sessionId, tile.layerId, tile.tileX, tile.tileY);
+ if (tile.data === null) {
+ tile.data = raw;
+ this.activeBytes += raw.byteLength;
+ }
+ tile.isPagedToDisk = true;
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ this.touchTile(tile);
+ void this.checkBudgetAndEvict();
+ this.grid.bumpLayerVersion(tile.layerId);
+ this.grid.notifyChange();
+ return tile.data;
+ } finally {
+ this.inFlightPageIns.delete(key);
+ }
+ })();
+ this.inFlightPageIns.set(key, inFlight);
+ }
+ return inFlight;
+ }
+
+ /**
+ * Evaluates memory consumption against the configured RAM budget.
+ * Runs an LRU eviction pass prioritizing hidden layers, outside frustum, and inactive layers.
+ */
+ public async checkBudgetAndEvict(): Promise<void> {
+ if (this.evictionPromise) {
+ this.needsAnotherEvictionPass = true;
+ return this.evictionPromise;
+ }
+
+ if (this.activeBytes <= this.budgetBytes) {
+ return;
+ }
+
+ this.evictionPromise = (async () => {
+ try {
+ while (this.activeBytes > this.budgetBytes) {
+ this.needsAnotherEvictionPass = false;
+ const evictedCount = await this.performEvictionPass();
+ if (evictedCount === 0) {
+ break;
+ }
+ if (!this.needsAnotherEvictionPass && this.activeBytes <= this.budgetBytes) {
+ break;
+ }
+ }
+ } finally {
+ this.evictionPromise = null;
+ this.needsAnotherEvictionPass = false;
+ }
+ })();
+
+ return this.evictionPromise;
+ }
+
+ private static readonly MAX_EVICT_BATCH_TILES = 32;
+
+ private async performEvictionPass(): Promise<number> {
+ // 1. First drop any in-memory LOD > 0 tiles (they can always be re-downsampled on demand with 0 IO)
+ let droppedLodBytes = 0;
+ for (const tile of this.grid.tilesIterable()) {
+ if (tile.lod > 0 && tile.data !== null) {
+ this.activeBytes -= tile.data.byteLength;
+ droppedLodBytes += tile.data.byteLength;
+ tile.data = null;
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ }
+ }
+
+ if (this.activeBytes <= this.budgetBytes) {
+ return droppedLodBytes > 0 ? 1 : 0;
+ }
+
+ // 2. Gather candidate LOD 0 tiles with active data
+ const candidates: TileBuffer[] = [];
+ for (const tile of this.grid.tilesIterable()) {
+ if (tile.lod === 0 && tile.data !== null) {
+ candidates.push(tile);
+ }
+ }
+
+ if (candidates.length === 0) {
+ return droppedLodBytes > 0 ? 1 : 0;
+ }
+
+ const frustum = this.viewportFrustum;
+ const activeLayer = this.activeLayerId;
+ const layerVis = this.layerVisibility;
+
+ // 3. Score candidate eviction priority
+ const scored = candidates.map((tile) => {
+ const isHidden = layerVis.get(tile.layerId) === false;
+ const isInactiveLayer = activeLayer !== null && tile.layerId !== activeLayer;
+
+ let frustumDist = 0;
+ if (frustum) {
+ const minTx = pixelToTileCoord(frustum.minX, 0);
+ const maxTx = pixelToTileCoord(frustum.maxX, 0);
+ const minTy = pixelToTileCoord(frustum.minY, 0);
+ const maxTy = pixelToTileCoord(frustum.maxY, 0);
+
+ const dx = tile.tileX < minTx ? minTx - tile.tileX : tile.tileX > maxTx ? tile.tileX - maxTx : 0;
+ const dy = tile.tileY < minTy ? minTy - tile.tileY : tile.tileY > maxTy ? tile.tileY - maxTy : 0;
+ frustumDist = dx * dx + dy * dy;
+ }
+
+ let tier = 2;
+ if (isHidden) {
+ tier = 0; // Tier 0: Hidden layer tiles (evict first)
+ } else if (frustumDist > 0) {
+ tier = 1; // Tier 1: Outside viewport frustum (farthest first)
+ } else if (isInactiveLayer) {
+ tier = 2; // Tier 2: Inside frustum, but inactive layer (LRU)
+ } else {
+ tier = 3; // Tier 3: Inside frustum and active drawing layer (protected, evicted last if needed)
+ }
+
+ return {
+ tile,
+ tier,
+ frustumDist,
+ lastAccess: tile.lastAccessTimestamp,
+ };
+ });
+
+ scored.sort((a, b) => {
+ if (a.tier !== b.tier) return a.tier - b.tier;
+ if (a.tier === 1 && a.frustumDist !== b.frustumDist) {
+ return b.frustumDist - a.frustumDist; // Farthest distance outside frustum first
+ }
+ return a.lastAccess - b.lastAccess; // Oldest access timestamp first
+ });
+
+ // 4. Batch evict until within 90% of budget
+ const targetBytes = this.budgetBytes * 0.9;
+ const toEvict: TileBuffer[] = [];
+ let projectedBytes = this.activeBytes;
+
+ for (const item of scored) {
+ if (projectedBytes <= targetBytes) break;
+ toEvict.push(item.tile);
+ projectedBytes -= item.tile.data?.byteLength || 0;
+ }
+
+ if (toEvict.length > 0) {
+ try {
+ await this.evictTiles(toEvict);
+ return toEvict.length;
+ } catch (err) {
+ console.warn('[TileMemoryManager] Eviction write failed; aborting pass:', err);
+ return 0;
+ }
+ }
+
+ return droppedLodBytes > 0 ? 1 : 0;
+ }
+
+ public async evictTiles(tiles: TileBuffer[]): Promise<void> {
+ if (tiles.length === 0) return;
+
+ const batchSize = TileMemoryManager.MAX_EVICT_BATCH_TILES;
+ for (let start = 0; start < tiles.length; start += batchSize) {
+ const end = Math.min(tiles.length, start + batchSize);
+ const payloads: TileWritePayload[] = [];
+ const validTiles: TileBuffer[] = [];
+
+ for (let i = start; i < end; i++) {
+ const tile = tiles[i];
+ if (tile.data !== null) {
+ payloads.push({
+ layerId: tile.layerId,
+ tileX: tile.tileX,
+ tileY: tile.tileY,
+ data: tile.data,
+ });
+ validTiles.push(tile);
+ }
+ }
+
+ if (payloads.length > 0) {
+ await this.driver.writeTiles(this.sessionId, payloads);
+ for (const tile of validTiles) {
+ if (tile.data) {
+ this.activeBytes = Math.max(0, this.activeBytes - tile.data.byteLength);
+ tile.data = null;
+ tile.isPagedToDisk = true;
+ tile.dirty = false;
+ }
+ }
+ }
+
+ if (end < tiles.length) {
+ await yieldToMain();
+ }
+ }
+ }
+
+ /**
+ * Drops all cached LOD > 0 tiles and evicts up to `bytesToFree` of LOD 0 tiles to scratch disk.
+ * Used by DocumentStore to cooperatively reclaim RAM from inactive document tabs.
+ */
+ public async evictBytesToDisk(bytesToFree: number): Promise<number> {
+ if (bytesToFree <= 0 || this.activeBytes <= 0) return 0;
+ let freed = 0;
+
+ // 1. Drop regenerable LOD > 0 tiles first (zero disk I/O)
+ for (const tile of this.grid.tilesIterable()) {
+ if (tile.lod > 0 && tile.data !== null) {
+ const sz = tile.data.byteLength;
+ this.activeBytes = Math.max(0, this.activeBytes - sz);
+ freed += sz;
+ tile.data = null;
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ }
+ }
+
+ if (freed >= bytesToFree) return freed;
+
+ // 2. Evict LOD 0 tiles oldest-first to scratch disk
+ const lod0: TileBuffer[] = [];
+ for (const tile of this.grid.tilesIterable()) {
+ if (tile.lod === 0 && tile.data !== null) {
+ lod0.push(tile);
+ }
+ }
+ lod0.sort((a, b) => a.lastAccessTimestamp - b.lastAccessTimestamp);
+
+ const toEvict: TileBuffer[] = [];
+ for (const tile of lod0) {
+ if (freed >= bytesToFree) break;
+ toEvict.push(tile);
+ freed += tile.data?.byteLength || 0;
+ }
+
+ if (toEvict.length > 0) {
+ await this.evictTiles(toEvict);
+ }
+
+ return freed;
+ }
+
+ /**
+ * Offloads all in-memory tiles of this document to scratch disk.
+ */
+ public async evictAllToDisk(): Promise<number> {
+ return this.evictBytesToDisk(this.activeBytes);
+ }
+
+ public async clear(): Promise<void> {
+ this.inFlightPageIns.clear();
+ this.activeBytes = 0;
+ await this.driver.clear(this.sessionId);
+ }
+}
diff --git a/src/utils/tileEngine/mipmap.ts b/src/utils/tileEngine/mipmap.ts
new file mode 100644
index 0000000..6aece8c
--- /dev/null
+++ b/src/utils/tileEngine/mipmap.ts
@@ -0,0 +1,487 @@
+/**
+ * Multi-Resolution Mipmap Downsampling (2x2 Child Tiles -> 1 Parent LOD Tile)
+ * and on-demand LOD 1..3 pyramid generation / invalidation.
+ */
+
+import {
+ packRGBATo1Bit,
+ packRGBATo8Bit,
+ unpack1BitToRGBA,
+ unpack8BitToRGBA,
+} from './pixelCodec';
+import {
+ BYTES_1BIT,
+ BYTES_32BIT,
+ BYTES_8BIT,
+ ISparseTileGridHost,
+ TILE_PIXELS,
+ TILE_SIZE,
+ TileBuffer,
+ TileFormat,
+ allocateTileVersion,
+ createTileBuffer,
+ getTileByteSize,
+ getTileKey,
+ isLittleEndian,
+ parseTileKey,
+ unpackTileCoordX,
+ unpackTileCoordY,
+} from './types';
+
+const _downsampleRgbaScratch = new Uint8ClampedArray(BYTES_32BIT);
+const _downsampleRgbaView = new Uint8Array(_downsampleRgbaScratch.buffer);
+const _downsample8BitScratch = new Uint8Array(BYTES_8BIT);
+const _downsample1BitScratch = new Uint8Array(BYTES_1BIT);
+
+// Precomputed 256-entry LUT mapping an 8-bit 1-bit-row byte to a 4-bit downsampled nibble (2x1 horizontal OR)
+const _lut1BitByteToNibble = (() => {
+ const lut = new Uint8Array(256);
+ for (let b = 0; b < 256; b++) {
+ let nib = 0;
+ if (b & 0xc0) nib |= 0x08;
+ if (b & 0x30) nib |= 0x04;
+ if (b & 0x0c) nib |= 0x02;
+ if (b & 0x03) nib |= 0x01;
+ lut[b] = nib;
+ }
+ return lut;
+})();
+
+// Fast 2-bit popcount and coverage RGBA LUT for box-filtering monochrome-1bit -> color-32bit LOD tiles
+const _pop2 = new Uint8Array([0, 1, 1, 2]);
+const _monoCovU32 = new Uint32Array(
+ isLittleEndian
+ ? [0x00000000, 0x40000000, 0x80000000, 0xbf000000, 0xff000000]
+ : [0x00000000, 0x00000040, 0x00000080, 0x000000bf, 0x000000ff]
+);
+
+/**
+ * Downsample 4 child tiles (2x2 cluster) at LOD k-1 into a single destination tile at LOD k.
+ * Reuses pre-allocated scratch buffers for zero 256KB heap allocations during zoom-out LOD builds.
+ */
+export function downsample2x2ToParentTile(
+ childTiles: [TileBuffer | null, TileBuffer | null, TileBuffer | null, TileBuffer | null],
+ dstTile: TileBuffer
+): boolean {
+ const c0 = childTiles[0];
+ const c1 = childTiles[1];
+ const c2 = childTiles[2];
+ const c3 = childTiles[3];
+ if (
+ (!c0 || c0.data === null) &&
+ (!c1 || c1.data === null) &&
+ (!c2 || c2.data === null) &&
+ (!c3 || c3.data === null)
+ ) {
+ dstTile.solidColorU32 = undefined;
+ return false;
+ }
+
+ if (!dstTile.data) {
+ dstTile.data = new Uint8Array(getTileByteSize(dstTile.format));
+ }
+
+ const format = dstTile.format;
+ const dst = dstTile.data;
+ dstTile.solidColorU32 = undefined;
+
+ // Fast path #1: All 4 child tiles are identical solid color-32bit tiles (e.g. solid white paper)
+ if (
+ format === 'color-32bit' &&
+ c0 && c1 && c2 && c3 &&
+ c0.solidColorU32 !== undefined &&
+ c0.solidColorU32 === c1.solidColorU32 &&
+ c0.solidColorU32 === c2.solidColorU32 &&
+ c0.solidColorU32 === c3.solidColorU32
+ ) {
+ const dst32 = new Uint32Array(dst.buffer, dst.byteOffset, TILE_PIXELS);
+ dst32.fill(c0.solidColorU32);
+ dstTile.solidColorU32 = c0.solidColorU32;
+ dstTile.dirty = false;
+ dstTile.version++;
+ return true;
+ }
+
+ dst.fill(0);
+ const dst32 = format === 'color-32bit'
+ ? new Uint32Array(dst.buffer, dst.byteOffset, TILE_PIXELS)
+ : null;
+
+ for (let q = 0; q < 4; q++) {
+ const child = childTiles[q];
+ if (!child || !child.data) continue;
+
+ let childData = child.data;
+ const xBase = (q & 1) ? 128 : 0;
+ const yBase = (q >= 2) ? 128 : 0;
+
+ if (format === 'color-32bit') {
+ // Fast path #2: Uniform solid quadrant
+ if (child.solidColorU32 !== undefined && dst32) {
+ const fillU32 = child.solidColorU32;
+ for (let ly = 0; ly < 128; ly++) {
+ const rowStart = (yBase + ly) * TILE_SIZE + xBase;
+ dst32.fill(fillU32, rowStart, rowStart + 128);
+ }
+ continue;
+ }
+
+ if (child.format === 'monochrome-1bit' && dst32) {
+ // Fast zero-unpack 2x2 bit-counting box filter: 1-bit ink -> anti-aliased black coverage RGBA
+ for (let ly = 0; ly < 128; ly++) {
+ const sy0 = ly << 1;
+ const srcRow0 = sy0 << 5;
+ const srcRow1 = (sy0 + 1) << 5;
+ const dstRowBase = (yBase + ly) * TILE_SIZE + xBase;
+ for (let bx = 0; bx < 32; bx++) {
+ const b0 = childData[srcRow0 + bx];
+ const b1 = childData[srcRow1 + bx];
+ if ((b0 | b1) === 0) continue;
+ const outOff = dstRowBase + (bx << 2);
+ dst32[outOff] = _monoCovU32[_pop2[(b0 >> 6) & 3] + _pop2[(b1 >> 6) & 3]];
+ dst32[outOff + 1] = _monoCovU32[_pop2[(b0 >> 4) & 3] + _pop2[(b1 >> 4) & 3]];
+ dst32[outOff + 2] = _monoCovU32[_pop2[(b0 >> 2) & 3] + _pop2[(b1 >> 2) & 3]];
+ dst32[outOff + 3] = _monoCovU32[_pop2[b0 & 3] + _pop2[b1 & 3]];
+ }
+ }
+ continue;
+ } else if (child.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(childData, _downsampleRgbaScratch);
+ childData = _downsampleRgbaView;
+ } else if (child.format === 'grayscale-8bit') {
+ unpack8BitToRGBA(childData, _downsampleRgbaScratch);
+ childData = _downsampleRgbaView;
+ }
+ for (let ly = 0; ly < 128; ly++) {
+ const sy0 = ly << 1;
+ const dy = yBase + ly;
+ const dstRowOffset = dy * TILE_SIZE + xBase;
+ const srcRowOffset0 = sy0 * TILE_SIZE;
+ const srcRowOffset1 = (sy0 + 1) * TILE_SIZE;
+
+ for (let lx = 0; lx < 128; lx++) {
+ const sx0 = lx << 1;
+ const p00 = (srcRowOffset0 + sx0) << 2;
+ const p10 = p00 + 4;
+ const p01 = (srcRowOffset1 + sx0) << 2;
+ const p11 = p01 + 4;
+
+ const a0 = childData[p00 + 3];
+ const a1 = childData[p10 + 3];
+ const a2 = childData[p01 + 3];
+ const a3 = childData[p11 + 3];
+ const sumA = a0 + a1 + a2 + a3;
+
+ if (sumA === 0) {
+ continue; // dst is already zero-initialized
+ }
+ const outIdx = (dstRowOffset + lx) << 2;
+ if (sumA === 1020) {
+ dst[outIdx] = (childData[p00] + childData[p10] + childData[p01] + childData[p11] + 2) >> 2;
+ dst[outIdx + 1] = (childData[p00 + 1] + childData[p10 + 1] + childData[p01 + 1] + childData[p11 + 1] + 2) >> 2;
+ dst[outIdx + 2] = (childData[p00 + 2] + childData[p10 + 2] + childData[p01 + 2] + childData[p11 + 2] + 2) >> 2;
+ dst[outIdx + 3] = 255;
+ } else {
+ const halfA = sumA >> 1;
+ dst[outIdx + 3] = sumA >> 2;
+ dst[outIdx] = ((childData[p00] * a0 + childData[p10] * a1 + childData[p01] * a2 + childData[p11] * a3 + halfA) / sumA) | 0;
+ dst[outIdx + 1] = ((childData[p00 + 1] * a0 + childData[p10 + 1] * a1 + childData[p01 + 1] * a2 + childData[p11 + 1] * a3 + halfA) / sumA) | 0;
+ dst[outIdx + 2] = ((childData[p00 + 2] * a0 + childData[p10 + 2] * a1 + childData[p01 + 2] * a2 + childData[p11 + 2] * a3 + halfA) / sumA) | 0;
+ }
+ }
+ }
+ } else if (format === 'grayscale-8bit') {
+ if (child.format === 'color-32bit') {
+ packRGBATo8Bit(childData, _downsample8BitScratch);
+ childData = _downsample8BitScratch;
+ } else if (child.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(childData, _downsampleRgbaScratch);
+ packRGBATo8Bit(_downsampleRgbaScratch, _downsample8BitScratch);
+ childData = _downsample8BitScratch;
+ }
+ for (let ly = 0; ly < 128; ly++) {
+ const sy0 = ly << 1;
+ const sy1 = sy0 + 1;
+ const dy = yBase + ly;
+ const dstRowOffset = dy * TILE_SIZE;
+ const srcRowOffset0 = sy0 * TILE_SIZE;
+ const srcRowOffset1 = sy1 * TILE_SIZE;
+
+ for (let lx = 0; lx < 128; lx++) {
+ const sx0 = lx << 1;
+ const sx1 = sx0 + 1;
+ const dx = xBase + lx;
+
+ const v00 = childData[srcRowOffset0 + sx0];
+ const v10 = childData[srcRowOffset0 + sx1];
+ const v01 = childData[srcRowOffset1 + sx0];
+ const v11 = childData[srcRowOffset1 + sx1];
+
+ dst[dstRowOffset + dx] = (v00 + v10 + v01 + v11) >> 2;
+ }
+ }
+ } else {
+ if (child.format === 'color-32bit') {
+ packRGBATo1Bit(childData, _downsample1BitScratch);
+ childData = _downsample1BitScratch;
+ } else if (child.format === 'grayscale-8bit') {
+ unpack8BitToRGBA(childData, _downsampleRgbaScratch);
+ packRGBATo1Bit(_downsampleRgbaScratch, _downsample1BitScratch);
+ childData = _downsample1BitScratch;
+ }
+ const dstByteBaseX = xBase >> 3;
+ for (let ly = 0; ly < 128; ly++) {
+ const sy0 = ly << 1;
+ const srcRow0 = sy0 << 5;
+ const srcRow1 = (sy0 + 1) << 5;
+ const dstRow = ((yBase + ly) << 5) + dstByteBaseX;
+
+ for (let bx = 0; bx < 16; bx++) {
+ const sBx = bx << 1;
+ const comb0 = childData[srcRow0 + sBx] | childData[srcRow1 + sBx];
+ const comb1 = childData[srcRow0 + sBx + 1] | childData[srcRow1 + sBx + 1];
+ dst[dstRow + bx] = (_lut1BitByteToNibble[comb0] << 4) | _lut1BitByteToNibble[comb1];
+ }
+ }
+ }
+ }
+
+ dstTile.dirty = false;
+ dstTile.version++;
+ return true;
+}
+
+/**
+ * Ensures mipmap tiles at `targetLod` (0..3) exist and are up-to-date for all populated regions of `layerId`.
+ */
+export function getOrBuildLodTiles(
+ host: ISparseTileGridHost,
+ layerId: string,
+ targetLod: number
+): TileBuffer[] {
+ const lod = Math.max(0, Math.min(3, Math.floor(targetLod)));
+ if (lod === 0) {
+ return host.getLayerTiles(layerId);
+ }
+
+ const occ = host.layerLodOccupancy.get(layerId);
+ const lodOccMap = occ ? occ[lod - 1] : null;
+ if (!lodOccMap || lodOccMap.size === 0) {
+ return host.getLayerTiles(layerId, lod);
+ }
+
+ const result: TileBuffer[] = [];
+ for (const packed of lodOccMap.keys()) {
+ const tx = unpackTileCoordX(packed);
+ const ty = unpackTileCoordY(packed);
+ let tile = host.getTile(layerId, tx, ty, lod);
+ if (!tile || tile.data === null || isLodTileDirty(host, layerId, tx, ty, lod)) {
+ tile = generateLodTile(host, layerId, tx, ty, lod);
+ }
+ if (tile && tile.data !== null) {
+ result.push(tile);
+ }
+ }
+ return result;
+}
+
+export function isLodTileDirty(
+ host: ISparseTileGridHost,
+ layerId: string,
+ tileX: number,
+ tileY: number,
+ lod: number
+): boolean {
+ if (lod <= 0) return false;
+ return host.dirtyLodTiles.has(getTileKey(layerId, tileX, tileY, lod));
+}
+
+export function markLodAncestorsDirty(
+ host: ISparseTileGridHost,
+ layerId: string,
+ tileX: number,
+ tileY: number
+): void {
+ let tx = tileX;
+ let ty = tileY;
+ for (let lod = 1; lod <= 3; lod++) {
+ tx = tx >> 1;
+ ty = ty >> 1;
+ const key = getTileKey(layerId, tx, ty, lod);
+ host.dirtyLodTiles.add(key);
+ const existing = host.tiles.get(key);
+ if (existing) {
+ existing.dirty = true;
+ }
+ }
+}
+
+/**
+ * Generates or downsamples a specific LOD tile from its 4 child tiles at LOD - 1.
+ */
+export function generateLodTile(
+ host: ISparseTileGridHost,
+ layerId: string,
+ lodTx: number,
+ lodTy: number,
+ targetLod: number
+): TileBuffer | null {
+ if (targetLod <= 0) {
+ return host.getTile(layerId, lodTx, lodTy, 0);
+ }
+
+ const key = getTileKey(layerId, lodTx, lodTy, targetLod);
+ const memoryManager = host.getMemoryManager();
+
+ // O(1) empty-region fast-out: if no LOD 0 tile exists anywhere under this LOD node,
+ // never recurse or allocate a temporary 256KB TileBuffer.
+ if (!host.hasPopulatedLodTile(layerId, lodTx, lodTy, targetLod)) {
+ const stale = host.tiles.get(key);
+ if (stale) {
+ memoryManager?.notifyTileFreed(stale);
+ host.tiles.delete(key);
+ }
+ host.dirtyLodTiles.delete(key);
+ return null;
+ }
+
+ const childLod = targetLod - 1;
+ const cX0 = lodTx << 1;
+ const cY0 = lodTy << 1;
+
+ let c00 = host.getTile(layerId, cX0, cY0, childLod);
+ let c10 = host.getTile(layerId, cX0 + 1, cY0, childLod);
+ let c01 = host.getTile(layerId, cX0, cY0 + 1, childLod);
+ let c11 = host.getTile(layerId, cX0 + 1, cY0 + 1, childLod);
+
+ if (childLod > 0) {
+ if (host.hasPopulatedLodTile(layerId, cX0, cY0, childLod)) {
+ if (!c00 || c00.data === null || isLodTileDirty(host, layerId, cX0, cY0, childLod)) {
+ c00 = generateLodTile(host, layerId, cX0, cY0, childLod);
+ }
+ } else {
+ c00 = null;
+ }
+ if (host.hasPopulatedLodTile(layerId, cX0 + 1, cY0, childLod)) {
+ if (!c10 || c10.data === null || isLodTileDirty(host, layerId, cX0 + 1, cY0, childLod)) {
+ c10 = generateLodTile(host, layerId, cX0 + 1, cY0, childLod);
+ }
+ } else {
+ c10 = null;
+ }
+ if (host.hasPopulatedLodTile(layerId, cX0, cY0 + 1, childLod)) {
+ if (!c01 || c01.data === null || isLodTileDirty(host, layerId, cX0, cY0 + 1, childLod)) {
+ c01 = generateLodTile(host, layerId, cX0, cY0 + 1, childLod);
+ }
+ } else {
+ c01 = null;
+ }
+ if (host.hasPopulatedLodTile(layerId, cX0 + 1, cY0 + 1, childLod)) {
+ if (!c11 || c11.data === null || isLodTileDirty(host, layerId, cX0 + 1, cY0 + 1, childLod)) {
+ c11 = generateLodTile(host, layerId, cX0 + 1, cY0 + 1, childLod);
+ }
+ } else {
+ c11 = null;
+ }
+ }
+
+ const firstChild =
+ (c00 && c00.data !== null ? c00 : null) ||
+ (c10 && c10.data !== null ? c10 : null) ||
+ (c01 && c01.data !== null ? c01 : null) ||
+ (c11 && c11.data !== null ? c11 : null);
+
+ let tile = host.tiles.get(key);
+ if (!firstChild) {
+ if (tile) {
+ memoryManager?.notifyTileFreed(tile);
+ host.tiles.delete(key);
+ }
+ host.dirtyLodTiles.delete(key);
+ return null;
+ }
+
+ // Ephemeral display LOD > 0 tiles for monochrome-1bit layers use box-filtered color-32bit
+ // coverage instead of bitwise-OR dilation so zoomed-out lines match live mipmapped drafts.
+ const format: TileFormat =
+ firstChild.format === 'monochrome-1bit' ? 'color-32bit' : firstChild.format;
+
+ let allocatedNew = false;
+ if (!tile) {
+ tile = createTileBuffer(layerId, lodTx, lodTy, format, targetLod);
+ host.tiles.set(key, tile);
+ allocatedNew = true;
+ } else if (tile.format !== format) {
+ if (tile.data !== null) {
+ memoryManager?.notifyTileFreed(tile);
+ }
+ tile.format = format;
+ tile.data = new Uint8Array(getTileByteSize(format));
+ allocatedNew = true;
+ } else if (tile.data === null) {
+ allocatedNew = true;
+ }
+
+ const success = downsample2x2ToParentTile([c00, c10, c01, c11], tile);
+ if (!success) {
+ if (!allocatedNew) {
+ memoryManager?.notifyTileFreed(tile);
+ }
+ host.tiles.delete(key);
+ host.dirtyLodTiles.delete(key);
+ return null;
+ }
+
+ if (allocatedNew) {
+ memoryManager?.notifyTileAllocated(tile);
+ }
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ host.dirtyLodTiles.delete(key);
+ return tile;
+}
+
+/**
+ * Progressively downsamples up to `maxCount` dirty mipmap tiles.
+ */
+export function updateDirtyMipmaps(host: ISparseTileGridHost, maxCount: number = 16): number {
+ let count = 0;
+ const keys = Array.from(host.dirtyLodTiles);
+
+ // Process lower LODs (LOD 1) before higher LODs (LOD 2, 3)
+ keys.sort((a, b) => {
+ const pa = parseTileKey(a);
+ const pb = parseTileKey(b);
+ return pa.lod - pb.lod;
+ });
+
+ for (const key of keys) {
+ if (count >= maxCount) break;
+ host.dirtyLodTiles.delete(key);
+ const { layerId, tileX, tileY, lod } = parseTileKey(key);
+ generateLodTile(host, layerId, tileX, tileY, lod);
+ count++;
+ }
+
+ return count;
+}
+
+/**
+ * Flushes all pending dirty mipmap tiles immediately.
+ */
+export function flushMipmaps(host: ISparseTileGridHost, layerId?: string): void {
+ const keys = Array.from(host.dirtyLodTiles);
+ keys.sort((a, b) => {
+ const pa = parseTileKey(a);
+ const pb = parseTileKey(b);
+ return pa.lod - pb.lod;
+ });
+
+ for (const key of keys) {
+ const { layerId: lId, tileX, tileY, lod } = parseTileKey(key);
+ if (!layerId || lId === layerId) {
+ host.dirtyLodTiles.delete(key);
+ generateLodTile(host, lId, tileX, tileY, lod);
+ }
+ }
+}
diff --git a/src/utils/tileEngine/pixelCodec.ts b/src/utils/tileEngine/pixelCodec.ts
new file mode 100644
index 0000000..461f829
--- /dev/null
+++ b/src/utils/tileEngine/pixelCodec.ts
@@ -0,0 +1,468 @@
+/**
+ * Multi-format pixel packing/unpacking (1-bit, 8-bit, 32-bit RGBA)
+ * and LZ4-compressed single-tile binary packet serialization.
+ */
+
+import { lz4CompressBlock, lz4DecompressBlock } from '../lz4';
+import {
+ compressTilesLz4BatchNative,
+ decompressTilesLz4BatchNative,
+ isNativeRustAvailable,
+} from '../nativeBackend';
+import {
+ BYTES_1BIT,
+ BYTES_32BIT,
+ INK_BLACK_U32,
+ PAPER_WHITE_U32,
+ TILE_PIXELS,
+ TILE_SIZE,
+ TRANSPARENT_U32,
+ TileBuffer,
+ TileFormat,
+ createTileBuffer,
+ getTileByteSize,
+ isLittleEndian,
+} from './types';
+
+/**
+ * 256-entry lookup table mapping a 1-bit byte (8 pixels)
+ * into eight 32-bit pixel values for ultra-fast zero-loop unpacking.
+ */
+const LUT_1BIT_TO_RGBA_BLACK = new Uint32Array(256 * 8);
+const LUT_1BIT_TO_RGBA_WHITE = new Uint32Array(256 * 8);
+
+for (let b = 0; b < 256; b++) {
+ const offset = b * 8;
+ for (let bit = 0; bit < 8; bit++) {
+ // MSB first: bit 7 is the leftmost pixel
+ const isSet = (b & (1 << (7 - bit))) !== 0;
+ LUT_1BIT_TO_RGBA_BLACK[offset + bit] = isSet ? INK_BLACK_U32 : TRANSPARENT_U32;
+ LUT_1BIT_TO_RGBA_WHITE[offset + bit] = isSet ? PAPER_WHITE_U32 : TRANSPARENT_U32;
+ }
+}
+
+/**
+ * Set a single 1-bit pixel (MSB first packing).
+ */
+export function setPixel1Bit(data: Uint8Array, x: number, y: number, value: boolean | number): void {
+ const pixelIndex = y * TILE_SIZE + x;
+ const byteIndex = pixelIndex >> 3;
+ const bitOffset = 7 - (pixelIndex & 7);
+ if (value) {
+ data[byteIndex] |= 1 << bitOffset;
+ } else {
+ data[byteIndex] &= ~(1 << bitOffset);
+ }
+}
+
+/**
+ * Get a single 1-bit pixel (MSB first packing). Returns 0 or 1.
+ */
+export function getPixel1Bit(data: Uint8Array, x: number, y: number): number {
+ const pixelIndex = y * TILE_SIZE + x;
+ const byteIndex = pixelIndex >> 3;
+ const bitOffset = 7 - (pixelIndex & 7);
+ return (data[byteIndex] >> bitOffset) & 1;
+}
+
+/**
+ * Unpacks an 8,192-byte 1-bit tile into a 262,144-byte RGBA buffer
+ * using the precomputed 32-bit LUT.
+ */
+export function unpack1BitToRGBA(
+ src1Bit: Uint8Array,
+ dstRGBA: Uint8ClampedArray | Uint8Array,
+ inkColorU32: number = INK_BLACK_U32,
+ paperColorU32: number = TRANSPARENT_U32
+): void {
+ const dst32 = new Uint32Array(dstRGBA.buffer, dstRGBA.byteOffset, TILE_PIXELS);
+
+ if (inkColorU32 === INK_BLACK_U32 && paperColorU32 === TRANSPARENT_U32) {
+ // Fast path: direct copy from black ink LUT
+ let dstOffset = 0;
+ for (let i = 0; i < BYTES_1BIT; i++) {
+ const lutOffset = src1Bit[i] * 8;
+ dst32[dstOffset] = LUT_1BIT_TO_RGBA_BLACK[lutOffset];
+ dst32[dstOffset + 1] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 1];
+ dst32[dstOffset + 2] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 2];
+ dst32[dstOffset + 3] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 3];
+ dst32[dstOffset + 4] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 4];
+ dst32[dstOffset + 5] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 5];
+ dst32[dstOffset + 6] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 6];
+ dst32[dstOffset + 7] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 7];
+ dstOffset += 8;
+ }
+ } else {
+ // General path with custom colors
+ let dstOffset = 0;
+ for (let i = 0; i < BYTES_1BIT; i++) {
+ const b = src1Bit[i];
+ dst32[dstOffset] = (b & 0x80) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 1] = (b & 0x40) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 2] = (b & 0x20) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 3] = (b & 0x10) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 4] = (b & 0x08) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 5] = (b & 0x04) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 6] = (b & 0x02) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 7] = (b & 0x01) ? inkColorU32 : paperColorU32;
+ dstOffset += 8;
+ }
+ }
+}
+
+/**
+ * Packs a 256x256 RGBA buffer (262,144 bytes) into an 8,192-byte 1-bit tile.
+ * Applies perceptual ITU-R BT.601 luminance thresholding and alpha checking.
+ */
+export function packRGBATo1Bit(
+ srcRGBA: Uint8ClampedArray | Uint8Array,
+ dst1Bit: Uint8Array,
+ threshold: number = 128
+): void {
+ const thresh1000 = threshold * 1000;
+ const src32 =
+ srcRGBA.byteOffset % 4 === 0
+ ? new Uint32Array(srcRGBA.buffer, srcRGBA.byteOffset, TILE_PIXELS)
+ : null;
+ let srcOffset = 0;
+
+ for (let i = 0; i < BYTES_1BIT; i++) {
+ if (src32 !== null) {
+ const p = i << 3;
+ if (
+ (src32[p] |
+ src32[p + 1] |
+ src32[p + 2] |
+ src32[p + 3] |
+ src32[p + 4] |
+ src32[p + 5] |
+ src32[p + 6] |
+ src32[p + 7]) === 0
+ ) {
+ dst1Bit[i] = 0;
+ srcOffset += 32;
+ continue;
+ }
+ }
+ let byteVal = 0;
+ for (let bit = 7; bit >= 0; bit--) {
+ const a = srcRGBA[srcOffset + 3];
+ if (a >= 24) {
+ // Luminance: 0.299*R + 0.587*G + 0.114*B (integer scaled x1000)
+ const lum1000 =
+ srcRGBA[srcOffset] * 299 +
+ srcRGBA[srcOffset + 1] * 587 +
+ srcRGBA[srcOffset + 2] * 114;
+ // Dark pixels become ink (1), light pixels transparent (0)
+ if (lum1000 < thresh1000) {
+ byteVal |= 1 << bit;
+ }
+ }
+ srcOffset += 4;
+ }
+ dst1Bit[i] = byteVal;
+ }
+}
+
+/**
+ * Unpacks an 8-bit grayscale tile into RGBA.
+ */
+export function unpack8BitToRGBA(
+ src8Bit: Uint8Array,
+ dstRGBA: Uint8ClampedArray | Uint8Array
+): void {
+ const dst32 = new Uint32Array(dstRGBA.buffer, dstRGBA.byteOffset, TILE_PIXELS);
+ for (let i = 0; i < TILE_PIXELS; i++) {
+ const val = src8Bit[i];
+ if (val === 0) {
+ dst32[i] = TRANSPARENT_U32;
+ } else {
+ const a = 255;
+ dst32[i] = isLittleEndian
+ ? (a << 24) | (val << 16) | (val << 8) | val
+ : (val << 24) | (val << 16) | (val << 8) | a;
+ }
+ }
+}
+
+/**
+ * Packs RGBA to 8-bit grayscale using perceptual ITU-R BT.601 luminance.
+ */
+export function packRGBATo8Bit(
+ srcRGBA: Uint8ClampedArray | Uint8Array,
+ dst8Bit: Uint8Array
+): void {
+ let srcOffset = 0;
+ for (let i = 0; i < TILE_PIXELS; i++) {
+ const a = srcRGBA[srcOffset + 3];
+ if (a < 10) {
+ dst8Bit[i] = 0;
+ } else {
+ const r = srcRGBA[srcOffset];
+ const g = srcRGBA[srcOffset + 1];
+ const b = srcRGBA[srcOffset + 2];
+ dst8Bit[i] = Math.round((r * 299 + g * 587 + b * 114) / 1000);
+ }
+ srcOffset += 4;
+ }
+}
+
+export const TILE_CODEC_EMPTY = 0;
+export const TILE_CODEC_RAW = 1;
+export const TILE_CODEC_LZ4 = 2;
+const TILE_PACKET_HEADER_BYTES = 14;
+
+/**
+ * Serializes a single tile into a compact LZ4-compressed binary packet:
+ * [tileX: i32][tileY: i32][formatCode: u8][version: u32][codec: u8][payload...]
+ * Empty/deleted tiles (tile.data === null) serialize to a 14-byte tombstone (codec = 0).
+ */
+export function serializeTileBuffer(tile: TileBuffer): Uint8Array {
+ const formatCode =
+ tile.format === 'monochrome-1bit' ? 1 : tile.format === 'grayscale-8bit' ? 2 : 4;
+
+ if (tile.data === null) {
+ const packet = new Uint8Array(TILE_PACKET_HEADER_BYTES);
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
+ view.setInt32(0, tile.tileX, true);
+ view.setInt32(4, tile.tileY, true);
+ view.setUint8(8, formatCode);
+ view.setUint32(9, tile.version, true);
+ view.setUint8(13, TILE_CODEC_EMPTY);
+ return packet;
+ }
+
+ const expectedLen = getTileByteSize(tile.format);
+ const rawBytes =
+ tile.data.byteLength === expectedLen ? tile.data : new Uint8Array(expectedLen);
+ const compressed = lz4CompressBlock(rawBytes);
+
+ // Use LZ4 whenever it does not exceed raw size; otherwise raw fallback prevents expansion on noise
+ const useLz4 = compressed.byteLength <= rawBytes.byteLength;
+ const payload = useLz4 ? compressed : rawBytes;
+ const codec = useLz4 ? TILE_CODEC_LZ4 : TILE_CODEC_RAW;
+
+ const packet = new Uint8Array(TILE_PACKET_HEADER_BYTES + payload.byteLength);
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
+ view.setInt32(0, tile.tileX, true);
+ view.setInt32(4, tile.tileY, true);
+ view.setUint8(8, formatCode);
+ view.setUint32(9, tile.version, true);
+ view.setUint8(13, codec);
+ packet.set(payload, TILE_PACKET_HEADER_BYTES);
+
+ return packet;
+}
+
+/**
+ * Strictly validates and deserializes an LZ4-compressed tile packet.
+ * Returns null on malformed headers, unsupported codecs, or corrupt LZ4 streams.
+ */
+export function deserializeTileBufferStrict(
+ layerId: string,
+ packet: Uint8Array
+): TileBuffer | null {
+ if (!packet || packet.byteLength < TILE_PACKET_HEADER_BYTES) {
+ return null;
+ }
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
+ const tileX = view.getInt32(0, true);
+ const tileY = view.getInt32(4, true);
+ const formatCode = view.getUint8(8);
+ const version = view.getUint32(9, true);
+ const codec = view.getUint8(13);
+
+ let format: TileFormat;
+ if (formatCode === 1) {
+ format = 'monochrome-1bit';
+ } else if (formatCode === 2) {
+ format = 'grayscale-8bit';
+ } else if (formatCode === 4) {
+ format = 'color-32bit';
+ } else {
+ return null;
+ }
+
+ const expectedLen = getTileByteSize(format);
+ const payload = packet.subarray(TILE_PACKET_HEADER_BYTES);
+ let data: Uint8Array | null;
+
+ if (codec === TILE_CODEC_EMPTY) {
+ if (payload.byteLength !== 0) return null;
+ data = null;
+ } else if (codec === TILE_CODEC_LZ4) {
+ data = lz4DecompressBlock(payload, expectedLen, BYTES_32BIT);
+ if (!data) return null;
+ } else if (codec === TILE_CODEC_RAW) {
+ if (payload.byteLength !== expectedLen) return null;
+ data = new Uint8Array(expectedLen);
+ data.set(payload);
+ } else {
+ return null;
+ }
+
+ return {
+ layerId,
+ tileX,
+ tileY,
+ format,
+ data,
+ dirty: true,
+ version,
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
+ };
+}
+
+export function deserializeTileBuffer(layerId: string, packet: Uint8Array): TileBuffer {
+ return (
+ deserializeTileBufferStrict(layerId, packet) ??
+ createTileBuffer(layerId, 0, 0, 'color-32bit', 0)
+ );
+}
+
+/**
+ * Parallel batch tile serialization via Rust Rayon + LZ4 when in Tauri,
+ * falling back to synchronous JS compression outside Tauri.
+ */
+export async function serializeTileBatchAsync(tiles: TileBuffer[]): Promise<Uint8Array[]> {
+ if (tiles.length === 0) return [];
+ if (!isNativeRustAvailable() || tiles.length < 2) {
+ return tiles.map(serializeTileBuffer);
+ }
+
+ const nonEmptyIndices: number[] = [];
+ const rawPayloads: Uint8Array[] = [];
+ for (let i = 0; i < tiles.length; i++) {
+ const t = tiles[i];
+ if (t.data !== null) {
+ const expectedLen = getTileByteSize(t.format);
+ nonEmptyIndices.push(i);
+ rawPayloads.push(t.data.byteLength === expectedLen ? t.data : new Uint8Array(expectedLen));
+ }
+ }
+
+ const compressed =
+ rawPayloads.length > 0 ? await compressTilesLz4BatchNative(rawPayloads) : [];
+ const out: Uint8Array[] = new Array(tiles.length);
+ let compCursor = 0;
+
+ for (let i = 0; i < tiles.length; i++) {
+ const tile = tiles[i];
+ const formatCode =
+ tile.format === 'monochrome-1bit' ? 1 : tile.format === 'grayscale-8bit' ? 2 : 4;
+ if (tile.data === null) {
+ const packet = new Uint8Array(TILE_PACKET_HEADER_BYTES);
+ const view = new DataView(packet.buffer);
+ view.setInt32(0, tile.tileX, true);
+ view.setInt32(4, tile.tileY, true);
+ view.setUint8(8, formatCode);
+ view.setUint32(9, tile.version, true);
+ view.setUint8(13, TILE_CODEC_EMPTY);
+ out[i] = packet;
+ } else {
+ const entry = compressed[compCursor++];
+ const packet = new Uint8Array(TILE_PACKET_HEADER_BYTES + entry.data.byteLength);
+ const view = new DataView(packet.buffer);
+ view.setInt32(0, tile.tileX, true);
+ view.setInt32(4, tile.tileY, true);
+ view.setUint8(8, formatCode);
+ view.setUint32(9, tile.version, true);
+ view.setUint8(13, entry.codec);
+ packet.set(entry.data, TILE_PACKET_HEADER_BYTES);
+ out[i] = packet;
+ }
+ }
+ return out;
+}
+
+/**
+ * Parallel batch tile deserialization via Rust Rayon + LZ4 when in Tauri.
+ */
+export async function deserializeTileBatchAsync(
+ layerId: string,
+ packets: Uint8Array[]
+): Promise<Array<TileBuffer | null>> {
+ if (packets.length === 0) return [];
+ if (!isNativeRustAvailable() || packets.length < 2) {
+ return packets.map((p) => deserializeTileBufferStrict(layerId, p));
+ }
+
+ const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ const results: Array<TileBuffer | null> = new Array(packets.length).fill(null);
+ const batchMeta: Array<{
+ idx: number;
+ tileX: number;
+ tileY: number;
+ format: TileFormat;
+ version: number;
+ }> = [];
+ const batchItems: Array<{ codec: number; expectedLen: number; data: Uint8Array }> = [];
+
+ for (let i = 0; i < packets.length; i++) {
+ const packet = packets[i];
+ if (!packet || packet.byteLength < TILE_PACKET_HEADER_BYTES) continue;
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
+ const tileX = view.getInt32(0, true);
+ const tileY = view.getInt32(4, true);
+ const formatCode = view.getUint8(8);
+ const version = view.getUint32(9, true);
+ const codec = view.getUint8(13);
+
+ const format: TileFormat | null =
+ formatCode === 1
+ ? 'monochrome-1bit'
+ : formatCode === 2
+ ? 'grayscale-8bit'
+ : formatCode === 4
+ ? 'color-32bit'
+ : null;
+ if (!format) continue;
+
+ const payload = packet.subarray(TILE_PACKET_HEADER_BYTES);
+ if (codec === TILE_CODEC_EMPTY) {
+ if (payload.byteLength === 0) {
+ results[i] = {
+ layerId,
+ tileX,
+ tileY,
+ format,
+ data: null,
+ dirty: true,
+ version,
+ isPagedToDisk: false,
+ lastAccessTimestamp: now,
+ lod: 0,
+ };
+ }
+ continue;
+ }
+
+ if (codec === TILE_CODEC_RAW || codec === TILE_CODEC_LZ4) {
+ batchMeta.push({ idx: i, tileX, tileY, format, version });
+ batchItems.push({ codec, expectedLen: getTileByteSize(format), data: payload });
+ }
+ }
+
+ if (batchItems.length > 0) {
+ const decoded = await decompressTilesLz4BatchNative(batchItems);
+ for (let k = 0; k < batchMeta.length; k++) {
+ const m = batchMeta[k];
+ results[m.idx] = {
+ layerId,
+ tileX: m.tileX,
+ tileY: m.tileY,
+ format: m.format,
+ data: decoded[k],
+ dirty: true,
+ version: m.version,
+ isPagedToDisk: false,
+ lastAccessTimestamp: now,
+ lod: 0,
+ };
+ }
+ }
+
+ return results;
+}
diff --git a/src/utils/tileEngine/scratchDriver.ts b/src/utils/tileEngine/scratchDriver.ts
new file mode 100644
index 0000000..6d0f20f
--- /dev/null
+++ b/src/utils/tileEngine/scratchDriver.ts
@@ -0,0 +1,228 @@
+/**
+ * Scratch Disk Driver interface, binary IPC batch codec,
+ * and Tauri v2 / In-Memory driver implementations.
+ */
+
+export interface TileWritePayload {
+ layerId: string;
+ tileX: number;
+ tileY: number;
+ data: Uint8Array;
+}
+
+export interface IScratchDiskDriver {
+ init(sessionId: string): Promise<void>;
+ writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number>;
+ readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array>;
+ clear(sessionId: string): Promise<void>;
+}
+
+export function isTauriEnvironment(): boolean {
+ if (typeof window === 'undefined') return false;
+ return Boolean(
+ (window as any).__TAURI_INTERNALS__ ||
+ (window as any).__TAURI__ ||
+ (window as any).isTauri
+ );
+}
+
+const _tileBatchEncoder = new TextEncoder();
+const _tileBatchDecoder = new TextDecoder();
+const MIN_TILE_BATCH_RECORD_BYTES = 14; // layerIdLen(u16) + tx(i32) + ty(i32) + dataLen(u32)
+
+/**
+ * Packs a batch of tiles into a compact little-endian binary frame for raw Tauri IPC:
+ * `[count:u32][layerIdLen:u16, layerId(utf8), tx:i32, ty:i32, dataLen:u32, data]...`
+ */
+export function packTileWriteBatch(tiles: TileWritePayload[]): Uint8Array {
+ const encodedIds: Uint8Array[] = new Array(tiles.length);
+ let totalBytes = 4;
+
+ for (let i = 0; i < tiles.length; i++) {
+ const idBytes = _tileBatchEncoder.encode(tiles[i].layerId);
+ if (idBytes.byteLength > 0xffff) {
+ throw new Error(`Layer ID exceeds u16 byte length limit: ${tiles[i].layerId}`);
+ }
+ encodedIds[i] = idBytes;
+ totalBytes += MIN_TILE_BATCH_RECORD_BYTES + idBytes.byteLength + tiles[i].data.byteLength;
+ }
+
+ const out = new Uint8Array(totalBytes);
+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
+ view.setUint32(0, tiles.length, true);
+
+ let offset = 4;
+ for (let i = 0; i < tiles.length; i++) {
+ const t = tiles[i];
+ const idBytes = encodedIds[i];
+
+ view.setUint16(offset, idBytes.byteLength, true);
+ offset += 2;
+
+ out.set(idBytes, offset);
+ offset += idBytes.byteLength;
+
+ view.setInt32(offset, t.tileX, true);
+ offset += 4;
+
+ view.setInt32(offset, t.tileY, true);
+ offset += 4;
+
+ view.setUint32(offset, t.data.byteLength, true);
+ offset += 4;
+
+ out.set(t.data, offset);
+ offset += t.data.byteLength;
+ }
+
+ return out;
+}
+
+/**
+ * Unpacks a compact binary tile batch frame back into TileWritePayload entries.
+ */
+export function unpackTileWriteBatch(buffer: Uint8Array | ArrayBuffer): TileWritePayload[] {
+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
+ if (bytes.byteLength < 4) {
+ throw new Error('Truncated tile batch header');
+ }
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const count = view.getUint32(0, true);
+ if (count > Math.floor((bytes.byteLength - 4) / MIN_TILE_BATCH_RECORD_BYTES)) {
+ throw new Error('Truncated tile batch payload');
+ }
+
+ const tiles: TileWritePayload[] = new Array(count);
+ let offset = 4;
+
+ for (let i = 0; i < count; i++) {
+ if (offset + 2 > bytes.byteLength) {
+ throw new Error('Truncated tile record layerIdLen');
+ }
+ const idLen = view.getUint16(offset, true);
+ offset += 2;
+
+ if (offset + idLen + 12 > bytes.byteLength) {
+ throw new Error('Truncated tile record metadata');
+ }
+ const layerId = _tileBatchDecoder.decode(bytes.subarray(offset, offset + idLen));
+ offset += idLen;
+
+ const tileX = view.getInt32(offset, true);
+ offset += 4;
+ const tileY = view.getInt32(offset, true);
+ offset += 4;
+ const dataLen = view.getUint32(offset, true);
+ offset += 4;
+
+ if (offset + dataLen > bytes.byteLength) {
+ throw new Error('Truncated tile record data');
+ }
+ const data = bytes.slice(offset, offset + dataLen);
+ offset += dataLen;
+
+ tiles[i] = { layerId, tileX, tileY, data };
+ }
+
+ if (offset !== bytes.byteLength) {
+ throw new Error('Unexpected trailing bytes in tile batch payload');
+ }
+
+ return tiles;
+}
+
+/**
+ * Production Tauri v2 Rust Scratch Disk Driver.
+ * Direct raw binary IPC with high-throughput LZ4 compression and atomic file index tables.
+ */
+export class TauriScratchDiskDriver implements IScratchDiskDriver {
+ private invokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;
+
+ private getInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {
+ if (!this.invokePromise) {
+ this.invokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);
+ }
+ return this.invokePromise;
+ }
+
+ public async init(sessionId: string): Promise<void> {
+ const invoke = await this.getInvoke();
+ await invoke('scratch_disk_init', { sessionId });
+ }
+
+ public async writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number> {
+ if (tiles.length === 0) return 0;
+ const invoke = await this.getInvoke();
+ const packed = packTileWriteBatch(tiles);
+ return invoke<number>('scratch_disk_write_tiles', packed, {
+ headers: {
+ 'x-session-id': encodeURIComponent(sessionId),
+ },
+ });
+ }
+
+ public async readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array> {
+ const invoke = await this.getInvoke();
+ const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('scratch_disk_read_tile', undefined, {
+ headers: {
+ 'x-session-id': encodeURIComponent(sessionId),
+ 'x-layer-id': encodeURIComponent(layerId),
+ 'x-tile-x': String(tileX),
+ 'x-tile-y': String(tileY),
+ },
+ });
+ if (raw instanceof Uint8Array) return raw;
+ if (raw instanceof ArrayBuffer) return new Uint8Array(raw);
+ return new Uint8Array(raw);
+ }
+
+ public async clear(sessionId: string): Promise<void> {
+ const invoke = await this.getInvoke();
+ await invoke('scratch_disk_clear', { sessionId });
+ }
+}
+
+/**
+ * High-speed In-Memory / Fallback Scratch Disk Driver.
+ * Used during automated Vitest suites and pure browser previews without Tauri.
+ */
+export class InMemoryScratchDiskDriver implements IScratchDiskDriver {
+ private storage: Map<string, Uint8Array> = new Map();
+
+ public async init(sessionId: string): Promise<void> {
+ await this.clear(sessionId);
+ }
+
+ public async writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number> {
+ for (const t of tiles) {
+ const copy = new Uint8Array(t.data.byteLength);
+ copy.set(t.data);
+ this.storage.set(`${sessionId}:${t.layerId}:${t.tileX}:${t.tileY}`, copy);
+ }
+ return tiles.length;
+ }
+
+ public async readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array> {
+ const key = `${sessionId}:${layerId}:${tileX}:${tileY}`;
+ const found = this.storage.get(key);
+ if (!found) {
+ throw new Error(`Tile not found on in-memory scratch disk: ${key}`);
+ }
+ const copy = new Uint8Array(found.byteLength);
+ copy.set(found);
+ return copy;
+ }
+
+ public async clear(sessionId: string): Promise<void> {
+ const prefix = `${sessionId}:`;
+ for (const key of Array.from(this.storage.keys())) {
+ if (key.startsWith(prefix)) {
+ this.storage.delete(key);
+ }
+ }
+ }
+}
+
+export function createDefaultScratchDiskDriver(): IScratchDiskDriver {
+ return isTauriEnvironment() ? new TauriScratchDiskDriver() : new InMemoryScratchDiskDriver();
+}
diff --git a/src/utils/tileEngine/serialization.ts b/src/utils/tileEngine/serialization.ts
new file mode 100644
index 0000000..5813616
--- /dev/null
+++ b/src/utils/tileEngine/serialization.ts
@@ -0,0 +1,510 @@
+/**
+ * Binary snapshot serialization (INKG v1) and TileDelta serialization (TD v1)
+ * with both synchronous and time-sliced asynchronous codecs.
+ */
+
+import type { TileDelta } from '../../types/editor';
+import { yieldToMain } from '../asyncCompression';
+import type { SparseTileGrid } from '../tileEngine';
+import type { TileBuffer, TileFormat } from './types';
+
+const FORMAT_TO_BYTE: Record<TileFormat, number> = {
+ 'monochrome-1bit': 0,
+ 'grayscale-8bit': 1,
+ 'color-32bit': 2,
+};
+
+const BYTE_TO_FORMAT: TileFormat[] = [
+ 'monochrome-1bit',
+ 'grayscale-8bit',
+ 'color-32bit',
+];
+
+const _sharedTileEncoder = new TextEncoder();
+
+function encodeLayerIdCached(cache: Map<string, Uint8Array>, layerId: string): Uint8Array {
+ let bytes = cache.get(layerId);
+ if (!bytes) {
+ bytes = _sharedTileEncoder.encode(layerId);
+ cache.set(layerId, bytes);
+ }
+ return bytes;
+}
+
+export function serializeSparseTileGrid(grid: SparseTileGrid): Uint8Array {
+ const layerKeyCache = new Map<string, Uint8Array>();
+ const layerFormats = grid.getAllLayerFormats();
+
+ let totalBytes = 4 + 1 + 4;
+
+ const encodedFormats: Array<{ keyBytes: Uint8Array; format: TileFormat }> = [];
+ for (const [layerId, fmt] of layerFormats.entries()) {
+ const keyBytes = encodeLayerIdCached(layerKeyCache, layerId);
+ encodedFormats.push({ keyBytes, format: fmt });
+ totalBytes += 2 + keyBytes.length + 1;
+ }
+
+ totalBytes += 4;
+
+ const encodedTiles: Array<{ keyBytes: Uint8Array; tile: TileBuffer; data: Uint8Array | null }> = [];
+ for (const t of grid.tilesIterable()) {
+ if ((t.lod ?? 0) !== 0) continue;
+ const keyBytes = encodeLayerIdCached(layerKeyCache, t.layerId);
+ const data = t.data;
+ encodedTiles.push({ keyBytes, tile: t, data });
+ const dataLen = data ? data.byteLength : 0;
+ totalBytes += 2 + keyBytes.length + 4 + 4 + 1 + 4 + 4 + dataLen;
+ }
+
+ const out = new Uint8Array(totalBytes);
+ const view = new DataView(out.buffer, out.byteOffset, totalBytes);
+
+ let offset = 0;
+ out[offset++] = 0x49; // 'I'
+ out[offset++] = 0x4e; // 'N'
+ out[offset++] = 0x4b; // 'K'
+ out[offset++] = 0x47; // 'G'
+ out[offset++] = 1; // Version
+
+ view.setUint32(offset, encodedFormats.length, true);
+ offset += 4;
+
+ for (const item of encodedFormats) {
+ view.setUint16(offset, item.keyBytes.length, true);
+ offset += 2;
+ out.set(item.keyBytes, offset);
+ offset += item.keyBytes.length;
+ out[offset++] = FORMAT_TO_BYTE[item.format] ?? 2;
+ }
+
+ view.setUint32(offset, encodedTiles.length, true);
+ offset += 4;
+
+ for (const item of encodedTiles) {
+ const t = item.tile;
+ view.setUint16(offset, item.keyBytes.length, true);
+ offset += 2;
+ out.set(item.keyBytes, offset);
+ offset += item.keyBytes.length;
+
+ view.setInt32(offset, t.tileX, true);
+ offset += 4;
+ view.setInt32(offset, t.tileY, true);
+ offset += 4;
+ out[offset++] = FORMAT_TO_BYTE[t.format] ?? 2;
+ view.setUint32(offset, t.version, true);
+ offset += 4;
+
+ const data = item.data;
+ const dataLen = data ? data.byteLength : 0;
+ view.setUint32(offset, dataLen, true);
+ offset += 4;
+ if (data) {
+ out.set(data, offset);
+ offset += dataLen;
+ }
+ }
+
+ return out;
+}
+
+/**
+ * Time-sliced asynchronous SparseTileGrid serializer for background recovery checkpoints.
+ * Yields to the browser event loop every ~4ms and supports cooperative cancellation
+ * if the user resumes drawing mid-snapshot. Produces identical INKG v1 output.
+ */
+export async function serializeSparseTileGridAsync(
+ grid: SparseTileGrid,
+ options?: { shouldAbort?: () => boolean; chunkBudgetMs?: number }
+): Promise<Uint8Array | null> {
+ if (options?.shouldAbort?.()) return null;
+
+ const budgetMs = options?.chunkBudgetMs ?? 4;
+ const layerKeyCache = new Map<string, Uint8Array>();
+ const layerFormats = grid.getAllLayerFormats();
+
+ let totalBytes = 4 + 1 + 4;
+
+ const encodedFormats: Array<{ keyBytes: Uint8Array; format: TileFormat }> = [];
+ for (const [layerId, fmt] of layerFormats.entries()) {
+ const keyBytes = encodeLayerIdCached(layerKeyCache, layerId);
+ encodedFormats.push({ keyBytes, format: fmt });
+ totalBytes += 2 + keyBytes.length + 1;
+ }
+
+ totalBytes += 4;
+
+ // Capture immutable per-tile references (data ref + metadata) before yielding
+ const encodedTiles: Array<{
+ keyBytes: Uint8Array;
+ tileX: number;
+ tileY: number;
+ formatByte: number;
+ version: number;
+ data: Uint8Array | null;
+ }> = [];
+
+ for (const t of grid.tilesIterable()) {
+ if ((t.lod ?? 0) !== 0) continue;
+ const keyBytes = encodeLayerIdCached(layerKeyCache, t.layerId);
+ const data = t.data;
+ encodedTiles.push({
+ keyBytes,
+ tileX: t.tileX,
+ tileY: t.tileY,
+ formatByte: FORMAT_TO_BYTE[t.format] ?? 2,
+ version: t.version,
+ data,
+ });
+ const dataLen = data ? data.byteLength : 0;
+ totalBytes += 2 + keyBytes.length + 4 + 4 + 1 + 4 + 4 + dataLen;
+ }
+
+ if (options?.shouldAbort?.()) return null;
+
+ const out = new Uint8Array(totalBytes);
+ const view = new DataView(out.buffer, out.byteOffset, totalBytes);
+
+ let offset = 0;
+ out[offset++] = 0x49; // 'I'
+ out[offset++] = 0x4e; // 'N'
+ out[offset++] = 0x4b; // 'K'
+ out[offset++] = 0x47; // 'G'
+ out[offset++] = 1; // Version
+
+ view.setUint32(offset, encodedFormats.length, true);
+ offset += 4;
+
+ for (const item of encodedFormats) {
+ view.setUint16(offset, item.keyBytes.length, true);
+ offset += 2;
+ out.set(item.keyBytes, offset);
+ offset += item.keyBytes.length;
+ out[offset++] = FORMAT_TO_BYTE[item.format] ?? 2;
+ }
+
+ view.setUint32(offset, encodedTiles.length, true);
+ offset += 4;
+
+ const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
+ let sliceStart = now();
+
+ for (let i = 0; i < encodedTiles.length; i++) {
+ const item = encodedTiles[i];
+ view.setUint16(offset, item.keyBytes.length, true);
+ offset += 2;
+ out.set(item.keyBytes, offset);
+ offset += item.keyBytes.length;
+
+ view.setInt32(offset, item.tileX, true);
+ offset += 4;
+ view.setInt32(offset, item.tileY, true);
+ offset += 4;
+ out[offset++] = item.formatByte;
+ view.setUint32(offset, item.version, true);
+ offset += 4;
+
+ const dataLen = item.data ? item.data.byteLength : 0;
+ view.setUint32(offset, dataLen, true);
+ offset += 4;
+ if (item.data) {
+ out.set(item.data, offset);
+ offset += dataLen;
+ }
+
+ if ((i & 15) === 15 && i + 1 < encodedTiles.length && now() - sliceStart >= budgetMs) {
+ await yieldToMain();
+ if (options?.shouldAbort?.()) return null;
+ sliceStart = now();
+ }
+ }
+
+ return out;
+}
+
+export function deserializeSparseTileGrid(grid: SparseTileGrid, buffer: Uint8Array): void {
+ if (buffer.byteLength < 9) {
+ throw new Error('Invalid SparseTileGrid buffer: too short');
+ }
+ if (
+ buffer[0] !== 0x49 ||
+ buffer[1] !== 0x4e ||
+ buffer[2] !== 0x4b ||
+ buffer[3] !== 0x47
+ ) {
+ throw new Error('Invalid SparseTileGrid buffer: bad magic');
+ }
+ const version = buffer[4];
+ if (version !== 1) {
+ throw new Error(`Unsupported SparseTileGrid version: ${version}`);
+ }
+
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
+ const decoder = new TextDecoder();
+ let offset = 5;
+
+ const formatCount = view.getUint32(offset, true);
+ offset += 4;
+
+ const layerFormats = new Map<string, TileFormat>();
+ for (let i = 0; i < formatCount; i++) {
+ const kLen = view.getUint16(offset, true);
+ offset += 2;
+ const kBytes = buffer.subarray(offset, offset + kLen);
+ const layerId = decoder.decode(kBytes);
+ offset += kLen;
+ const fmtByte = buffer[offset++];
+ layerFormats.set(layerId, BYTE_TO_FORMAT[fmtByte] || 'color-32bit');
+ }
+
+ const tileCount = view.getUint32(offset, true);
+ offset += 4;
+
+ const restoredTiles: TileBuffer[] = [];
+ for (let i = 0; i < tileCount; i++) {
+ const kLen = view.getUint16(offset, true);
+ offset += 2;
+ const kBytes = buffer.subarray(offset, offset + kLen);
+ const layerId = decoder.decode(kBytes);
+ offset += kLen;
+
+ const tileX = view.getInt32(offset, true);
+ offset += 4;
+ const tileY = view.getInt32(offset, true);
+ offset += 4;
+ const fmtByte = buffer[offset++];
+ const format = BYTE_TO_FORMAT[fmtByte] || 'color-32bit';
+ const ver = view.getUint32(offset, true);
+ offset += 4;
+
+ const dLen = view.getUint32(offset, true);
+ offset += 4;
+ const data = new Uint8Array(dLen);
+ data.set(buffer.subarray(offset, offset + dLen));
+ offset += dLen;
+
+ restoredTiles.push({
+ layerId,
+ tileX,
+ tileY,
+ format,
+ data,
+ dirty: true,
+ version: ver,
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
+ });
+ }
+
+ grid.restoreFromSnapshot(restoredTiles, layerFormats);
+}
+
+export function serializeTileDeltas(deltas: TileDelta[]): Uint8Array {
+ let totalBytes = 2 + 1 + 4;
+ const encodedKeys: Uint8Array[] = new Array(deltas.length);
+
+ for (let i = 0; i < deltas.length; i++) {
+ const d = deltas[i];
+ const keyBytes = _sharedTileEncoder.encode(d.key);
+ encodedKeys[i] = keyBytes;
+
+ totalBytes += 2 + keyBytes.length;
+ totalBytes += 1;
+ totalBytes += 1;
+ if (d.beforeData && d.beforeData.byteLength > 0) {
+ totalBytes += 4 + d.beforeData.byteLength;
+ }
+ totalBytes += 1;
+ if (d.afterData && d.afterData.byteLength > 0) {
+ totalBytes += 4 + d.afterData.byteLength;
+ }
+ }
+
+ const out = new Uint8Array(totalBytes);
+ const view = new DataView(out.buffer, out.byteOffset, totalBytes);
+
+ let offset = 0;
+ out[offset++] = 0x54; // 'T'
+ out[offset++] = 0x44; // 'D'
+ out[offset++] = 1; // Version
+ view.setUint32(offset, deltas.length, true);
+ offset += 4;
+
+ for (let i = 0; i < deltas.length; i++) {
+ const d = deltas[i];
+ const keyBytes = encodedKeys[i];
+
+ view.setUint16(offset, keyBytes.length, true);
+ offset += 2;
+ out.set(keyBytes, offset);
+ offset += keyBytes.length;
+
+ out[offset++] = FORMAT_TO_BYTE[d.format] ?? 2;
+
+ if (d.beforeData && d.beforeData.byteLength > 0) {
+ out[offset++] = 1;
+ view.setUint32(offset, d.beforeData.byteLength, true);
+ offset += 4;
+ out.set(d.beforeData, offset);
+ offset += d.beforeData.byteLength;
+ } else {
+ out[offset++] = 0;
+ }
+
+ if (d.afterData && d.afterData.byteLength > 0) {
+ out[offset++] = 1;
+ view.setUint32(offset, d.afterData.byteLength, true);
+ offset += 4;
+ out.set(d.afterData, offset);
+ offset += d.afterData.byteLength;
+ } else {
+ out[offset++] = 0;
+ }
+ }
+
+ return out;
+}
+
+/**
+ * Time-sliced asynchronous TileDelta serializer for large multi-tile operations
+ * (full-canvas fills, filters, transforms, clears). Yields every ~4ms so UI stays responsive.
+ */
+export async function serializeTileDeltasAsync(
+ deltas: TileDelta[],
+ chunkBudgetMs: number = 4
+): Promise<Uint8Array> {
+ if (deltas.length <= 16) {
+ return serializeTileDeltas(deltas);
+ }
+
+ let totalBytes = 2 + 1 + 4;
+ const encodedKeys: Uint8Array[] = new Array(deltas.length);
+
+ for (let i = 0; i < deltas.length; i++) {
+ const d = deltas[i];
+ const keyBytes = _sharedTileEncoder.encode(d.key);
+ encodedKeys[i] = keyBytes;
+
+ totalBytes += 2 + keyBytes.length + 1 + 1 + 1;
+ if (d.beforeData && d.beforeData.byteLength > 0) {
+ totalBytes += 4 + d.beforeData.byteLength;
+ }
+ if (d.afterData && d.afterData.byteLength > 0) {
+ totalBytes += 4 + d.afterData.byteLength;
+ }
+ }
+
+ const out = new Uint8Array(totalBytes);
+ const view = new DataView(out.buffer, out.byteOffset, totalBytes);
+
+ let offset = 0;
+ out[offset++] = 0x54; // 'T'
+ out[offset++] = 0x44; // 'D'
+ out[offset++] = 1; // Version
+ view.setUint32(offset, deltas.length, true);
+ offset += 4;
+
+ const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
+ let sliceStart = now();
+
+ for (let i = 0; i < deltas.length; i++) {
+ const d = deltas[i];
+ const keyBytes = encodedKeys[i];
+
+ view.setUint16(offset, keyBytes.length, true);
+ offset += 2;
+ out.set(keyBytes, offset);
+ offset += keyBytes.length;
+
+ out[offset++] = FORMAT_TO_BYTE[d.format] ?? 2;
+
+ if (d.beforeData && d.beforeData.byteLength > 0) {
+ out[offset++] = 1;
+ view.setUint32(offset, d.beforeData.byteLength, true);
+ offset += 4;
+ out.set(d.beforeData, offset);
+ offset += d.beforeData.byteLength;
+ } else {
+ out[offset++] = 0;
+ }
+
+ if (d.afterData && d.afterData.byteLength > 0) {
+ out[offset++] = 1;
+ view.setUint32(offset, d.afterData.byteLength, true);
+ offset += 4;
+ out.set(d.afterData, offset);
+ offset += d.afterData.byteLength;
+ } else {
+ out[offset++] = 0;
+ }
+
+ if ((i & 7) === 7 && i + 1 < deltas.length && now() - sliceStart >= chunkBudgetMs) {
+ await yieldToMain();
+ sliceStart = now();
+ }
+ }
+
+ return out;
+}
+
+export function deserializeTileDeltas(buffer: Uint8Array): TileDelta[] {
+ if (buffer.byteLength < 7) {
+ throw new Error('Invalid TileDelta buffer: too short');
+ }
+ if (buffer[0] !== 0x54 || buffer[1] !== 0x44) {
+ throw new Error('Invalid TileDelta buffer: bad magic');
+ }
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
+ const version = buffer[2];
+ if (version !== 1) {
+ throw new Error(`Unsupported TileDelta version: ${version}`);
+ }
+
+ let offset = 3;
+ const count = view.getUint32(offset, true);
+ offset += 4;
+
+ const decoder = new TextDecoder();
+ const deltas: TileDelta[] = [];
+
+ for (let i = 0; i < count; i++) {
+ const keyLen = view.getUint16(offset, true);
+ offset += 2;
+ const keyBytes = buffer.subarray(offset, offset + keyLen);
+ const key = decoder.decode(keyBytes);
+ offset += keyLen;
+
+ const formatByte = buffer[offset++];
+ const format = BYTE_TO_FORMAT[formatByte] || 'color-32bit';
+
+ const hasBefore = buffer[offset++];
+ let beforeData: Uint8Array | null = null;
+ if (hasBefore === 1) {
+ const bLen = view.getUint32(offset, true);
+ offset += 4;
+ beforeData = new Uint8Array(bLen);
+ beforeData.set(buffer.subarray(offset, offset + bLen));
+ offset += bLen;
+ }
+
+ const hasAfter = buffer[offset++];
+ let afterData: Uint8Array | null = null;
+ if (hasAfter === 1) {
+ const aLen = view.getUint32(offset, true);
+ offset += 4;
+ afterData = new Uint8Array(aLen);
+ afterData.set(buffer.subarray(offset, offset + aLen));
+ offset += aLen;
+ }
+
+ deltas.push({
+ key,
+ format,
+ beforeData,
+ afterData,
+ });
+ }
+
+ return deltas;
+}
diff --git a/src/utils/tileEngine/strokeComposite.ts b/src/utils/tileEngine/strokeComposite.ts
new file mode 100644
index 0000000..44e76b8
--- /dev/null
+++ b/src/utils/tileEngine/strokeComposite.ts
@@ -0,0 +1,391 @@
+/**
+ * In-place brush stroke compositing directly onto LOD 0 sparse tiles.
+ */
+
+import { packRGBATo1Bit, packRGBATo8Bit, unpack8BitToRGBA } from './pixelCodec';
+import {
+ ISparseTileGridHost,
+ TILE_SIZE,
+ TileFormat,
+ allocateTileVersion,
+ getTileByteSize,
+ getTileKey,
+ pixelToTileCoord,
+} from './types';
+
+export interface CompositeStrokeOptions {
+ layerId: string;
+ strokeData: { data: Uint8ClampedArray | Uint8Array; width: number; height: number };
+ destX: number;
+ destY: number;
+ format: TileFormat;
+ compositeOp: 'source-over' | 'destination-out' | 'source-atop';
+ opacity: number;
+ monochrome?: {
+ threshold: number;
+ expressBlack: boolean;
+ expressWhite: boolean;
+ };
+ selectionMask?: {
+ mask: Uint8Array;
+ bounds: { x: number; y: number; width: number; height: number };
+ } | null;
+ snapshotOut?: Map<string, { format: TileFormat; data: Uint8Array | null }>;
+ suppressNotify?: boolean;
+}
+
+/**
+ * Composites an isolated stroke RGBA buffer directly onto LOD 0 tiles in-place,
+ * avoiding full-region canvas allocation, existing-tile unpacking, and separate
+ * binarization passes. Records pre-edit tile snapshots into `snapshotOut` only
+ * for tiles with non-zero stroke pixels.
+ */
+export function compositeStrokeToTiles(
+ host: ISparseTileGridHost,
+ options: CompositeStrokeOptions
+): boolean {
+ const {
+ layerId,
+ strokeData,
+ destX,
+ destY,
+ format: targetFormat,
+ compositeOp,
+ monochrome,
+ selectionMask,
+ snapshotOut,
+ suppressNotify = false,
+ } = options;
+ const opacity = Math.max(0, Math.min(1, options.opacity));
+ const w = strokeData.width;
+ const h = strokeData.height;
+ if (w <= 0 || h <= 0 || opacity <= 0.001) return false;
+
+ host.ingestedLayers.add(layerId);
+ host.setLayerFormat(layerId, targetFormat);
+
+ const minTileX = pixelToTileCoord(destX, 0);
+ const minTileY = pixelToTileCoord(destY, 0);
+ const maxTileX = pixelToTileCoord(destX + w - 1, 0);
+ const maxTileY = pixelToTileCoord(destY + h - 1, 0);
+
+ const srcData = strokeData.data;
+ const src32 =
+ srcData.byteOffset % 4 === 0 && srcData.byteLength >= w * h * 4
+ ? new Uint32Array(srcData.buffer, srcData.byteOffset, w * h)
+ : null;
+
+ const monoThresh = Math.max(1, Math.min(255, monochrome?.threshold ?? 128));
+ const monoExpressBlack = monochrome?.expressBlack !== false;
+ const hasSelMask = Boolean(selectionMask?.mask);
+ const selMask = selectionMask?.mask ?? null;
+ const selBx = selectionMask ? Math.floor(selectionMask.bounds.x) : 0;
+ const selBy = selectionMask ? Math.floor(selectionMask.bounds.y) : 0;
+ const selBw = selectionMask ? Math.ceil(selectionMask.bounds.width) : 0;
+ const selBh = selectionMask ? Math.ceil(selectionMask.bounds.height) : 0;
+ const fullOpacity = opacity >= 0.999;
+ const memoryManager = host.getMemoryManager();
+
+ let anyModified = false;
+
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+
+ const srcStartX = Math.max(0, tileDocX - destX);
+ const srcStartY = Math.max(0, tileDocY - destY);
+ const srcEndX = Math.min(w, tileDocX + TILE_SIZE - destX);
+ const srcEndY = Math.min(h, tileDocY + TILE_SIZE - destY);
+ if (srcStartX >= srcEndX || srcStartY >= srcEndY) continue;
+
+ let existingTile = host.getTile(layerId, tx, ty, 0);
+
+ // Erasing or alpha-locking against an empty tile is a no-op
+ if ((compositeOp === 'destination-out' || compositeOp === 'source-atop') && (!existingTile || !existingTile.data)) {
+ if (existingTile && existingTile.data === null && existingTile.isPagedToDisk && memoryManager) {
+ void memoryManager.requestTileData(existingTile);
+ }
+ continue;
+ }
+
+ // Fast zero-scan: skip tiles where the stroke overlap is completely transparent
+ let hasNonZero = false;
+ if (src32 !== null) {
+ outerZero32: for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const rowOff = sy * w;
+ for (let sx = rowOff + srcStartX, end = rowOff + srcEndX; sx < end; sx++) {
+ if ((src32[sx] >>> 24) !== 0) {
+ hasNonZero = true;
+ break outerZero32;
+ }
+ }
+ }
+ } else {
+ outerZero8: for (let sy = srcStartY; sy < srcEndY; sy++) {
+ let off = (sy * w + srcStartX) << 2;
+ const endOff = (sy * w + srcEndX) << 2;
+ for (; off < endOff; off += 4) {
+ if (srcData[off + 3] !== 0) {
+ hasNonZero = true;
+ break outerZero8;
+ }
+ }
+ }
+ }
+ if (!hasNonZero) continue;
+
+ // Snapshot pre-edit tile state before mutating
+ if (snapshotOut) {
+ const tileKey = getTileKey(layerId, tx, ty, 0);
+ if (!snapshotOut.has(tileKey)) {
+ snapshotOut.set(tileKey, {
+ format: existingTile ? existingTile.format : targetFormat,
+ data: existingTile?.data ? new Uint8Array(existingTile.data) : null,
+ });
+ }
+ }
+
+ const tile = existingTile ?? host.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
+ if (tile.format !== targetFormat) {
+ const prevRGBA = tile.data ? new Uint8Array(host.getTileAsRGBA(tile)) : null;
+ if (tile.data !== null) {
+ memoryManager?.notifyTileFreed(tile);
+ }
+ tile.format = targetFormat;
+ tile.data = new Uint8Array(getTileByteSize(targetFormat));
+ if (prevRGBA) {
+ if (targetFormat === 'color-32bit') {
+ tile.data.set(prevRGBA);
+ } else if (targetFormat === 'monochrome-1bit') {
+ packRGBATo1Bit(prevRGBA, tile.data, monoThresh);
+ } else {
+ packRGBATo8Bit(prevRGBA, tile.data);
+ }
+ }
+ memoryManager?.notifyTileAllocated(tile);
+ } else if (tile.data === null) {
+ tile.data = new Uint8Array(getTileByteSize(tile.format));
+ memoryManager?.notifyTileAllocated(tile);
+ }
+
+ const localStartX = destX + srcStartX - tileDocX;
+ const copyWidth = srcEndX - srcStartX;
+
+ if (tile.format === 'monochrome-1bit') {
+ const dst = tile.data;
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ const docY = destY + sy;
+ const rowByteBase = tileLocalY << 5;
+ let srcOff = (sy * w + srcStartX) << 2;
+ const selRowValid = hasSelMask && docY >= selBy && docY < selBy + selBh;
+ const selRowOff = selRowValid ? (docY - selBy) * selBw : 0;
+
+ for (let dx = 0; dx < copyWidth; dx++, srcOff += 4) {
+ const sa = srcData[srcOff + 3];
+ if (sa === 0) continue;
+
+ let effA = fullOpacity ? sa : Math.round(sa * opacity);
+ if (hasSelMask) {
+ const docX = destX + srcStartX + dx;
+ if (!selRowValid || docX < selBx || docX >= selBx + selBw) continue;
+ const ma = selMask![selRowOff + (docX - selBx)];
+ if (ma === 0) continue;
+ if (ma < 255) {
+ effA = Math.round((effA * ma) / 255);
+ }
+ }
+
+ const lx = localStartX + dx;
+ const byteIdx = rowByteBase + (lx >> 3);
+ const mask = 1 << (7 - (lx & 7));
+
+ if (compositeOp === 'destination-out') {
+ if (effA >= 128) {
+ dst[byteIdx] &= ~mask;
+ }
+ } else if (compositeOp === 'source-atop') {
+ if ((dst[byteIdx] & mask) === 0) continue;
+ const r = srcData[srcOff];
+ const g = srcData[srcOff + 1];
+ const b = srcData[srcOff + 2];
+ const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;
+ const outLum = (lum * effA) / 255;
+ if (outLum < monoThresh && monoExpressBlack) {
+ dst[byteIdx] |= mask;
+ } else {
+ dst[byteIdx] &= ~mask;
+ }
+ } else {
+ const hadInk = (dst[byteIdx] & mask) !== 0;
+ const r = srcData[srcOff];
+ const g = srcData[srcOff + 1];
+ const b = srcData[srcOff + 2];
+ const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;
+ if (!hadInk) {
+ if (effA >= 128 && lum < monoThresh && monoExpressBlack) {
+ dst[byteIdx] |= mask;
+ }
+ } else {
+ const outLum = (lum * effA) / 255;
+ if (outLum >= monoThresh || !monoExpressBlack) {
+ dst[byteIdx] &= ~mask;
+ }
+ }
+ }
+ }
+ }
+ } else if (tile.format === 'color-32bit') {
+ const dst = tile.data;
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ const docY = destY + sy;
+ let srcOff = (sy * w + srcStartX) << 2;
+ let dstOff = (tileLocalY * TILE_SIZE + localStartX) << 2;
+ const selRowValid = hasSelMask && docY >= selBy && docY < selBy + selBh;
+ const selRowOff = selRowValid ? (docY - selBy) * selBw : 0;
+
+ for (let dx = 0; dx < copyWidth; dx++, srcOff += 4, dstOff += 4) {
+ const sa = srcData[srcOff + 3];
+ if (sa === 0) continue;
+
+ let effA = fullOpacity ? sa : Math.round(sa * opacity);
+ if (effA === 0) continue;
+
+ let maskFrac = 1.0;
+ if (hasSelMask) {
+ const docX = destX + srcStartX + dx;
+ if (!selRowValid || docX < selBx || docX >= selBx + selBw) continue;
+ const ma = selMask![selRowOff + (docX - selBx)];
+ if (ma === 0) continue;
+ if (ma < 255) maskFrac = ma / 255;
+ }
+
+ const sr = srcData[srcOff];
+ const sg = srcData[srcOff + 1];
+ const sb = srcData[srcOff + 2];
+ const da = dst[dstOff + 3];
+
+ let outR = dst[dstOff];
+ let outG = dst[dstOff + 1];
+ let outB = dst[dstOff + 2];
+ let outA = da;
+
+ if (compositeOp === 'destination-out') {
+ if (da === 0) continue;
+ if (effA === 255) {
+ outR = 0;
+ outG = 0;
+ outB = 0;
+ outA = 0;
+ } else {
+ outA = Math.round(da * (1 - effA / 255));
+ if (outA === 0) {
+ outR = 0;
+ outG = 0;
+ outB = 0;
+ }
+ }
+ } else if (compositeOp === 'source-atop') {
+ if (da === 0) continue;
+ if (effA === 255) {
+ outR = sr;
+ outG = sg;
+ outB = sb;
+ } else {
+ const sA = effA / 255;
+ const inv = 1 - sA;
+ outR = Math.round(sr * sA + outR * inv);
+ outG = Math.round(sg * sA + outG * inv);
+ outB = Math.round(sb * sA + outB * inv);
+ }
+ } else {
+ if (effA === 255 || da === 0) {
+ outR = sr;
+ outG = sg;
+ outB = sb;
+ outA = effA;
+ } else {
+ const sA = effA / 255;
+ const dA = da / 255;
+ const invSA = 1 - sA;
+ const compA = sA + dA * invSA;
+ if (compA > 0) {
+ const invOut = 1 / compA;
+ outR = Math.round((sr * sA + outR * dA * invSA) * invOut);
+ outG = Math.round((sg * sA + outG * dA * invSA) * invOut);
+ outB = Math.round((sb * sA + outB * dA * invSA) * invOut);
+ outA = Math.round(compA * 255);
+ }
+ }
+ }
+
+ if (maskFrac < 1.0) {
+ const invM = 1 - maskFrac;
+ const bA = da / 255;
+ const aA = outA / 255;
+ const mixA = bA * invM + aA * maskFrac;
+ if (mixA <= 0.0001) {
+ dst[dstOff] = 0;
+ dst[dstOff + 1] = 0;
+ dst[dstOff + 2] = 0;
+ dst[dstOff + 3] = 0;
+ } else {
+ const invMixA = 1 / mixA;
+ dst[dstOff] = Math.round((dst[dstOff] * bA * invM + outR * aA * maskFrac) * invMixA);
+ dst[dstOff + 1] = Math.round((dst[dstOff + 1] * bA * invM + outG * aA * maskFrac) * invMixA);
+ dst[dstOff + 2] = Math.round((dst[dstOff + 2] * bA * invM + outB * aA * maskFrac) * invMixA);
+ dst[dstOff + 3] = Math.round(mixA * 255);
+ }
+ } else {
+ dst[dstOff] = outR;
+ dst[dstOff + 1] = outG;
+ dst[dstOff + 2] = outB;
+ dst[dstOff + 3] = outA;
+ }
+ }
+ }
+ } else {
+ // grayscale-8bit fallback
+ const tileScratch = host.writeScratchRGBA;
+ unpack8BitToRGBA(tile.data, tileScratch);
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ let srcOff = (sy * w + srcStartX) << 2;
+ let dstOff = (tileLocalY * TILE_SIZE + localStartX) << 2;
+ for (let dx = 0; dx < copyWidth; dx++, srcOff += 4, dstOff += 4) {
+ const sa = srcData[srcOff + 3];
+ if (sa === 0) continue;
+ const effA = fullOpacity ? sa : Math.round(sa * opacity);
+ if (compositeOp === 'destination-out') {
+ tileScratch[dstOff + 3] = Math.round(tileScratch[dstOff + 3] * (1 - effA / 255));
+ } else if (effA > 0) {
+ const sA = effA / 255;
+ const inv = 1 - sA;
+ tileScratch[dstOff] = Math.round(srcData[srcOff] * sA + tileScratch[dstOff] * inv);
+ tileScratch[dstOff + 1] = Math.round(srcData[srcOff + 1] * sA + tileScratch[dstOff + 1] * inv);
+ tileScratch[dstOff + 2] = Math.round(srcData[srcOff + 2] * sA + tileScratch[dstOff + 2] * inv);
+ tileScratch[dstOff + 3] = Math.min(255, Math.round(tileScratch[dstOff + 3] * inv + effA));
+ }
+ }
+ }
+ packRGBATo8Bit(tileScratch, tile.data);
+ }
+
+ tile.solidColorU32 = undefined;
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ host.markLodAncestorsDirty(layerId, tx, ty);
+ anyModified = true;
+ }
+ }
+
+ if (anyModified) {
+ host.bumpLayerVersion(layerId);
+ if (!suppressNotify) {
+ host.notifyChange();
+ }
+ }
+ return anyModified;
+}
diff --git a/src/utils/tileEngine/tileFill.ts b/src/utils/tileEngine/tileFill.ts
new file mode 100644
index 0000000..9cdd70e
--- /dev/null
+++ b/src/utils/tileEngine/tileFill.ts
@@ -0,0 +1,244 @@
+/**
+ * Solid layer fills and full-canvas ingestion operations for SparseTileGrid.
+ */
+
+import { setPixel1Bit } from './pixelCodec';
+import {
+ ISparseTileGridHost,
+ PAPER_WHITE_U32,
+ TILE_PIXELS,
+ TILE_SIZE,
+ TileFormat,
+ allocateTileVersion,
+ getTileByteSize,
+ isLittleEndian,
+ pixelToTileCoord,
+} from './types';
+
+export function fillLayerSolidColor(
+ host: ISparseTileGridHost,
+ layerId: string,
+ width: number,
+ height: number,
+ colorCss: string,
+ format?: TileFormat
+): void {
+ const lower = (colorCss || '').trim().toLowerCase();
+ if (!lower || lower === 'transparent') {
+ host.clearLayer(layerId);
+ host.ingestedLayers.add(layerId);
+ if (format) host.setLayerFormat(layerId, format);
+ return;
+ }
+ if (lower === '#ffffff' || lower === '#fff' || lower === 'white') {
+ host.fillLayerSolidWhite(layerId, width, height, format);
+ return;
+ }
+
+ let r = 255, g = 255, b = 255, a = 255;
+ if (lower.startsWith('#')) {
+ const hex = lower.slice(1);
+ if (hex.length === 3) {
+ r = parseInt(hex[0] + hex[0], 16) || 0;
+ g = parseInt(hex[1] + hex[1], 16) || 0;
+ b = parseInt(hex[2] + hex[2], 16) || 0;
+ } else if (hex.length >= 6) {
+ r = parseInt(hex.slice(0, 2), 16) || 0;
+ g = parseInt(hex.slice(2, 4), 16) || 0;
+ b = parseInt(hex.slice(4, 6), 16) || 0;
+ if (hex.length === 8) {
+ a = parseInt(hex.slice(6, 8), 16) || 255;
+ }
+ }
+ } else if (lower === 'black') {
+ r = 0; g = 0; b = 0;
+ }
+
+ host.clearLayer(layerId);
+ host.ingestedLayers.add(layerId);
+ if (format) host.setLayerFormat(layerId, format);
+ if (width <= 0 || height <= 0) return;
+
+ const targetFormat = format || host.getLayerFormat(layerId);
+ const pixelU32 = isLittleEndian
+ ? ((a << 24) | (b << 16) | (g << 8) | r) >>> 0
+ : ((r << 24) | (g << 16) | (b << 8) | a) >>> 0;
+ const grayVal = Math.round((r * 299 + g * 587 + b * 114) / 1000);
+ const isInk1Bit = a >= 24 && grayVal < 128;
+
+ if (targetFormat === 'monochrome-1bit' && !isInk1Bit) {
+ host.notifyChange();
+ return;
+ }
+
+ const maxTileX = pixelToTileCoord(width - 1, 0);
+ const maxTileY = pixelToTileCoord(height - 1, 0);
+ const memoryManager = host.getMemoryManager();
+
+ for (let ty = 0; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const validH = Math.min(TILE_SIZE, height - tileDocY);
+ for (let tx = 0; tx <= maxTileX; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, width - tileDocX);
+ const tile = host.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
+ if (!tile.data) {
+ tile.data = new Uint8Array(getTileByteSize(tile.format));
+ memoryManager?.notifyTileAllocated(tile);
+ }
+ if (tile.format === 'color-32bit') {
+ const dst32 = new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS);
+ if (validW === TILE_SIZE && validH === TILE_SIZE) {
+ dst32.fill(pixelU32);
+ tile.solidColorU32 = pixelU32;
+ } else {
+ tile.solidColorU32 = undefined;
+ dst32.fill(0);
+ for (let y = 0; y < validH; y++) {
+ const rowStart = y * TILE_SIZE;
+ dst32.fill(pixelU32, rowStart, rowStart + validW);
+ }
+ }
+ } else if (tile.format === 'grayscale-8bit') {
+ tile.solidColorU32 = undefined;
+ if (validW === TILE_SIZE && validH === TILE_SIZE) {
+ tile.data.fill(grayVal);
+ } else {
+ tile.data.fill(0);
+ for (let y = 0; y < validH; y++) {
+ const rowStart = y * TILE_SIZE;
+ tile.data.fill(grayVal, rowStart, rowStart + validW);
+ }
+ }
+ } else {
+ tile.solidColorU32 = undefined;
+ tile.data.fill(0);
+ for (let y = 0; y < validH; y++) {
+ for (let x = 0; x < validW; x++) {
+ setPixel1Bit(tile.data, x, y, true);
+ }
+ }
+ }
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ host.markLodAncestorsDirty(layerId, tx, ty);
+ }
+ }
+ host.bumpLayerVersion(layerId);
+ host.notifyChange();
+}
+
+export function fillLayerSolidWhite(
+ host: ISparseTileGridHost,
+ layerId: string,
+ width: number,
+ height: number,
+ format?: TileFormat
+): void {
+ host.clearLayer(layerId);
+ host.ingestedLayers.add(layerId);
+ if (format) {
+ host.setLayerFormat(layerId, format);
+ }
+ if (width <= 0 || height <= 0) return;
+
+ const targetFormat = format || host.getLayerFormat(layerId);
+ if (targetFormat === 'monochrome-1bit') {
+ // Solid white in monochrome-1bit has 0 black ink bits
+ host.notifyChange();
+ return;
+ }
+
+ const maxTileX = pixelToTileCoord(width - 1, 0);
+ const maxTileY = pixelToTileCoord(height - 1, 0);
+ const memoryManager = host.getMemoryManager();
+
+ for (let ty = 0; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const validH = Math.min(TILE_SIZE, height - tileDocY);
+ for (let tx = 0; tx <= maxTileX; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, width - tileDocX);
+ const tile = host.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
+ if (!tile.data) {
+ tile.data = new Uint8Array(getTileByteSize(tile.format));
+ memoryManager?.notifyTileAllocated(tile);
+ }
+ if (validW === TILE_SIZE && validH === TILE_SIZE) {
+ if (tile.format === 'color-32bit') {
+ new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS).fill(PAPER_WHITE_U32);
+ tile.solidColorU32 = PAPER_WHITE_U32;
+ } else {
+ tile.data.fill(255);
+ tile.solidColorU32 = undefined;
+ }
+ } else if (tile.format === 'color-32bit') {
+ tile.solidColorU32 = undefined;
+ const dst32 = new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS);
+ dst32.fill(0);
+ for (let y = 0; y < validH; y++) {
+ const rowStart = y * TILE_SIZE;
+ dst32.fill(PAPER_WHITE_U32, rowStart, rowStart + validW);
+ }
+ } else {
+ tile.solidColorU32 = undefined;
+ tile.data.fill(0);
+ for (let y = 0; y < validH; y++) {
+ const rowStart = y * TILE_SIZE;
+ tile.data.fill(255, rowStart, rowStart + validW);
+ }
+ }
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ host.markLodAncestorsDirty(layerId, tx, ty);
+ }
+ }
+ host.bumpLayerVersion(layerId);
+ host.notifyChange();
+}
+
+export function ingestCanvas(
+ host: ISparseTileGridHost,
+ layerId: string,
+ canvas: HTMLCanvasElement,
+ format?: TileFormat
+): void {
+ if (canvas.width <= 0 || canvas.height <= 0) return;
+ if (format) {
+ host.setLayerFormat(layerId, format);
+ }
+ if ((canvas as any).__isBlank) {
+ host.clearLayer(layerId);
+ host.ingestedLayers.add(layerId);
+ if (format) {
+ host.setLayerFormat(layerId, format);
+ }
+ return;
+ }
+ if ((canvas as any).__isSolidWhite) {
+ host.fillLayerSolidWhite(layerId, canvas.width, canvas.height, format);
+ return;
+ }
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return;
+
+ host.clearLayer(layerId);
+ host.ingestedLayers.add(layerId);
+ if (format) {
+ host.setLayerFormat(layerId, format);
+ }
+ const w = canvas.width;
+ const h = canvas.height;
+ if (w * h <= 1024 * 1024) {
+ const imgData = ctx.getImageData(0, 0, w, h);
+ host.writeImageData(layerId, imgData, 0, 0, format, true);
+ } else {
+ const stripH = TILE_SIZE;
+ for (let y = 0; y < h; y += stripH) {
+ const curH = Math.min(stripH, h - y);
+ const stripData = ctx.getImageData(0, y, w, curH);
+ host.writeImageData(layerId, stripData, 0, y, format, true);
+ }
+ }
+ host.notifyChange();
+}
diff --git a/src/utils/tileEngine/tileIO.ts b/src/utils/tileEngine/tileIO.ts
new file mode 100644
index 0000000..d89c30e
--- /dev/null
+++ b/src/utils/tileEngine/tileIO.ts
@@ -0,0 +1,378 @@
+/**
+ * Pixel-buffer I/O operations for SparseTileGrid:
+ * writing and reading arbitrary RGBA rectangles across sparse tiles.
+ */
+
+import { packRGBATo8Bit, unpack1BitToRGBA, unpack8BitToRGBA } from './pixelCodec';
+import {
+ BYTES_32BIT,
+ ISparseTileGridHost,
+ TILE_SIZE,
+ TileBuffer,
+ TileFormat,
+ allocateTileVersion,
+ getTileByteSize,
+ pixelToTileCoord,
+} from './types';
+
+export function getTilesInBounds(
+ host: ISparseTileGridHost,
+ layerId: string,
+ minX: number,
+ minY: number,
+ maxX: number,
+ maxY: number,
+ lod: number = 0
+): TileBuffer[] {
+ if (lod === 0 && !host.hasLayerTiles(layerId)) {
+ return [];
+ }
+ const minTileX = pixelToTileCoord(minX, lod);
+ const minTileY = pixelToTileCoord(minY, lod);
+ const maxTileX = pixelToTileCoord(maxX, lod);
+ const maxTileY = pixelToTileCoord(maxY, lod);
+
+ const result: TileBuffer[] = [];
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ if (lod > 0 && !host.hasPopulatedLodTile(layerId, tx, ty, lod)) {
+ const direct = host.getTile(layerId, tx, ty, lod);
+ if (direct) result.push(direct);
+ continue;
+ }
+ let tile = host.getTile(layerId, tx, ty, lod);
+ if (lod > 0 && (!tile || host.isLodTileDirty(layerId, tx, ty, lod))) {
+ tile = host.generateLodTile(layerId, tx, ty, lod);
+ }
+ if (tile) {
+ result.push(tile);
+ }
+ }
+ }
+ return result;
+}
+
+export function getIntersectingCoords(
+ minX: number,
+ minY: number,
+ maxX: number,
+ maxY: number,
+ lod: number = 0
+): Array<{ tileX: number; tileY: number }> {
+ const minTileX = pixelToTileCoord(minX, lod);
+ const minTileY = pixelToTileCoord(minY, lod);
+ const maxTileX = pixelToTileCoord(maxX, lod);
+ const maxTileY = pixelToTileCoord(maxY, lod);
+
+ const coords: Array<{ tileX: number; tileY: number }> = [];
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ coords.push({ tileX: tx, tileY: ty });
+ }
+ }
+ return coords;
+}
+
+/**
+ * Transparently returns a 256x256 RGBA Uint8ClampedArray for WebGL texture upload or 2D blitting.
+ * If tile data is paged to disk, kicks off an asynchronous fetch without freezing rendering.
+ */
+export function getTileAsRGBA(host: ISparseTileGridHost, tile: TileBuffer): Uint8ClampedArray {
+ if (tile.data === null) {
+ const memoryManager = host.getMemoryManager();
+ if (tile.isPagedToDisk && memoryManager) {
+ void memoryManager.requestTileData(tile);
+ }
+ host.scratchRGBA.fill(0);
+ return host.scratchRGBA;
+ }
+
+ if (tile.format === 'color-32bit') {
+ return new Uint8ClampedArray(tile.data.buffer, tile.data.byteOffset, BYTES_32BIT);
+ }
+ if (tile.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(tile.data, host.scratchRGBA);
+ return host.scratchRGBA;
+ }
+ // 8-bit grayscale
+ unpack8BitToRGBA(tile.data, host.scratchRGBA);
+ return host.scratchRGBA;
+}
+
+/**
+ * Writes an ImageData or RGBA buffer into the sparse tile grid.
+ * Only allocates tiles that actually intersect the drawn rectangle.
+ */
+export function writeImageData(
+ host: ISparseTileGridHost,
+ layerId: string,
+ imgData: { data: Uint8ClampedArray | Uint8Array; width: number; height: number },
+ destX: number,
+ destY: number,
+ format?: TileFormat,
+ suppressNotify: boolean = false
+): { minTileX: number; minTileY: number; maxTileX: number; maxTileY: number } {
+ host.ingestedLayers.add(layerId);
+ if (format) {
+ host.setLayerFormat(layerId, format);
+ }
+ const targetFormat = format || host.getLayerFormat(layerId);
+ const w = imgData.width;
+ const h = imgData.height;
+ if (w <= 0 || h <= 0) {
+ return { minTileX: 0, minTileY: 0, maxTileX: 0, maxTileY: 0 };
+ }
+
+ const minTileX = pixelToTileCoord(destX, 0);
+ const minTileY = pixelToTileCoord(destY, 0);
+ const maxTileX = pixelToTileCoord(destX + w - 1, 0);
+ const maxTileY = pixelToTileCoord(destY + h - 1, 0);
+
+ const tileScratch = host.writeScratchRGBA;
+ const srcData = imgData.data;
+ const src32 =
+ srcData.byteOffset % 4 === 0 && srcData.byteLength >= w * h * 4
+ ? new Uint32Array(srcData.buffer, srcData.byteOffset, w * h)
+ : null;
+ const memoryManager = host.getMemoryManager();
+
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+
+ const srcStartX = Math.max(0, tileDocX - destX);
+ const srcStartY = Math.max(0, tileDocY - destY);
+ const srcEndX = Math.min(w, tileDocX + TILE_SIZE - destX);
+ const srcEndY = Math.min(h, tileDocY + TILE_SIZE - destY);
+
+ if (srcStartX >= srcEndX || srcStartY >= srcEndY) continue;
+
+ let existingTile = host.getTile(layerId, tx, ty, 0);
+ if (!existingTile) {
+ let hasNonZero = false;
+ if (src32 !== null) {
+ outer32: for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const rowOff = sy * w;
+ for (let sx = rowOff + srcStartX, end = rowOff + srcEndX; sx < end; sx++) {
+ if (src32[sx] !== 0) {
+ hasNonZero = true;
+ break outer32;
+ }
+ }
+ }
+ } else {
+ outer: for (let sy = srcStartY; sy < srcEndY; sy++) {
+ let idx = (sy * w + srcStartX) * 4;
+ const endIdx = (sy * w + srcEndX) * 4;
+ for (; idx < endIdx; idx += 4) {
+ if (srcData[idx + 3] !== 0 || srcData[idx] !== 0 || srcData[idx + 1] !== 0 || srcData[idx + 2] !== 0) {
+ hasNonZero = true;
+ break outer;
+ }
+ }
+ }
+ }
+ if (!hasNonZero) continue;
+ existingTile = host.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
+ }
+
+ const tile = existingTile;
+ if (tile.format !== targetFormat) {
+ if (tile.data !== null) {
+ memoryManager?.notifyTileFreed(tile);
+ }
+ tile.format = targetFormat;
+ tile.data = new Uint8Array(getTileByteSize(targetFormat));
+ memoryManager?.notifyTileAllocated(tile);
+ } else if (tile.data === null) {
+ tile.data = new Uint8Array(getTileByteSize(tile.format));
+ memoryManager?.notifyTileAllocated(tile);
+ }
+
+ if (tile.format === 'color-32bit') {
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ const tileLocalX = destX + srcStartX - tileDocX;
+ const copyWidth = srcEndX - srcStartX;
+
+ const srcByteOffset = (sy * w + srcStartX) * 4;
+ const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
+
+ tile.data.set(
+ srcData.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
+ tileByteOffset
+ );
+ }
+ } else if (tile.format === 'monochrome-1bit') {
+ const dst = tile.data;
+ const localStartX = destX + srcStartX - tileDocX;
+ const copyWidth = srcEndX - srcStartX;
+ const localEndX = localStartX + copyWidth;
+
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ const rowByteBase = tileLocalY << 5; // TILE_SIZE / 8 = 32
+ let lx = localStartX;
+ let srcPixIdx = sy * w + srcStartX;
+ let srcOff = srcPixIdx << 2;
+
+ // Leading unaligned pixels before an 8-pixel boundary
+ if ((lx & 7) !== 0) {
+ const byteIdx = rowByteBase + (lx >> 3);
+ let byteVal = dst[byteIdx];
+ const stop = Math.min(localEndX, (lx + 7) & ~7);
+ while (lx < stop) {
+ const mask = 1 << (7 - (lx & 7));
+ const a = srcData[srcOff + 3];
+ if (
+ a >= 24 &&
+ srcData[srcOff] * 299 + srcData[srcOff + 1] * 587 + srcData[srcOff + 2] * 114 < 128000
+ ) {
+ byteVal |= mask;
+ } else {
+ byteVal &= ~mask;
+ }
+ lx++;
+ srcPixIdx++;
+ srcOff += 4;
+ }
+ dst[byteIdx] = byteVal;
+ }
+
+ // Full 8-pixel aligned bytes
+ while (lx + 8 <= localEndX) {
+ const byteIdx = rowByteBase + (lx >> 3);
+ if (
+ src32 !== null &&
+ (src32[srcPixIdx] |
+ src32[srcPixIdx + 1] |
+ src32[srcPixIdx + 2] |
+ src32[srcPixIdx + 3] |
+ src32[srcPixIdx + 4] |
+ src32[srcPixIdx + 5] |
+ src32[srcPixIdx + 6] |
+ src32[srcPixIdx + 7]) === 0
+ ) {
+ dst[byteIdx] = 0;
+ lx += 8;
+ srcPixIdx += 8;
+ srcOff += 32;
+ continue;
+ }
+ let byteVal = 0;
+ for (let bit = 7; bit >= 0; bit--) {
+ const a = srcData[srcOff + 3];
+ if (
+ a >= 24 &&
+ srcData[srcOff] * 299 + srcData[srcOff + 1] * 587 + srcData[srcOff + 2] * 114 < 128000
+ ) {
+ byteVal |= 1 << bit;
+ }
+ srcOff += 4;
+ }
+ dst[byteIdx] = byteVal;
+ lx += 8;
+ srcPixIdx += 8;
+ }
+
+ // Trailing unaligned pixels
+ if (lx < localEndX) {
+ const byteIdx = rowByteBase + (lx >> 3);
+ let byteVal = dst[byteIdx];
+ while (lx < localEndX) {
+ const mask = 1 << (7 - (lx & 7));
+ const a = srcData[srcOff + 3];
+ if (
+ a >= 24 &&
+ srcData[srcOff] * 299 + srcData[srcOff + 1] * 587 + srcData[srcOff + 2] * 114 < 128000
+ ) {
+ byteVal |= mask;
+ } else {
+ byteVal &= ~mask;
+ }
+ lx++;
+ srcOff += 4;
+ }
+ dst[byteIdx] = byteVal;
+ }
+ }
+ } else {
+ unpack8BitToRGBA(tile.data, tileScratch);
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ const tileLocalX = destX + srcStartX - tileDocX;
+ const copyWidth = srcEndX - srcStartX;
+
+ const srcByteOffset = (sy * w + srcStartX) * 4;
+ const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
+
+ tileScratch.set(
+ srcData.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
+ tileByteOffset
+ );
+ }
+ packRGBATo8Bit(tileScratch, tile.data);
+ }
+
+ tile.solidColorU32 = undefined;
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ host.markLodAncestorsDirty(layerId, tx, ty);
+ }
+ }
+
+ host.bumpLayerVersion(layerId);
+ if (!suppressNotify) {
+ host.notifyChange();
+ }
+ return { minTileX, minTileY, maxTileX, maxTileY };
+}
+
+export function readImageData(
+ host: ISparseTileGridHost,
+ layerId: string,
+ x: number,
+ y: number,
+ width: number,
+ height: number
+): { data: Uint8ClampedArray; width: number; height: number } {
+ const outData = new Uint8ClampedArray(width * height * 4);
+ if (width <= 0 || height <= 0) return { data: outData, width, height };
+
+ const minTileX = pixelToTileCoord(x, 0);
+ const minTileY = pixelToTileCoord(y, 0);
+ const maxTileX = pixelToTileCoord(x + width - 1, 0);
+ const maxTileY = pixelToTileCoord(y + height - 1, 0);
+
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ const tile = host.getTile(layerId, tx, ty, 0);
+ if (!tile) continue;
+
+ const tileDocX = tx * TILE_SIZE;
+ const tileRGBA = host.getTileAsRGBA(tile);
+
+ const interStartX = Math.max(x, tileDocX);
+ const interStartY = Math.max(y, tileDocY);
+ const interEndX = Math.min(x + width, tileDocX + TILE_SIZE);
+ const interEndY = Math.min(y + height, tileDocY + TILE_SIZE);
+
+ for (let py = interStartY; py < interEndY; py++) {
+ const tileLocalY = py - tileDocY;
+ const tileLocalX = interStartX - tileDocX;
+ const outLocalY = py - y;
+ const outLocalX = interStartX - x;
+ const copyWidth = interEndX - interStartX;
+
+ const tileOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
+ const outOffset = (outLocalY * width + outLocalX) * 4;
+
+ outData.set(tileRGBA.subarray(tileOffset, tileOffset + copyWidth * 4), outOffset);
+ }
+ }
+ }
+
+ return { data: outData, width, height };
+}
diff --git a/src/utils/tileEngine/tileOps.ts b/src/utils/tileEngine/tileOps.ts
new file mode 100644
index 0000000..cfd85a9
--- /dev/null
+++ b/src/utils/tileEngine/tileOps.ts
@@ -0,0 +1,1134 @@
+/**
+ * Direct tile-native pixel operations for SparseTileGrid.
+ * Eliminates full-document HTMLCanvasElement materialization across tools,
+ * transforms, merges, masks, resizes, and clipboard operations.
+ */
+
+import type { BlendMode, CanvasDimensions, DirtyRect } from '../../types/editor';
+import { getCanvasCompositeOperation } from '../canvasUtils';
+import { getPixel1Bit, packRGBATo1Bit, packRGBATo8Bit, unpack1BitToRGBA, unpack8BitToRGBA } from './pixelCodec';
+import {
+ BYTES_32BIT,
+ ISparseTileGridHost,
+ PAPER_WHITE_U32,
+ TILE_PIXELS,
+ TILE_SIZE,
+ TileBuffer,
+ TileFormat,
+ TileSnapshotEntry,
+ allocateTileVersion,
+ getTileByteSize,
+ getTileKey,
+ parseTileKey,
+ pixelToTileCoord,
+ releaseTemporaryCanvas,
+} from './types';
+
+function isBufferAllZero(buf: Uint8Array): boolean {
+ const len = buf.byteLength;
+ if (buf.byteOffset % 4 === 0 && len % 4 === 0) {
+ const u32 = new Uint32Array(buf.buffer, buf.byteOffset, len >>> 2);
+ for (let i = 0; i < u32.length; i++) {
+ if (u32[i] !== 0) return false;
+ }
+ return true;
+ }
+ for (let i = 0; i < len; i++) {
+ if (buf[i] !== 0) return false;
+ }
+ return true;
+}
+
+function isRgbaAllTransparent(rgba: Uint8ClampedArray | Uint8Array): boolean {
+ for (let i = 3; i < rgba.length; i += 4) {
+ if (rgba[i] !== 0) return false;
+ }
+ return true;
+}
+
+/**
+ * O(1) zero-allocation single-pixel RGBA read from LOD 0 tiles.
+ */
+export function getPixelRGBA(
+ host: ISparseTileGridHost,
+ layerId: string,
+ x: number,
+ y: number,
+ out: [number, number, number, number] = [0, 0, 0, 0]
+): [number, number, number, number] {
+ const ix = Math.floor(x);
+ const iy = Math.floor(y);
+ const tx = pixelToTileCoord(ix, 0);
+ const ty = pixelToTileCoord(iy, 0);
+ const tile = host.getTile(layerId, tx, ty, 0);
+ if (!tile || !tile.data) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ return out;
+ }
+ const lx = ix - tx * TILE_SIZE;
+ const ly = iy - ty * TILE_SIZE;
+ if (tile.format === 'color-32bit') {
+ const off = (ly * TILE_SIZE + lx) << 2;
+ out[0] = tile.data[off];
+ out[1] = tile.data[off + 1];
+ out[2] = tile.data[off + 2];
+ out[3] = tile.data[off + 3];
+ return out;
+ }
+ if (tile.format === 'monochrome-1bit') {
+ const ink = getPixel1Bit(tile.data, lx, ly);
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = ink ? 255 : 0;
+ return out;
+ }
+ const gray = tile.data[ly * TILE_SIZE + lx];
+ out[0] = gray;
+ out[1] = gray;
+ out[2] = gray;
+ out[3] = 255 - gray;
+ return out;
+}
+
+/**
+ * Lazily records a single LOD 0 tile's pre-edit bytes into `snapshotOut` if not yet recorded.
+ */
+export function snapshotSingleTileInto(
+ host: ISparseTileGridHost,
+ layerId: string,
+ tileX: number,
+ tileY: number,
+ snapshotOut: Map<string, TileSnapshotEntry>
+): void {
+ const key = getTileKey(layerId, tileX, tileY, 0);
+ if (snapshotOut.has(key)) return;
+ const tile = host.getTile(layerId, tileX, tileY, 0);
+ if (tile && tile.data) {
+ const copy = new Uint8Array(tile.data.length);
+ copy.set(tile.data);
+ snapshotOut.set(key, { format: tile.format, data: copy });
+ } else {
+ snapshotOut.set(key, { format: host.getLayerFormat(layerId), data: null });
+ }
+}
+
+/**
+ * Restores a layer's LOD 0 tiles from a pre-edit snapshot map (for cancel/revert operations).
+ */
+export function restoreLayerSnapshot(
+ host: ISparseTileGridHost,
+ layerId: string,
+ snapshot: Map<string, TileSnapshotEntry>,
+ suppressNotify: boolean = false
+): void {
+ const memoryManager = host.getMemoryManager();
+ // Delete any tiles that currently exist for this layer if snapshot says they didn't exist
+ for (const [key, entry] of snapshot.entries()) {
+ const parsed = parseTileKey(key);
+ if (parsed.layerId !== layerId) continue;
+ const { tileX, tileY } = parsed;
+ if (!entry.data) {
+ host.deleteTile(layerId, tileX, tileY, 0);
+ } else {
+ let tile = host.getTile(layerId, tileX, tileY, 0);
+ if (!tile) {
+ tile = host.getOrCreateTile(layerId, tileX, tileY, entry.format, 0);
+ }
+ if (!tile.data || tile.data.byteLength !== entry.data.byteLength) {
+ if (tile.data) memoryManager?.notifyTileFreed(tile);
+ tile.data = new Uint8Array(entry.data.length);
+ memoryManager?.notifyTileAllocated(tile);
+ }
+ tile.data.set(entry.data);
+ tile.format = entry.format;
+ tile.solidColorU32 = undefined;
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ host.setLayerFormat(layerId, entry.format);
+ host.markLodAncestorsDirty(layerId, tileX, tileY);
+ }
+ }
+ host.bumpLayerVersion(layerId);
+ if (!suppressNotify) {
+ host.notifyChange(true);
+ }
+}
+
+/**
+ * Computes the union bounding box of allocated LOD 0 tiles clamped to document dimensions.
+ */
+export function getLayerTileBounds(
+ host: ISparseTileGridHost,
+ layerId: string,
+ dims: CanvasDimensions
+): DirtyRect | null {
+ const tiles = host.getLayerTiles(layerId, 0);
+ if (tiles.length === 0) return null;
+
+ let minX = dims.width;
+ let minY = dims.height;
+ let maxX = 0;
+ let maxY = 0;
+
+ for (const tile of tiles) {
+ const x0 = tile.tileX * TILE_SIZE;
+ const y0 = tile.tileY * TILE_SIZE;
+ if (x0 < minX) minX = x0;
+ if (y0 < minY) minY = y0;
+ if (x0 + TILE_SIZE > maxX) maxX = x0 + TILE_SIZE;
+ if (y0 + TILE_SIZE > maxY) maxY = y0 + TILE_SIZE;
+ }
+
+ const x = Math.max(0, minX);
+ const y = Math.max(0, minY);
+ const x1 = Math.min(dims.width, maxX);
+ const y1 = Math.min(dims.height, maxY);
+ if (x1 <= x || y1 <= y) return null;
+ return { x, y, width: x1 - x, height: y1 - y };
+}
+
+/**
+ * Computes tight pixel bounding box of non-transparent (or non-white for background) pixels
+ * by scanning ONLY populated LOD 0 tiles. Zero full-canvas reads.
+ */
+export function getLayerContentBounds(
+ host: ISparseTileGridHost,
+ layerId: string,
+ dims: CanvasDimensions,
+ isBackground: boolean = false
+): DirtyRect | null {
+ const tiles = host.getLayerTiles(layerId, 0);
+ if (tiles.length === 0 || dims.width <= 0 || dims.height <= 0) return null;
+
+ let minX = dims.width;
+ let minY = dims.height;
+ let maxX = -1;
+ let maxY = -1;
+
+ for (const tile of tiles) {
+ if (!tile.data) continue;
+ if (isBackground && tile.solidColorU32 === PAPER_WHITE_U32) continue;
+
+ const tileDocX = tile.tileX * TILE_SIZE;
+ const tileDocY = tile.tileY * TILE_SIZE;
+ if (tileDocX >= dims.width || tileDocY >= dims.height) continue;
+ if (tileDocX + TILE_SIZE <= 0 || tileDocY + TILE_SIZE <= 0) continue;
+
+ const startLX = Math.max(0, -tileDocX);
+ const startLY = Math.max(0, -tileDocY);
+ const endLX = Math.min(TILE_SIZE, dims.width - tileDocX);
+ const endLY = Math.min(TILE_SIZE, dims.height - tileDocY);
+
+ if (tile.format === 'monochrome-1bit') {
+ const data = tile.data;
+ for (let ly = startLY; ly < endLY; ly++) {
+ const rowByteBase = ly << 5;
+ const docY = tileDocY + ly;
+ for (let bx = startLX >> 3, endBx = (endLX + 7) >> 3; bx < endBx; bx++) {
+ const byte = data[rowByteBase + bx];
+ if (byte === 0) continue;
+ for (let bit = 7; bit >= 0; bit--) {
+ if ((byte & (1 << bit)) === 0) continue;
+ const lx = (bx << 3) + (7 - bit);
+ if (lx < startLX || lx >= endLX) continue;
+ const docX = tileDocX + lx;
+ if (docX < minX) minX = docX;
+ if (docX > maxX) maxX = docX;
+ if (docY < minY) minY = docY;
+ if (docY > maxY) maxY = docY;
+ }
+ }
+ }
+ continue;
+ }
+
+ const rgba = host.getTileAsRGBA(tile);
+ for (let ly = startLY; ly < endLY; ly++) {
+ const docY = tileDocY + ly;
+ let off = (ly * TILE_SIZE + startLX) << 2;
+ for (let lx = startLX; lx < endLX; lx++, off += 4) {
+ const a = rgba[off + 3];
+ if (a === 0) continue;
+ if (isBackground && rgba[off] === 255 && rgba[off + 1] === 255 && rgba[off + 2] === 255) {
+ continue;
+ }
+ const docX = tileDocX + lx;
+ if (docX < minX) minX = docX;
+ if (docX > maxX) maxX = docX;
+ if (docY < minY) minY = docY;
+ if (docY > maxY) maxY = docY;
+ }
+ }
+ }
+
+ if (maxX < 0 || maxY < 0) return null;
+
+ const pad = 4;
+ const clampedMinX = Math.max(0, minX - pad);
+ const clampedMinY = Math.max(0, minY - pad);
+ const clampedMaxX = Math.min(dims.width - 1, maxX + pad);
+ const clampedMaxY = Math.min(dims.height - 1, maxY + pad);
+
+ return {
+ x: clampedMinX,
+ y: clampedMinY,
+ width: Math.min(dims.width - clampedMinX, Math.max(10, clampedMaxX - clampedMinX + 1)),
+ height: Math.min(dims.height - clampedMinY, Math.max(10, clampedMaxY - clampedMinY + 1)),
+ };
+}
+
+/**
+ * Deletes any LOD 0 tiles in `layerId` whose pixel buffers are completely zero/transparent.
+ */
+export function pruneEmptyTiles(host: ISparseTileGridHost, layerId: string): number {
+ const tiles = host.getLayerTiles(layerId, 0);
+ let pruned = 0;
+ for (const tile of tiles) {
+ if (!tile.data) continue;
+ const isEmpty =
+ tile.format === 'color-32bit'
+ ? isRgbaAllTransparent(tile.data)
+ : isBufferAllZero(tile.data);
+ if (isEmpty) {
+ host.deleteTile(layerId, tile.tileX, tile.tileY, 0);
+ pruned++;
+ }
+ }
+ return pruned;
+}
+
+/**
+ * Clears (or fills solid white for background layers) an arbitrary document rect directly in LOD 0 tiles.
+ */
+export function clearRectInLayer(
+ host: ISparseTileGridHost,
+ layerId: string,
+ rect: DirtyRect,
+ fillWhite: boolean = false,
+ snapshotOut?: Map<string, TileSnapshotEntry>,
+ suppressNotify: boolean = false
+): void {
+ const x0 = Math.floor(rect.x);
+ const y0 = Math.floor(rect.y);
+ const x1 = Math.ceil(rect.x + rect.width);
+ const y1 = Math.ceil(rect.y + rect.height);
+ if (x1 <= x0 || y1 <= y0) return;
+
+ const minTx = pixelToTileCoord(x0, 0);
+ const minTy = pixelToTileCoord(y0, 0);
+ const maxTx = pixelToTileCoord(x1 - 1, 0);
+ const maxTy = pixelToTileCoord(y1 - 1, 0);
+ const layerFmt = host.getLayerFormat(layerId);
+
+ for (let ty = minTy; ty <= maxTy; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const startLY = Math.max(0, y0 - tileDocY);
+ const endLY = Math.min(TILE_SIZE, y1 - tileDocY);
+ if (startLY >= endLY) continue;
+
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+ const startLX = Math.max(0, x0 - tileDocX);
+ const endLX = Math.min(TILE_SIZE, x1 - tileDocX);
+ if (startLX >= endLX) continue;
+
+ const existing = host.getTile(layerId, tx, ty, 0);
+ if (!fillWhite && !existing) continue;
+
+ if (snapshotOut) {
+ snapshotSingleTileInto(host, layerId, tx, ty, snapshotOut);
+ }
+
+ const fullTile = startLX === 0 && startLY === 0 && endLX === TILE_SIZE && endLY === TILE_SIZE;
+ if (!fillWhite && fullTile) {
+ host.deleteTile(layerId, tx, ty, 0);
+ continue;
+ }
+
+ const tile = existing ?? host.getOrCreateTile(layerId, tx, ty, layerFmt, 0);
+ if (!tile.data) {
+ tile.data = new Uint8Array(getTileByteSize(tile.format));
+ host.getMemoryManager()?.notifyTileAllocated(tile);
+ }
+
+ if (tile.format === 'color-32bit') {
+ const u32 = new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS);
+ const fillVal = fillWhite ? PAPER_WHITE_U32 : 0;
+ if (fullTile) {
+ u32.fill(fillVal);
+ tile.solidColorU32 = fillWhite ? PAPER_WHITE_U32 : undefined;
+ } else {
+ tile.solidColorU32 = undefined;
+ for (let ly = startLY; ly < endLY; ly++) {
+ const row = ly * TILE_SIZE;
+ u32.fill(fillVal, row + startLX, row + endLX);
+ }
+ }
+ if (!fillWhite && isRgbaAllTransparent(tile.data)) {
+ host.deleteTile(layerId, tx, ty, 0);
+ continue;
+ }
+ } else if (tile.format === 'monochrome-1bit') {
+ const dst = tile.data;
+ for (let ly = startLY; ly < endLY; ly++) {
+ const rowBase = ly << 5;
+ for (let lx = startLX; lx < endLX; lx++) {
+ dst[rowBase + (lx >> 3)] &= ~(1 << (7 - (lx & 7)));
+ }
+ }
+ if (isBufferAllZero(dst)) {
+ host.deleteTile(layerId, tx, ty, 0);
+ continue;
+ }
+ } else {
+ const fillByte = fillWhite ? 255 : 0;
+ for (let ly = startLY; ly < endLY; ly++) {
+ const row = ly * TILE_SIZE;
+ tile.data.fill(fillByte, row + startLX, row + endLX);
+ }
+ if (!fillWhite && isBufferAllZero(tile.data)) {
+ host.deleteTile(layerId, tx, ty, 0);
+ continue;
+ }
+ }
+
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ host.markLodAncestorsDirty(layerId, tx, ty);
+ }
+ }
+
+ host.bumpLayerVersion(layerId);
+ if (!suppressNotify) {
+ host.notifyChange(true);
+ }
+}
+
+/**
+ * Applies an in-place RGBA transform callback to every populated LOD 0 tile of `layerId`.
+ * Automatically unpacks/repacks 1-bit/8-bit/32-bit tiles and deletes tiles that become empty.
+ */
+export function transformLayerTiles(
+ host: ISparseTileGridHost,
+ layerId: string,
+ visitor: (rgba: Uint8ClampedArray, tileX: number, tileY: number) => boolean | void,
+ options?: {
+ targetFormat?: TileFormat;
+ monoThreshold?: number;
+ snapshotOut?: Map<string, TileSnapshotEntry>;
+ suppressNotify?: boolean;
+ }
+): boolean {
+ const tiles = host.getLayerTiles(layerId, 0);
+ if (tiles.length === 0) return false;
+
+ const targetFormat = options?.targetFormat ?? host.getLayerFormat(layerId);
+ const monoThreshold = options?.monoThreshold ?? 128;
+ const memoryManager = host.getMemoryManager();
+ let anyModified = false;
+
+ for (const tile of tiles) {
+ if (!tile.data) continue;
+ if (options?.snapshotOut) {
+ snapshotSingleTileInto(host, layerId, tile.tileX, tile.tileY, options.snapshotOut);
+ }
+
+ const workRgba =
+ tile.format === 'color-32bit' && targetFormat === 'color-32bit'
+ ? new Uint8ClampedArray(tile.data.buffer, tile.data.byteOffset, BYTES_32BIT)
+ : new Uint8ClampedArray(host.getTileAsRGBA(tile));
+
+ const changed = visitor(workRgba, tile.tileX, tile.tileY);
+ if (changed === false) continue;
+
+ if (isRgbaAllTransparent(workRgba)) {
+ host.deleteTile(layerId, tile.tileX, tile.tileY, 0);
+ anyModified = true;
+ continue;
+ }
+
+ if (tile.format !== targetFormat) {
+ memoryManager?.notifyTileFreed(tile);
+ tile.format = targetFormat;
+ tile.data = new Uint8Array(getTileByteSize(targetFormat));
+ memoryManager?.notifyTileAllocated(tile);
+ }
+
+ if (targetFormat === 'color-32bit') {
+ if (workRgba.buffer !== tile.data.buffer) {
+ tile.data.set(workRgba);
+ }
+ } else if (targetFormat === 'monochrome-1bit') {
+ packRGBATo1Bit(workRgba, tile.data, monoThreshold);
+ if (isBufferAllZero(tile.data)) {
+ host.deleteTile(layerId, tile.tileX, tile.tileY, 0);
+ anyModified = true;
+ continue;
+ }
+ } else {
+ packRGBATo8Bit(workRgba, tile.data);
+ }
+
+ tile.solidColorU32 = undefined;
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ host.markLodAncestorsDirty(layerId, tile.tileX, tile.tileY);
+ anyModified = true;
+ }
+
+ host.setLayerFormat(layerId, targetFormat);
+ if (anyModified) {
+ host.bumpLayerVersion(layerId);
+ if (!options?.suppressNotify) {
+ host.notifyChange(true);
+ }
+ }
+ return anyModified;
+}
+
+/**
+ * Merges `srcLayerId` down onto `dstLayerId` strictly tile-by-tile (peak scratch: two 256x256 canvases = 512 KB).
+ */
+export function mergeLayersInGrid(
+ host: ISparseTileGridHost,
+ srcLayerId: string,
+ dstLayerId: string,
+ options: {
+ opacity: number;
+ blendMode: BlendMode;
+ visible: boolean;
+ maskCanvas?: HTMLCanvasElement;
+ maskEnabled?: boolean;
+ dimensions: CanvasDimensions;
+ dstFormat?: TileFormat;
+ }
+): void {
+ const { opacity, blendMode, visible, maskCanvas, maskEnabled, dimensions } = options;
+ const effectiveAlpha = visible ? Math.max(0, Math.min(1, opacity)) : 0;
+ if (effectiveAlpha <= 0.001 || !host.hasLayerTiles(srcLayerId)) {
+ host.clearLayer(srcLayerId);
+ host.notifyChange(true);
+ return;
+ }
+
+ const srcTiles = host.getLayerTiles(srcLayerId, 0);
+ const dstFormat = options.dstFormat ?? host.getLayerFormat(dstLayerId);
+
+ if (typeof document === 'undefined') {
+ // Headless fallback: straight alpha-over per tile
+ for (const srcTile of srcTiles) {
+ if (!srcTile.data) continue;
+ const srcRgba = new Uint8ClampedArray(host.getTileAsRGBA(srcTile));
+ const dstTile = host.getOrCreateTile(dstLayerId, srcTile.tileX, srcTile.tileY, dstFormat, 0);
+ const dstRgba = new Uint8ClampedArray(host.getTileAsRGBA(dstTile));
+ for (let i = 0; i < BYTES_32BIT; i += 4) {
+ const sA = (srcRgba[i + 3] / 255) * effectiveAlpha;
+ if (sA <= 0) continue;
+ const dA = dstRgba[i + 3] / 255;
+ const outA = sA + dA * (1 - sA);
+ if (outA > 0) {
+ dstRgba[i] = Math.round((srcRgba[i] * sA + dstRgba[i] * dA * (1 - sA)) / outA);
+ dstRgba[i + 1] = Math.round((srcRgba[i + 1] * sA + dstRgba[i + 1] * dA * (1 - sA)) / outA);
+ dstRgba[i + 2] = Math.round((srcRgba[i + 2] * sA + dstRgba[i + 2] * dA * (1 - sA)) / outA);
+ dstRgba[i + 3] = Math.round(outA * 255);
+ }
+ }
+ host.writeImageData(
+ dstLayerId,
+ { data: dstRgba, width: TILE_SIZE, height: TILE_SIZE },
+ srcTile.tileX * TILE_SIZE,
+ srcTile.tileY * TILE_SIZE,
+ dstFormat,
+ true
+ );
+ }
+ host.clearLayer(srcLayerId);
+ host.notifyChange(true);
+ return;
+ }
+
+ const srcTileCanvas = document.createElement('canvas');
+ srcTileCanvas.width = TILE_SIZE;
+ srcTileCanvas.height = TILE_SIZE;
+ const sCtx = srcTileCanvas.getContext('2d', { willReadFrequently: true });
+
+ const dstTileCanvas = document.createElement('canvas');
+ dstTileCanvas.width = TILE_SIZE;
+ dstTileCanvas.height = TILE_SIZE;
+ const dCtx = dstTileCanvas.getContext('2d', { willReadFrequently: true });
+
+ const hasMask = Boolean(maskCanvas && maskEnabled !== false);
+ const maskCtx = hasMask && maskCanvas ? maskCanvas.getContext('2d', { willReadFrequently: true }) : null;
+ const compositeOp = getCanvasCompositeOperation(blendMode);
+
+ try {
+ if (!sCtx || !dCtx) return;
+
+ for (const srcTile of srcTiles) {
+ if (!srcTile.data) continue;
+ const tx = srcTile.tileX;
+ const ty = srcTile.tileY;
+ const docX = tx * TILE_SIZE;
+ const docY = ty * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, dimensions.width - docX);
+ const validH = Math.min(TILE_SIZE, dimensions.height - docY);
+ if (validW <= 0 || validH <= 0) continue;
+
+ const srcRgba = new Uint8ClampedArray(host.getTileAsRGBA(srcTile));
+
+ if (hasMask && maskCtx && maskCanvas) {
+ const mw = Math.min(validW, Math.max(0, maskCanvas.width - docX));
+ const mh = Math.min(validH, Math.max(0, maskCanvas.height - docY));
+ if (mw > 0 && mh > 0) {
+ const mData = maskCtx.getImageData(docX, docY, mw, mh).data;
+ for (let py = 0; py < validH; py++) {
+ for (let px = 0; px < validW; px++) {
+ const pOff = (py * TILE_SIZE + px) << 2;
+ if (srcRgba[pOff + 3] === 0) continue;
+ if (px < mw && py < mh) {
+ const mOff = (py * mw + px) << 2;
+ const maskLum =
+ ((0.299 * mData[mOff] + 0.587 * mData[mOff + 1] + 0.114 * mData[mOff + 2]) / 255) *
+ (mData[mOff + 3] / 255);
+ srcRgba[pOff + 3] = Math.round(srcRgba[pOff + 3] * maskLum);
+ } else {
+ srcRgba[pOff + 3] = 0;
+ }
+ }
+ }
+ }
+ }
+
+ sCtx.clearRect(0, 0, TILE_SIZE, TILE_SIZE);
+ sCtx.putImageData(new ImageData(srcRgba, TILE_SIZE, TILE_SIZE), 0, 0);
+
+ dCtx.clearRect(0, 0, TILE_SIZE, TILE_SIZE);
+ const existingDst = host.getTile(dstLayerId, tx, ty, 0);
+ if (existingDst && existingDst.data) {
+ const dstRgba = new Uint8ClampedArray(host.getTileAsRGBA(existingDst));
+ dCtx.putImageData(new ImageData(dstRgba, TILE_SIZE, TILE_SIZE), 0, 0);
+ }
+
+ dCtx.save();
+ dCtx.globalAlpha = effectiveAlpha;
+ dCtx.globalCompositeOperation = compositeOp;
+ dCtx.drawImage(srcTileCanvas, 0, 0);
+ dCtx.restore();
+
+ const merged = dCtx.getImageData(0, 0, validW, validH);
+ host.writeImageData(dstLayerId, merged, docX, docY, dstFormat, true);
+ }
+ } finally {
+ releaseTemporaryCanvas(srcTileCanvas);
+ releaseTemporaryCanvas(dstTileCanvas);
+ }
+
+ host.clearLayer(srcLayerId);
+ host.notifyChange(true);
+}
+
+/**
+ * Permanently applies a grayscale mask canvas directly to populated tiles of `layerId`.
+ * Peak memory: 1 tile (256 KB).
+ */
+export function applyMaskCanvasToLayer(
+ host: ISparseTileGridHost,
+ layerId: string,
+ maskCanvas: HTMLCanvasElement,
+ dimensions: CanvasDimensions
+): void {
+ const mCtx = maskCanvas.getContext('2d', { willReadFrequently: true });
+ if (!mCtx) return;
+
+ transformLayerTiles(host, layerId, (rgba, tx, ty) => {
+ const docX = tx * TILE_SIZE;
+ const docY = ty * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, dimensions.width - docX, maskCanvas.width - docX);
+ const validH = Math.min(TILE_SIZE, dimensions.height - docY, maskCanvas.height - docY);
+ if (validW <= 0 || validH <= 0) {
+ rgba.fill(0);
+ return true;
+ }
+ const mData = mCtx.getImageData(docX, docY, validW, validH).data;
+ for (let py = 0; py < TILE_SIZE; py++) {
+ for (let px = 0; px < TILE_SIZE; px++) {
+ const off = (py * TILE_SIZE + px) << 2;
+ if (rgba[off + 3] === 0) continue;
+ if (px < validW && py < validH) {
+ const mOff = (py * validW + px) << 2;
+ const lum =
+ ((0.299 * mData[mOff] + 0.587 * mData[mOff + 1] + 0.114 * mData[mOff + 2]) / 255) *
+ (mData[mOff + 3] / 255);
+ rgba[off + 3] = Math.round(rgba[off + 3] * lum);
+ } else {
+ rgba[off + 3] = 0;
+ }
+ }
+ }
+ return true;
+ });
+}
+
+/**
+ * Resizes a single layer directly in SparseTileGrid (anchor shift/crop or chunked bilinear scale)
+ * without allocating monolithic old/new full-document HTMLCanvasElements.
+ */
+export function resizeLayerInGrid(
+ host: ISparseTileGridHost,
+ layerId: string,
+ oldDims: CanvasDimensions,
+ newDims: CanvasDimensions,
+ options: {
+ scaleContent: boolean;
+ offsetX: number;
+ offsetY: number;
+ isBackground: boolean;
+ backgroundColor: string;
+ targetFormat: TileFormat;
+ }
+): void {
+ const { scaleContent, offsetX, offsetY, isBackground, backgroundColor, targetFormat } = options;
+ const newW = newDims.width;
+ const newH = newDims.height;
+
+ const oldTiles = host.getLayerTiles(layerId, 0);
+ if (oldTiles.length === 0) {
+ host.clearLayer(layerId);
+ if (isBackground && backgroundColor !== 'transparent') {
+ // Caller handles solid fill via fillLayerSolidColor
+ host.fillLayerSolidWhite(layerId, newW, newH, 'color-32bit');
+ } else {
+ host.setLayerFormat(layerId, targetFormat);
+ host.ingestedLayers.add(layerId);
+ }
+ return;
+ }
+
+ // Detach a snapshot of old LOD 0 tiles so we can rebuild layerId cleanly
+ const oldTileMap = new Map<string, { format: TileFormat; data: Uint8Array }>();
+ for (const t of oldTiles) {
+ if (!t.data) continue;
+ const copy = new Uint8Array(t.data.length);
+ copy.set(t.data);
+ oldTileMap.set(`${t.tileX}:${t.tileY}`, { format: t.format, data: copy });
+ }
+
+ const readOldRgba = (tx: number, ty: number, scratch: Uint8ClampedArray): Uint8ClampedArray | null => {
+ const entry = oldTileMap.get(`${tx}:${ty}`);
+ if (!entry) return null;
+ if (entry.format === 'color-32bit') {
+ return new Uint8ClampedArray(entry.data.buffer, entry.data.byteOffset, BYTES_32BIT);
+ }
+ if (entry.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(entry.data, scratch);
+ return scratch;
+ }
+ unpack8BitToRGBA(entry.data, scratch);
+ return scratch;
+ };
+
+ host.clearLayer(layerId);
+ host.setLayerFormat(layerId, targetFormat);
+ host.ingestedLayers.add(layerId);
+
+ const bgRgb = isBackground && backgroundColor !== 'transparent' ? parseHexSimple(backgroundColor) : null;
+
+ if (!scaleContent) {
+ // Fast exact tile-aligned shift when offset is a multiple of TILE_SIZE and no bg fill needed
+ if (!bgRgb && offsetX % TILE_SIZE === 0 && offsetY % TILE_SIZE === 0) {
+ const dTx = offsetX / TILE_SIZE;
+ const dTy = offsetY / TILE_SIZE;
+ const maxNewTx = pixelToTileCoord(newW - 1, 0);
+ const maxNewTy = pixelToTileCoord(newH - 1, 0);
+
+ for (const [k, entry] of oldTileMap.entries()) {
+ const [otxStr, otyStr] = k.split(':');
+ const ntx = parseInt(otxStr, 10) + dTx;
+ const nty = parseInt(otyStr, 10) + dTy;
+ if (ntx < 0 || nty < 0 || ntx > maxNewTx || nty > maxNewTy) continue;
+
+ const docX = ntx * TILE_SIZE;
+ const docY = nty * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, newW - docX);
+ const validH = Math.min(TILE_SIZE, newH - docY);
+ if (validW === TILE_SIZE && validH === TILE_SIZE && entry.format === targetFormat) {
+ const newTile: TileBuffer = {
+ layerId,
+ tileX: ntx,
+ tileY: nty,
+ format: entry.format,
+ data: entry.data,
+ dirty: true,
+ version: allocateTileVersion(),
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
+ };
+ host.setTile(layerId, ntx, nty, newTile);
+ } else {
+ const scratch = new Uint8ClampedArray(BYTES_32BIT);
+ const rgba = readOldRgba(parseInt(otxStr, 10), parseInt(otyStr, 10), scratch);
+ if (rgba) {
+ const cropped = new Uint8ClampedArray(validW * validH * 4);
+ for (let y = 0; y < validH; y++) {
+ cropped.set(rgba.subarray(y * TILE_SIZE * 4, y * TILE_SIZE * 4 + validW * 4), y * validW * 4);
+ }
+ host.writeImageData(layerId, { data: cropped, width: validW, height: validH }, docX, docY, targetFormat, true);
+ }
+ }
+ }
+ host.bumpLayerVersion(layerId);
+ return;
+ }
+
+ // General anchor offset (tile-by-tile, zero monolithic canvas)
+ const dstTileCoords = new Set<string>();
+ const maxNewTx = pixelToTileCoord(newW - 1, 0);
+ const maxNewTy = pixelToTileCoord(newH - 1, 0);
+
+ if (bgRgb) {
+ for (let ty = 0; ty <= maxNewTy; ty++) {
+ for (let tx = 0; tx <= maxNewTx; tx++) {
+ dstTileCoords.add(`${tx}:${ty}`);
+ }
+ }
+ } else {
+ for (const k of oldTileMap.keys()) {
+ const [otxStr, otyStr] = k.split(':');
+ const nx0 = Math.max(0, parseInt(otxStr, 10) * TILE_SIZE + offsetX);
+ const ny0 = Math.max(0, parseInt(otyStr, 10) * TILE_SIZE + offsetY);
+ const nx1 = Math.min(newW, (parseInt(otxStr, 10) + 1) * TILE_SIZE + offsetX);
+ const ny1 = Math.min(newH, (parseInt(otyStr, 10) + 1) * TILE_SIZE + offsetY);
+ if (nx1 <= nx0 || ny1 <= ny0) continue;
+ const tx0 = pixelToTileCoord(nx0, 0);
+ const ty0 = pixelToTileCoord(ny0, 0);
+ const tx1 = pixelToTileCoord(nx1 - 1, 0);
+ const ty1 = pixelToTileCoord(ny1 - 1, 0);
+ for (let ty = ty0; ty <= ty1; ty++) {
+ for (let tx = tx0; tx <= tx1; tx++) {
+ dstTileCoords.add(`${tx}:${ty}`);
+ }
+ }
+ }
+ }
+
+ const srcScratch = new Uint8ClampedArray(BYTES_32BIT);
+ const dstRgba = new Uint8ClampedArray(BYTES_32BIT);
+
+ for (const key of dstTileCoords) {
+ const [txStr, tyStr] = key.split(':');
+ const tx = parseInt(txStr, 10);
+ const ty = parseInt(tyStr, 10);
+ const docX = tx * TILE_SIZE;
+ const docY = ty * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, newW - docX);
+ const validH = Math.min(TILE_SIZE, newH - docY);
+ if (validW <= 0 || validH <= 0) continue;
+
+ dstRgba.fill(0);
+ if (bgRgb) {
+ for (let y = 0; y < validH; y++) {
+ let off = y * TILE_SIZE * 4;
+ for (let x = 0; x < validW; x++, off += 4) {
+ dstRgba[off] = bgRgb[0];
+ dstRgba[off + 1] = bgRgb[1];
+ dstRgba[off + 2] = bgRgb[2];
+ dstRgba[off + 3] = bgRgb[3];
+ }
+ }
+ }
+
+ const oldMinX = Math.max(0, docX - offsetX);
+ const oldMinY = Math.max(0, docY - offsetY);
+ const oldMaxX = Math.min(oldDims.width, docX + validW - offsetX);
+ const oldMaxY = Math.min(oldDims.height, docY + validH - offsetY);
+
+ if (oldMaxX > oldMinX && oldMaxY > oldMinY) {
+ const oTx0 = pixelToTileCoord(oldMinX, 0);
+ const oTy0 = pixelToTileCoord(oldMinY, 0);
+ const oTx1 = pixelToTileCoord(oldMaxX - 1, 0);
+ const oTy1 = pixelToTileCoord(oldMaxY - 1, 0);
+
+ for (let oty = oTy0; oty <= oTy1; oty++) {
+ const oDocY = oty * TILE_SIZE;
+ for (let otx = oTx0; otx <= oTx1; otx++) {
+ const srcRgba = readOldRgba(otx, oty, srcScratch);
+ if (!srcRgba) continue;
+ const oDocX = otx * TILE_SIZE;
+
+ const sx0 = Math.max(oldMinX, oDocX);
+ const sy0 = Math.max(oldMinY, oDocY);
+ const sx1 = Math.min(oldMaxX, oDocX + TILE_SIZE);
+ const sy1 = Math.min(oldMaxY, oDocY + TILE_SIZE);
+ const copyW = sx1 - sx0;
+ if (copyW <= 0 || sy1 <= sy0) continue;
+
+ for (let sy = sy0; sy < sy1; sy++) {
+ const sLocalY = sy - oDocY;
+ const sLocalX = sx0 - oDocX;
+ const dLocalY = sy + offsetY - docY;
+ const dLocalX = sx0 + offsetX - docX;
+ const sOff = (sLocalY * TILE_SIZE + sLocalX) << 2;
+ const dOff = (dLocalY * TILE_SIZE + dLocalX) << 2;
+ if (bgRgb) {
+ // Alpha-over onto background color
+ for (let k = 0; k < copyW; k++) {
+ const si = sOff + (k << 2);
+ const di = dOff + (k << 2);
+ const sa = srcRgba[si + 3];
+ if (sa === 255) {
+ dstRgba[di] = srcRgba[si];
+ dstRgba[di + 1] = srcRgba[si + 1];
+ dstRgba[di + 2] = srcRgba[si + 2];
+ dstRgba[di + 3] = 255;
+ } else if (sa > 0) {
+ const a = sa / 255;
+ const inv = 1 - a;
+ dstRgba[di] = Math.round(srcRgba[si] * a + dstRgba[di] * inv);
+ dstRgba[di + 1] = Math.round(srcRgba[si + 1] * a + dstRgba[di + 1] * inv);
+ dstRgba[di + 2] = Math.round(srcRgba[si + 2] * a + dstRgba[di + 2] * inv);
+ dstRgba[di + 3] = 255;
+ }
+ }
+ } else {
+ dstRgba.set(srcRgba.subarray(sOff, sOff + (copyW << 2)), dOff);
+ }
+ }
+ }
+ }
+ }
+
+ if (!isRgbaAllTransparent(dstRgba)) {
+ const outBuf =
+ validW === TILE_SIZE && validH === TILE_SIZE
+ ? dstRgba
+ : cropTileRgba(dstRgba, validW, validH);
+ host.writeImageData(layerId, { data: outBuf, width: validW, height: validH }, docX, docY, targetFormat, true);
+ }
+ }
+ host.bumpLayerVersion(layerId);
+ return;
+ }
+
+ // Scaled resize: process destination tiles one by one via bilinear sampling from oldTileMap (zero monolithic canvas!)
+ const scaleX = oldDims.width / Math.max(1, newW);
+ const scaleY = oldDims.height / Math.max(1, newH);
+ const maxNewTx = pixelToTileCoord(newW - 1, 0);
+ const maxNewTy = pixelToTileCoord(newH - 1, 0);
+
+ // Determine which destination tiles overlap any populated old tile
+ const dstTileCoords = new Set<string>();
+ if (bgRgb) {
+ for (let ty = 0; ty <= maxNewTy; ty++) {
+ for (let tx = 0; tx <= maxNewTx; tx++) {
+ dstTileCoords.add(`${tx}:${ty}`);
+ }
+ }
+ } else {
+ for (const k of oldTileMap.keys()) {
+ const [otxStr, otyStr] = k.split(':');
+ const ox0 = parseInt(otxStr, 10) * TILE_SIZE;
+ const oy0 = parseInt(otyStr, 10) * TILE_SIZE;
+ const nx0 = Math.max(0, Math.floor(ox0 / scaleX) - 1);
+ const ny0 = Math.max(0, Math.floor(oy0 / scaleY) - 1);
+ const nx1 = Math.min(newW, Math.ceil((ox0 + TILE_SIZE) / scaleX) + 1);
+ const ny1 = Math.min(newH, Math.ceil((oy0 + TILE_SIZE) / scaleY) + 1);
+ if (nx1 <= nx0 || ny1 <= ny0) continue;
+ for (let ty = pixelToTileCoord(ny0, 0); ty <= pixelToTileCoord(ny1 - 1, 0); ty++) {
+ for (let tx = pixelToTileCoord(nx0, 0); tx <= pixelToTileCoord(nx1 - 1, 0); tx++) {
+ dstTileCoords.add(`${tx}:${ty}`);
+ }
+ }
+ }
+ }
+
+ // Small LRU cache of unpacked old tiles during scaling
+ const unpackedCache = new Map<string, Uint8ClampedArray | null>();
+ const sampleOld = (ix: number, iy: number, out: [number, number, number, number]) => {
+ const cx = Math.max(0, Math.min(oldDims.width - 1, ix));
+ const cy = Math.max(0, Math.min(oldDims.height - 1, iy));
+ const otx = cx >> 8;
+ const oty = cy >> 8;
+ const key = `${otx}:${oty}`;
+ let rgba = unpackedCache.get(key);
+ if (rgba === undefined) {
+ if (unpackedCache.size > 64) unpackedCache.clear();
+ const scratch = new Uint8ClampedArray(BYTES_32BIT);
+ rgba = readOldRgba(otx, oty, scratch);
+ unpackedCache.set(key, rgba);
+ }
+ if (!rgba) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ return;
+ }
+ const off = ((cy & 255) * TILE_SIZE + (cx & 255)) << 2;
+ out[0] = rgba[off];
+ out[1] = rgba[off + 1];
+ out[2] = rgba[off + 2];
+ out[3] = rgba[off + 3];
+ };
+
+ const dstRgba = new Uint8ClampedArray(BYTES_32BIT);
+ const p00: [number, number, number, number] = [0, 0, 0, 0];
+ const p10: [number, number, number, number] = [0, 0, 0, 0];
+ const p01: [number, number, number, number] = [0, 0, 0, 0];
+ const p11: [number, number, number, number] = [0, 0, 0, 0];
+
+ for (const key of dstTileCoords) {
+ const [txStr, tyStr] = key.split(':');
+ const tx = parseInt(txStr, 10);
+ const ty = parseInt(tyStr, 10);
+ const docX = tx * TILE_SIZE;
+ const docY = ty * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, newW - docX);
+ const validH = Math.min(TILE_SIZE, newH - docY);
+ if (validW <= 0 || validH <= 0) continue;
+
+ dstRgba.fill(0);
+ for (let ly = 0; ly < validH; ly++) {
+ const sy = (docY + ly + 0.5) * scaleY - 0.5;
+ const y0 = Math.floor(sy);
+ const fy = sy - y0;
+ for (let lx = 0; lx < validW; lx++) {
+ const sx = (docX + lx + 0.5) * scaleX - 0.5;
+ const x0 = Math.floor(sx);
+ const fx = sx - x0;
+
+ sampleOld(x0, y0, p00);
+ sampleOld(x0 + 1, y0, p10);
+ sampleOld(x0, y0 + 1, p01);
+ sampleOld(x0 + 1, y0 + 1, p11);
+
+ const w00 = (1 - fx) * (1 - fy);
+ const w10 = fx * (1 - fy);
+ const w01 = (1 - fx) * fy;
+ const w11 = fx * fy;
+
+ const a = Math.round(p00[3] * w00 + p10[3] * w10 + p01[3] * w01 + p11[3] * w11);
+ const off = (ly * TILE_SIZE + lx) << 2;
+ if (a > 0) {
+ const r = Math.round(p00[0] * w00 + p10[0] * w10 + p01[0] * w01 + p11[0] * w11);
+ const g = Math.round(p00[1] * w00 + p10[1] * w10 + p01[1] * w01 + p11[1] * w11);
+ const b = Math.round(p00[2] * w00 + p10[2] * w10 + p01[2] * w01 + p11[2] * w11);
+ if (bgRgb && a < 255) {
+ const af = a / 255;
+ const inv = 1 - af;
+ dstRgba[off] = Math.round(r * af + bgRgb[0] * inv);
+ dstRgba[off + 1] = Math.round(g * af + bgRgb[1] * inv);
+ dstRgba[off + 2] = Math.round(b * af + bgRgb[2] * inv);
+ dstRgba[off + 3] = 255;
+ } else {
+ dstRgba[off] = r;
+ dstRgba[off + 1] = g;
+ dstRgba[off + 2] = b;
+ dstRgba[off + 3] = a;
+ }
+ } else if (bgRgb) {
+ dstRgba[off] = bgRgb[0];
+ dstRgba[off + 1] = bgRgb[1];
+ dstRgba[off + 2] = bgRgb[2];
+ dstRgba[off + 3] = bgRgb[3];
+ }
+ }
+ }
+
+ if (!isRgbaAllTransparent(dstRgba)) {
+ const outBuf =
+ validW === TILE_SIZE && validH === TILE_SIZE
+ ? dstRgba
+ : cropTileRgba(dstRgba, validW, validH);
+ host.writeImageData(layerId, { data: outBuf, width: validW, height: validH }, docX, docY, targetFormat, true);
+ }
+ }
+ host.bumpLayerVersion(layerId);
+}
+
+/**
+ * Deep-clones populated LOD 0 tiles of `layerId` for tile-backed clipboard storage.
+ */
+export function copyLayerTilesSnapshot(
+ host: ISparseTileGridHost,
+ layerId: string
+): { format: TileFormat; tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }> } {
+ const format = host.getLayerFormat(layerId);
+ const tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }> = [];
+ for (const tile of host.getLayerTiles(layerId, 0)) {
+ if (!tile.data) continue;
+ const copy = new Uint8Array(tile.data.length);
+ copy.set(tile.data);
+ tiles.push({ tileX: tile.tileX, tileY: tile.tileY, format: tile.format, data: copy });
+ }
+ return { format, tiles };
+}
+
+/**
+ * Pastes a tile snapshot directly into `dstLayerId` without touching HTMLCanvasElement.
+ */
+export function pasteLayerTilesSnapshot(
+ host: ISparseTileGridHost,
+ dstLayerId: string,
+ snapshot: { format: TileFormat; tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }> }
+): void {
+ host.clearLayer(dstLayerId);
+ host.setLayerFormat(dstLayerId, snapshot.format);
+ host.ingestedLayers.add(dstLayerId);
+ for (const entry of snapshot.tiles) {
+ const copy = new Uint8Array(entry.data.length);
+ copy.set(entry.data);
+ host.setTile(dstLayerId, entry.tileX, entry.tileY, {
+ layerId: dstLayerId,
+ tileX: entry.tileX,
+ tileY: entry.tileY,
+ format: entry.format,
+ data: copy,
+ dirty: true,
+ version: allocateTileVersion(),
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
+ });
+ }
+ host.notifyChange(true);
+}
+
+function cropTileRgba(fullTile: Uint8ClampedArray, validW: number, validH: number): Uint8ClampedArray {
+ const out = new Uint8ClampedArray(validW * validH * 4);
+ for (let y = 0; y < validH; y++) {
+ const srcOff = y * TILE_SIZE * 4;
+ out.set(fullTile.subarray(srcOff, srcOff + validW * 4), y * validW * 4);
+ }
+ return out;
+}
+
+function parseHexSimple(css: string): [number, number, number, number] {
+ const lower = css.trim().toLowerCase();
+ if (lower === 'white' || lower === '#fff' || lower === '#ffffff') return [255, 255, 255, 255];
+ if (lower === 'black' || lower === '#000' || lower === '#000000') return [0, 0, 0, 255];
+ if (lower.startsWith('#')) {
+ const hex = lower.slice(1);
+ if (hex.length === 3) {
+ return [
+ parseInt(hex[0] + hex[0], 16) || 0,
+ parseInt(hex[1] + hex[1], 16) || 0,
+ parseInt(hex[2] + hex[2], 16) || 0,
+ 255,
+ ];
+ }
+ if (hex.length >= 6) {
+ return [
+ parseInt(hex.slice(0, 2), 16) || 0,
+ parseInt(hex.slice(2, 4), 16) || 0,
+ parseInt(hex.slice(4, 6), 16) || 0,
+ hex.length === 8 ? parseInt(hex.slice(6, 8), 16) || 255 : 255,
+ ];
+ }
+ }
+ return [255, 255, 255, 255];
+}
diff --git a/src/utils/tileEngine/tileRender.ts b/src/utils/tileEngine/tileRender.ts
new file mode 100644
index 0000000..b943004
--- /dev/null
+++ b/src/utils/tileEngine/tileRender.ts
@@ -0,0 +1,260 @@
+/**
+ * Canvas materialization and thumbnail rendering operations for SparseTileGrid.
+ */
+
+import {
+ BYTES_32BIT,
+ ISparseTileGridHost,
+ TILE_SIZE,
+ pixelToTileCoord,
+} from './types';
+
+export function renderLayerToCanvas(
+ host: ISparseTileGridHost,
+ layerId: string,
+ targetCanvas: HTMLCanvasElement,
+ dirtyRect?: { x: number; y: number; width: number; height: number }
+): void {
+ const ctx = targetCanvas.getContext('2d');
+ if (!ctx) return;
+
+ let minX = 0;
+ let minY = 0;
+ let maxX = targetCanvas.width;
+ let maxY = targetCanvas.height;
+
+ if (dirtyRect) {
+ minX = Math.max(0, Math.floor(dirtyRect.x));
+ minY = Math.max(0, Math.floor(dirtyRect.y));
+ maxX = Math.min(targetCanvas.width, Math.ceil(dirtyRect.x + dirtyRect.width));
+ maxY = Math.min(targetCanvas.height, Math.ceil(dirtyRect.y + dirtyRect.height));
+ }
+
+ if (maxX <= minX || maxY <= minY) return;
+
+ const minTileX = pixelToTileCoord(minX, 0);
+ const minTileY = pixelToTileCoord(minY, 0);
+ const maxTileX = pixelToTileCoord(maxX - 1, 0);
+ const maxTileY = pixelToTileCoord(maxY - 1, 0);
+
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const validH = Math.min(TILE_SIZE, targetCanvas.height - tileDocY);
+ if (validH <= 0) continue;
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, targetCanvas.width - tileDocX);
+ if (validW <= 0) continue;
+ const tile = host.getTile(layerId, tx, ty, 0);
+ if (!tile) {
+ ctx.clearRect(tileDocX, tileDocY, validW, validH);
+ continue;
+ }
+
+ const rgba = host.getTileAsRGBA(tile);
+ if (typeof ImageData !== 'undefined') {
+ const clamped = new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, BYTES_32BIT);
+ const imgData = new ImageData(clamped, TILE_SIZE, TILE_SIZE);
+ ctx.putImageData(imgData, tileDocX, tileDocY, 0, 0, validW, validH);
+ }
+ }
+ }
+}
+
+/**
+ * Populates a temporary (or caller-supplied pooled) HTMLCanvasElement strictly sized to `rect` from tiles.
+ * When `targetCanvas` is omitted, caller must release the returned canvas via `releaseTemporaryCanvas(canvas)`.
+ */
+export function createRegionCanvas(
+ host: ISparseTileGridHost,
+ layerId: string,
+ rect: { x: number; y: number; width: number; height: number },
+ targetCanvas?: HTMLCanvasElement | null
+): HTMLCanvasElement | null {
+ if (typeof document === 'undefined' || rect.width <= 0 || rect.height <= 0) return null;
+ const w = Math.max(1, Math.ceil(rect.width));
+ const h = Math.max(1, Math.ceil(rect.height));
+ const canvas = targetCanvas || document.createElement('canvas');
+ const resized = canvas.width !== w || canvas.height !== h;
+ if (canvas.width !== w) canvas.width = w;
+ if (canvas.height !== h) canvas.height = h;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return canvas;
+ if (!resized) {
+ if (typeof ctx.resetTransform === 'function') {
+ ctx.resetTransform();
+ } else {
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ }
+ ctx.clearRect(0, 0, w, h);
+ }
+
+ if (host.hasLayerTiles(layerId) && typeof ImageData !== 'undefined') {
+ const originX = Math.floor(rect.x);
+ const originY = Math.floor(rect.y);
+ const minTileX = pixelToTileCoord(originX, 0);
+ const minTileY = pixelToTileCoord(originY, 0);
+ const maxTileX = pixelToTileCoord(originX + w - 1, 0);
+ const maxTileY = pixelToTileCoord(originY + h - 1, 0);
+
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const interStartY = Math.max(originY, tileDocY);
+ const interEndY = Math.min(originY + h, tileDocY + TILE_SIZE);
+ const dirtyH = interEndY - interStartY;
+ if (dirtyH <= 0) continue;
+ const dirtyY = interStartY - tileDocY;
+
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ const tile = host.getTile(layerId, tx, ty, 0);
+ if (!tile) continue;
+
+ const tileDocX = tx * TILE_SIZE;
+ const interStartX = Math.max(originX, tileDocX);
+ const interEndX = Math.min(originX + w, tileDocX + TILE_SIZE);
+ const dirtyW = interEndX - interStartX;
+ if (dirtyW <= 0) continue;
+ const dirtyX = interStartX - tileDocX;
+
+ const rgba = host.getTileAsRGBA(tile);
+ const clamped = new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, BYTES_32BIT);
+ const imgData = new ImageData(clamped, TILE_SIZE, TILE_SIZE);
+ ctx.putImageData(
+ imgData,
+ tileDocX - originX,
+ tileDocY - originY,
+ dirtyX,
+ dirtyY,
+ dirtyW,
+ dirtyH
+ );
+ }
+ }
+ }
+ return canvas;
+}
+
+/**
+ * Materializes a full-layer temporary HTMLCanvasElement from tiles (for export/filters).
+ * Caller MUST release it immediately after use via `releaseTemporaryCanvas(canvas)`.
+ */
+export function exportLayerToCanvas(
+ host: ISparseTileGridHost,
+ layerId: string,
+ width: number,
+ height: number
+): HTMLCanvasElement | null {
+ if (typeof document === 'undefined' || width <= 0 || height <= 0) return null;
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ if (host.hasLayerTiles(layerId)) {
+ host.renderLayerToCanvas(layerId, canvas);
+ }
+ return canvas;
+}
+
+/**
+ * Generates a layer thumbnail directly from LOD 3 mipmap tiles (1/8 resolution: 2048px per tile).
+ * Completely bypasses full-size canvas allocation and full-resolution pixel reads.
+ */
+export function generateThumbnail(
+ host: ISparseTileGridHost,
+ layerId: string,
+ thumbWidth: number,
+ thumbHeight: number,
+ docDimensions: { width: number; height: number },
+ preserveAlpha: boolean = true
+): string {
+ if (typeof document === 'undefined') return '';
+ let canvas = host.getThumbCanvas();
+ if (!canvas) {
+ canvas = document.createElement('canvas');
+ host.setThumbCanvas(canvas);
+ }
+ if (canvas.width !== thumbWidth) canvas.width = thumbWidth;
+ if (canvas.height !== thumbHeight) canvas.height = thumbHeight;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return '';
+
+ const docW = Math.max(1, docDimensions.width);
+ const docH = Math.max(1, docDimensions.height);
+
+ const tiles = host.getOrBuildLod3Tiles(layerId);
+
+ if (tiles.length === 0) {
+ if (preserveAlpha) {
+ ctx.clearRect(0, 0, thumbWidth, thumbHeight);
+ return canvas.toDataURL('image/png');
+ }
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, thumbWidth, thumbHeight);
+ return canvas.toDataURL('image/jpeg', 0.65);
+ }
+
+ const renderLod = 3;
+ const lodDocSize = TILE_SIZE << renderLod; // 2048 document pixels per LOD 3 tile
+ const thumbImg = ctx.createImageData(thumbWidth, thumbHeight);
+ const outData = thumbImg.data;
+ if (!preserveAlpha) {
+ outData.fill(255);
+ }
+ const scaleX = docW / thumbWidth;
+ const scaleY = docH / thumbHeight;
+
+ for (const tile of tiles) {
+ const tileDocX = tile.tileX * lodDocSize;
+ const tileDocY = tile.tileY * lodDocSize;
+
+ const x0 = Math.max(0, Math.floor((tileDocX / docW) * thumbWidth));
+ const y0 = Math.max(0, Math.floor((tileDocY / docH) * thumbHeight));
+ const x1 = Math.min(thumbWidth, Math.ceil(((tileDocX + lodDocSize) / docW) * thumbWidth));
+ const y1 = Math.min(thumbHeight, Math.ceil(((tileDocY + lodDocSize) / docH) * thumbHeight));
+
+ if (x0 >= x1 || y0 >= y1) continue;
+
+ const rgba = host.getTileAsRGBA(tile);
+
+ for (let py = y0; py < y1; py++) {
+ const docY = (py + 0.5) * scaleY;
+ const ly = Math.min(TILE_SIZE - 1, Math.max(0, Math.floor(((docY - tileDocY) / lodDocSize) * TILE_SIZE)));
+ const ly2 = Math.min(TILE_SIZE - 1, ly + 1);
+ for (let px = x0; px < x1; px++) {
+ const docX = (px + 0.5) * scaleX;
+ const lx = Math.min(TILE_SIZE - 1, Math.max(0, Math.floor(((docX - tileDocX) / lodDocSize) * TILE_SIZE)));
+ const lx2 = Math.min(TILE_SIZE - 1, lx + 1);
+
+ let srcIdx = (ly * TILE_SIZE + lx) * 4;
+ if (rgba[srcIdx + 3] === 0) {
+ const alt1 = (ly * TILE_SIZE + lx2) * 4;
+ const alt2 = (ly2 * TILE_SIZE + lx) * 4;
+ const alt3 = (ly2 * TILE_SIZE + lx2) * 4;
+ if (rgba[alt1 + 3] > 0) srcIdx = alt1;
+ else if (rgba[alt2 + 3] > 0) srcIdx = alt2;
+ else if (rgba[alt3 + 3] > 0) srcIdx = alt3;
+ }
+
+ const sa = rgba[srcIdx + 3];
+ if (sa > 0) {
+ const dstIdx = (py * thumbWidth + px) * 4;
+ if (preserveAlpha || sa === 255) {
+ outData[dstIdx] = rgba[srcIdx];
+ outData[dstIdx + 1] = rgba[srcIdx + 1];
+ outData[dstIdx + 2] = rgba[srcIdx + 2];
+ outData[dstIdx + 3] = sa;
+ } else {
+ const a = sa / 255;
+ const inv = 1 - a;
+ outData[dstIdx] = Math.round(rgba[srcIdx] * a + 255 * inv);
+ outData[dstIdx + 1] = Math.round(rgba[srcIdx + 1] * a + 255 * inv);
+ outData[dstIdx + 2] = Math.round(rgba[srcIdx + 2] * a + 255 * inv);
+ outData[dstIdx + 3] = 255;
+ }
+ }
+ }
+ }
+ }
+
+ ctx.putImageData(thumbImg, 0, 0);
+ return preserveAlpha ? canvas.toDataURL('image/png') : canvas.toDataURL('image/jpeg', 0.65);
+}
diff --git a/src/utils/tileEngine/tileSnapshots.ts b/src/utils/tileEngine/tileSnapshots.ts
new file mode 100644
index 0000000..2764c9b
--- /dev/null
+++ b/src/utils/tileEngine/tileSnapshots.ts
@@ -0,0 +1,381 @@
+/**
+ * Layer lifecycle, memory statistics, tile snapshots, undo/redo delta diffing,
+ * and full-grid snapshot restoration for SparseTileGrid.
+ */
+
+import type { TileDelta } from '../../types/editor';
+import {
+ ISparseTileGridHost,
+ TileBuffer,
+ TileFormat,
+ TileMemoryStats,
+ TileSnapshotEntry,
+ allocateTileVersion,
+ getTileByteSize,
+ getTileKey,
+ packTileCoord,
+ parseTileKey,
+ pixelToTileCoord,
+ reserveTileVersion,
+} from './types';
+
+export function registerLod0Tile(host: ISparseTileGridHost, tile: TileBuffer): void {
+ if ((tile.lod ?? 0) !== 0) return;
+ let set = host.layerLod0Tiles.get(tile.layerId);
+ if (!set) {
+ set = new Set<TileBuffer>();
+ host.layerLod0Tiles.set(tile.layerId, set);
+ }
+ if (set.has(tile)) return;
+ set.add(tile);
+
+ let occ = host.layerLodOccupancy.get(tile.layerId);
+ if (!occ) {
+ occ = [new Map<number, number>(), new Map<number, number>(), new Map<number, number>()];
+ host.layerLodOccupancy.set(tile.layerId, occ);
+ }
+ let tx = tile.tileX;
+ let ty = tile.tileY;
+ for (let i = 0; i < 3; i++) {
+ tx = tx >> 1;
+ ty = ty >> 1;
+ const pk = packTileCoord(tx, ty);
+ occ[i].set(pk, (occ[i].get(pk) ?? 0) + 1);
+ }
+}
+
+export function unregisterLod0Tile(host: ISparseTileGridHost, tile: TileBuffer): void {
+ if ((tile.lod ?? 0) !== 0) return;
+ const set = host.layerLod0Tiles.get(tile.layerId);
+ if (!set || !set.delete(tile)) return;
+ if (set.size === 0) {
+ host.layerLod0Tiles.delete(tile.layerId);
+ }
+
+ const occ = host.layerLodOccupancy.get(tile.layerId);
+ if (!occ) return;
+ let tx = tile.tileX;
+ let ty = tile.tileY;
+ for (let i = 0; i < 3; i++) {
+ tx = tx >> 1;
+ ty = ty >> 1;
+ const pk = packTileCoord(tx, ty);
+ const next = (occ[i].get(pk) ?? 0) - 1;
+ if (next <= 0) {
+ occ[i].delete(pk);
+ } else {
+ occ[i].set(pk, next);
+ }
+ }
+ if (set.size === 0) {
+ host.layerLodOccupancy.delete(tile.layerId);
+ }
+}
+
+export function clearLayer(host: ISparseTileGridHost, layerId: string): void {
+ host.ingestedLayers.delete(layerId);
+ host.layerLod0Tiles.delete(layerId);
+ host.layerLodOccupancy.delete(layerId);
+ const memoryManager = host.getMemoryManager();
+ const prefix = `${layerId}:`;
+ const toDelete: string[] = [];
+ for (const [key, tile] of host.tiles.entries()) {
+ if (key.startsWith(prefix)) {
+ toDelete.push(key);
+ if (memoryManager) {
+ memoryManager.notifyTileFreed(tile);
+ }
+ }
+ }
+ for (const key of toDelete) {
+ host.tiles.delete(key);
+ host.dirtyLodTiles.delete(key);
+ }
+ host.bumpLayerVersion(layerId);
+ host.notifyChange();
+}
+
+export function cloneLayer(host: ISparseTileGridHost, srcLayerId: string, dstLayerId: string): void {
+ host.clearLayer(dstLayerId);
+ host.ingestedLayers.add(dstLayerId);
+ host.setLayerFormat(dstLayerId, host.getLayerFormat(srcLayerId));
+ const memoryManager = host.getMemoryManager();
+ const srcTiles = host.getLayerTiles(srcLayerId, 0);
+ for (const srcTile of srcTiles) {
+ if (!srcTile.data && srcTile.isPagedToDisk && memoryManager) {
+ void memoryManager.requestTileData(srcTile);
+ }
+ const clonedData = srcTile.data ? new Uint8Array(srcTile.data.length) : new Uint8Array(getTileByteSize(srcTile.format));
+ if (srcTile.data) clonedData.set(srcTile.data);
+
+ const clonedTile: TileBuffer = {
+ layerId: dstLayerId,
+ tileX: srcTile.tileX,
+ tileY: srcTile.tileY,
+ format: srcTile.format,
+ data: clonedData,
+ dirty: true,
+ version: allocateTileVersion(),
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
+ solidColorU32: srcTile.solidColorU32,
+ };
+ host.setTile(dstLayerId, srcTile.tileX, srcTile.tileY, clonedTile);
+ }
+}
+
+export function getMemoryStats(host: ISparseTileGridHost): TileMemoryStats {
+ let totalBytes = 0;
+ let activeBytes = 0;
+ let pagedBytes = 0;
+ let activeTileCount = 0;
+ let pagedTileCount = 0;
+
+ const formatCounts: Record<TileFormat, number> = {
+ 'monochrome-1bit': 0,
+ 'grayscale-8bit': 0,
+ 'color-32bit': 0,
+ };
+ const lodCounts: Record<number, number> = { 0: 0, 1: 0, 2: 0, 3: 0 };
+
+ for (const tile of host.tiles.values()) {
+ const bSize = getTileByteSize(tile.format);
+ totalBytes += bSize;
+ lodCounts[tile.lod ?? 0] = (lodCounts[tile.lod ?? 0] || 0) + 1;
+
+ if (tile.data !== null) {
+ activeBytes += tile.data.byteLength;
+ activeTileCount++;
+ formatCounts[tile.format]++;
+ } else if (tile.isPagedToDisk) {
+ pagedBytes += bSize;
+ pagedTileCount++;
+ }
+ }
+
+ return {
+ totalBytes,
+ activeBytes,
+ pagedBytes,
+ tileCount: host.tiles.size,
+ activeTileCount,
+ pagedTileCount,
+ formatCounts,
+ lodCounts,
+ };
+}
+
+export function snapshotLayerTiles(
+ host: ISparseTileGridHost,
+ layerId: string
+): Map<string, TileSnapshotEntry> {
+ const snapshot = new Map<string, TileSnapshotEntry>();
+ for (const tile of host.getLayerTiles(layerId, 0)) {
+ const key = getTileKey(layerId, tile.tileX, tile.tileY, 0);
+ if (tile.data) {
+ const copy = new Uint8Array(tile.data.length);
+ copy.set(tile.data);
+ snapshot.set(key, { format: tile.format, data: copy });
+ } else {
+ snapshot.set(key, { format: tile.format, data: null });
+ }
+ }
+ return snapshot;
+}
+
+export function snapshotTilesInRect(
+ host: ISparseTileGridHost,
+ layerId: string,
+ bounds: { x: number; y: number; width: number; height: number }
+): Map<string, TileSnapshotEntry> {
+ const snapshot = new Map<string, TileSnapshotEntry>();
+ if (bounds.width <= 0 || bounds.height <= 0) return snapshot;
+
+ const minTileX = pixelToTileCoord(bounds.x, 0);
+ const minTileY = pixelToTileCoord(bounds.y, 0);
+ const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1, 0);
+ const maxTileY = pixelToTileCoord(bounds.y + bounds.height - 1, 0);
+
+ const layerFormat = host.getLayerFormat(layerId);
+
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ const key = getTileKey(layerId, tx, ty, 0);
+ const tile = host.getTile(layerId, tx, ty, 0);
+ if (tile && tile.data) {
+ const copy = new Uint8Array(tile.data.length);
+ copy.set(tile.data);
+ snapshot.set(key, { format: tile.format, data: copy });
+ } else {
+ snapshot.set(key, { format: layerFormat, data: null });
+ }
+ }
+ }
+
+ return snapshot;
+}
+
+export function computeDeltasFromSnapshot(
+ host: ISparseTileGridHost,
+ beforeSnapshot: Map<string, TileSnapshotEntry>,
+ layerId: string,
+ bounds?: { x: number; y: number; width: number; height: number }
+): TileDelta[] {
+ const deltas: TileDelta[] = [];
+ const keysToCheck = new Set<string>(beforeSnapshot.keys());
+
+ if (beforeSnapshot.size === 0 && bounds && bounds.width > 0 && bounds.height > 0) {
+ const minTileX = pixelToTileCoord(bounds.x, 0);
+ const minTileY = pixelToTileCoord(bounds.y, 0);
+ const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1, 0);
+ const maxTileY = pixelToTileCoord(bounds.y + bounds.height - 1, 0);
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ keysToCheck.add(getTileKey(layerId, tx, ty, 0));
+ }
+ }
+ }
+
+ for (const key of keysToCheck) {
+ if (beforeSnapshot.size > 0 && !beforeSnapshot.has(key)) continue;
+ const before = beforeSnapshot.get(key);
+ const { tileX, tileY } = parseTileKey(key);
+ const currentTile = host.getTile(layerId, tileX, tileY, 0);
+
+ const beforeData = before ? before.data : null;
+ const currentData = currentTile && currentTile.data ? currentTile.data : null;
+ const format = currentTile ? currentTile.format : (before ? before.format : host.getLayerFormat(layerId));
+
+ if (beforeData === null && currentData === null) continue;
+
+ let changed = false;
+ if ((beforeData === null) !== (currentData === null)) {
+ changed = true;
+ } else if (beforeData && currentData) {
+ if (beforeData.byteLength !== currentData.byteLength) {
+ changed = true;
+ } else if (
+ beforeData.byteLength % 4 === 0 &&
+ beforeData.byteOffset % 4 === 0 &&
+ currentData.byteOffset % 4 === 0
+ ) {
+ const len32 = beforeData.byteLength >>> 2;
+ const b32 = new Uint32Array(beforeData.buffer, beforeData.byteOffset, len32);
+ const c32 = new Uint32Array(currentData.buffer, currentData.byteOffset, len32);
+ for (let i = 0; i < len32; i++) {
+ if (b32[i] !== c32[i]) {
+ changed = true;
+ break;
+ }
+ }
+ } else {
+ for (let i = 0; i < beforeData.byteLength; i++) {
+ if (beforeData[i] !== currentData[i]) {
+ changed = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if (changed) {
+ deltas.push({
+ key,
+ format,
+ beforeData,
+ afterData: currentData ? new Uint8Array(currentData) : null,
+ });
+ }
+ }
+
+ return deltas;
+}
+
+export function applyTileDeltas(
+ host: ISparseTileGridHost,
+ deltas: TileDelta[],
+ direction: 'undo' | 'redo'
+): void {
+ const memoryManager = host.getMemoryManager();
+ for (const delta of deltas) {
+ const { layerId, tileX, tileY } = parseTileKey(delta.key);
+ const targetData = direction === 'undo' ? delta.beforeData : delta.afterData;
+
+ if (!targetData) {
+ host.deleteTile(layerId, tileX, tileY, 0);
+ } else {
+ let tile = host.getTile(layerId, tileX, tileY, 0);
+ if (!tile) {
+ tile = host.getOrCreateTile(layerId, tileX, tileY, delta.format, 0);
+ }
+ if (!tile.data || tile.data.byteLength !== targetData.byteLength) {
+ if (tile.data) {
+ memoryManager?.notifyTileFreed(tile);
+ }
+ tile.data = new Uint8Array(targetData.length);
+ memoryManager?.notifyTileAllocated(tile);
+ }
+ tile.data.set(targetData);
+ tile.solidColorU32 = undefined;
+ tile.format = delta.format;
+ host.setLayerFormat(layerId, delta.format);
+ tile.dirty = true;
+ tile.version = allocateTileVersion();
+ host.markLodAncestorsDirty(layerId, tileX, tileY);
+ host.bumpLayerVersion(layerId);
+ }
+ }
+ host.notifyChange();
+}
+
+export function clearAll(host: ISparseTileGridHost): void {
+ const memoryManager = host.getMemoryManager();
+ if (memoryManager) {
+ for (const tile of host.tiles.values()) {
+ memoryManager.notifyTileFreed(tile);
+ }
+ }
+ host.tiles.clear();
+ host.layerLod0Tiles.clear();
+ host.layerLodOccupancy.clear();
+ host.layerFormats.clear();
+ host.ingestedLayers.clear();
+ host.dirtyLodTiles.clear();
+ host.layerVersions.clear();
+ host.incrementGridEpochAndContentVersion();
+ host.notifyChange(true);
+}
+
+export function restoreFromSnapshot(
+ host: ISparseTileGridHost,
+ tiles: TileBuffer[],
+ layerFormats?: Map<string, TileFormat>
+): void {
+ host.clearAll();
+ const memoryManager = host.getMemoryManager();
+ if (layerFormats) {
+ for (const [layerId, fmt] of layerFormats.entries()) {
+ host.layerFormats.set(layerId, fmt);
+ }
+ }
+ for (const tile of tiles) {
+ if (tile.version > 0) {
+ reserveTileVersion(tile.version);
+ } else {
+ tile.version = allocateTileVersion();
+ }
+ tile.dirty = true;
+ host.tiles.set(getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0), tile);
+ if ((tile.lod ?? 0) === 0) {
+ host.registerLod0Tile(tile);
+ }
+ if (memoryManager) {
+ memoryManager.notifyTileAllocated(tile);
+ }
+ if ((tile.lod ?? 0) === 0) {
+ host.bumpLayerVersion(tile.layerId);
+ }
+ }
+ host.notifyChange(true);
+}
diff --git a/src/utils/tileEngine/types.ts b/src/utils/tileEngine/types.ts
new file mode 100644
index 0000000..4b29f01
--- /dev/null
+++ b/src/utils/tileEngine/types.ts
@@ -0,0 +1,238 @@
+/**
+ * Core tile constants, types, coordinate helpers, and internal host contracts
+ * for the Sparse Virtual Tile Engine.
+ */
+
+export const TILE_SIZE = 256;
+export const TILE_PIXELS = TILE_SIZE * TILE_SIZE; // 65,536 pixels
+export const BYTES_1BIT = TILE_PIXELS >> 3; // 8,192 bytes (8 KB)
+export const BYTES_8BIT = TILE_PIXELS; // 65,536 bytes (64 KB)
+export const BYTES_32BIT = TILE_PIXELS << 2; // 262,144 bytes (256 KB)
+
+export type TileFormat = 'monochrome-1bit' | 'grayscale-8bit' | 'color-32bit';
+
+export interface TileBuffer {
+ layerId: string;
+ tileX: number;
+ tileY: number;
+ format: TileFormat;
+ data: Uint8Array | null; // null when paged out to disk
+ dirty: boolean;
+ version: number;
+ isPagedToDisk: boolean;
+ lastAccessTimestamp: number;
+ lod: number; // 0 = 1:1 (256x256 doc area), 1 = 1/2 (512x512), 2 = 1/4 (1024x1024), 3 = 1/8 (2048x2048)
+ solidColorU32?: number; // When defined on a color-32bit tile, all 65,536 pixels share this exact U32 RGBA value
+}
+
+export interface TileSnapshotEntry {
+ format: TileFormat;
+ data: Uint8Array | null;
+}
+
+export interface TileMemoryStats {
+ totalBytes: number;
+ activeBytes: number;
+ pagedBytes: number;
+ tileCount: number;
+ activeTileCount: number;
+ pagedTileCount: number;
+ formatCounts: Record<TileFormat, number>;
+ lodCounts: Record<number, number>;
+}
+
+export function getTileByteSize(format: TileFormat): number {
+ if (format === 'monochrome-1bit') return BYTES_1BIT;
+ if (format === 'grayscale-8bit') return BYTES_8BIT;
+ return BYTES_32BIT;
+}
+
+// System endianness detection for 32-bit operations
+export const isLittleEndian = (() => {
+ if (typeof ArrayBuffer === 'undefined') return true;
+ const buf = new ArrayBuffer(4);
+ new Uint32Array(buf)[0] = 0x11223344;
+ return new Uint8Array(buf)[0] === 0x44;
+})();
+
+// Default binary colors in system byte order
+// Black ink: RGBA(0, 0, 0, 255)
+export const INK_BLACK_U32 = isLittleEndian ? 0xff000000 : 0x000000ff;
+// Transparent: RGBA(0, 0, 0, 0)
+export const TRANSPARENT_U32 = 0x00000000;
+// Paper white: RGBA(255, 255, 255, 255)
+export const PAPER_WHITE_U32 = 0xffffffff;
+
+/**
+ * Get tile coordinate from document pixel coordinate.
+ */
+export function pixelToTileCoord(pixel: number, lod: number = 0): number {
+ const tileSizeDoc = TILE_SIZE << lod;
+ return Math.floor(pixel / tileSizeDoc);
+}
+
+/**
+ * Spatial hash map key for tiles.
+ * LOD 0 produces backwards-compatible key: `${layerId}:${tileX}:${tileY}`.
+ * LOD > 0 produces: `${layerId}:${lod}:${tileX}:${tileY}`.
+ */
+export function getTileKey(layerId: string, tileX: number, tileY: number, lod: number = 0): string {
+ return lod === 0 ? `${layerId}:${tileX}:${tileY}` : `${layerId}:${lod}:${tileX}:${tileY}`;
+}
+
+/**
+ * Parse spatial hash map key into components.
+ */
+export function parseTileKey(key: string): { layerId: string; tileX: number; tileY: number; lod: number } {
+ const parts = key.split(':');
+ if (parts.length === 4) {
+ return {
+ layerId: parts[0],
+ lod: parseInt(parts[1], 10),
+ tileX: parseInt(parts[2], 10),
+ tileY: parseInt(parts[3], 10),
+ };
+ }
+ return {
+ layerId: parts[0],
+ tileX: parseInt(parts[1], 10),
+ tileY: parseInt(parts[2], 10),
+ lod: 0,
+ };
+}
+
+let nextGlobalTileVersion = 1;
+
+export function allocateTileVersion(): number {
+ return ++nextGlobalTileVersion;
+}
+
+export function reserveTileVersion(version: number): void {
+ if (Number.isFinite(version) && version > nextGlobalTileVersion) {
+ nextGlobalTileVersion = Math.floor(version);
+ }
+}
+
+/**
+ * Allocate a new TileBuffer with zero-initialized memory.
+ */
+export function createTileBuffer(
+ layerId: string,
+ tileX: number,
+ tileY: number,
+ format: TileFormat,
+ lod: number = 0
+): TileBuffer {
+ const size = getTileByteSize(format);
+
+ return {
+ layerId,
+ tileX,
+ tileY,
+ format,
+ data: new Uint8Array(size),
+ dirty: true,
+ version: allocateTileVersion(),
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod,
+ };
+}
+
+/**
+ * Releases an HTMLCanvasElement's backing store immediately so Chromium/WebView2 reclaims RAM.
+ */
+export function releaseTemporaryCanvas(canvas: HTMLCanvasElement | null | undefined): void {
+ if (!canvas) return;
+ try {
+ canvas.width = 0;
+ canvas.height = 0;
+ } catch {
+ // Ignore read-only or detached mock canvases in tests
+ }
+}
+
+const TILE_COORD_BIAS = 32768;
+const TILE_COORD_STRIDE = 65536;
+
+export function packTileCoord(tx: number, ty: number): number {
+ return (ty + TILE_COORD_BIAS) * TILE_COORD_STRIDE + (tx + TILE_COORD_BIAS);
+}
+
+export function unpackTileCoordX(packed: number): number {
+ return (packed % TILE_COORD_STRIDE) - TILE_COORD_BIAS;
+}
+
+export function unpackTileCoordY(packed: number): number {
+ return Math.floor(packed / TILE_COORD_STRIDE) - TILE_COORD_BIAS;
+}
+
+/**
+ * Minimal grid contract consumed by TileMemoryManager to avoid circular module imports.
+ */
+export interface ISparseTileGridMemoryHost {
+ tilesIterable(): IterableIterator<TileBuffer>;
+ bumpLayerVersion(layerId: string): void;
+ notifyChange(immediate?: boolean): void;
+}
+
+/**
+ * Minimal memory-manager contract consumed by internal tileEngine helper modules.
+ */
+export interface ITileMemoryManagerHost {
+ touchTile(tile: TileBuffer): void;
+ notifyTileAllocated(tile: TileBuffer): void;
+ notifyTileFreed(tile: TileBuffer): void;
+ requestTileData(tile: TileBuffer): Promise<Uint8Array>;
+}
+
+/**
+ * Internal host contract implemented by SparseTileGrid for modular tile operations.
+ */
+export interface ISparseTileGridHost extends ISparseTileGridMemoryHost {
+ readonly tiles: Map<string, TileBuffer>;
+ readonly layerLod0Tiles: Map<string, Set<TileBuffer>>;
+ readonly layerLodOccupancy: Map<string, [Map<number, number>, Map<number, number>, Map<number, number>]>;
+ readonly layerFormats: Map<string, TileFormat>;
+ readonly ingestedLayers: Set<string>;
+ readonly dirtyLodTiles: Set<string>;
+ readonly layerVersions: Map<string, number>;
+ readonly scratchRGBA: Uint8ClampedArray;
+ readonly writeScratchRGBA: Uint8ClampedArray;
+ getThumbCanvas(): HTMLCanvasElement | null;
+ setThumbCanvas(canvas: HTMLCanvasElement | null): void;
+ getMemoryManager(): ITileMemoryManagerHost | null;
+ incrementGridEpochAndContentVersion(): void;
+ registerLod0Tile(tile: TileBuffer): void;
+ unregisterLod0Tile(tile: TileBuffer): void;
+ hasLayerTiles(layerId: string): boolean;
+ hasPopulatedLodTile(layerId: string, tileX: number, tileY: number, lod: number): boolean;
+ setLayerFormat(layerId: string, format: TileFormat): void;
+ getLayerFormat(layerId: string): TileFormat;
+ getTile(layerId: string, tileX: number, tileY: number, lod?: number): TileBuffer | null;
+ getOrCreateTile(layerId: string, tileX: number, tileY: number, format?: TileFormat, lod?: number): TileBuffer;
+ setTile(layerId: string, tileX: number, tileY: number, tile: TileBuffer): void;
+ deleteTile(layerId: string, tileX: number, tileY: number, lod?: number): void;
+ getLayerTiles(layerId: string, lod?: number): TileBuffer[];
+ getTileAsRGBA(tile: TileBuffer): Uint8ClampedArray;
+ isLodTileDirty(layerId: string, tileX: number, tileY: number, lod: number): boolean;
+ markLodAncestorsDirty(layerId: string, tileX: number, tileY: number): void;
+ generateLodTile(layerId: string, lodTx: number, lodTy: number, targetLod: number): TileBuffer | null;
+ getOrBuildLod3Tiles(layerId: string): TileBuffer[];
+ writeImageData(
+ layerId: string,
+ imgData: { data: Uint8ClampedArray | Uint8Array; width: number; height: number },
+ destX: number,
+ destY: number,
+ format?: TileFormat,
+ suppressNotify?: boolean
+ ): { minTileX: number; minTileY: number; maxTileX: number; maxTileY: number };
+ renderLayerToCanvas(
+ layerId: string,
+ targetCanvas: HTMLCanvasElement,
+ dirtyRect?: { x: number; y: number; width: number; height: number }
+ ): void;
+ fillLayerSolidWhite(layerId: string, width: number, height: number, format?: TileFormat): void;
+ clearLayer(layerId: string): void;
+ clearAll(): void;
+}
diff --git a/src/utils/tonalEngine.ts b/src/utils/tonalEngine.ts
index 6338322..b087c04 100644
--- a/src/utils/tonalEngine.ts
+++ b/src/utils/tonalEngine.ts
@@ -1,10 +1,22 @@
import {
+ CanvasDimensions,
CanvasSelection,
AdjustmentLayerData,
ToneCurvePoints,
GradientStop,
ColorBalanceAdjustmentData,
+ TileDelta,
} from '../types/editor';
+import {
+ BYTES_32BIT,
+ SparseTileGrid,
+ TILE_SIZE,
+ TileFormat,
+ TileSnapshotEntry,
+ parseTileKey,
+ unpack1BitToRGBA,
+ unpack8BitToRGBA,
+} from './tileEngine';
export type TonalCorrectionType =
| 'brightness-contrast'
@@ -957,3 +969,165 @@ export function applyAdjustment(
}
}
+export interface TileHistogramMap {
+ rgb: Uint32Array;
+ r: Uint32Array;
+ g: Uint32Array;
+ b: Uint32Array;
+}
+
+/**
+ * Computes RGB + luminance histograms directly from a SparseTileGrid tile snapshot
+ * without materializing a full-document ImageData buffer.
+ */
+export function computeHistogramsFromTileSnapshot(
+ snapshot: Map<string, TileSnapshotEntry>,
+ dimensions: CanvasDimensions,
+ selectionMask?: Uint8Array | null
+): TileHistogramMap {
+ const rgb = new Uint32Array(256);
+ const rHist = new Uint32Array(256);
+ const gHist = new Uint32Array(256);
+ const bHist = new Uint32Array(256);
+ const scratch = new Uint8ClampedArray(BYTES_32BIT);
+ const docW = dimensions.width;
+ const docH = dimensions.height;
+
+ for (const [key, entry] of snapshot.entries()) {
+ if (!entry.data) continue;
+ const { tileX, tileY } = parseTileKey(key);
+ const tileDocX = tileX * TILE_SIZE;
+ const tileDocY = tileY * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, docW - tileDocX);
+ const validH = Math.min(TILE_SIZE, docH - tileDocY);
+ if (validW <= 0 || validH <= 0) continue;
+
+ let rgba: Uint8ClampedArray;
+ if (entry.format === 'color-32bit') {
+ rgba = new Uint8ClampedArray(entry.data.buffer, entry.data.byteOffset, BYTES_32BIT);
+ } else if (entry.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(entry.data, scratch);
+ rgba = scratch;
+ } else {
+ unpack8BitToRGBA(entry.data, scratch);
+ rgba = scratch;
+ }
+
+ for (let ly = 0; ly < validH; ly++) {
+ const gy = tileDocY + ly;
+ const selRow = gy * docW;
+ let off = (ly * TILE_SIZE) << 2;
+ for (let lx = 0; lx < validW; lx++, off += 4) {
+ if (rgba[off + 3] === 0) continue;
+ if (selectionMask && selectionMask[selRow + tileDocX + lx] === 0) continue;
+ const rv = rgba[off];
+ const gv = rgba[off + 1];
+ const bv = rgba[off + 2];
+ rHist[rv]++;
+ gHist[gv]++;
+ bHist[bv]++;
+ const lum = Math.round(0.299 * rv + 0.587 * gv + 0.114 * bv);
+ rgb[lum]++;
+ }
+ }
+ }
+
+ return { rgb, r: rHist, g: gHist, b: bHist };
+}
+
+/**
+ * Applies any point-wise tonal correction directly from a pre-edit tile snapshot into
+ * SparseTileGrid tiles (zero full-document canvas or full-document ImageData).
+ */
+export function applyTonalToTileGrid(params: {
+ grid: SparseTileGrid;
+ layerId: string;
+ dimensions: CanvasDimensions;
+ beforeSnapshot: Map<string, TileSnapshotEntry>;
+ type: TonalCorrectionType;
+ tonalParams: any;
+ targetFormat: TileFormat;
+ selectionMask?: Uint8Array | null;
+ bounds?: ProcessingBounds;
+}): { tileDeltas: TileDelta[] } {
+ const {
+ grid,
+ layerId,
+ dimensions,
+ beforeSnapshot,
+ type,
+ tonalParams,
+ targetFormat,
+ selectionMask,
+ bounds,
+ } = params;
+
+ const docW = dimensions.width;
+ const docH = dimensions.height;
+ const bX0 = bounds ? bounds.x0 : 0;
+ const bY0 = bounds ? bounds.y0 : 0;
+ const bX1 = bounds ? bounds.x1 : docW;
+ const bY1 = bounds ? bounds.y1 : docH;
+
+ const scratch = new Uint8ClampedArray(BYTES_32BIT);
+ const dstBuf = new Uint8ClampedArray(BYTES_32BIT);
+ const tileMaskBuf = selectionMask ? new Uint8Array(TILE_SIZE * TILE_SIZE) : null;
+
+ for (const [key, entry] of beforeSnapshot.entries()) {
+ if (!entry.data) continue;
+ const { tileX, tileY } = parseTileKey(key);
+ const tileDocX = tileX * TILE_SIZE;
+ const tileDocY = tileY * TILE_SIZE;
+
+ const ix0 = Math.max(bX0, tileDocX);
+ const iy0 = Math.max(bY0, tileDocY);
+ const ix1 = Math.min(bX1, tileDocX + TILE_SIZE, docW);
+ const iy1 = Math.min(bY1, tileDocY + TILE_SIZE, docH);
+ if (ix1 <= ix0 || iy1 <= iy0) continue;
+
+ let srcRgba: Uint8ClampedArray;
+ if (entry.format === 'color-32bit') {
+ srcRgba = new Uint8ClampedArray(entry.data.buffer, entry.data.byteOffset, BYTES_32BIT);
+ } else if (entry.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(entry.data, scratch);
+ srcRgba = scratch;
+ } else {
+ unpack8BitToRGBA(entry.data, scratch);
+ srcRgba = scratch;
+ }
+
+ dstBuf.set(srcRgba);
+
+ let localMask: Uint8Array | null = null;
+ if (selectionMask && tileMaskBuf) {
+ tileMaskBuf.fill(0);
+ const localX0 = ix0 - tileDocX;
+ const localY0 = iy0 - tileDocY;
+ const localX1 = ix1 - tileDocX;
+ const localY1 = iy1 - tileDocY;
+ for (let ly = localY0; ly < localY1; ly++) {
+ const srcOff = (tileDocY + ly) * docW + tileDocX + localX0;
+ const dstOff = ly * TILE_SIZE + localX0;
+ tileMaskBuf.set(selectionMask.subarray(srcOff, srcOff + (localX1 - localX0)), dstOff);
+ }
+ localMask = tileMaskBuf;
+ }
+
+ const srcImg = { data: srcRgba, width: TILE_SIZE, height: TILE_SIZE } as ImageData;
+ const dstImg = { data: dstBuf, width: TILE_SIZE, height: TILE_SIZE } as ImageData;
+ const tileBounds: ProcessingBounds = {
+ x0: ix0 - tileDocX,
+ y0: iy0 - tileDocY,
+ x1: ix1 - tileDocX,
+ y1: iy1 - tileDocY,
+ };
+
+ applyTonalFilter(srcImg, dstImg, type, tonalParams, localMask, tileBounds);
+ grid.writeImageData(layerId, { data: dstBuf, width: TILE_SIZE, height: TILE_SIZE }, tileDocX, tileDocY, targetFormat, true);
+ }
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId);
+ grid.notifyChange(true);
+ return { tileDeltas };
+}
+
diff --git a/src/utils/vectorLayerRenderer.ts b/src/utils/vectorLayerRenderer.ts
index a7fa3e7..905242b 100644
--- a/src/utils/vectorLayerRenderer.ts
+++ b/src/utils/vectorLayerRenderer.ts
@@ -110,45 +110,88 @@ export function hitTestEditableVectorLayer(
/**
* Re-renders a non-destructive text or balloon layer from its vector definition into
- * SparseTileGrid (and updates any materialized display canvas) without quality loss.
+ * SparseTileGrid using a tight bounding-box scratch canvas (zero full-doc canvas allocation).
*/
export function syncVectorObjectLayerToGrid(
layer: LayerItem,
dimensions: CanvasDimensions,
- tileGrid: SparseTileGrid,
- layerCanvasesMap?: Map<string, HTMLCanvasElement>
+ tileGrid: SparseTileGrid
): void {
if (typeof document === 'undefined') return;
if (layer.type !== 'text' && layer.type !== 'balloon') return;
if (dimensions.width <= 0 || dimensions.height <= 0) return;
- const existingCanvas = layerCanvasesMap?.get(layer.id);
- const targetCanvas = existingCanvas ?? document.createElement('canvas');
- if (!existingCanvas) {
- targetCanvas.width = dimensions.width;
- targetCanvas.height = dimensions.height;
+ let minX = 0;
+ let minY = 0;
+ let maxX = dimensions.width;
+ let maxY = dimensions.height;
+
+ if (layer.type === 'text' && layer.textData) {
+ const b = getTextLayerBounds(layer.textData);
+ const pad = Math.ceil(Math.max(32, (layer.textData.outlineWidth ?? 0) * 4 + layer.textData.fontSize));
+ minX = Math.max(0, Math.floor(b.x - pad));
+ minY = Math.max(0, Math.floor(b.y - pad));
+ maxX = Math.min(dimensions.width, Math.ceil(b.x + b.width + pad));
+ maxY = Math.min(dimensions.height, Math.ceil(b.y + b.height + pad));
+ } else if (layer.type === 'balloon' && layer.balloonData) {
+ const bd = layer.balloonData;
+ const flashExtra =
+ bd.shape === 'jagged-flash' ? Math.max(bd.bounds.width, bd.bounds.height) * 0.25 : 0;
+ const pad = Math.ceil(
+ Math.max(48, (bd.strokeWidth ?? 3) * 4 + (bd.fontSize ?? 24) * 2 + flashExtra)
+ );
+ let bx0 = bd.bounds.x;
+ let by0 = bd.bounds.y;
+ let bx1 = bd.bounds.x + bd.bounds.width;
+ let by1 = bd.bounds.y + bd.bounds.height;
+ if (bd.tail) {
+ const pts = [bd.tail.start, bd.tail.control1, bd.tail.control2, bd.tail.tip];
+ for (const p of pts) {
+ if (!p) continue;
+ bx0 = Math.min(bx0, p.x);
+ by0 = Math.min(by0, p.y);
+ bx1 = Math.max(bx1, p.x);
+ by1 = Math.max(by1, p.y);
+ }
+ }
+ minX = Math.max(0, Math.floor(bx0 - pad));
+ minY = Math.max(0, Math.floor(by0 - pad));
+ maxX = Math.min(dimensions.width, Math.ceil(bx1 + pad));
+ maxY = Math.min(dimensions.height, Math.ceil(by1 + pad));
}
- const ctx = targetCanvas.getContext('2d');
- if (!ctx) {
- if (!existingCanvas) releaseTemporaryCanvas(targetCanvas);
+ const rw = maxX - minX;
+ const rh = maxY - minY;
+ const format = layer.expressionColor === 'monochrome' ? 'monochrome-1bit' : 'color-32bit';
+ tileGrid.clearLayer(layer.id);
+ tileGrid.setLayerFormat(layer.id, format);
+ tileGrid.markLayerIngested(layer.id);
+
+ if (rw <= 0 || rh <= 0) {
+ tileGrid.notifyChange(true);
return;
}
- ctx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
+ const targetCanvas = document.createElement('canvas');
+ targetCanvas.width = rw;
+ targetCanvas.height = rh;
+ const ctx = targetCanvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) {
+ releaseTemporaryCanvas(targetCanvas);
+ return;
+ }
+ ctx.save();
+ ctx.translate(-minX, -minY);
if (layer.type === 'text' && layer.textData) {
renderTextLayerData(ctx, layer.textData);
} else if (layer.type === 'balloon' && layer.balloonData) {
renderBalloonLayerData(ctx, layer.balloonData);
}
+ ctx.restore();
- const format = layer.expressionColor === 'monochrome' ? 'monochrome-1bit' : 'color-32bit';
- tileGrid.clearLayer(layer.id);
- tileGrid.ingestCanvas(layer.id, targetCanvas, format);
+ const imgData = ctx.getImageData(0, 0, rw, rh);
+ tileGrid.writeImageData(layer.id, imgData, minX, minY, format, true);
tileGrid.notifyChange(true);
-
- if (!existingCanvas) {
- releaseTemporaryCanvas(targetCanvas);
- }
+ releaseTemporaryCanvas(targetCanvas);
}